From 9018ee8980591758ddcd69ba33cd18b1c58ef6d6 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sun, 29 Nov 2026 10:21:28 +0100 Subject: [PATCH] test(atlas): cover the new Atlas from engine to hub views SonarCloud measured 16.9% coverage on this PR's new code. Tests now cover the WebGL globe engine (boot, caching, input, camera, regions, prefetch) and renderer (against a fake WebGL2 context that reads the real shaders), the paint, labels, sky and pins, the central useAtlasGlobe hook and the hub hooks, the snapshot, account queue and Atlas repos, every desktop and phone hub view, the server's people, flights and mesh routes, the shared badge rules, and the new view transition, warm bags and kept planner maps. --- .../Admin/AddonManager.atlas.test.tsx | 87 ++ .../addons/useAddonManager.atlas.test.ts | 74 + .../Atlas/tourActivity/tourHubFigures.test.ts | 151 ++ .../components/AtlasGlobe/AtlasGlobe.test.tsx | 278 ++++ .../components/AtlasGlobe/GlobeEngine.test.ts | 1228 +++++++++++++++++ .../components/AtlasGlobe/GlobePins.test.tsx | 119 ++ .../AtlasGlobe/GlobeRenderer.test.ts | 678 +++++++++ .../components/AtlasGlobe/GlobeSky.test.tsx | 203 +++ .../AtlasGlobe/GlobeStatsBar.test.tsx | 142 ++ .../components/AtlasGlobe/globeLabels.test.ts | 368 +++++ .../AtlasGlobe/globeMath.edge.test.ts | 131 ++ .../AtlasGlobe/globeMesh.edge.test.ts | 214 +++ .../AtlasGlobe/globeMesh.worker.test.ts | 119 ++ .../components/AtlasGlobe/globeTheme.test.ts | 75 + .../Dawarich/useDawarichAtlas.test.ts | 435 ++++++ .../Packing/usePackingBags.kept.test.ts | 94 ++ .../atlas/MAtlasCountrySheets.test.tsx | 151 ++ .../mobile/screens/atlas/MAtlasGlobe.test.tsx | 216 +++ .../screens/atlas/MAtlasLayersSheet.test.tsx | 72 + .../screens/atlas/hub/MAtlasHub.test.tsx | 85 ++ .../screens/atlas/hub/MHubBadges.test.tsx | 157 +++ .../screens/atlas/hub/MHubDawarich.test.tsx | 198 +++ .../screens/atlas/hub/MHubOverview.test.tsx | 114 ++ .../screens/atlas/hub/MHubTours.test.tsx | 180 +++ .../screens/atlas/hub/MHubTravellers.test.tsx | 124 ++ .../screens/atlas/hub/MHubWishlist.test.tsx | 405 ++++++ .../mobile/screens/atlas/hub/mHubKit.test.tsx | 133 ++ .../src/pages/atlas/AtlasBadgeUnlock.test.tsx | 185 +++ .../atlas/AtlasCountryActionDialog.test.tsx | 221 +++ .../src/pages/atlas/AtlasGlobeBadges.test.tsx | 171 +++ .../pages/atlas/AtlasGlobeDawarich.test.tsx | 225 +++ .../pages/atlas/AtlasGlobeDialogs.test.tsx | 236 ++++ .../pages/atlas/AtlasGlobeOverview.test.tsx | 104 ++ .../pages/atlas/AtlasGlobePassport.test.tsx | 202 +++ .../src/pages/atlas/AtlasGlobeSearch.test.tsx | 146 ++ .../src/pages/atlas/AtlasGlobeStatus.test.tsx | 59 + .../pages/atlas/AtlasGlobeTimeline.test.tsx | 151 ++ .../src/pages/atlas/AtlasGlobeTours.test.tsx | 195 +++ .../pages/atlas/AtlasGlobeTravellers.test.tsx | 94 ++ .../src/pages/atlas/AtlasGlobeView.test.tsx | 404 ++++++ .../pages/atlas/AtlasGlobeWishAdd.test.tsx | 257 ++++ .../pages/atlas/AtlasGlobeWishlist.test.tsx | 161 +++ client/src/pages/atlas/AtlasHubRail.test.tsx | 63 + .../src/pages/atlas/atlasGlobePaint.test.ts | 458 ++++++ client/src/pages/atlas/atlasHubHooks.test.ts | 239 ++++ client/src/pages/atlas/atlasHubKit.test.tsx | 216 +++ client/src/pages/atlas/atlasHubModel.test.ts | 241 ++++ client/src/pages/atlas/useAtlasBucket.test.ts | 275 ++++ client/src/pages/atlas/useAtlasGlobe.test.ts | 1222 ++++++++++++++++ .../pages/atlas/useGlobePlaceSearch.test.ts | 164 +++ .../useTripPlanner.keptTabs.test.tsx | 162 +++ client/src/repo/atlasBucketRepo.test.ts | 57 + client/src/repo/atlasPluginLayersRepo.test.ts | 24 + client/src/repo/atlasRepo.data.test.ts | 205 +++ client/src/repo/dawarichRepo.atlas.test.ts | 39 + client/src/sync/atlasSnapshot.test.ts | 356 +++++ client/src/sync/queuePolicy.test.ts | 30 + client/src/sync/userMutationQueue.test.ts | 572 ++++++++ client/src/utils/viewTransition.test.ts | 191 +++ client/tests/helpers/atlasGlobeState.ts | 114 ++ client/tests/helpers/atlasGlobeViews.ts | 122 ++ client/tests/helpers/atlasViewState.ts | 93 ++ client/tests/helpers/fakeWebGl2.ts | 340 +++++ .../admin/MAdminAddonManager.atlas.test.tsx | 63 + .../unit/nest/atlas-flights.service.test.ts | 141 ++ .../nest/atlas-mesh.controller.stream.test.ts | 125 ++ .../unit/nest/atlas-people.manifest.test.ts | 199 +++ .../nest/atlas-people.no-manifest.test.ts | 85 ++ shared/src/atlas/atlas-badges.rules.spec.ts | 141 ++ 69 files changed, 14979 insertions(+) create mode 100644 client/src/components/Admin/AddonManager.atlas.test.tsx create mode 100644 client/src/components/Admin/addons/useAddonManager.atlas.test.ts create mode 100644 client/src/components/Atlas/tourActivity/tourHubFigures.test.ts create mode 100644 client/src/components/AtlasGlobe/AtlasGlobe.test.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeEngine.test.ts create mode 100644 client/src/components/AtlasGlobe/GlobePins.test.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeRenderer.test.ts create mode 100644 client/src/components/AtlasGlobe/GlobeSky.test.tsx create mode 100644 client/src/components/AtlasGlobe/GlobeStatsBar.test.tsx create mode 100644 client/src/components/AtlasGlobe/globeLabels.test.ts create mode 100644 client/src/components/AtlasGlobe/globeMath.edge.test.ts create mode 100644 client/src/components/AtlasGlobe/globeMesh.edge.test.ts create mode 100644 client/src/components/AtlasGlobe/globeMesh.worker.test.ts create mode 100644 client/src/components/AtlasGlobe/globeTheme.test.ts create mode 100644 client/src/components/Dawarich/useDawarichAtlas.test.ts create mode 100644 client/src/components/Packing/usePackingBags.kept.test.ts create mode 100644 client/src/mobile/screens/atlas/MAtlasCountrySheets.test.tsx create mode 100644 client/src/mobile/screens/atlas/MAtlasGlobe.test.tsx create mode 100644 client/src/mobile/screens/atlas/MAtlasLayersSheet.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MAtlasHub.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubBadges.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubDawarich.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubOverview.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubTours.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubTravellers.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/MHubWishlist.test.tsx create mode 100644 client/src/mobile/screens/atlas/hub/mHubKit.test.tsx create mode 100644 client/src/pages/atlas/AtlasBadgeUnlock.test.tsx create mode 100644 client/src/pages/atlas/AtlasCountryActionDialog.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeBadges.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeDawarich.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeDialogs.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeOverview.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobePassport.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeSearch.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeStatus.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeTimeline.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeTours.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeTravellers.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeView.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeWishAdd.test.tsx create mode 100644 client/src/pages/atlas/AtlasGlobeWishlist.test.tsx create mode 100644 client/src/pages/atlas/AtlasHubRail.test.tsx create mode 100644 client/src/pages/atlas/atlasGlobePaint.test.ts create mode 100644 client/src/pages/atlas/atlasHubHooks.test.ts create mode 100644 client/src/pages/atlas/atlasHubKit.test.tsx create mode 100644 client/src/pages/atlas/atlasHubModel.test.ts create mode 100644 client/src/pages/atlas/useAtlasBucket.test.ts create mode 100644 client/src/pages/atlas/useAtlasGlobe.test.ts create mode 100644 client/src/pages/atlas/useGlobePlaceSearch.test.ts create mode 100644 client/src/pages/tripPlanner/useTripPlanner.keptTabs.test.tsx create mode 100644 client/src/repo/atlasBucketRepo.test.ts create mode 100644 client/src/repo/atlasPluginLayersRepo.test.ts create mode 100644 client/src/repo/atlasRepo.data.test.ts create mode 100644 client/src/repo/dawarichRepo.atlas.test.ts create mode 100644 client/src/sync/atlasSnapshot.test.ts create mode 100644 client/src/sync/queuePolicy.test.ts create mode 100644 client/src/sync/userMutationQueue.test.ts create mode 100644 client/src/utils/viewTransition.test.ts create mode 100644 client/tests/helpers/atlasGlobeState.ts create mode 100644 client/tests/helpers/atlasGlobeViews.ts create mode 100644 client/tests/helpers/atlasViewState.ts create mode 100644 client/tests/helpers/fakeWebGl2.ts create mode 100644 client/tests/unit/mobile/admin/MAdminAddonManager.atlas.test.tsx create mode 100644 server/tests/unit/nest/atlas-flights.service.test.ts create mode 100644 server/tests/unit/nest/atlas-mesh.controller.stream.test.ts create mode 100644 server/tests/unit/nest/atlas-people.manifest.test.ts create mode 100644 server/tests/unit/nest/atlas-people.no-manifest.test.ts create mode 100644 shared/src/atlas/atlas-badges.rules.spec.ts diff --git a/client/src/components/Admin/AddonManager.atlas.test.tsx b/client/src/components/Admin/AddonManager.atlas.test.tsx new file mode 100644 index 000000000..987ec3a01 --- /dev/null +++ b/client/src/components/Admin/AddonManager.atlas.test.tsx @@ -0,0 +1,87 @@ +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { server } from '../../../tests/helpers/msw/server'; +import { render, screen, waitFor } from '../../../tests/helpers/render'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { useAddonStore } from '../../store/addonStore'; +import { useAuthStore } from '../../store/authStore'; +import { useSettingsStore } from '../../store/settingsStore'; +import { ToastContainer } from '../shared/Toast'; +import AddonManager from './AddonManager'; + +// FE-ATLAS2-REST-040 to 042: the Atlas ranking row under the Atlas addon on the desktop admin page. + +const RANKING = 'Ranking and profiles'; + +function atlasAddon(enabled: boolean) { + return { id: 'atlas', name: 'Atlas', description: 'World map', icon: 'Globe', type: 'global', enabled }; +} + +function isOn(toggle: HTMLElement): boolean { + return toggle.getAttribute('aria-pressed') === 'true'; +} + +beforeAll(() => { + Object.defineProperty(window, 'matchMedia', { + writable: true, + value: vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })), + }); +}); + +beforeEach(() => { + resetAllStores(); + seedStore(useSettingsStore, { settings: { dark_mode: false } }); + useAuthStore.setState({ atlasCompareEnabled: true }); + vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined); + server.use( + http.get('/api/admin/tours-wanderer', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/tours-hiking-map', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/tours-cycle-map', () => HttpResponse.json({ enabled: false })), + http.get('/api/admin/tours-ski-routing', () => HttpResponse.json({ enabled: false })) + ); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('AddonManager: Atlas ranking', () => { + it('FE-ATLAS2-REST-040: an enabled Atlas shows the ranking row, on as the app config says', async () => { + server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] }))); + render(); + const toggle = await screen.findByRole('button', { name: RANKING }); + expect(isOn(toggle)).toBe(true); + expect(screen.getByText(RANKING)).toHaveAttribute('title', expect.stringContaining('Atlas ranking')); + }); + + it('FE-ATLAS2-REST-041: the row stays away while Atlas itself is off', async () => { + server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(false)] }))); + render(); + await screen.findByRole('button', { name: 'Atlas' }); + expect(screen.queryByRole('button', { name: RANKING })).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-REST-042: flipping the row saves atlas_compare_enabled and shows it off', async () => { + const user = userEvent.setup(); + const bodies: unknown[] = []; + server.use( + http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })), + http.put('/api/auth/app-settings', async ({ request }) => { + bodies.push(await request.json()); + return HttpResponse.json({ success: true }); + }) + ); + render( + <> + + + + ); + await user.click(await screen.findByRole('button', { name: RANKING })); + await screen.findByText('Addon updated'); + expect(bodies).toEqual([{ atlas_compare_enabled: false }]); + await waitFor(() => expect(isOn(screen.getByRole('button', { name: RANKING }))).toBe(false)); + expect(useAuthStore.getState().atlasCompareEnabled).toBe(false); + }); +}); diff --git a/client/src/components/Admin/addons/useAddonManager.atlas.test.ts b/client/src/components/Admin/addons/useAddonManager.atlas.test.ts new file mode 100644 index 000000000..f8e3759b1 --- /dev/null +++ b/client/src/components/Admin/addons/useAddonManager.atlas.test.ts @@ -0,0 +1,74 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { adminApi, authApi } from '../../../api/client'; +import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps'; +import { wandererAdminApi } from '../../../api/wanderer'; +import { useAddonStore } from '../../../store/addonStore'; +import { useAuthStore } from '../../../store/authStore'; +import { useAddonManager } from './useAddonManager'; + +// FE-ATLAS2-REST-030 to 032: the Atlas ranking switch the admin flips under the Atlas addon. + +const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() })); +vi.mock('../../shared/Toast', () => ({ useToast: () => toast })); +vi.mock('../../../i18n', () => ({ useTranslation: () => ({ t: (k: string) => k }) })); + +let loadAddons: ReturnType Promise>>; + +beforeEach(() => { + toast.success.mockReset(); + toast.error.mockReset(); + loadAddons = vi.fn<() => Promise>().mockResolvedValue(undefined); + useAddonStore.setState({ loadAddons }); + useAuthStore.setState({ atlasCompareEnabled: true }); + vi.spyOn(adminApi, 'addons').mockResolvedValue({ addons: [] }); + vi.spyOn(wandererAdminApi, 'get').mockResolvedValue({ enabled: false }); + vi.spyOn(hikingMapAdminApi, 'get').mockResolvedValue({ enabled: false }); + vi.spyOn(cycleMapAdminApi, 'get').mockResolvedValue({ enabled: false }); + vi.spyOn(skiRoutingAdminApi, 'get').mockResolvedValue({ enabled: false }); +}); +afterEach(() => vi.restoreAllMocks()); + +async function loaded() { + const hook = renderHook(() => useAddonManager()); + await waitFor(() => expect(hook.result.current.loading).toBe(false)); + return hook; +} + +describe('useAddonManager: Atlas ranking switch', () => { + it('FE-ATLAS2-REST-030: reads the switch from the app config the auth store holds', async () => { + useAuthStore.setState({ atlasCompareEnabled: false }); + const { result } = await loaded(); + expect(result.current.atlasCompare).toBe(false); + act(() => useAuthStore.setState({ atlasCompareEnabled: true })); + expect(result.current.atlasCompare).toBe(true); + }); + + it('FE-ATLAS2-REST-031: a flip turns it off at once, saves the app setting, refreshes the addons and toasts', async () => { + const save = vi.spyOn(authApi, 'updateAppSettings').mockResolvedValue({}); + const { result } = await loaded(); + await act(() => result.current.toggleAtlasCompare()); + expect(save).toHaveBeenCalledWith({ atlas_compare_enabled: false }); + expect(useAuthStore.getState().atlasCompareEnabled).toBe(false); + expect(result.current.atlasCompare).toBe(false); + expect(loadAddons).toHaveBeenCalledTimes(1); + expect(toast.success).toHaveBeenCalledWith('admin.addons.toast.updated'); + + // And on again from off. + await act(() => result.current.toggleAtlasCompare()); + expect(save).toHaveBeenLastCalledWith({ atlas_compare_enabled: true }); + expect(useAuthStore.getState().atlasCompareEnabled).toBe(true); + }); + + it('FE-ATLAS2-REST-032: a failed save puts the switch back and says so, without refreshing', async () => { + vi.spyOn(authApi, 'updateAppSettings').mockRejectedValue(new Error('down')); + const { result } = await loaded(); + await act(() => result.current.toggleAtlasCompare()); + expect(useAuthStore.getState().atlasCompareEnabled).toBe(true); + expect(result.current.atlasCompare).toBe(true); + expect(toast.error).toHaveBeenCalledWith('admin.addons.toast.error'); + expect(toast.success).not.toHaveBeenCalled(); + expect(loadAddons).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Atlas/tourActivity/tourHubFigures.test.ts b/client/src/components/Atlas/tourActivity/tourHubFigures.test.ts new file mode 100644 index 000000000..8ffdeba12 --- /dev/null +++ b/client/src/components/Atlas/tourActivity/tourHubFigures.test.ts @@ -0,0 +1,151 @@ +// FE-ATLAS2-PAINT-301 to FE-ATLAS2-PAINT-318: the tours page figures of the Atlas hub +// and the readings and labels the tour activity views share. +import { act, renderHook } from '@testing-library/react'; +import type { TourActivityStatsResponse, TourActivitySum, TourActivitySummary, TourActivityTotals } from '@trek/shared'; +import { Bike, Layers, Mountain, Route } from 'lucide-react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { useSettingsStore } from '../../../store/settingsStore'; +import { + distanceReading, + heightReading, + partialHint, + periodLabel, + typeIcon, + typeLabel, + useDistanceUnit, +} from './tourActivityReading'; +import { tourHubFigures } from './tourHubFigures'; + +const echoT = (key: string, params?: Record): string => + params ? `${key}:${JSON.stringify(params)}` : key; + +function sum(value: number | null, known = 1, of = known): TourActivitySum { + return { value, known, of }; +} + +function totals(over: Partial = {}): TourActivityTotals { + return { + count: 3, + distanceKm: sum(42.5, 3), + ascentM: sum(1200, 3), + descentM: sum(1100, 3), + byBasis: { plan: 2, track: 1 }, + ...over, + }; +} + +function summary(over: Partial = {}): TourActivitySummary { + return { totals: totals(), types: [], done: [], upcoming: 0, ...over }; +} + +const initialSettings = useSettingsStore.getState(); + +afterEach(() => { + useSettingsStore.setState(initialSettings, true); +}); + +describe('tourHubFigures', () => { + it('FE-ATLAS2-PAINT-301: leads with the distance split into number and unit, with the climbs beside it', () => { + const figures = tourHubFigures(summary(), null, 'metric'); + expect(figures.hero).toEqual({ value: '42.5', unit: 'km' }); + expect(figures.ascent).toEqual({ text: '1200 m', partial: false }); + expect(figures.descent).toEqual({ text: '1100 m', partial: false }); + }); + + it('FE-ATLAS2-PAINT-302: marks a distance some tours lack as at least that much', () => { + const figures = tourHubFigures(summary({ totals: totals({ distanceKm: sum(10, 1, 3) }) }), null, 'metric'); + expect(figures.hero).toEqual({ value: '≥ 10', unit: 'km' }); + }); + + it('FE-ATLAS2-PAINT-303: leads with the tour count when no tour knows its distance', () => { + const figures = tourHubFigures( + summary({ totals: totals({ count: 7, distanceKm: sum(null, 0, 7), ascentM: sum(null, 0, 7) }) }), + null, + 'metric' + ); + expect(figures.hero).toEqual({ value: '7', unit: '' }); + expect(figures.ascent).toBeNull(); + }); + + it('FE-ATLAS2-PAINT-304: reads in miles and feet for imperial', () => { + const figures = tourHubFigures(summary(), null, 'imperial'); + expect(figures.hero).toEqual({ value: '26.4', unit: 'mi' }); + expect(figures.ascent?.text).toBe('3937 ft'); + }); + + it('FE-ATLAS2-PAINT-305: scales the types to the longest one', () => { + const types = [ + { ...totals({ distanceKm: sum(30) }), type: 'hike' as const }, + { ...totals({ distanceKm: sum(120) }), type: 'bike' as const }, + { ...totals({ distanceKm: sum(null, 0, 1) }), type: 'kayak' as const }, + ]; + const figures = tourHubFigures(summary({ types }), null, 'metric'); + expect(figures.types).toBe(types); + expect(figures.maxKm).toBe(120); + }); + + it('FE-ATLAS2-PAINT-306: never scales against zero, with no types or none with a distance', () => { + expect(tourHubFigures(summary(), null, 'metric').maxKm).toBe(1e-9); + const types = [{ ...totals({ distanceKm: sum(null, 0, 2) }), type: 'run' as const }]; + expect(tourHubFigures(summary({ types }), null, 'metric').maxKm).toBe(1e-9); + }); + + it('FE-ATLAS2-PAINT-307: says which tours are left out of the sums, none before the data loads', () => { + expect(tourHubFigures(summary(), null, 'metric').uncounted).toEqual({ unassigned: 0, undated: 0 }); + const data: TourActivityStatsResponse = { entries: [], uncounted: { unassigned: 2, undated: 1 } }; + expect(tourHubFigures(summary(), data, 'metric').uncounted).toEqual({ unassigned: 2, undated: 1 }); + }); +}); + +describe('tourActivityReading', () => { + it('FE-ATLAS2-PAINT-308: reads the distance unit from the user settings', () => { + useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'imperial' } }); + const { result } = renderHook(() => useDistanceUnit()); + expect(result.current).toBe('imperial'); + act(() => { + useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'metric' } }); + }); + expect(result.current).toBe('metric'); + }); + + it('FE-ATLAS2-PAINT-309: falls back to metric when the setting is missing', () => { + useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: undefined } }); + const { result } = renderHook(() => useDistanceUnit()); + expect(result.current).toBe('metric'); + }); + + it('FE-ATLAS2-PAINT-310: names every type at once apart from a single type', () => { + expect(typeLabel('all', echoT)).toBe('tours.stats.allTypes'); + expect(typeLabel('hike', echoT)).toBe('tourTypes.hike'); + }); + + it('FE-ATLAS2-PAINT-311: draws every type at once as a stack and a single type with its own icon', () => { + expect(typeIcon('all')).toBe(Layers); + expect(typeIcon('bike')).toBe(Bike); + expect(typeIcon('hike')).toBe(Mountain); + expect(typeIcon('food')).toBe(Route); + }); + + it('FE-ATLAS2-PAINT-312: reads a distance, short ones in metres, and none without a value', () => { + expect(distanceReading({ distanceKm: sum(0.3) }, 'metric')).toEqual({ text: '300 m', partial: false }); + expect(distanceReading({ distanceKm: sum(5, 2, 4) }, 'metric')).toEqual({ text: '≥ 5 km', partial: true }); + expect(distanceReading({ distanceKm: sum(null, 0, 4) }, 'metric')).toBeNull(); + }); + + it('FE-ATLAS2-PAINT-313: reads a height sum in metres or feet', () => { + expect(heightReading(sum(500), 'metric')).toEqual({ text: '500 m', partial: false }); + expect(heightReading(sum(500, 1, 2), 'imperial')).toEqual({ text: '≥ 1640 ft', partial: true }); + expect(heightReading(sum(null, 0, 2), 'imperial')).toBeNull(); + }); + + it('FE-ATLAS2-PAINT-314: explains a short sum with how many tours know their value', () => { + expect(partialHint(sum(5, 2, 4), echoT)).toBe('tours.scope.partialBody:{"known":2,"of":4}'); + }); + + it('FE-ATLAS2-PAINT-315: names each period of the filter, an earlier year by its number', () => { + expect(periodLabel('all', echoT)).toBe('tours.stats.period.all'); + expect(periodLabel('thisYear', echoT)).toBe('tours.stats.period.thisYear'); + expect(periodLabel('last12', echoT)).toBe('tours.stats.period.last12'); + expect(periodLabel('year:2023', echoT)).toBe('2023'); + }); +}); diff --git a/client/src/components/AtlasGlobe/AtlasGlobe.test.tsx b/client/src/components/AtlasGlobe/AtlasGlobe.test.tsx new file mode 100644 index 000000000..bbf11c0a7 --- /dev/null +++ b/client/src/components/AtlasGlobe/AtlasGlobe.test.tsx @@ -0,0 +1,278 @@ +// FE-ATLAS2-RENDER-200 to FE-ATLAS2-RENDER-214: the AtlasGlobe component wiring a (faked) GlobeEngine +// to its props: lifecycle, callbacks, painting, theme, inset and the label overlay. +import { act, render } from '@testing-library/react'; +import { createRef, type ComponentProps } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { AtlasMeshManifest, GlobeEngine, GlobeEngineOptions, GlobeHit } from './GlobeEngine'; +import type { GlobeTheme } from './GlobeRenderer'; + +const h = vi.hoisted(() => { + const state = { engines: [] as FakeEngine[], failNext: null as unknown }; + class FakeEngine { + opts: GlobeEngineOptions; + manifest: AtlasMeshManifest | null = null; + onRegionLoaded: ((a2: string) => void) | null = null; + themes: GlobeTheme[] = []; + insets: number[] = []; + kicks = 0; + disposed = false; + constructor(opts: GlobeEngineOptions) { + if (state.failNext !== null) { + const err = state.failNext; + state.failNext = null; + throw err; + } + this.opts = opts; + state.engines.push(this); + } + setTheme(theme: GlobeTheme): void { + this.themes.push(theme); + } + setInsetBottom(px: number): void { + this.insets.push(px); + } + kick(): void { + this.kicks++; + } + dispose(): void { + this.disposed = true; + } + } + const placeLabels = vi.fn( + ( + _host: HTMLDivElement, + _pool: unknown[], + _engine: GlobeEngine, + _labelFor: (a2: string) => string | null, + _labelRegionsOf?: (a2: string) => boolean + ) => undefined + ); + return { FakeEngine, state, placeLabels }; +}); + +vi.mock('./GlobeEngine', () => ({ GlobeEngine: h.FakeEngine })); +vi.mock('./globeLabels', () => ({ placeLabels: h.placeLabels })); + +import AtlasGlobe, { type AtlasGlobeHandle } from './AtlasGlobe'; + +type Props = ComponentProps; + +const MANIFEST = { + version: 1, + lods: ['110m'], + regionLods: [], + world: {}, + countries: [], +} as unknown as AtlasMeshManifest; + +function baseProps(over: Partial = {}): Props { + return { + fetchJson: vi.fn(async (_path: string) => ({})), + dark: true, + labelFor: (a2: string) => a2, + paint: vi.fn(), + paintKey: 1, + ...over, + }; +} + +function engine(i = 0): InstanceType { + const e = h.state.engines[i]; + if (!e) throw new Error(`no engine ${i}`); + return e; +} + +/** The fake as the GlobeEngine the callbacks hand around. */ +function asEngine(e: InstanceType): GlobeEngine { + return e as unknown as GlobeEngine; +} + +beforeEach(() => { + h.state.engines.length = 0; + h.state.failNext = null; + h.placeLabels.mockClear(); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('AtlasGlobe', () => { + it('FE-ATLAS2-RENDER-200: renders the canvas as an image named Atlas with a hidden label layer', () => { + const { container, getByRole } = render(); + const canvas = getByRole('img', { name: 'Atlas' }); + expect(canvas.tagName).toBe('CANVAS'); + expect(container.firstElementChild).toHaveClass('globe-host'); + expect(container.querySelector('[aria-hidden="true"]')).not.toBeNull(); + }); + + it('FE-ATLAS2-RENDER-201: creates one engine on the canvas with the theme for the mode', () => { + const { getByRole } = render(); + expect(h.state.engines).toHaveLength(1); + expect(engine().opts.canvas).toBe(getByRole('img', { name: 'Atlas' })); + expect(engine().opts.theme.dark).toBe(false); + }); + + it('FE-ATLAS2-RENDER-202: exposes the engine through the ref and drops it on unmount', () => { + const ref = createRef(); + const { unmount } = render(); + const e = engine(); + expect(ref.current?.engine).toBe(e); + unmount(); + expect(e.disposed).toBe(true); + }); + + it('FE-ATLAS2-RENDER-203: reports an engine that cannot start to onError and keeps no engine', () => { + const onError = vi.fn(); + const err = new Error('WebGL2 unavailable'); + h.state.failNext = err; + const ref = createRef(); + const { unmount } = render(); + expect(onError).toHaveBeenCalledWith(err); + expect(ref.current?.engine).toBeNull(); + expect(() => unmount()).not.toThrow(); + }); + + it('FE-ATLAS2-RENDER-204: an engine failure without onError is swallowed quietly', () => { + h.state.failNext = new Error('nope'); + expect(() => render()).not.toThrow(); + expect(h.state.engines).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-205: fetches through the latest fetchJson prop', async () => { + const first = vi.fn(async (_path: string) => 'first'); + const second = vi.fn(async (_path: string) => 'second'); + const { rerender } = render(); + rerender(); + await expect(engine().opts.fetchJson('manifest')).resolves.toBe('second'); + expect(second).toHaveBeenCalledWith('manifest'); + expect(first).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-RENDER-206: forwards hover, select and error to the current callbacks', () => { + const onHover = vi.fn(); + const onSelect = vi.fn(); + const onError = vi.fn(); + render(); + const hit: GlobeHit = { kind: 'country', index: 4, a2: 'DE' }; + const opts = engine().opts; + opts.onHover?.(hit, 1, 2); + opts.onSelect?.(null, 3, 4); + opts.onError?.('boom'); + expect(onHover).toHaveBeenCalledWith(hit, 1, 2); + expect(onSelect).toHaveBeenCalledWith(null, 3, 4); + expect(onError).toHaveBeenCalledWith('boom'); + }); + + it('FE-ATLAS2-RENDER-207: callbacks without handlers do nothing', () => { + render(); + const opts = engine().opts; + expect(() => { + opts.onHover?.(null, 0, 0); + opts.onSelect?.(null, 0, 0); + opts.onError?.(new Error('x')); + opts.onFrame?.(asEngine(engine())); + }).not.toThrow(); + }); + + it('FE-ATLAS2-RENDER-208: when the engine is ready it reports the manifest and paints', () => { + const paint = vi.fn(); + const onReady = vi.fn(); + render(); + const e = engine(); + e.manifest = MANIFEST; + act(() => e.opts.onReady?.()); + expect(onReady).toHaveBeenCalledWith(MANIFEST); + // Once from onReady, once from the paint effect now that the globe is ready. + expect(paint).toHaveBeenCalledTimes(2); + expect(paint).toHaveBeenCalledWith(e); + expect(e.kicks).toBe(1); + }); + + it('FE-ATLAS2-RENDER-209: a ready engine without a manifest still paints but reports nothing', () => { + const paint = vi.fn(); + const onReady = vi.fn(); + render(); + act(() => engine().opts.onReady?.()); + expect(onReady).not.toHaveBeenCalled(); + expect(paint).toHaveBeenCalled(); + }); + + it('FE-ATLAS2-RENDER-210: does not paint before the engine is ready, nor without a paint key', () => { + const paint = vi.fn(); + const { rerender } = render(); + expect(paint).not.toHaveBeenCalled(); + act(() => engine().opts.onReady?.()); + // onReady paints; the effect stays quiet while paintKey is undefined. + expect(paint).toHaveBeenCalledTimes(1); + expect(engine().kicks).toBe(0); + rerender(); + expect(paint).toHaveBeenCalledTimes(2); + expect(engine().kicks).toBe(1); + }); + + it('FE-ATLAS2-RENDER-211: repaints and kicks the engine when the paint key changes', () => { + const paint = vi.fn(); + const { rerender } = render(); + act(() => engine().opts.onReady?.()); + const before = paint.mock.calls.length; + rerender(); + expect(paint.mock.calls.length).toBe(before + 1); + rerender(); + expect(paint.mock.calls.length).toBe(before + 1); + }); + + it('FE-ATLAS2-RENDER-212: a loaded region repaints through the latest paint prop', () => { + const first = vi.fn(); + const second = vi.fn(); + const { rerender } = render(); + rerender(); + engine().onRegionLoaded?.('DE'); + expect(second).toHaveBeenCalledWith(engine()); + expect(first).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-RENDER-213: switching dark mode hands the engine the other theme', () => { + const { rerender } = render(); + rerender(); + const themes = engine().themes.map((t) => t.dark); + expect(themes[themes.length - 1]).toBe(false); + expect(themes[0]).toBe(true); + }); + + it('FE-ATLAS2-RENDER-214: passes the bottom inset on, zero when none is given', () => { + const { rerender } = render(); + expect(engine().insets).toEqual([0]); + rerender(); + expect(engine().insets).toEqual([0, 120]); + }); + + it('FE-ATLAS2-RENDER-215: every frame places the labels with the current label props and reports it', () => { + const onFrame = vi.fn(); + const labelFor = (a2: string) => `Land ${a2}`; + const labelRegionsOf = (a2: string) => a2 === 'DE'; + const { container } = render(); + const e = asEngine(engine()); + engine().opts.onFrame?.(e); + engine().opts.onFrame?.(e); + expect(h.placeLabels).toHaveBeenCalledTimes(2); + const [host, pool, eng, lf, lr] = h.placeLabels.mock.calls[0]; + expect(host).toBe(container.querySelector('[aria-hidden="true"]')); + expect(Array.isArray(pool)).toBe(true); + // The pool is kept across frames, so labels are reused rather than rebuilt. + expect(h.placeLabels.mock.calls[1][1]).toBe(pool); + expect(eng).toBe(e); + expect(lf).toBe(labelFor); + expect(lr).toBe(labelRegionsOf); + expect(onFrame).toHaveBeenCalledWith(e); + }); + + it('FE-ATLAS2-RENDER-216: a frame after unmount skips the labels', () => { + const { unmount } = render(); + const e = engine(); + unmount(); + e.opts.onFrame?.(asEngine(e)); + expect(h.placeLabels).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/AtlasGlobe/GlobeEngine.test.ts b/client/src/components/AtlasGlobe/GlobeEngine.test.ts new file mode 100644 index 000000000..608bc87f5 --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeEngine.test.ts @@ -0,0 +1,1228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { AtlasMeshManifest, GlobeEngine, GlobeEngineOptions, RegionIndex } from './GlobeEngine'; +import type { DrawState, GlobeTheme } from './GlobeRenderer'; +import { latLimits, MAX_ZOOM, MIN_ZOOM, RAD, xSqueeze } from './globeMath'; +import type { BuiltLayer, LineMesh } from './globeMesh'; +import type { MeshRequest, MeshResponse } from './globeMesh.worker'; + +// FE-ATLAS2-ENGINE-001 to 113: the Atlas globe engine with a fake renderer, worker, +// resize observer and animation frame, driven through its public surface. + +const fakes = vi.hoisted(() => { + class FakeRenderer { + static instances: FakeRenderer[] = []; + canvas: HTMLCanvasElement; + worlds = new Map(); + regions = new Map(); + pickId = -1; + setOcean = vi.fn(); + setWorld = vi.fn<(key: string, layer: BuiltLayer) => void>((key, layer) => { + this.worlds.set(key, layer); + }); + hasWorld = (key: string): boolean => this.worlds.has(key); + setRegion = vi.fn<(key: string, layer: BuiltLayer, inUse?: ReadonlySet) => void>((key, layer) => { + this.regions.set(key, layer); + }); + hasRegion = (key: string): boolean => this.regions.has(key); + touchRegion = vi.fn<(key: string) => void>(); + draw = vi.fn<(s: DrawState) => void>(); + pick = vi.fn<(x: number, y: number, includeRegions: boolean) => number>(() => this.pickId); + dispose = vi.fn(); + constructor(canvas: HTMLCanvasElement) { + this.canvas = canvas; + FakeRenderer.instances.push(this); + } + } + return { FakeRenderer }; +}); + +vi.mock('./GlobeRenderer', () => ({ GlobeRenderer: fakes.FakeRenderer, MAX_FEATURES: 256 * 64 })); + +type FakeRenderer = InstanceType; + +class FakeWorker { + static instances: FakeWorker[] = []; + onmessage: ((e: MessageEvent) => void) | null = null; + posted: MeshRequest[] = []; + open: MeshRequest[] = []; + terminate = vi.fn(); + constructor() { + FakeWorker.instances.push(this); + } + postMessage(m: MeshRequest): void { + this.posted.push(m); + this.open.push(m); + } + reply(data: MeshResponse): void { + this.onmessage?.({ data } as MessageEvent); + } + /** Answers the open jobs that match, each with a layer tagged by what it built. */ + answer(match: (m: MeshRequest) => boolean = () => true): void { + const now = this.open.filter(match); + this.open = this.open.filter((m) => !match(m)); + for (const m of now) this.reply({ job: m.job, layer: layerOf(m) }); + } +} + +class FakeResizeObserver { + static instances: FakeResizeObserver[] = []; + cb: () => void; + observe = vi.fn(); + disconnect = vi.fn(); + constructor(cb: () => void) { + this.cb = cb; + FakeResizeObserver.instances.push(this); + } +} + +const layerOf = (m: MeshRequest): BuiltLayer => + ({ tag: `${m.object}:${m.idBase}:${m.maxEdge}` }) as unknown as BuiltLayer; +const tagOf = (l: BuiltLayer | undefined): string => (l as unknown as { tag: string } | undefined)?.tag ?? ''; + +const LIGHT: GlobeTheme = { + land: [1, 1, 1], + ocean: [0, 0, 1], + oceanDeep: [0, 0, 0.5], + space0: [0, 0, 0], + space1: [0, 0, 0.1], + glow: [1, 1, 1], + border: [0, 0, 0, 1], + coast: [0, 0, 0, 1], + regionBorder: [0, 0, 0, 0.5], + selection: [1, 0, 0, 1], + arc: [1, 1, 0, 1], + dark: false, +}; +const DARK: GlobeTheme = { ...LIGHT, dark: true }; + +const TOPO = { type: 'Topology', objects: {}, arcs: [] }; + +function manifest(): AtlasMeshManifest { + return { + version: 1, + lods: ['l0', 'l1', 'l2'], + regionLods: ['r0', 'r1'], + world: { l0: 'w0.json', l1: 'w1.json', l2: 'w2.json' }, + countries: [ + { a2: 'FR', a3: 'FRA', name: 'France', anchor: [2, 46], bbox: [-5, 42, 8, 51], area: 1 }, + { a2: null, a3: 'XKX', name: 'Nowhere', anchor: null, bbox: [0, 0, 1, 1], area: 1 }, + { a2: 'DE', a3: 'DEU', name: 'Germany', anchor: null, bbox: [6, 47, 15, 55], area: 1 }, + { a2: 'AU', a3: 'AUS', name: 'Australia', anchor: [134, -25], bbox: [113, -44, 154, -10], area: 1 }, + { a2: 'IT', a3: 'ITA', name: 'Italy', anchor: [12, 43], bbox: [7, 37, 18, 47], area: 1 }, + ], + regions: { + FR: { bbox: [-5, 42, 8, 51], counted: 2, total: 2, index: 'regions/FR.json' }, + DE: { bbox: [6, 47, 15, 55], counted: 1, total: 1, index: 'regions/DE.json' }, + AU: { bbox: [113, -44, 154, -10], counted: 1, total: 1, index: 'regions/AU.json' }, + }, + attribution: [], + }; +} + +function regionIndex(a2: string, codes: Array<[string, string | null, string | null]>): RegionIndex { + return { + bbox: [0, 0, 1, 1], + counted: codes.length, + features: codes.map(([code, name, nameEn]) => ({ code, name, nameEn, anchor: null, counted: true })), + files: { r0: `regions/${a2}.r0.json`, r1: `regions/${a2}.r1.json` }, + }; +} + +function defaultFiles(): Record { + return { + manifest: manifest(), + 'world/w0.json': TOPO, + 'world/w1.json': TOPO, + 'world/w2.json': TOPO, + 'regions/FR.json': regionIndex('FR', [ + ['FR-IDF', 'Île-de-France', 'Paris Region'], + ['FR-ARA', 'Auvergne', null], + ]), + 'regions/DE.json': regionIndex('DE', [['DE-BY', 'Bayern', 'Bavaria']]), + 'regions/AU.json': regionIndex('AU', [['AU-NSW', 'NSW', null]]), + 'regions/FR.r0.json': TOPO, + 'regions/FR.r1.json': TOPO, + 'regions/DE.r0.json': TOPO, + 'regions/DE.r1.json': TOPO, + }; +} + +let clock = 1000; +let rafQueue: FrameRequestCallback[] = []; +const engines: GlobeEngine[] = []; + +function last(list: T[]): T { + const v = list[list.length - 1]; + if (v === undefined) throw new Error('empty list'); + return v; +} + +async function flush(): Promise { + for (let i = 0; i < 60; i++) await Promise.resolve(); +} + +/** Runs up to n queued animation frames, each dt ms after the last; returns how many ran. */ +function frames(n: number, dt = 16): number { + for (let i = 0; i < n; i++) { + const cb = rafQueue.shift(); + if (!cb) return i; + clock += dt; + cb(clock); + } + return n; +} + +function lastDraw(r: FakeRenderer): DrawState { + return last(r.draw.mock.calls)[0]; +} + +interface StartOptions { + initial?: GlobeEngineOptions['initial']; + theme?: GlobeTheme; + width?: number; + height?: number; + /** Changes the served files before the engine starts reading them. */ + prepare?: (files: Record) => void; +} + +/** A manifest that never arrives, for what the engine does before it has one. */ +const NEVER = new Promise(() => undefined); + +async function start(o: StartOptions = {}) { + const mod = await import('./GlobeEngine'); + const files = defaultFiles(); + o.prepare?.(files); + const fetchJson = vi.fn(async (path: string): Promise => { + const v = files[path]; + if (v === undefined) throw new Error(`404 ${path}`); + if (v instanceof Error) throw v; + return v; + }); + const rect = { width: o.width ?? 800, height: o.height ?? 600 }; + const canvas = document.createElement('canvas'); + canvas.getBoundingClientRect = () => + ({ x: 0, y: 0, left: 0, top: 0, right: rect.width, bottom: rect.height, ...rect, toJSON: () => rect }) as DOMRect; + canvas.setPointerCapture = vi.fn(); + const cb = { + onReady: vi.fn(), + onError: vi.fn<(err: unknown) => void>(), + onHover: vi.fn(), + onSelect: vi.fn(), + onFrame: vi.fn(), + }; + const engine = new mod.GlobeEngine({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb }); + engines.push(engine); + return { + mod, + engine, + canvas, + rect, + files, + fetchJson, + cb, + renderer: last(fakes.FakeRenderer.instances), + worker: last(FakeWorker.instances), + resizeObs: last(FakeResizeObserver.instances), + }; +} + +type Ctx = Awaited>; + +/** Lets the manifest and the world file arrive and answers the world build. */ +async function boot(ctx: Ctx): Promise { + await flush(); + ctx.worker.answer(); + await flush(); +} + +const fetched = (ctx: Ctx, path: string): number => ctx.fetchJson.mock.calls.filter(([p]) => p === path).length; + +function pointer(canvas: HTMLCanvasElement, type: string, id: number, x: number, y: number): void { + const e = new MouseEvent(type, { clientX: x, clientY: y, bubbles: true }); + Object.defineProperty(e, 'pointerId', { value: id }); + canvas.dispatchEvent(e); +} + +function wheel(canvas: HTMLCanvasElement, deltaY: number, x = 400, y = 300, deltaMode = 0): WheelEvent { + const e = new WheelEvent('wheel', { deltaY, deltaMode, clientX: x, clientY: y, cancelable: true }); + canvas.dispatchEvent(e); + return e; +} + +/** Captures window.setTimeout calls instead of running them. */ +function captureTimeouts(): Array<{ cb: () => void; ms: number }> { + const pending: Array<{ cb: () => void; ms: number }> = []; + vi.spyOn(window, 'setTimeout').mockImplementation(((cb: () => void, ms?: number) => { + pending.push({ cb, ms: ms ?? 0 }); + return 100000 + pending.length; + }) as unknown as typeof window.setTimeout); + return pending; +} + +beforeEach(() => { + clock = 1000; + rafQueue = []; + FakeWorker.instances = []; + FakeResizeObserver.instances = []; + fakes.FakeRenderer.instances = []; + vi.spyOn(performance, 'now').mockImplementation(() => clock); + vi.stubGlobal('Worker', FakeWorker); + vi.stubGlobal('ResizeObserver', FakeResizeObserver); + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn((cb: FrameRequestCallback) => { + rafQueue.push(cb); + return rafQueue.length; + }) + ); + vi.stubGlobal('cancelAnimationFrame', vi.fn()); + vi.stubGlobal('devicePixelRatio', 1); + vi.resetModules(); +}); + +afterEach(() => { + for (const e of engines.splice(0)) e.dispose(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('GlobeEngine boot', () => { + it('FE-ATLAS2-ENGINE-001: reads the manifest, builds the coarse world in the worker and reports ready', async () => { + const ctx = await start(); + expect(ctx.renderer.setOcean).toHaveBeenCalledTimes(1); + expect(ctx.resizeObs.observe).toHaveBeenCalledWith(ctx.canvas); + await flush(); + expect(ctx.fetchJson.mock.calls.map(([p]) => p)).toEqual(['manifest', 'world/w0.json']); + expect(ctx.worker.posted).toEqual([{ job: 1, topo: TOPO, object: 'countries', maxEdge: 8, idBase: 0 }]); + expect(ctx.cb.onReady).not.toHaveBeenCalled(); + ctx.worker.answer(); + await flush(); + expect(ctx.engine.manifest?.countries).toHaveLength(5); + expect(tagOf(ctx.renderer.worlds.get('l0'))).toBe('countries:0:8'); + expect(ctx.cb.onReady).toHaveBeenCalledTimes(1); + expect(ctx.cb.onError).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-002: a second visit in the same tab reuses the kept manifest and world without fetching', async () => { + const first = await start(); + await boot(first); + const firstLayer = first.renderer.worlds.get('l0'); + const otherFetch = vi.fn(async (): Promise => null); + const canvas = document.createElement('canvas'); + const onReady = vi.fn(); + const second = new first.mod.GlobeEngine({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady }); + engines.push(second); + await flush(); + expect(otherFetch).not.toHaveBeenCalled(); + expect(last(FakeWorker.instances).posted).toEqual([]); + expect(last(fakes.FakeRenderer.instances).worlds.get('l0')).toBe(firstLayer); + expect(onReady).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-ENGINE-003: a world file that keeps failing is retried four times, then reported', async () => { + const pending = captureTimeouts(); + const ctx = await start({ prepare: (f) => (f['world/w0.json'] = new Error('offline')) }); + for (let i = 0; i < 4; i++) { + await flush(); + const t = pending.shift(); + if (!t) throw new Error('no retry scheduled'); + t.cb(); + } + await flush(); + expect(fetched(ctx, 'world/w0.json')).toBe(5); + expect(ctx.cb.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'offline' })); + expect(ctx.cb.onReady).not.toHaveBeenCalled(); + expect(pending).toEqual([]); + }); +}); + +describe('GlobeEngine boot retries', () => { + it('FE-ATLAS2-ENGINE-004: the retry pauses double, and a manifest that failed is asked for again next visit', async () => { + const pending = captureTimeouts(); + const mod = await import('./GlobeEngine'); + const fail = vi.fn(async (): Promise => { + throw new Error('down'); + }); + const onError = vi.fn(); + engines.push( + new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError }) + ); + const delays: number[] = []; + for (let i = 0; i < 4; i++) { + await flush(); + const t = pending.shift(); + if (!t) throw new Error('no retry scheduled'); + delays.push(t.ms); + t.cb(); + } + await flush(); + expect(delays).toEqual([1000, 2000, 4000, 8000]); + expect(fail).toHaveBeenCalledTimes(5); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'down' })); + + const files = defaultFiles(); + const ok = vi.fn(async (p: string): Promise => files[p]); + const onReady = vi.fn(); + engines.push( + new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady }) + ); + await flush(); + expect(ok).toHaveBeenCalledWith('manifest'); + }); + + it('FE-ATLAS2-ENGINE-005: one failed read followed by a good one still brings the globe up', async () => { + const pending = captureTimeouts(); + const mod = await import('./GlobeEngine'); + const files = defaultFiles(); + let calls = 0; + const fetchJson = vi.fn(async (p: string): Promise => { + calls++; + if (calls === 1) throw new Error('blip'); + return files[p]; + }); + const onReady = vi.fn(); + engines.push(new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })); + await flush(); + expect(pending.map((t) => t.ms)).toEqual([1000]); + pending[0].cb(); + await flush(); + last(FakeWorker.instances).answer(); + await flush(); + expect(onReady).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-ENGINE-006: a dispose while waiting to retry stops the retries', async () => { + const pending = captureTimeouts(); + const ctx = await start({ prepare: (f) => (f.manifest = new Error('gone')) }); + await flush(); + ctx.engine.dispose(); + const t = pending.shift(); + if (!t) throw new Error('no retry scheduled'); + t.cb(); + await flush(); + expect(fetched(ctx, 'manifest')).toBe(2); + expect(ctx.cb.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'gone' })); + expect(pending).toEqual([]); + }); +}); + +describe('GlobeEngine worker builds', () => { + it('FE-ATLAS2-ENGINE-010: a build the worker refuses reports its error through onError', async () => { + const ctx = await start(); + await flush(); + ctx.worker.reply({ job: 1, error: 'bad topology' }); + await flush(); + expect(ctx.cb.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'bad topology' })); + expect(ctx.cb.onReady).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-011: a refusal without a message falls back to a generic one', async () => { + const ctx = await start(); + await flush(); + ctx.worker.reply({ job: 1 }); + await flush(); + expect(ctx.cb.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'Atlas mesh build failed' })); + }); + + it('FE-ATLAS2-ENGINE-012: an answer for an unknown job is ignored', async () => { + const ctx = await start(); + await flush(); + ctx.worker.reply({ job: 99, layer: layerOf(ctx.worker.posted[0]) }); + await flush(); + expect(ctx.renderer.setWorld).not.toHaveBeenCalled(); + ctx.worker.answer(); + await flush(); + expect(ctx.cb.onReady).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-ENGINE-013: a world that arrives after dispose is not handed to the renderer', async () => { + const ctx = await start(); + await flush(); + ctx.engine.dispose(); + ctx.worker.answer(); + await flush(); + expect(ctx.renderer.setWorld).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-014: zooming past 2 and 4.2 loads the finer world levels and draws them', async () => { + const ctx = await start({ initial: { zoom: 2.5 } }); + await boot(ctx); + frames(1); + await flush(); + expect(fetched(ctx, 'world/w1.json')).toBe(1); + expect(last(ctx.worker.posted)).toMatchObject({ object: 'countries', maxEdge: 4 }); + // Until it arrives the coarse level stays on screen. + expect(lastDraw(ctx.renderer).worldKey).toBe('l0'); + ctx.worker.answer(); + await flush(); + frames(1); + expect(lastDraw(ctx.renderer).worldKey).toBe('l1'); + }); + + it('FE-ATLAS2-ENGINE-015: a finer world that fails keeps the coarser one and raises no error', async () => { + const ctx = await start({ initial: { zoom: 2.5 } }); + await boot(ctx); + frames(1); + await flush(); + ctx.worker.reply({ job: last(ctx.worker.posted).job, error: 'nope' }); + ctx.worker.open = []; + await flush(); + frames(1); + expect(lastDraw(ctx.renderer).worldKey).toBe('l0'); + expect(ctx.cb.onError).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-016: with only a finer level loaded, a low zoom still draws that level', async () => { + const ctx = await start(); + ctx.renderer.worlds.set('l1', { tag: 'l1' } as unknown as BuiltLayer); + frames(1); + expect(lastDraw(ctx.renderer).worldKey).toBe('l1'); + }); + + it('FE-ATLAS2-ENGINE-017: before any world is loaded the draw asks for the coarse level', async () => { + const ctx = await start(); + frames(1); + expect(lastDraw(ctx.renderer).worldKey).toBe('l0'); + expect(ctx.cb.onFrame).toHaveBeenCalledWith(ctx.engine); + }); +}); + +describe('GlobeEngine regions in view', () => { + it('FE-ATLAS2-ENGINE-020: zoomed in on France, the coarse regions of the countries in view load and draw', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 6 } }); + const loaded = vi.fn(); + ctx.engine.onRegionLoaded = loaded; + await boot(ctx); + frames(1); + expect(ctx.renderer.touchRegion.mock.calls.map(([k]) => k)).toEqual(['FR:r0', 'FR:r1', 'DE:r0', 'DE:r1']); + await flush(); + expect(ctx.engine.regionBase.get('FR')).toBe(512); + expect(ctx.engine.regionBase.get('DE')).toBe(514); + expect(fetched(ctx, 'regions/AU.json')).toBe(0); + expect(fetched(ctx, 'regions/FR.r1.json')).toBe(0); + const regionJobs = ctx.worker.posted.filter((m) => m.object === 'regions'); + expect(regionJobs.map((m) => [m.idBase, m.maxEdge])).toEqual([ + [512, 3], + [514, 3], + ]); + ctx.worker.answer(); + await flush(); + const inUse = ctx.renderer.setRegion.mock.calls[0][2]; + expect(inUse?.has('FR:r0')).toBe(true); + expect(inUse?.has('AU:r0')).toBe(false); + expect(loaded.mock.calls.map(([a2]) => a2)).toEqual(['FR', 'DE']); + frames(1); + const s = lastDraw(ctx.renderer); + expect(s.regionKeys).toEqual(['FR:r0', 'DE:r0']); + expect(s.regionAlpha).toBe(1); + expect(s.worldKey).toBe('l2'); + }); + + it('FE-ATLAS2-ENGINE-021: the view is scanned at most every 0.2 s and a loaded region is not fetched twice', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 6 } }); + await boot(ctx); + frames(1); + await flush(); + ctx.worker.answer(); + await flush(); + const touches = ctx.renderer.touchRegion.mock.calls.length; + frames(1, 16); + expect(ctx.renderer.touchRegion.mock.calls.length).toBe(touches); + frames(1, 250); + await flush(); + expect(ctx.renderer.touchRegion.mock.calls.length).toBe(touches + 4); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(1); + expect(fetched(ctx, 'regions/FR.json')).toBe(1); + }); + + it('FE-ATLAS2-ENGINE-022: from zoom 7 the fine regions load too and win once the zoom passes 8', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 9 } }); + await boot(ctx); + frames(1); + await flush(); + expect(fetched(ctx, 'regions/FR.r1.json')).toBe(1); + ctx.worker.answer((m) => m.object === 'regions' && m.maxEdge === 3); + await flush(); + frames(1); + expect(lastDraw(ctx.renderer).regionKeys).toEqual(['FR:r0', 'DE:r0']); + ctx.worker.answer(); + await flush(); + frames(1); + expect(lastDraw(ctx.renderer).regionKeys).toEqual(['FR:r1', 'DE:r1']); + }); + + it('FE-ATLAS2-ENGINE-023: below zoom 8 a country with only its fine regions still draws those', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 7.5 } }); + await boot(ctx); + frames(1); + await flush(); + ctx.worker.answer((m) => m.object === 'regions' && m.maxEdge === 1.5); + await flush(); + frames(1); + expect(lastDraw(ctx.renderer).regionKeys).toEqual(['FR:r1', 'DE:r1']); + }); +}); + +describe('GlobeEngine region prefetch and failures', () => { + it('FE-ATLAS2-ENGINE-024: regions are fetched ahead from zoom 3 but stay undrawn until they fade in', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 4 } }); + await boot(ctx); + frames(1); + await flush(); + ctx.worker.answer(); + await flush(); + frames(1); + expect(ctx.renderer.hasRegion('FR:r0')).toBe(true); + expect(lastDraw(ctx.renderer).regionKeys).toEqual([]); + expect(lastDraw(ctx.renderer).regionAlpha).toBe(0); + }); + + it('FE-ATLAS2-ENGINE-025: a zoom heading past 3 already fetches while the camera is still lower', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 2 } }); + await boot(ctx); + ctx.engine.zoomBy(2); + frames(1); + expect(ctx.engine.zoom).toBeLessThan(3); + await flush(); + expect(fetched(ctx, 'regions/FR.json')).toBe(1); + }); + + it('FE-ATLAS2-ENGINE-026: a region file that fails is asked for again only after 20 s', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 6 } }); + ctx.files['regions/FR.r0.json'] = new Error('500'); + await boot(ctx); + frames(1); + await flush(); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(1); + expect(ctx.cb.onError).not.toHaveBeenCalled(); + frames(1, 1000); + await flush(); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(1); + frames(1, 21000); + await flush(); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(2); + }); + + it('FE-ATLAS2-ENGINE-027: a region built after dispose is dropped', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 6 } }); + await boot(ctx); + frames(1); + await flush(); + ctx.engine.dispose(); + ctx.worker.answer(); + await flush(); + expect(ctx.renderer.setRegion).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-028: a country whose regions would overflow the status texture gets no ids and no file', async () => { + const ctx = await start({ initial: { lon: 2, lat: 46, zoom: 6 } }); + const huge = regionIndex('FR', []); + huge.features = Array.from({ length: 20000 }, (_, i) => ({ + code: `X${i}`, + name: null, + nameEn: null, + anchor: null, + counted: false, + })); + ctx.files['regions/FR.json'] = huge; + await boot(ctx); + frames(1); + await flush(); + expect(ctx.engine.regionIndex.get('FR')).toBe(huge); + expect(ctx.engine.regionBase.has('FR')).toBe(false); + expect(ctx.engine.regionBase.get('DE')).toBe(512); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(0); + }); +}); + +describe('GlobeEngine region index', () => { + it('FE-ATLAS2-ENGINE-030: before the manifest and for a country without regions there is no index', async () => { + const waiting = await start({ prepare: (f) => (f.manifest = NEVER) }); + await flush(); + expect(await waiting.engine.loadRegionIndex('FR')).toBeNull(); + vi.resetModules(); + const ctx = await start(); + await boot(ctx); + expect(await ctx.engine.loadRegionIndex('IT')).toBeNull(); + expect(fetched(ctx, 'regions/FR.json')).toBe(0); + }); + + it('FE-ATLAS2-ENGINE-031: an index is fetched once, kept, and two racing reads keep the first', async () => { + const ctx = await start(); + await boot(ctx); + const [a, b] = await Promise.all([ctx.engine.loadRegionIndex('FR'), ctx.engine.loadRegionIndex('FR')]); + expect(a).toBe(b); + expect(ctx.engine.regionBase.get('FR')).toBe(512); + expect(await ctx.engine.loadRegionIndex('DE')).not.toBeNull(); + // The race did not hand out FR's ids twice. + expect(ctx.engine.regionBase.get('DE')).toBe(514); + const before = fetched(ctx, 'regions/FR.json'); + expect(await ctx.engine.loadRegionIndex('FR')).toBe(a); + expect(fetched(ctx, 'regions/FR.json')).toBe(before); + }); +}); + +describe('GlobeEngine picking', () => { + it('FE-ATLAS2-ENGINE-040: hitAt maps pick ids to countries and regions', async () => { + const ctx = await start(); + await boot(ctx); + await ctx.engine.loadRegionIndex('FR'); + const r = ctx.renderer; + r.pickId = -1; + expect(ctx.engine.hitAt(10, 10)).toBeNull(); + r.pickId = 2; + expect(ctx.engine.hitAt(10, 10)).toEqual({ kind: 'country', index: 2, a2: 'DE' }); + r.pickId = 300; + expect(ctx.engine.hitAt(10, 10)).toBeNull(); + r.pickId = 512; + expect(ctx.engine.hitAt(10, 10)).toEqual({ kind: 'region', a2: 'FR', code: 'FR-IDF', name: 'Paris Region' }); + r.pickId = 513; + expect(ctx.engine.hitAt(10, 10)).toEqual({ kind: 'region', a2: 'FR', code: 'FR-ARA', name: 'Auvergne' }); + r.pickId = 600; + expect(ctx.engine.hitAt(10, 10)).toBeNull(); + expect(last(r.pick.mock.calls)).toEqual([10, 10, false]); + }); + + it('FE-ATLAS2-ENGINE-041: hitAt asks for regions once they are more than half faded in', async () => { + const ctx = await start({ initial: { zoom: 5.6 } }); + ctx.engine.hitAt(1, 2); + expect(last(ctx.renderer.pick.mock.calls)).toEqual([1, 2, true]); + }); + + it('FE-ATLAS2-ENGINE-042: idOf gives the status id of a country or a region, -1 when unknown', async () => { + const ctx = await start(); + await boot(ctx); + await ctx.engine.loadRegionIndex('FR'); + expect(ctx.engine.idOf({ kind: 'country', index: 4, a2: 'IT' })).toBe(4); + expect(ctx.engine.idOf({ kind: 'region', a2: 'FR', code: 'FR-ARA', name: null })).toBe(513); + expect(ctx.engine.idOf({ kind: 'region', a2: 'FR', code: 'FR-XX', name: null })).toBe(-1); + expect(ctx.engine.idOf({ kind: 'region', a2: 'IT', code: 'IT-1', name: null })).toBe(-1); + }); + + it('FE-ATLAS2-ENGINE-043: focusCountry reads the middle of the view and only re-reads after the camera moved', async () => { + const ctx = await start(); + await boot(ctx); + ctx.renderer.pickId = 0; + expect(ctx.engine.focusCountry()).toBe('FR'); + expect(last(ctx.renderer.pick.mock.calls).slice(0, 2)).toEqual([400, 300]); + const picks = ctx.renderer.pick.mock.calls.length; + ctx.renderer.pickId = 2; + ctx.engine.cam.lon = 40; + clock += 50; + expect(ctx.engine.focusCountry()).toBe('FR'); + expect(ctx.renderer.pick.mock.calls.length).toBe(picks); + clock += 200; + expect(ctx.engine.focusCountry()).toBe('DE'); + ctx.renderer.pickId = -1; + clock += 1000; + // Same camera: the last answer stands, however long ago it was read. + expect(ctx.engine.focusCountry()).toBe('DE'); + ctx.engine.cam.lon = 50; + expect(ctx.engine.focusCountry()).toBeNull(); + }); +}); + +describe('GlobeEngine layout', () => { + it('FE-ATLAS2-ENGINE-050: a wide canvas centres a globe 0.31 of the shorter side, backed at the device ratio', async () => { + vi.stubGlobal('devicePixelRatio', 1.5); + const ctx = await start(); + expect(ctx.engine.vp).toEqual({ width: 800, height: 600, baseRadius: 186, globeY: 300, flatY: 300 }); + expect(ctx.canvas.width).toBe(1200); + expect(ctx.canvas.height).toBe(900); + }); + + it('FE-ATLAS2-ENGINE-051: a phone canvas uses a larger globe set lower, and the backing ratio caps at 2', async () => { + vi.stubGlobal('devicePixelRatio', 3); + const ctx = await start({ width: 400, height: 800 }); + expect(ctx.engine.vp.baseRadius).toBeCloseTo(168); + expect(ctx.engine.vp.globeY).toBeCloseTo(432); + expect(ctx.engine.vp.flatY).toBe(400); + expect(ctx.canvas.width).toBe(800); + }); + + it('FE-ATLAS2-ENGINE-052: an empty canvas keeps a 1 px backing store', async () => { + const ctx = await start({ width: 0, height: 0 }); + expect(ctx.canvas.width).toBe(1); + expect(ctx.canvas.height).toBe(1); + }); + + it('FE-ATLAS2-ENGINE-053: the resize observer re-lays the view out', async () => { + const ctx = await start(); + ctx.rect.width = 1000; + ctx.resizeObs.cb(); + expect(ctx.engine.vp.width).toBe(1000); + expect(ctx.canvas.width).toBe(1000); + }); + + it('FE-ATLAS2-ENGINE-054: a bottom inset lifts the view, a sub-pixel change is ignored', async () => { + const ctx = await start(); + ctx.engine.setInsetBottom(100); + expect(ctx.engine.vp.flatY).toBe(250); + expect(ctx.engine.vp.baseRadius).toBeCloseTo(155); + const vp = ctx.engine.vp; + ctx.engine.setInsetBottom(100.5); + expect(ctx.engine.vp).toBe(vp); + }); + + it('FE-ATLAS2-ENGINE-055: morph, regionAlpha and isMorphing follow the zoom', async () => { + const ctx = await start({ initial: { zoom: 2 } }); + expect(ctx.engine.isMorphing()).toBe(true); + frames(1); + expect(ctx.engine.morph).toBeGreaterThan(0); + expect(ctx.engine.morph).toBeLessThan(1); + expect(ctx.engine.regionAlpha).toBe(0); + ctx.engine.cam.zoom = 5.5; + expect(ctx.engine.regionAlpha).toBeCloseTo(0.5); + expect(ctx.engine.isMorphing()).toBe(false); + ctx.engine.cam.zoom = 1; + expect(ctx.engine.isMorphing()).toBe(false); + expect(ctx.engine.zoom).toBe(1); + }); + + it('FE-ATLAS2-ENGINE-056: project places the view centre at the middle of the canvas', async () => { + const ctx = await start({ initial: { lon: 20, lat: 10, zoom: 1 } }); + frames(1); + const p = ctx.engine.project(20, 10); + expect(p.x).toBeCloseTo(400); + expect(p.y).toBeCloseTo(300); + expect(p.visible).toBeGreaterThan(0); + }); + + it('FE-ATLAS2-ENGINE-057: a lost WebGL context is reported as an error', async () => { + const ctx = await start(); + const e = new Event('webglcontextlost', { cancelable: true }); + ctx.canvas.dispatchEvent(e); + expect(e.defaultPrevented).toBe(true); + expect(ctx.cb.onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'WebGL context lost' })); + }); +}); + +describe('GlobeEngine drag and click', () => { + it('FE-ATLAS2-ENGINE-060: dragging turns the globe by the drag over the radius, and lets it coast', async () => { + const ctx = await start(); + await boot(ctx); + frames(1); + const k = 1 / (186 * RAD); + pointer(ctx.canvas, 'pointerdown', 1, 400, 300); + expect(ctx.canvas.setPointerCapture).toHaveBeenCalledWith(1); + pointer(ctx.canvas, 'pointermove', 1, 410, 300); + expect(ctx.engine.cam.lon).toBeCloseTo(10 - 10 * k); + pointer(ctx.canvas, 'pointermove', 1, 420, 300); + const released = ctx.engine.cam.lon; + clock += 50; + pointer(ctx.canvas, 'pointerup', 1, 420, 300); + expect(ctx.cb.onSelect).not.toHaveBeenCalled(); + frames(5); + expect(ctx.engine.cam.lon).toBeLessThan(released); + frames(400); + const rested = ctx.engine.cam.lon; + frames(3); + expect(ctx.engine.cam.lon).toBe(rested); + }); + + it('FE-ATLAS2-ENGINE-061: dragging far down holds the latitude at the globe limit of 80', async () => { + const ctx = await start(); + await boot(ctx); + frames(1); + pointer(ctx.canvas, 'pointerdown', 1, 400, 100); + pointer(ctx.canvas, 'pointermove', 1, 400, 590); + expect(ctx.engine.cam.lat).toBe(80); + }); + + it('FE-ATLAS2-ENGINE-062: a short tap selects what is under it', async () => { + const ctx = await start(); + await boot(ctx); + ctx.renderer.pickId = 0; + pointer(ctx.canvas, 'pointerdown', 1, 400, 300); + clock += 100; + pointer(ctx.canvas, 'pointerup', 1, 402, 301); + expect(ctx.cb.onSelect).toHaveBeenCalledWith({ kind: 'country', index: 0, a2: 'FR' }, 402, 301); + }); + + it('FE-ATLAS2-ENGINE-063: a press held past 400 ms or an unknown pointer selects nothing', async () => { + const ctx = await start(); + await boot(ctx); + pointer(ctx.canvas, 'pointerup', 7, 400, 300); + pointer(ctx.canvas, 'pointerdown', 1, 400, 300); + clock += 500; + pointer(ctx.canvas, 'pointercancel', 1, 400, 300); + expect(ctx.cb.onSelect).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-ENGINE-064: hovering reports the hit, throttled to one pick per 45 ms', async () => { + const ctx = await start(); + await boot(ctx); + ctx.renderer.pickId = 2; + pointer(ctx.canvas, 'pointermove', 1, 100, 120); + expect(ctx.engine.hover).toBe(2); + expect(ctx.cb.onHover).toHaveBeenLastCalledWith({ kind: 'country', index: 2, a2: 'DE' }, 100, 120); + pointer(ctx.canvas, 'pointermove', 1, 101, 120); + expect(ctx.cb.onHover).toHaveBeenCalledTimes(1); + clock += 50; + pointer(ctx.canvas, 'pointermove', 1, 102, 120); + expect(ctx.cb.onHover).toHaveBeenCalledTimes(2); + ctx.renderer.pickId = -1; + clock += 50; + pointer(ctx.canvas, 'pointermove', 1, 300, 120); + expect(ctx.engine.hover).toBe(-1); + expect(ctx.cb.onHover).toHaveBeenLastCalledWith(null, 300, 120); + }); + + it('FE-ATLAS2-ENGINE-065: pressing drops the hover, leaving clears it but not while dragging', async () => { + const ctx = await start(); + await boot(ctx); + ctx.renderer.pickId = 0; + pointer(ctx.canvas, 'pointermove', 1, 100, 100); + expect(ctx.engine.hover).toBe(0); + pointer(ctx.canvas, 'pointerdown', 1, 100, 100); + expect(ctx.engine.hover).toBe(-1); + expect(ctx.cb.onHover).toHaveBeenLastCalledWith(null, 0, 0); + const calls = ctx.cb.onHover.mock.calls.length; + ctx.canvas.dispatchEvent(new MouseEvent('pointerleave')); + expect(ctx.cb.onHover).toHaveBeenCalledTimes(calls); + clock += 1000; + pointer(ctx.canvas, 'pointerup', 1, 300, 300); + ctx.canvas.dispatchEvent(new MouseEvent('pointerleave')); + expect(ctx.cb.onHover).toHaveBeenCalledTimes(calls + 1); + expect(ctx.cb.onHover).toHaveBeenLastCalledWith(null, 0, 0); + }); + + it('FE-ATLAS2-ENGINE-066: a double click on open water zooms in by 1.8, one on a country does not', async () => { + const ctx = await start(); + await boot(ctx); + ctx.renderer.pickId = 0; + ctx.canvas.dispatchEvent(new MouseEvent('dblclick', { clientX: 400, clientY: 300 })); + frames(100); + expect(ctx.engine.zoom).toBeCloseTo(1, 3); + ctx.renderer.pickId = -1; + ctx.canvas.dispatchEvent(new MouseEvent('dblclick', { clientX: 400, clientY: 300 })); + frames(100); + expect(ctx.engine.zoom).toBeCloseTo(1.8, 2); + }); +}); + +describe('GlobeEngine pinch and wheel', () => { + it('FE-ATLAS2-ENGINE-070: two fingers zoom by the change in their distance, capped, and spring back after', async () => { + const ctx = await start(); + await boot(ctx); + frames(1); + pointer(ctx.canvas, 'pointerdown', 1, 300, 300); + pointer(ctx.canvas, 'pointerdown', 2, 400, 300); + pointer(ctx.canvas, 'pointermove', 2, 500, 300); + expect(ctx.engine.zoom).toBeCloseTo(2); + pointer(ctx.canvas, 'pointerdown', 3, 10, 10); + pointer(ctx.canvas, 'pointermove', 3, 20, 20); + expect(ctx.engine.zoom).toBeCloseTo(2); + pointer(ctx.canvas, 'pointerup', 3, 20, 20); + pointer(ctx.canvas, 'pointermove', 2, 5000, 300); + expect(ctx.engine.zoom).toBeCloseTo(MAX_ZOOM * 1.1); + frames(1); + expect(ctx.engine.zoom).toBeCloseTo(MAX_ZOOM * 1.1); + pointer(ctx.canvas, 'pointerup', 1, 300, 300); + pointer(ctx.canvas, 'pointerup', 2, 5000, 300); + expect(ctx.cb.onSelect).not.toHaveBeenCalled(); + frames(200); + expect(ctx.engine.zoom).toBeCloseTo(MAX_ZOOM, 1); + }); + + it('FE-ATLAS2-ENGINE-071: the wheel zooms smoothly and its default scroll is prevented', async () => { + const ctx = await start(); + await boot(ctx); + frames(1); + const e = wheel(ctx.canvas, -100); + expect(e.defaultPrevented).toBe(true); + frames(1); + expect(ctx.engine.zoom).toBeGreaterThan(1); + frames(100); + expect(ctx.engine.zoom).toBeCloseTo(Math.exp(0.16), 2); + }); + + it('FE-ATLAS2-ENGINE-072: zooming out in line mode overshoots below the minimum and springs back', async () => { + const ctx = await start(); + await boot(ctx); + wheel(ctx.canvas, 10, 400, 300, 1); + frames(200); + expect(ctx.engine.zoom).toBeCloseTo(MIN_ZOOM, 2); + }); + + it('FE-ATLAS2-ENGINE-073: on the flat map the place under the cursor stays under it while zooming', async () => { + const ctx = await start({ initial: { lon: 0, lat: 0, zoom: 4 } }); + await boot(ctx); + frames(1); + const f = ctx.engine.frame; + const k = 1 / (f.scale * RAD); + const lon = ctx.engine.cam.lon + ((600 - f.originX) * k) / xSqueeze(f); + const lat = ctx.engine.cam.lat - (300 - f.originY) * k; + wheel(ctx.canvas, -100, 600, 300); + frames(100); + expect(ctx.engine.zoom).toBeCloseTo(4 * Math.exp(0.16), 2); + expect(ctx.engine.cam.lon).toBeGreaterThan(1); + const p = ctx.engine.project(lon, lat); + expect(Math.abs(p.x - 600)).toBeLessThan(3); + expect(Math.abs(p.y - 300)).toBeLessThan(3); + }); + + it('FE-ATLAS2-ENGINE-074: at the maximum zoom another wheel step changes nothing', async () => { + const ctx = await start({ initial: { lon: 0, lat: 0, zoom: MAX_ZOOM } }); + await boot(ctx); + frames(1); + const lon = ctx.engine.cam.lon; + wheel(ctx.canvas, -100, 700, 300); + frames(20); + expect(ctx.engine.zoom).toBe(MAX_ZOOM); + expect(ctx.engine.cam.lon).toBe(lon); + }); + + it('FE-ATLAS2-ENGINE-075: zoomBy clamps the target between the minimum and maximum zoom', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.zoomBy(1000); + frames(150); + expect(ctx.engine.zoom).toBeCloseTo(MAX_ZOOM, 1); + ctx.engine.zoomBy(0.0001); + frames(150); + expect(ctx.engine.zoom).toBeCloseTo(MIN_ZOOM, 2); + }); +}); + +describe('GlobeEngine flights', () => { + it('FE-ATLAS2-ENGINE-080: flyTo takes the short way round and holds the target latitude within 70', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.flyTo(350, 85); + frames(12, 100); + expect(ctx.engine.cam.lon).toBeCloseTo(-10); + expect(ctx.engine.cam.lat).toBeCloseTo(70); + expect(ctx.engine.zoom).toBeCloseTo(1); + }); + + it('FE-ATLAS2-ENGINE-081: a long hop pulls the zoom back mid-flight and lands on the target zoom', async () => { + const ctx = await start({ initial: { lon: 0, lat: 0, zoom: 3 } }); + await boot(ctx); + ctx.engine.flyTo(150, 0, 3, 1000); + frames(1, 500); + expect(ctx.engine.zoom).toBeCloseTo(3 - 0.35 * 3, 1); + frames(1, 600); + expect(ctx.engine.zoom).toBeCloseTo(3); + expect(ctx.engine.cam.lon).toBeCloseTo(150); + }); + + it('FE-ATLAS2-ENGINE-082: flyToBox frames a country box, small boxes capped at the max zoom', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.flyToBox([-5, 42, 8, 51]); + frames(12, 100); + expect(ctx.engine.zoom).toBeCloseTo((110 / 14.4) ** 0.85, 3); + expect(ctx.engine.cam.lon).toBeCloseTo(1.5); + expect(ctx.engine.cam.lat).toBeCloseTo(46.5); + ctx.engine.flyToBox([7.4, 43.7, 7.5, 43.8], 1, 7); + frames(12, 100); + expect(ctx.engine.zoom).toBeCloseTo(7); + }); + + it('FE-ATLAS2-ENGINE-083: grabbing the globe stops a flight where it is', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.flyTo(100, 0); + frames(1, 300); + pointer(ctx.canvas, 'pointerdown', 1, 400, 300); + const lon = ctx.engine.cam.lon; + frames(10, 100); + expect(ctx.engine.cam.lon).toBeCloseTo(lon); + expect(lon).toBeLessThan(100); + }); + + it('FE-ATLAS2-ENGINE-084: the frame wraps longitude and clamps latitude to what the flat map allows', async () => { + const ctx = await start({ initial: { lon: 190, lat: 85, zoom: 6 } }); + frames(1); + expect(ctx.engine.cam.lon).toBeCloseTo(-170); + expect(ctx.engine.cam.lat).toBeCloseTo(latLimits(6, ctx.engine.vp)[1]); + expect(ctx.engine.cam.lat).toBeLessThan(80); + }); +}); + +describe('GlobeEngine draw state', () => { + it('FE-ATLAS2-ENGINE-090: ink spreads from its point for 0.75 s and then ends', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.startInk(5, 2, 46); + frames(1, 100); + const ink = lastDraw(ctx.renderer).ink; + expect(ink).toMatchObject({ id: 5, lon: 2, lat: 46 }); + expect(ink?.radius).toBeGreaterThan(0); + expect(ink?.radius).toBeLessThan(Math.PI); + frames(1, 800); + expect(lastDraw(ctx.renderer).ink?.radius).toBeCloseTo(Math.PI); + frames(1); + expect(lastDraw(ctx.renderer).ink).toBeNull(); + }); + + it('FE-ATLAS2-ENGINE-091: selection, arcs and theme reach the renderer', async () => { + const ctx = await start(); + await boot(ctx); + const outline = { seg: new Float32Array(4), count: 1 } as LineMesh; + const arc = { data: new Float32Array(8), count: 1, width: 2 }; + ctx.engine.setSelected(7, outline); + ctx.engine.setArcs([arc]); + ctx.engine.setTheme(DARK); + frames(1, 160); + const s = lastDraw(ctx.renderer); + expect(s.selected).toBe(7); + expect(s.selectedOutline).toBe(outline); + expect(s.arcs).toEqual([arc]); + expect(s.arcProgress).toBeCloseTo(0.1); + expect(s.theme).toBe(DARK); + expect(s.night).toBe(0.34); + expect(s.width).toBe(800); + expect(s.dpr).toBe(1); + frames(1, 2000); + expect(lastDraw(ctx.renderer).arcProgress).toBe(1.001); + }); + + it('FE-ATLAS2-ENGINE-092: the sun direction is a unit vector, refreshed every 30 s', async () => { + const ctx = await start(); + frames(1); + const sun = lastDraw(ctx.renderer).sun; + expect(Math.hypot(...sun)).toBeCloseTo(1); + frames(1); + expect(lastDraw(ctx.renderer).sun).toBe(sun); + frames(1, 31000); + const next = lastDraw(ctx.renderer).sun; + expect(next).not.toBe(sun); + expect(Math.hypot(...next)).toBeCloseTo(1); + expect(lastDraw(ctx.renderer).night).toBe(0.1); + }); +}); + +describe('GlobeEngine loop', () => { + it('FE-ATLAS2-ENGINE-100: once everything rests the loop sleeps after three idle frames', async () => { + const ctx = await start(); + await boot(ctx); + frames(1, 4000); + expect(frames(10)).toBe(2); + expect(rafQueue).toEqual([]); + const draws = ctx.renderer.draw.mock.calls.length; + ctx.engine.zoomBy(1.2); + expect(rafQueue).toHaveLength(1); + frames(1); + expect(ctx.renderer.draw.mock.calls.length).toBe(draws + 1); + }); + + it('FE-ATLAS2-ENGINE-101: a dark globe keeps its stars twinkling at a low rate while it rests', async () => { + const pending = captureTimeouts(); + const ctx = await start({ theme: DARK }); + await boot(ctx); + frames(1, 4000); + frames(10); + expect(rafQueue).toEqual([]); + const twinkle = pending.find((t) => t.ms === 90); + if (!twinkle) throw new Error('no twinkle timer'); + twinkle.cb(); + expect(rafQueue).toHaveLength(1); + }); + + it('FE-ATLAS2-ENGINE-102: an ambient globe runs every frame unless reduced motion is asked for', async () => { + Object.defineProperty(document, 'hidden', { configurable: true, get: () => false }); + try { + const ctx = await start(); + ctx.engine.ambient = true; + await boot(ctx); + frames(1, 4000); + expect(frames(20)).toBe(20); + expect(rafQueue).toHaveLength(1); + + ctx.engine.dispose(); + rafQueue = []; + vi.mocked(window.matchMedia).mockImplementationOnce( + (query: string) => ({ matches: true, media: query }) as unknown as MediaQueryList + ); + vi.resetModules(); + const calm = await start(); + calm.engine.ambient = true; + frames(1, 4000); + expect(frames(10)).toBe(2); + } finally { + Reflect.deleteProperty(document, 'hidden'); + } + }); + + it('FE-ATLAS2-ENGINE-103: dispose stops the loop, the observers, the worker and the input', async () => { + const ctx = await start(); + await boot(ctx); + ctx.engine.dispose(); + expect(cancelAnimationFrame).toHaveBeenCalled(); + expect(ctx.resizeObs.disconnect).toHaveBeenCalled(); + expect(ctx.worker.terminate).toHaveBeenCalled(); + expect(ctx.renderer.dispose).toHaveBeenCalled(); + const draws = ctx.renderer.draw.mock.calls.length; + frames(1); + expect(ctx.renderer.draw.mock.calls.length).toBe(draws); + ctx.engine.kick(); + expect(rafQueue).toEqual([]); + pointer(ctx.canvas, 'pointerdown', 1, 400, 300); + expect(ctx.canvas.setPointerCapture).not.toHaveBeenCalled(); + ctx.canvas.dispatchEvent(new Event('webglcontextlost', { cancelable: true })); + expect(ctx.cb.onError).not.toHaveBeenCalled(); + }); +}); + +describe('GlobeEngine prefetch', () => { + it('FE-ATLAS2-ENGINE-110: prefetchRegions loads the coarse regions one country at a time', async () => { + vi.stubGlobal('requestIdleCallback', undefined); + const pending = captureTimeouts(); + const ctx = await start(); + await boot(ctx); + ctx.engine.prefetchRegions(['FR', 'DE', 'IT']); + ctx.engine.prefetchRegions(['DE']); + expect(pending.map((t) => t.ms)).toEqual([120]); + const first = pending.shift(); + first?.cb(); + await flush(); + expect(fetched(ctx, 'regions/FR.r0.json')).toBe(1); + expect(fetched(ctx, 'regions/DE.json')).toBe(0); + expect(pending).toEqual([]); + ctx.worker.answer(); + await flush(); + expect(ctx.renderer.hasRegion('FR:r0')).toBe(true); + const second = pending.shift(); + second?.cb(); + await flush(); + ctx.worker.answer(); + await flush(); + expect(ctx.renderer.hasRegion('DE:r0')).toBe(true); + expect(fetched(ctx, 'regions/IT.json')).toBe(0); + expect(pending).toEqual([]); + }); + + it('FE-ATLAS2-ENGINE-111: prefetch waits for an idle moment where the browser offers one', async () => { + const idle = vi.fn<(cb: () => void, o?: { timeout: number }) => number>(() => 3); + vi.stubGlobal('requestIdleCallback', idle); + const ctx = await start(); + await boot(ctx); + ctx.engine.prefetchRegions(['FR']); + expect(idle).toHaveBeenCalledWith(expect.any(Function), { timeout: 1500 }); + }); + + it('FE-ATLAS2-ENGINE-112: nothing is prefetched after dispose, even from a timer already set', async () => { + vi.stubGlobal('requestIdleCallback', undefined); + const pending = captureTimeouts(); + const ctx = await start(); + await boot(ctx); + ctx.engine.prefetchRegions(['FR']); + ctx.engine.dispose(); + pending.shift()?.cb(); + await flush(); + ctx.engine.prefetchRegions(['DE']); + expect(pending).toEqual([]); + expect(fetched(ctx, 'regions/FR.json')).toBe(0); + }); + + it('FE-ATLAS2-ENGINE-113: before the manifest arrives there is nothing to prefetch', async () => { + vi.stubGlobal('requestIdleCallback', undefined); + const pending = captureTimeouts(); + const ctx = await start({ prepare: (f) => (f.manifest = NEVER) }); + await flush(); + ctx.engine.prefetchRegions(['FR']); + expect(pending).toEqual([]); + }); +}); diff --git a/client/src/components/AtlasGlobe/GlobePins.test.tsx b/client/src/components/AtlasGlobe/GlobePins.test.tsx new file mode 100644 index 000000000..5d46f160b --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobePins.test.tsx @@ -0,0 +1,119 @@ +// FE-ATLAS2-RENDER-400 to FE-ATLAS2-RENDER-406: wishes pinned on the globe, placed per frame and hidden +// behind the horizon or off screen. +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { createRef, type RefObject } from 'react'; +import { describe, expect, it, vi } from 'vitest'; + +import type { GlobeEngine } from './GlobeEngine'; +import GlobePins, { type GlobePin, type GlobePinsHandle } from './GlobePins'; +import type { ScreenPoint } from './globeMath'; + +/** An engine whose projection answers from a table keyed by "lon,lat". */ +function fakeEngine(points: Record, width = 800, height = 600) { + const project = vi.fn((lon: number, lat: number): ScreenPoint => { + const p = points[`${lon},${lat}`]; + if (!p) throw new Error(`unexpected point ${lon},${lat}`); + return p; + }); + const engine = { vp: { width, height, baseRadius: 1, globeY: 0, flatY: 0 }, project } as unknown as GlobeEngine; + return { engine, project }; +} + +function handle(ref: RefObject): GlobePinsHandle { + if (!ref.current) throw new Error('GlobePins handle missing'); + return ref.current; +} + +const PARIS: GlobePin = { key: 'paris', lon: 2, lat: 49, title: 'Paris' }; +const KYOTO: GlobePin = { key: 'kyoto', lon: 136, lat: 35, title: 'Kyoto', reached: true }; + +describe('GlobePins', () => { + it('FE-ATLAS2-RENDER-400: renders one labelled star button per pin, marking reached wishes', () => { + render(); + const paris = screen.getByRole('button', { name: 'Paris' }); + const kyoto = screen.getByRole('button', { name: 'Kyoto' }); + expect(paris).toHaveAttribute('title', 'Paris'); + expect(paris).toHaveAttribute('data-reached', '0'); + expect(kyoto).toHaveAttribute('data-reached', '1'); + expect(paris).toHaveAttribute('data-no-press'); + expect(paris.querySelector('svg')).not.toBeNull(); + }); + + it('FE-ATLAS2-RENDER-401: clicking a pin runs its action', () => { + const onClick = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Paris' })); + expect(onClick).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-RENDER-402: moves a visible pin to its screen point and makes it clickable', () => { + const ref = createRef(); + render(); + const { engine, project } = fakeEngine({ '2,49': { x: 120.04, y: 80.36, visible: 0.5, shade: 1 } }); + act(() => handle(ref).layout(engine)); + expect(project).toHaveBeenCalledWith(2, 49); + const pin = screen.getByRole('button', { name: 'Paris' }); + expect(pin.style.transform).toBe('translate3d(120.0px, 80.4px, 0) translate(-50%, -50%)'); + expect(pin.style.opacity).toBe('1'); + expect(pin.style.pointerEvents).toBe('auto'); + }); + + it('FE-ATLAS2-RENDER-403: fades a pin in as it comes over the horizon', () => { + const ref = createRef(); + render(); + const { engine } = fakeEngine({ '2,49': { x: 10, y: 10, visible: 0.1, shade: 0.2 } }); + act(() => handle(ref).layout(engine)); + const pin = screen.getByRole('button', { name: 'Paris' }); + expect(Number(pin.style.opacity)).toBeCloseTo(0.6); + expect(pin.style.pointerEvents).toBe('auto'); + }); + + it('FE-ATLAS2-RENDER-404: hides a pin behind the globe', () => { + const ref = createRef(); + render(); + const { engine } = fakeEngine({ '2,49': { x: 100, y: 100, visible: 0.01, shade: 0 } }); + act(() => handle(ref).layout(engine)); + const pin = screen.getByRole('button', { name: 'Paris' }); + expect(pin.style.opacity).toBe('0'); + expect(pin.style.pointerEvents).toBe('none'); + }); + + it('FE-ATLAS2-RENDER-405: hides pins more than 20 px off any edge of the screen', () => { + const ref = createRef(); + const pins: GlobePin[] = [ + { key: 'l', lon: 1, lat: 0, title: 'Left' }, + { key: 'r', lon: 2, lat: 0, title: 'Right' }, + { key: 't', lon: 3, lat: 0, title: 'Top' }, + { key: 'b', lon: 4, lat: 0, title: 'Bottom' }, + { key: 'edge', lon: 5, lat: 0, title: 'Edge' }, + ]; + render(); + const { engine } = fakeEngine( + { + '1,0': { x: -21, y: 100, visible: 1, shade: 1 }, + '2,0': { x: 821, y: 100, visible: 1, shade: 1 }, + '3,0': { x: 100, y: -21, visible: 1, shade: 1 }, + '4,0': { x: 100, y: 621, visible: 1, shade: 1 }, + '5,0': { x: -19, y: 619, visible: 1, shade: 1 }, + }, + 800, + 600 + ); + act(() => handle(ref).layout(engine)); + for (const title of ['Left', 'Right', 'Top', 'Bottom']) { + expect(screen.getByRole('button', { name: title }).style.opacity).toBe('0'); + } + expect(screen.getByRole('button', { name: 'Edge' }).style.opacity).toBe('1'); + }); + + it('FE-ATLAS2-RENDER-406: after the pin list changes, layout places the new pins', () => { + const ref = createRef(); + const { rerender } = render(); + rerender(); + expect(screen.queryByRole('button', { name: 'Paris' })).toBeNull(); + const { engine, project } = fakeEngine({ '136,35': { x: 5, y: 5, visible: 1, shade: 1 } }); + act(() => handle(ref).layout(engine)); + expect(project).toHaveBeenCalledTimes(1); + expect(screen.getByRole('button', { name: 'Kyoto' }).style.pointerEvents).toBe('auto'); + }); +}); diff --git a/client/src/components/AtlasGlobe/GlobeRenderer.test.ts b/client/src/components/AtlasGlobe/GlobeRenderer.test.ts new file mode 100644 index 000000000..b540f9f1f --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeRenderer.test.ts @@ -0,0 +1,678 @@ +// FE-ATLAS2-RENDER-001 to FE-ATLAS2-RENDER-040: the WebGL2 renderer of the Atlas globe, driven +// against a hand-written WebGL2 fake that records draws, uniforms and buffer lifetimes. +import { describe, expect, it } from 'vitest'; + +import { createFakeGl, GL, type FakeGl, type FakeGlOptions } from '../../../tests/helpers/fakeWebGl2'; +import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type DrawState, type GlobeTheme } from './GlobeRenderer'; +import type { BuiltLayer, FillMesh, LineMesh } from './globeMesh'; +import { FILL_FS, FILL_VS, LINE_FS, LINE_VS, PICK_FS, RIM_FS, SKY_FS, SKY_VS } from './globeShaders'; + +const DARK: GlobeTheme = { + land: [0.19, 0.19, 0.2], + ocean: [0.08, 0.08, 0.09], + oceanDeep: [0.03, 0.03, 0.03], + space0: [0.01, 0.01, 0.01], + space1: [0.04, 0.04, 0.04], + glow: [0.18, 0.18, 0.19], + border: [0.05, 0.05, 0.06, 0.9], + coast: [0.85, 0.85, 0.87, 0.14], + regionBorder: [0.95, 0.95, 0.95, 0.5], + selection: [1, 1, 1, 0.95], + arc: [0.9, 0.9, 0.9, 0.8], + dark: true, +}; +const LIGHT: GlobeTheme = { ...DARK, dark: false }; + +function fill(tris: number): FillMesh { + return { + ll: new Float32Array(6), + ref: new Float32Array(6), + fid: new Float32Array(3), + index: new Uint32Array(tris * 3), + }; +} + +function lines(count: number): LineMesh { + return { seg: new Float32Array(count * 4), count }; +} + +function layer(tris: number, coast: number, borders: number): BuiltLayer { + return { fill: fill(tris), coast: lines(coast), borders: lines(borders) }; +} + +function arc(count: number, width = 2): ArcLayer { + return { data: new Float32Array(count * 8), count, width }; +} + +function state(over: Partial = {}): DrawState { + return { + frame: { t: 0.25, k: 1, scale: 200, originX: 400, originY: 300, centerLon: 0.1, centerLat: 0.2 }, + dpr: 2, + width: 800, + height: 600, + time: 1.5, + revealStart: 0.75, + hover: 3, + selected: 7, + ink: null, + regionAlpha: 0, + theme: DARK, + arcs: [], + arcProgress: 0.6, + regionKeys: [], + worldKey: 'w', + selectedOutline: null, + sun: [1, 0, 0], + night: 0.5, + ...over, + }; +} + +function setup(opts: FakeGlOptions = {}): { fake: FakeGl; r: GlobeRenderer } { + const fake = createFakeGl(opts); + const r = new GlobeRenderer(fake.canvas()); + return { fake, r }; +} + +/** Fill draws with this triangle count. */ +function fillDraws(fake: FakeGl, count: number) { + return fake.drawsWith(FILL_FS).filter((d) => d.call === 'drawElements' && d.count === count); +} + +function lineDraws(fake: FakeGl, instances: number) { + return fake.drawsWith(LINE_FS).filter((d) => d.call === 'drawArraysInstanced' && d.instances === instances); +} + +function deletedBuffers(fake: FakeGl): unknown[] { + return fake.gl.deleteBuffer.mock.calls.map((c) => c[0]); +} + +describe('GlobeRenderer setup', () => { + it('FE-ATLAS2-RENDER-001: throws when the canvas has no WebGL2 context', () => { + const canvas = { getContext: () => null } as unknown as HTMLCanvasElement; + expect(() => new GlobeRenderer(canvas)).toThrow('WebGL2 unavailable'); + }); + + it('FE-ATLAS2-RENDER-002: asks for an opaque, antialiased webgl2 context', () => { + const fake = createFakeGl(); + const canvas = fake.canvas(); + const r = new GlobeRenderer(canvas); + expect(r.gl).toBe(fake.gl); + expect(canvas.getContext).toHaveBeenCalledWith('webgl2', { + antialias: true, + alpha: false, + premultipliedAlpha: false, + preserveDrawingBuffer: false, + }); + }); + + it('FE-ATLAS2-RENDER-003: links the five programs from the right shader pairs', () => { + const { fake } = setup(); + expect(fake.programs.map((p) => p.srcs)).toEqual([ + [FILL_VS, FILL_FS], + [FILL_VS, PICK_FS], + [LINE_VS, LINE_FS], + [SKY_VS, SKY_FS], + [SKY_VS, RIM_FS], + ]); + expect(fake.gl.linkProgram).toHaveBeenCalledTimes(5); + }); + + it('FE-ATLAS2-RENDER-004: makes two 256x64 nearest-filtered status textures', () => { + const { fake } = setup(); + expect(fake.textures).toHaveLength(2); + const sizes = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]); + expect(sizes).toEqual([ + [256, 64], + [256, 64], + ]); + expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST); + expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST); + expect(MAX_FEATURES).toBe(256 * 64); + }); + + it('FE-ATLAS2-RENDER-005: a shader that fails to compile throws with its log and is deleted', () => { + const fake = createFakeGl({ compileOk: (src) => src !== PICK_FS, shaderLog: 'syntax error at 3' }); + expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: syntax error at 3'); + expect(fake.gl.deleteShader).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-RENDER-006: a compile failure without a log says unknown', () => { + const fake = createFakeGl({ compileOk: () => false, shaderLog: null }); + expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: unknown'); + }); + + it('FE-ATLAS2-RENDER-007: a program that fails to link throws with its log, or unknown', () => { + const withLog = createFakeGl({ linkOk: false, programLog: 'varying mismatch' }); + expect(() => new GlobeRenderer(withLog.canvas())).toThrow('Atlas globe program failed: varying mismatch'); + const noLog = createFakeGl({ linkOk: false, programLog: null }); + expect(() => new GlobeRenderer(noLog.canvas())).toThrow('Atlas globe program failed: unknown'); + }); + + it('FE-ATLAS2-RENDER-008: binds the full-screen quad for the sky and the rim', () => { + const { fake } = setup(); + // a_pos is attribute 0 of both SKY_VS programs, set up once inside the quad VAO each. + const quadAttr = fake.gl.vertexAttribPointer.mock.calls.filter((c) => c[0] === 0 && c[1] === 2 && c[4] === 0); + expect(quadAttr.length).toBeGreaterThanOrEqual(2); + const quadData = fake.buffers.find((b) => b.data instanceof Float32Array && b.data.length === 8); + expect(Array.from(quadData?.data as Float32Array)).toEqual([-1, -1, 1, -1, -1, 1, 1, 1]); + }); + + it('FE-ATLAS2-RENDER-009: skips attributes a compiler dropped or placed at -1', () => { + const { fake, r } = setup({ + attribLocation: (fs, name, i) => { + if (fs === RIM_FS && name === 'a_pos') return null; + if (fs === PICK_FS && name === 'a_ref') return -1; + if (fs === LINE_FS && name === 'a_h') return null; + if (fs === LINE_FS && name === 'a_s') return -1; + return i; + }, + }); + expect(fake.programWith(RIM_FS).attribs).toEqual([]); + r.setWorld('w', layer(2, 1, 1)); + r.draw(state({ arcs: [arc(3)] })); + expect(fake.gl.enableVertexAttribArray.mock.calls.some((c) => c[0] === -1)).toBe(false); + expect(fake.gl.vertexAttribPointer.mock.calls.some((c) => c[0] === -1)).toBe(false); + // Only a_a and a_b get a divisor once a_h and a_s are gone. + const line = fake.programWith(LINE_FS); + const divisorLocs = new Set(fake.gl.vertexAttribDivisor.mock.calls.map((c) => c[0])); + expect(divisorLocs).toEqual(new Set([line.attribLoc.get('a_a'), line.attribLoc.get('a_b')])); + }); +}); + +describe('GlobeRenderer draw', () => { + it('FE-ATLAS2-RENDER-010: sets every uniform it uses on a location its shaders declare', () => { + const { fake, r } = setup(); + r.setOcean(fill(5)); + r.setWorld('w', layer(2, 1, 1)); + r.setRegion('DE', layer(4, 1, 1)); + r.draw( + state({ + regionAlpha: 1, + regionKeys: ['DE'], + arcs: [arc(2)], + selectedOutline: lines(2), + ink: { id: 1, lon: 0, lat: 0, radius: 1 }, + }) + ); + const methods = [ + fake.gl.uniform1f, + fake.gl.uniform1i, + fake.gl.uniform2f, + fake.gl.uniform4f, + fake.gl.uniform3fv, + fake.gl.uniform4fv, + ]; + for (const m of methods) { + for (const call of m.mock.calls) expect(call[0]).toBeDefined(); + } + }); + + it('FE-ATLAS2-RENDER-011: sizes the viewport in device pixels and draws the sky first', () => { + const { fake, r } = setup(); + r.draw(state({ width: 800.4, height: 600, dpr: 2 })); + expect(fake.gl.viewport).toHaveBeenCalledWith(0, 0, 1601, 1200); + expect(fake.enabled.has(GL.BLEND)).toBe(true); + expect(fake.enabled.has(GL.DEPTH_TEST)).toBe(false); + const first = fake.draws[0]; + expect(first.program?.srcs[1]).toBe(SKY_FS); + expect(first.call).toBe('drawArrays'); + expect(first.mode).toBe(GL.TRIANGLE_STRIP); + expect(first.count).toBe(4); + expect(first.values.u_viewport).toEqual([1601, 1200]); + expect(first.values.u_globe).toEqual([800, 600]); + expect(first.values.u_radius).toBe(400); + expect(first.values.u_t).toBe(0.25); + expect(first.values.u_time).toBe(1.5); + expect(first.values.u_space0).toEqual(DARK.space0); + expect(first.values.u_space1).toEqual(DARK.space1); + expect(first.values.u_dark).toBe(1); + }); + + it('FE-ATLAS2-RENDER-012: draws the rim last, over the limb, and unbinds the VAO', () => { + const { fake, r } = setup(); + r.draw(state()); + const last = fake.draws[fake.draws.length - 1]; + expect(last.program?.srcs[1]).toBe(RIM_FS); + expect(last.values.u_glow).toEqual(DARK.glow); + expect(last.values.u_radius).toBe(400); + expect(fake.gl.bindVertexArray).toHaveBeenLastCalledWith(null); + }); + + it('FE-ATLAS2-RENDER-013: passes the projection to the fill program in device pixels', () => { + const { fake, r } = setup(); + r.setOcean(fill(5)); + r.draw(state()); + const [ocean] = fillDraws(fake, 15); + expect(ocean.values.u_center).toEqual([0.1, 0.2]); + expect(ocean.values.u_scale).toBe(400); + expect(ocean.values.u_origin).toEqual([800, 600]); + expect(ocean.values.u_viewport).toEqual([1600, 1200]); + expect(ocean.values.u_status).toBe(0); + expect(ocean.values.u_fx).toBe(1); + expect(ocean.values.u_hover).toBe(3); + expect(ocean.values.u_selected).toBe(7); + expect(ocean.values.u_revealStart).toBe(0.75); + expect(ocean.values.u_sun).toEqual([1, 0, 0]); + expect(ocean.values.u_night).toBe(0.5); + expect(ocean.values.u_dpr).toBe(2); + }); + + it('FE-ATLAS2-RENDER-014: draws the ocean in mode 1 only once it is set', () => { + const { fake, r } = setup(); + r.draw(state()); + expect(fake.drawsWith(FILL_FS)).toHaveLength(0); + r.setOcean(fill(5)); + r.draw(state()); + const ocean = fillDraws(fake, 15); + expect(ocean).toHaveLength(1); + expect(ocean[0].values.u_mode).toBe(1); + expect(ocean[0].mode).toBe(GL.TRIANGLES); + }); + + it('FE-ATLAS2-RENDER-015: dark mode lights a hovered country up and keeps the limb darker', () => { + const { fake, r } = setup(); + r.setOcean(fill(1)); + r.draw(state({ theme: DARK })); + const [d] = fillDraws(fake, 3); + expect(d.values.u_shadeMin).toBe(0.42); + expect(d.values.u_hoverTint).toEqual([1, 1, 1, 0.09]); + }); + + it('FE-ATLAS2-RENDER-016: light mode tints a hovered country blue and keeps the limb bright', () => { + const { fake, r } = setup(); + r.setOcean(fill(1)); + r.draw(state({ theme: LIGHT })); + const [d] = fillDraws(fake, 3); + expect(d.values.u_shadeMin).toBe(0.82); + expect(d.values.u_hoverTint).toEqual([0.42, 0.56, 0.82, 0.16]); + expect(fake.drawsWith(SKY_FS)[0].values.u_dark).toBe(0); + }); + + it('FE-ATLAS2-RENDER-017: hands the ink spot over in radians, or a neutral one without ink', () => { + const { fake, r } = setup(); + r.setOcean(fill(1)); + r.draw(state({ ink: { id: 42, lon: 180, lat: -90, radius: 0.3 } })); + r.draw(state({ ink: null })); + const [withInk, without] = fillDraws(fake, 3); + expect(withInk.values.u_inkId).toBe(42); + const [inkLon, inkLat] = withInk.values.u_inkLL as number[]; + expect(inkLon).toBeCloseTo(Math.PI); + expect(inkLat).toBeCloseTo(-Math.PI / 2); + expect(withInk.values.u_inkR).toBe(0.3); + expect(without.values.u_inkId).toBe(-1); + expect(without.values.u_inkLL).toEqual([0, 0]); + expect(without.values.u_inkR).toBe(0); + }); +}); + +describe('GlobeRenderer status textures', () => { + it('FE-ATLAS2-RENDER-018: uploads status and fx once at the first draw, then only when dirty', () => { + const { fake, r } = setup(); + r.draw(state()); + expect(fake.statusUploads).toHaveLength(2); + r.draw(state()); + expect(fake.statusUploads).toHaveLength(2); + }); + + it('FE-ATLAS2-RENDER-019: writes a feature colour and effects at its four bytes', () => { + const { fake, r } = setup(); + r.draw(state()); + r.setStatus(3, [10, 20, 30, 40], [1, 2, 3, 4]); + r.draw(state()); + const [status, fx] = fake.statusUploads.slice(2); + expect(Array.from(status.slice(12, 16))).toEqual([10, 20, 30, 40]); + expect(Array.from(fx.slice(12, 16))).toEqual([1, 2, 3, 4]); + expect(status.length).toBe(MAX_FEATURES * 4); + }); + + it('FE-ATLAS2-RENDER-020: leaves the effects empty when only a colour is given', () => { + const { fake, r } = setup(); + r.setStatus(5, [9, 9, 9, 255], [7, 7, 7, 7]); + r.setStatus(5, [1, 2, 3, 4]); + r.draw(state()); + const [status, fx] = fake.statusUploads; + expect(Array.from(status.slice(20, 24))).toEqual([1, 2, 3, 4]); + expect(Array.from(fx.slice(20, 24))).toEqual([0, 0, 0, 0]); + }); + + it('FE-ATLAS2-RENDER-021: ignores ids outside the texture without marking it dirty', () => { + const { fake, r } = setup(); + r.draw(state()); + r.setStatus(-1, [1, 1, 1, 1]); + r.setStatus(MAX_FEATURES, [1, 1, 1, 1]); + r.draw(state()); + expect(fake.statusUploads).toHaveLength(2); + }); + + it('FE-ATLAS2-RENDER-022: clearStatus zeroes a range of ids and re-uploads', () => { + const { fake, r } = setup(); + r.setStatus(1, [1, 1, 1, 1], [1, 1, 1, 1]); + r.setStatus(2, [2, 2, 2, 2], [2, 2, 2, 2]); + r.setStatus(4, [4, 4, 4, 4], [4, 4, 4, 4]); + r.draw(state()); + r.clearStatus(1, 3); + r.draw(state()); + const [status, fx] = fake.statusUploads.slice(2); + expect(Array.from(status.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]); + expect(Array.from(fx.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]); + expect(Array.from(status.slice(16, 20))).toEqual([4, 4, 4, 4]); + }); +}); + +describe('GlobeRenderer world layers', () => { + it('FE-ATLAS2-RENDER-023: draws the world named by the frame, in mode 0 with its lines', () => { + const { fake, r } = setup(); + expect(r.hasWorld('w')).toBe(false); + r.setWorld('w', layer(2, 3, 4)); + expect(r.hasWorld('w')).toBe(true); + r.draw(state({ regionAlpha: 0.4 })); + const [world] = fillDraws(fake, 6); + expect(world.values.u_mode).toBe(0); + expect(world.values.u_dimBase).toBe(1); + expect(world.values.u_regionFade).toBe(0.4); + const [borders] = lineDraws(fake, 4); + expect(borders.values.u_color).toEqual(DARK.border); + expect(borders.values.u_width).toBeCloseTo(1.6); + expect(borders.values.u_lift).toBe(0); + expect(borders.values.u_progress).toBe(2); + const [coast] = lineDraws(fake, 3); + expect(coast.values.u_color).toEqual(DARK.coast); + expect(coast.values.u_width).toBeCloseTo(1.8); + expect(coast.count).toBe(6); + }); + + it('FE-ATLAS2-RENDER-024: draws no world when the frame names one that is not loaded', () => { + const { fake, r } = setup(); + r.setWorld('w', layer(2, 3, 4)); + r.draw(state({ worldKey: 'w-fine' })); + expect(fillDraws(fake, 6)).toHaveLength(0); + expect(fake.drawsWith(LINE_FS)).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-025: skips a line mesh without segments', () => { + const { fake, r } = setup(); + r.setWorld('w', layer(2, 0, 4)); + r.draw(state()); + const instanced = fake.drawsWith(LINE_FS); + expect(instanced).toHaveLength(1); + expect(instanced[0].instances).toBe(4); + }); + + it('FE-ATLAS2-RENDER-026: replacing a world frees the old one after the new one is up', () => { + const { fake, r } = setup(); + const first = layer(2, 3, 4); + r.setWorld('w', first); + const oldBuffers = [ + fake.bufferOf(first.fill.ll), + fake.bufferOf(first.fill.index), + fake.bufferOf(first.coast.seg), + fake.bufferOf(first.borders.seg), + ]; + const second = layer(1, 1, 1); + r.setWorld('w', second); + const deleted = deletedBuffers(fake); + for (const b of oldBuffers) expect(deleted).toContain(b); + expect(deleted).not.toContain(fake.bufferOf(second.fill.ll)); + // fill, pick, coast and border VAOs of the old layer. + expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(4); + r.draw(state()); + expect(fillDraws(fake, 3)).toHaveLength(1); + }); + + it('FE-ATLAS2-RENDER-027: uploads fill attributes with the element buffer bound to the VAO', () => { + const { fake, r } = setup(); + const l = layer(2, 1, 1); + r.setWorld('w', l); + expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ELEMENT_ARRAY_BUFFER, l.fill.index, GL.STATIC_DRAW); + expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ARRAY_BUFFER, l.fill.fid, GL.STATIC_DRAW); + const fillProg = fake.programWith(FILL_FS); + expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(fillProg.attribLoc.get('a_fid'), 1, GL.FLOAT, false, 0, 0); + }); +}); + +describe('GlobeRenderer region layers', () => { + it('FE-ATLAS2-RENDER-028: draws loaded regions in mode 2 over the world with faded borders', () => { + const { fake, r } = setup(); + r.setWorld('w', layer(1, 0, 0)); + r.setRegion('DE', layer(4, 1, 5)); + expect(r.hasRegion('DE')).toBe(true); + r.draw(state({ regionAlpha: 0.5, regionKeys: ['FR', 'DE'] })); + const [region] = fillDraws(fake, 12); + expect(region.values.u_mode).toBe(2); + expect(region.values.u_layerAlpha).toBe(0.5); + const [borders] = lineDraws(fake, 5); + expect(borders.values.u_color).toEqual([0.95, 0.95, 0.95, 0.25]); + expect(borders.values.u_width).toBeCloseTo(1.4); + // The theme is not changed by the fade. + expect(DARK.regionBorder[3]).toBe(0.5); + }); + + it('FE-ATLAS2-RENDER-029: does not draw regions faded out below the threshold', () => { + const { fake, r } = setup(); + r.setRegion('DE', layer(4, 1, 5)); + r.draw(state({ regionAlpha: 0.0005, regionKeys: ['DE'] })); + expect(fillDraws(fake, 12)).toHaveLength(0); + expect(lineDraws(fake, 5)).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-030: does not switch to region mode when none of the keys is loaded', () => { + const { fake, r } = setup(); + r.setOcean(fill(1)); + r.draw(state({ regionAlpha: 1, regionKeys: ['FR'] })); + expect(fake.drawsWith(FILL_FS).every((d) => d.values.u_mode !== 2)).toBe(true); + expect(fake.drawsWith(FILL_FS)[0].values.u_layerAlpha).toBe(1); + }); + + it('FE-ATLAS2-RENDER-031: replacing a region frees the old layer and keeps one entry', () => { + const { fake, r } = setup(); + const first = layer(4, 1, 1); + r.setRegion('DE', first); + r.setRegion('DE', layer(2, 1, 1)); + expect(deletedBuffers(fake)).toContain(fake.bufferOf(first.fill.index)); + r.draw(state({ regionAlpha: 1, regionKeys: ['DE'] })); + expect(fillDraws(fake, 12)).toHaveLength(0); + expect(fillDraws(fake, 6)).toHaveLength(1); + }); + + it('FE-ATLAS2-RENDER-032: past 64 region layers drops the one held longest', () => { + const { fake, r } = setup(); + const oldest = layer(1, 1, 1); + r.setRegion('r0', oldest); + for (let i = 1; i <= 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1)); + expect(r.hasRegion('r0')).toBe(false); + expect(r.hasRegion('r1')).toBe(true); + expect(r.hasRegion('r64')).toBe(true); + expect(deletedBuffers(fake)).toContain(fake.bufferOf(oldest.fill.ll)); + }); + + it('FE-ATLAS2-RENDER-033: never drops a region in use, the next oldest goes instead', () => { + const { r } = setup(); + for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1)); + r.setRegion('r64', layer(1, 1, 1), new Set(['r0'])); + expect(r.hasRegion('r0')).toBe(true); + expect(r.hasRegion('r1')).toBe(false); + expect(r.hasRegion('r64')).toBe(true); + }); + + it('FE-ATLAS2-RENDER-034: touching a region makes it the last to go; an unknown key is a no-op', () => { + const { r } = setup(); + for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1)); + r.touchRegion('r0'); + r.touchRegion('nope'); + expect(r.hasRegion('nope')).toBe(false); + r.setRegion('r64', layer(1, 1, 1)); + expect(r.hasRegion('r0')).toBe(true); + expect(r.hasRegion('r1')).toBe(false); + }); +}); + +describe('GlobeRenderer outline and arcs', () => { + it('FE-ATLAS2-RENDER-035: draws the selected outline glowing, uploading it once per mesh', () => { + const { fake, r } = setup(); + const outline = lines(7); + r.draw(state({ selectedOutline: outline })); + r.draw(state({ selectedOutline: outline })); + const uploads = fake.gl.bufferData.mock.calls.filter((c) => c[1] === outline.seg); + expect(uploads).toHaveLength(1); + const draws = lineDraws(fake, 7); + expect(draws).toHaveLength(2); + expect(draws[0].values.u_glow).toBe(0.55); + expect(draws[0].values.u_color).toEqual(DARK.selection); + expect(draws[0].values.u_width).toBeCloseTo(3.6); + expect(fake.programWith(LINE_FS).values.u_glow).toBe(0); + }); + + it('FE-ATLAS2-RENDER-036: a new outline frees the buffer of the previous one', () => { + const { fake, r } = setup(); + const a = lines(7); + r.draw(state({ selectedOutline: a })); + const aBuffer = fake.bufferOf(a.seg); + expect(deletedBuffers(fake)).not.toContain(aBuffer); + const b = lines(9); + r.draw(state({ selectedOutline: b })); + expect(deletedBuffers(fake)).toContain(aBuffer); + expect(lineDraws(fake, 9)).toHaveLength(1); + }); + + it('FE-ATLAS2-RENDER-037: draws arcs lifted with their progress, width and glow', () => { + const { fake, r } = setup(); + const a = arc(5, 3); + r.draw(state({ arcs: [a], arcProgress: 0.6 })); + const [d] = lineDraws(fake, 5); + expect(d.values.u_lift).toBe(1); + expect(d.values.u_progress).toBe(0.6); + expect(d.values.u_glow).toBe(0.35); + expect(d.values.u_width).toBe(6); + expect(d.values.u_color).toEqual(DARK.arc); + expect(fake.programWith(LINE_FS).values.u_lift).toBe(0); + // An arc carries heights and progress too: stride of eight floats, four attributes per instance. + const line = fake.programWith(LINE_FS); + expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(line.attribLoc.get('a_s'), 2, GL.FLOAT, false, 32, 24); + expect(fake.gl.vertexAttribDivisor).toHaveBeenCalledWith(line.attribLoc.get('a_h'), 1); + }); + + it('FE-ATLAS2-RENDER-038: keeps an arc on the GPU across frames and frees the ones no longer drawn', () => { + const { fake, r } = setup(); + const keep = arc(5); + const gone = arc(6); + r.draw(state({ arcs: [keep, gone] })); + r.draw(state({ arcs: [keep] })); + r.draw(state({ arcs: [keep] })); + expect(fake.gl.bufferData.mock.calls.filter((c) => c[1] === keep.data)).toHaveLength(1); + const deleted = deletedBuffers(fake); + expect(deleted).toContain(fake.bufferOf(gone.data)); + expect(deleted).not.toContain(fake.bufferOf(keep.data)); + expect(lineDraws(fake, 5)).toHaveLength(3); + expect(lineDraws(fake, 6)).toHaveLength(1); + }); +}); + +describe('GlobeRenderer picking', () => { + it('FE-ATLAS2-RENDER-039: returns -1 before any frame was drawn', () => { + const { fake, r } = setup({ pixel: [9, 0, 0, 255] }); + expect(r.pick(10, 10, true)).toBe(-1); + expect(fake.framebuffers).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-040: decodes the id under the pointer from the pick pass', () => { + const { fake, r } = setup({ pixel: [5, 1, 0, 255] }); + r.setWorld('w', layer(2, 1, 1)); + r.draw(state()); + expect(r.pick(10.2, 20.4, false)).toBe(5 + 256 - 1); + expect(fake.gl.readPixels).toHaveBeenCalledWith( + 20, + 1200 - 41 - 1, + 1, + 1, + GL.RGBA, + GL.UNSIGNED_BYTE, + expect.any(Uint8Array) + ); + const picks = fake.drawsWith(PICK_FS); + expect(picks).toHaveLength(1); + expect(picks[0].count).toBe(6); + expect(picks[0].framebuffer).toBe(fake.framebuffers[0]); + expect(picks[0].values.u_scale).toBe(400); + expect(fake.gl.bindFramebuffer).toHaveBeenLastCalledWith(GL.FRAMEBUFFER, null); + expect(fake.enabled.has(GL.BLEND)).toBe(true); + expect(fake.gl.clearColor).toHaveBeenCalledWith(0, 0, 0, 0); + }); + + it('FE-ATLAS2-RENDER-041: answers -1 on empty sea', () => { + const { r } = setup(); + r.draw(state()); + expect(r.pick(1, 1, true)).toBe(-1); + }); + + it('FE-ATLAS2-RENDER-042: reuses the pick target while the size holds and rebuilds it on resize', () => { + const { fake, r } = setup(); + r.draw(state()); + r.pick(1, 1, false); + r.pick(2, 2, false); + expect(fake.framebuffers).toHaveLength(1); + expect(fake.gl.deleteFramebuffer).not.toHaveBeenCalled(); + const firstTex = fake.textures[fake.textures.length - 1]; + r.draw(state({ width: 400 })); + r.pick(1, 1, false); + expect(fake.framebuffers).toHaveLength(2); + expect(fake.gl.deleteFramebuffer).toHaveBeenCalledWith(fake.framebuffers[0]); + expect(fake.gl.deleteTexture).toHaveBeenCalledWith(firstTex); + const sized = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]); + expect(sized).toContainEqual([1600, 1200]); + expect(sized).toContainEqual([800, 1200]); + }); + + it('FE-ATLAS2-RENDER-043: draws loaded regions into the pick pass only when asked to', () => { + const { fake, r } = setup(); + r.setWorld('w', layer(2, 1, 1)); + r.setRegion('DE', layer(4, 1, 1)); + r.draw(state({ regionKeys: ['DE', 'FR'], regionAlpha: 1 })); + r.pick(1, 1, false); + expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6]); + r.pick(1, 1, true); + expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6, 6, 12]); + }); + + it('FE-ATLAS2-RENDER-044: picks without a world when the frame names none that is loaded', () => { + const { fake, r } = setup({ pixel: [3, 0, 0, 255] }); + r.draw(state({ worldKey: 'none' })); + expect(r.pick(1, 1, false)).toBe(2); + expect(fake.drawsWith(PICK_FS)).toHaveLength(0); + }); +}); + +describe('GlobeRenderer dispose', () => { + it('FE-ATLAS2-RENDER-045: frees every world and region layer and forgets them', () => { + const { fake, r } = setup(); + const w = layer(2, 1, 1); + const reg = layer(3, 1, 1); + r.setWorld('w', w); + r.setRegion('DE', reg); + r.dispose(); + expect(r.hasWorld('w')).toBe(false); + expect(r.hasRegion('DE')).toBe(false); + const deleted = deletedBuffers(fake); + expect(deleted).toContain(fake.bufferOf(w.fill.ll)); + expect(deleted).toContain(fake.bufferOf(reg.borders.seg)); + expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(8); + }); +}); + +describe('globe shaders', () => { + it('FE-ATLAS2-RENDER-046: every shader is GLSL ES 3.00 with high precision', () => { + for (const src of [FILL_VS, FILL_FS, PICK_FS, LINE_VS, LINE_FS, SKY_VS, SKY_FS, RIM_FS]) { + expect(src.startsWith('#version 300 es\n')).toBe(true); + expect(src).toContain('precision highp float;'); + } + }); + + it('FE-ATLAS2-RENDER-047: the fill and line vertex shaders share the projection the picker relies on', () => { + for (const src of [FILL_VS, LINE_VS]) { + expect(src).toContain('vec4 project(vec2 ll, vec2 ref)'); + expect(src).toContain('uniform vec2 u_center;'); + } + // pick() subtracts one again: id 0 stays "nothing here". + expect(PICK_FS).toContain('int id = v_fid + 1;'); + }); +}); diff --git a/client/src/components/AtlasGlobe/GlobeSky.test.tsx b/client/src/components/AtlasGlobe/GlobeSky.test.tsx new file mode 100644 index 000000000..400ff28f9 --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeSky.test.tsx @@ -0,0 +1,203 @@ +// FE-ATLAS2-RENDER-300 to FE-ATLAS2-RENDER-312: the sky around the globe, the moon in its phase and the +// shooting stars, on their own timer and on demand. +import { act, render } from '@testing-library/react'; +import { createRef, type RefObject } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { GlobeEngine } from './GlobeEngine'; +import GlobeSky, { type GlobeSkyHandle } from './GlobeSky'; +import { smoothstep } from './globeMath'; + +const SYNODIC_MS = 29.530588853 * 86400000; +const NEW_MOON = Date.UTC(2000, 0, 6, 18, 14); + +/** A moment at this share of a lunation after a known new moon. */ +function atPhase(phase: number): Date { + return new Date(NEW_MOON + 300 * SYNODIC_MS + phase * SYNODIC_MS); +} + +interface AnimateCall { + el: HTMLElement; + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + animation: { onfinish: (() => void) | null }; +} + +let animations: AnimateCall[]; +let visibility: DocumentVisibilityState; + +function fakeEngine(over: { t?: number; scale?: number; width?: number; height?: number } = {}): GlobeEngine { + return { + frame: { t: over.t ?? 0, k: 1, scale: over.scale ?? 100, originX: 400, originY: 300, centerLon: 0, centerLat: 0 }, + vp: { width: over.width ?? 800, height: over.height ?? 600, baseRadius: 1, globeY: 0, flatY: 0 }, + } as unknown as GlobeEngine; +} + +function mount(dark: boolean) { + const ref = createRef(); + const utils = render(); + const starHost = utils.container.children[0] as HTMLDivElement; + const moon = utils.container.children[1] as HTMLDivElement; + Object.defineProperty(starHost, 'clientWidth', { configurable: true, value: 1000 }); + Object.defineProperty(starHost, 'clientHeight', { configurable: true, value: 400 }); + return { ...utils, ref, starHost, moon }; +} + +function handle(ref: RefObject): GlobeSkyHandle { + if (!ref.current) throw new Error('GlobeSky handle missing'); + return ref.current; +} + +beforeEach(() => { + vi.useFakeTimers({ now: atPhase(0.2) }); + vi.spyOn(Math, 'random').mockReturnValue(0); + animations = []; + visibility = 'visible'; + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }); + Object.defineProperty(HTMLElement.prototype, 'animate', { + configurable: true, + writable: true, + value: function animate(this: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions) { + const animation = { onfinish: null as (() => void) | null }; + animations.push({ el: this, keyframes, options, animation }); + return animation; + }, + }); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + Reflect.deleteProperty(document, 'visibilityState'); + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); +}); + +describe('GlobeSky moon', () => { + it('FE-ATLAS2-RENDER-300: draws a waxing crescent as a thin lit sliver', () => { + const { container } = mount(true); + const path = container.querySelector('path'); + expect(path?.getAttribute('d')).toBe('M 14 1 A 13 13 0 0 0 14 27 A 4.02 13 0 0 0 14 1 Z'); + }); + + it('FE-ATLAS2-RENDER-301: mirrors the shadow for a waning crescent', () => { + vi.setSystemTime(atPhase(0.8)); + const { container } = mount(true); + expect(container.querySelector('path')?.getAttribute('d')).toBe( + 'M 14 1 A 13 13 0 0 1 14 27 A 4.02 13 0 0 1 14 1 Z' + ); + }); + + it('FE-ATLAS2-RENDER-302: bulges the shadow ellipse the other way for a gibbous moon', () => { + vi.setSystemTime(atPhase(0.4)); + const { container } = mount(true); + expect(container.querySelector('path')?.getAttribute('d')).toBe( + 'M 14 1 A 13 13 0 0 0 14 27 A 10.52 13 0 0 1 14 1 Z' + ); + }); + + it('FE-ATLAS2-RENDER-303: hides the moon in light mode', () => { + const { ref, moon } = mount(false); + act(() => handle(ref).layout(fakeEngine())); + expect(moon.style.opacity).toBe('0'); + expect(moon.style.transform).toBe(''); + }); + + it('FE-ATLAS2-RENDER-304: places the moon up and to the side of the globe, fully shown on the globe', () => { + const { ref, moon } = mount(true); + act(() => handle(ref).layout(fakeEngine({ t: 0, scale: 100, width: 800, height: 600 }))); + const d = Math.max(175, 600 * 0.42); + const x = 400 + Math.cos(-0.65) * d * 1.25; + const y = 300 + Math.sin(-0.65) * d * 0.62; + expect(moon.style.transform).toBe(`translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`); + expect(moon.style.opacity).toBe('0.95'); + }); + + it('FE-ATLAS2-RENDER-305: keeps a zoomed-in globe clear of the moon and fades it as the map unrolls', () => { + const { ref, moon } = mount(true); + act(() => handle(ref).layout(fakeEngine({ t: 0.3, scale: 400 }))); + const d = 400 * 1.75; + const x = 400 + Math.cos(-0.65) * d * 1.25; + expect(moon.style.transform.startsWith(`translate3d(${x.toFixed(1)}px,`)).toBe(true); + expect(Number(moon.style.opacity)).toBeCloseTo((1 - smoothstep(0.05, 0.6, 0.3)) * 0.95); + act(() => handle(ref).layout(fakeEngine({ t: 1 }))); + expect(moon.style.opacity).toBe('0'); + }); +}); + +describe('GlobeSky shooting stars', () => { + it('FE-ATLAS2-RENDER-306: a shooting star crosses the upper right of the sky and removes itself', () => { + const { ref, starHost } = mount(true); + act(() => handle(ref).shootingStar()); + const star = starHost.querySelector('.ag-shooting-star') as HTMLElement; + expect(star).not.toBeNull(); + expect(star.style.left.endsWith('px')).toBe(true); + expect(parseFloat(star.style.left)).toBeCloseTo(550); + expect(parseFloat(star.style.top)).toBeCloseTo(20); + expect(animations).toHaveLength(1); + expect(animations[0].el).toBe(star); + expect(animations[0].options.duration).toBe(1100); + expect(animations[0].keyframes).toHaveLength(3); + animations[0].animation.onfinish?.(); + expect(starHost.querySelector('.ag-shooting-star')).toBeNull(); + }); + + it('FE-ATLAS2-RENDER-307: there are no shooting stars in light mode', () => { + const { ref, starHost } = mount(false); + act(() => handle(ref).shootingStar()); + expect(starHost.children).toHaveLength(0); + expect(animations).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-308: respects reduced motion', () => { + vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as unknown as MediaQueryList); + const { ref, starHost } = mount(true); + act(() => handle(ref).shootingStar()); + expect(starHost.children).toHaveLength(0); + }); + + it('FE-ATLAS2-RENDER-309: sends a star of its own now and then while the page is in view', () => { + const { starHost } = mount(true); + act(() => { + vi.advanceTimersByTime(39_999); + }); + expect(starHost.children).toHaveLength(0); + act(() => { + vi.advanceTimersByTime(1); + }); + expect(starHost.children).toHaveLength(1); + act(() => { + vi.advanceTimersByTime(40_000); + }); + expect(starHost.children).toHaveLength(2); + }); + + it('FE-ATLAS2-RENDER-310: skips its own star while the page is hidden but keeps the schedule', () => { + const { starHost } = mount(true); + visibility = 'hidden'; + act(() => { + vi.advanceTimersByTime(40_000); + }); + expect(starHost.children).toHaveLength(0); + visibility = 'visible'; + act(() => { + vi.advanceTimersByTime(40_000); + }); + expect(starHost.children).toHaveLength(1); + }); + + it('FE-ATLAS2-RENDER-311: schedules nothing in light mode', () => { + mount(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('FE-ATLAS2-RENDER-312: stops its timer on unmount and when switching to light mode', () => { + const { rerender, unmount } = mount(true); + expect(vi.getTimerCount()).toBe(1); + rerender(); + expect(vi.getTimerCount()).toBe(0); + rerender(); + expect(vi.getTimerCount()).toBe(1); + unmount(); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/client/src/components/AtlasGlobe/GlobeStatsBar.test.tsx b/client/src/components/AtlasGlobe/GlobeStatsBar.test.tsx new file mode 100644 index 000000000..ff98114e1 --- /dev/null +++ b/client/src/components/AtlasGlobe/GlobeStatsBar.test.tsx @@ -0,0 +1,142 @@ +// FE-ATLAS2-VIEWB-020 to FE-ATLAS2-VIEWB-029: the globe's stat cards, the medal and the Dawarich mark. +import { fireEvent, render, screen } from '@testing-library/react'; +import type { BadgeMotif } from '@trek/shared'; +import { Flag, Globe } from 'lucide-react'; +import { describe, expect, it, vi } from 'vitest'; +import BadgeMedal from './BadgeMedal'; +import DawarichMark from './DawarichMark'; +import GlobeStatsBar from './GlobeStatsBar'; + +describe('GlobeStatsBar', () => { + it('FE-ATLAS2-VIEWB-020: a stat with an action is a button, one without is plain', () => { + const onClick = vi.fn(); + const { container } = render( + + ); + const btn = screen.getByRole('button'); + expect(btn).toHaveTextContent('12'); + expect(btn).toHaveTextContent('Countries'); + fireEvent.click(btn); + expect(onClick).toHaveBeenCalledTimes(1); + expect(screen.getByText('Continents').closest('button')).toBeNull(); + expect(screen.getByText('3')).toBeInTheDocument(); + expect(container.firstElementChild?.className).toContain('bottom-[22px]'); + }); + + it('FE-ATLAS2-VIEWB-021: the bar takes a caller position instead of the corner', () => { + const { container } = render(); + expect(container.firstElementChild?.className).toContain('top-0 end-0'); + expect(container.firstElementChild?.className).not.toContain('bottom-[22px]'); + expect(container.firstElementChild?.children).toHaveLength(0); + }); +}); + +describe('BadgeMedal', () => { + it('FE-ATLAS2-VIEWB-022: an earned medal has a full ring and its gradients are named after its id', () => { + const { container } = render(); + const svg = container.querySelector('svg'); + expect(svg).toHaveAttribute('width', '92'); + expect(svg).toHaveAttribute('height', '104'); + expect(container.querySelector('#bm-x1-r')).not.toBeNull(); + const hex = container.querySelector('polygon'); + expect(hex).toHaveAttribute('stroke-width', '5'); + expect(hex).toHaveAttribute('stroke-opacity', '1'); + expect(hex).not.toHaveAttribute('stroke-dasharray'); + // No progress ring on an earned medal. + expect(container.querySelectorAll('polygon')).toHaveLength(2); + expect(container.querySelector('g')).toHaveAttribute('opacity', '1'); + }); + + it('FE-ATLAS2-VIEWB-023: a medal not yet earned is dashed, dim and draws its progress', () => { + const { container } = render( + + ); + const polys = container.querySelectorAll('polygon'); + expect(polys).toHaveLength(3); + expect(polys[0]).toHaveAttribute('stroke-dasharray', '4 3'); + expect(polys[0]).toHaveAttribute('stroke-width', '2'); + expect(polys[2]).toHaveAttribute('stroke-dasharray', '42 100'); + expect(container.querySelector('g')).toHaveAttribute('opacity', '0.38'); + expect(container.querySelector('svg')).toHaveAttribute('width', '46'); + expect(container.querySelector('svg')).toHaveAttribute('height', '52'); + }); + + it('FE-ATLAS2-VIEWB-024: a medal not earned and without progress draws no progress ring', () => { + const { container } = render(); + expect(container.querySelectorAll('polygon')).toHaveLength(2); + }); + + it('FE-ATLAS2-VIEWB-025: the seven-continents motif lights seven points', () => { + const { container } = render(); + expect(container.querySelectorAll('circle[r="2.4"]')).toHaveLength(7); + }); + + it('FE-ATLAS2-VIEWB-026: a stepped medal carries its label, smaller the longer it is', () => { + const sizes: Array<[string, string]> = [ + ['5', '15'], + ['100', '13'], + ['3/12', '11'], + ]; + for (const [label, size] of sizes) { + const { container, unmount } = render(); + const text = container.querySelector('text'); + expect(text).toHaveTextContent(label); + expect(text).toHaveAttribute('font-size', size); + unmount(); + } + }); + + it('FE-ATLAS2-VIEWB-027: a back side replaces the motif', () => { + const { container } = render( + B} /> + ); + expect(screen.getByTestId('back')).toBeInTheDocument(); + expect(container.querySelectorAll('text')).toHaveLength(1); + }); + + it('FE-ATLAS2-VIEWB-028: every motif draws a symbol', () => { + const motifs: BadgeMotif[] = [ + 'first', + 'countries', + 'continents', + 'region', + 'earth', + 'moon', + 'flights', + 'longhaul', + 'airports', + 'dateline', + 'equator', + 'hemispheres', + 'tropics', + 'polar', + 'streak', + 'burst', + 'wish', + 'islands', + ]; + for (const motif of motifs) { + const { container, unmount } = render(); + // The lucide symbol is an svg nested in the medal's own. + expect(container.querySelectorAll('svg').length).toBeGreaterThan(1); + unmount(); + } + }); +}); + +describe('DawarichMark', () => { + it('FE-ATLAS2-VIEWB-029: the mark sits two pixels larger than the icon size it stands for', () => { + const { container, rerender } = render(); + const box = container.firstElementChild as HTMLElement; + expect(box.style.width).toBe('18px'); + expect(container.querySelector('img')).toHaveAttribute('width', '18'); + rerender(); + expect((container.firstElementChild as HTMLElement).style.height).toBe('32px'); + expect(container.querySelector('img')).toHaveAttribute('src', '/brands/dawarich.svg'); + }); +}); diff --git a/client/src/components/AtlasGlobe/globeLabels.test.ts b/client/src/components/AtlasGlobe/globeLabels.test.ts new file mode 100644 index 000000000..c58120251 --- /dev/null +++ b/client/src/components/AtlasGlobe/globeLabels.test.ts @@ -0,0 +1,368 @@ +// FE-ATLAS2-PAINT-101 to FE-ATLAS2-PAINT-120: the country and region names placed +// over the globe, their collision rules and how their elements are reused. +import { beforeEach, describe, expect, it } from 'vitest'; +import type { AtlasMeshManifest, GlobeEngine, RegionIndex } from './GlobeEngine'; +import { placeLabels, type GlobeLabel } from './globeLabels'; + +type ManifestCountry = AtlasMeshManifest['countries'][number]; +type Feature = RegionIndex['features'][number]; + +interface FakeLabelEngine { + manifest: { countries: ManifestCountry[] } | null; + zoom: number; + vp: { width: number; height: number }; + regionIndex: Map; + regionAlpha: number; + focus: string | null; + /** Visibility by "x,y" of the anchor; 1 when not listed. */ + visibility: Map; +} + +/** + * A globe engine whose projection is the identity: an anchor [x, y] lands on + * screen at x, y, so a test places labels in pixels directly. + */ +function fakeEngine(over: Partial = {}) { + const state: FakeLabelEngine = { + manifest: { countries: [] }, + zoom: 1, + vp: { width: 1000, height: 800 }, + regionIndex: new Map(), + regionAlpha: 0, + focus: null, + visibility: new Map(), + ...over, + }; + const engine = { + get manifest() { + return state.manifest; + }, + get zoom() { + return state.zoom; + }, + get vp() { + return state.vp; + }, + get regionIndex() { + return state.regionIndex; + }, + get regionAlpha() { + return state.regionAlpha; + }, + focusCountry: () => state.focus, + project: (lon: number, lat: number) => ({ + x: lon, + y: lat, + visible: state.visibility.get(`${lon},${lat}`) ?? 1, + shade: 1, + }), + } as unknown as GlobeEngine; + return { engine, state }; +} + +function mc(a2: string | null, x: number, y: number, area = 1000, anchor = true): ManifestCountry { + return { a2, a3: a2 ?? 'XXX', name: a2 ?? '', anchor: anchor ? [x, y] : null, bbox: [], area }; +} + +function feat(over: Partial = {}): Feature { + return { code: null, name: null, nameEn: null, anchor: null, counted: true, ...over }; +} + +function index(features: Feature[]): RegionIndex { + return { bbox: [], counted: features.length, features, files: {} }; +} + +const nameOf = (a2: string) => `Name ${a2}`; + +let host: HTMLDivElement; +let pool: GlobeLabel[]; + +beforeEach(() => { + host = document.createElement('div'); + pool = []; +}); + +/** The labels that show, by text. */ +function shownTexts(): string[] { + return pool + .filter((l) => l.el.style.opacity !== '0') + .map((l) => l.el.textContent ?? '') + .sort(); +} + +function labelOf(text: string): GlobeLabel | undefined { + return pool.find((l) => l.el.textContent === text && l.el.style.opacity !== '0'); +} + +describe('placeLabels: country names', () => { + it('FE-ATLAS2-PAINT-101: places nothing before the manifest has loaded', () => { + const { engine } = fakeEngine({ manifest: null }); + placeLabels(host, pool, engine, nameOf); + expect(host.children).toHaveLength(0); + expect(pool).toHaveLength(0); + }); + + it('FE-ATLAS2-PAINT-102: names a large country in view at its anchor, in a fresh element on the host', () => { + const { engine } = fakeEngine({ manifest: { countries: [mc('FR', 100, 200)] } }); + placeLabels(host, pool, engine, nameOf); + expect(pool).toHaveLength(1); + const el = pool[0].el; + expect(host.firstChild).toBe(el); + expect(pool[0].key).toBe('FR'); + expect(el.className).toBe('atlas-globe-label text-caption'); + expect(el.textContent).toBe('Name FR'); + expect(el.dataset.region).toBe(''); + expect(el.style.transform).toBe('translate3d(100.0px, 200.0px, 0) translate(-50%, -50%)'); + expect(el.style.opacity).toBe('1'); + }); + + it('FE-ATLAS2-PAINT-103: leaves out countries too small for the zoom, unless they are the user own', () => { + // At zoom 1 a country needs 700 square degrees; one of the user's own needs 30 % of that. + const countries = [mc('BE', 100, 100, 300), mc('LU', 400, 100, 300), mc('MT', 700, 100, 100)]; + const { engine } = fakeEngine({ manifest: { countries } }); + placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'BE' || a2 === 'MT'); + expect(shownTexts()).toEqual(['Name BE']); + }); + + it('FE-ATLAS2-PAINT-104: zooming in brings smaller countries in', () => { + const { engine, state } = fakeEngine({ manifest: { countries: [mc('BE', 100, 100, 300)] } }); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual([]); + state.zoom = 2; + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Name BE']); + }); + + it('FE-ATLAS2-PAINT-105: skips countries without a code, an anchor, a name, or out of view', () => { + const countries = [ + mc(null, 100, 100), + mc('AQ', 200, 100, 1000, false), + mc('NO', 300, 100), + // Past the margin left, right, above and below the view. + mc('W1', -50, 300), + mc('E1', 1050, 300), + mc('N1', 500, -30), + mc('S1', 500, 830), + // Behind the limb. + mc('BK', 600, 600), + // Inside the margin: still named. + mc('IN', -30, 400), + ]; + const { engine } = fakeEngine({ manifest: { countries }, visibility: new Map([['600,600', 0.1]]) }); + placeLabels(host, pool, engine, (a2) => (a2 === 'NO' ? null : a2)); + expect(shownTexts()).toEqual(['IN']); + }); + + it('FE-ATLAS2-PAINT-106: fades a name in as it turns from the limb and as region fills take over', () => { + const { engine } = fakeEngine({ + manifest: { countries: [mc('FR', 100, 100)] }, + visibility: new Map([['100,100', 0.15]]), + regionAlpha: 0.5, + }); + placeLabels(host, pool, engine, nameOf); + expect(Number(pool[0].el.style.opacity)).toBeCloseTo(0.6 * (1 - 0.5 * 0.55), 6); + }); + + it('FE-ATLAS2-PAINT-107: of two overlapping names the larger country wins', () => { + const { engine } = fakeEngine({ manifest: { countries: [mc('SM', 100, 100, 800), mc('IT', 110, 104, 3000)] } }); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Name IT']); + expect(pool).toHaveLength(1); + }); + + it('FE-ATLAS2-PAINT-108: the user own country outranks a larger neighbour', () => { + const { engine } = fakeEngine({ manifest: { countries: [mc('CH', 100, 100, 1000), mc('DE', 110, 104, 3000)] } }); + placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'CH'); + expect(shownTexts()).toEqual(['Name CH']); + }); + + it('FE-ATLAS2-PAINT-109: a name on screen keeps its place against a slightly larger one, not a much larger one', () => { + const { engine, state } = fakeEngine({ manifest: { countries: [mc('AA', 100, 100, 1000)] } }); + placeLabels(host, pool, engine, nameOf); + const first = pool[0].el; + + state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1400)] }; + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Name AA']); + expect(labelOf('Name AA')?.el).toBe(first); + + state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1600)] }; + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Name BB']); + }); + + it('FE-ATLAS2-PAINT-110: a name that stays keeps its element and only moves', () => { + const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } }); + placeLabels(host, pool, engine, nameOf); + const el = pool[0].el; + state.manifest = { countries: [mc('FR', 150.04, 120)] }; + placeLabels(host, pool, engine, nameOf); + expect(pool).toHaveLength(1); + expect(pool[0].el).toBe(el); + expect(el.style.transform).toBe('translate3d(150.0px, 120.0px, 0) translate(-50%, -50%)'); + }); + + it('FE-ATLAS2-PAINT-111: a name that goes hides its element, and the next new name reuses it', () => { + const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } }); + placeLabels(host, pool, engine, nameOf); + const el = pool[0].el; + + state.manifest = { countries: [] }; + placeLabels(host, pool, engine, nameOf); + expect(el.style.opacity).toBe('0'); + expect(shownTexts()).toEqual([]); + + state.manifest = { countries: [mc('ES', 300, 300)] }; + placeLabels(host, pool, engine, nameOf); + expect(pool).toHaveLength(1); + expect(host.children).toHaveLength(1); + expect(pool[0].key).toBe('ES'); + expect(el.textContent).toBe('Name ES'); + expect(el.style.opacity).toBe('1'); + }); + + it('FE-ATLAS2-PAINT-112: shows at most 150 names at once', () => { + const countries: ManifestCountry[] = []; + for (let i = 0; i < 170; i++) { + countries.push(mc(`C${i}`, 20 + (i % 20) * 48, 20 + Math.floor(i / 20) * 30, 1000 + i)); + } + const { engine } = fakeEngine({ manifest: { countries } }); + placeLabels(host, pool, engine, (a2) => a2); + expect(pool).toHaveLength(150); + // The largest win the cut. + expect(labelOf('C169')).toBeDefined(); + expect(labelOf('C0')).toBeUndefined(); + }); +}); + +describe('placeLabels: region names', () => { + const US = mc('US', 500, 400, 9000); + const usRegions = () => + index([ + feat({ code: 'US-KS', name: 'Kansas', anchor: [300, 300] }), + feat({ code: null, name: 'Texas', nameEn: 'Texas (en)', anchor: [600, 500] }), + feat({ code: 'US-AK', name: 'Alaska', anchor: null }), + feat({ code: 'US-HI', name: 'Hawaii', anchor: [1200, 300] }), + feat({ code: 'US-GU', name: 'Guam', anchor: [-10, 300] }), + feat({ code: 'US-VI', name: 'Virgin', anchor: [300, -5] }), + feat({ code: 'US-AS', name: 'Samoa', anchor: [300, 900] }), + feat({ code: 'US-ME', name: 'Maine', anchor: [800, 100] }), + ]); + + it('FE-ATLAS2-PAINT-113: from the wide-screen region zoom on, a country with regions names them instead of itself', () => { + const { engine } = fakeEngine({ + manifest: { countries: [US, mc('CA', 900, 700, 9000)] }, + zoom: 18, + regionIndex: new Map([['US', usRegions()]]), + regionAlpha: 0.8, + visibility: new Map([['800,100', 0.05]]), + }); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Kansas', 'Name CA', 'Texas (en)']); + const kansas = labelOf('Kansas'); + expect(kansas?.key).toBe('US:US-KS'); + expect(kansas?.el.dataset.region).toBe('1'); + expect(kansas?.el.style.opacity).toBe('0.8'); + expect(labelOf('Texas (en)')?.key).toBe('US:Texas'); + expect(labelOf('Name CA')?.el.dataset.region).toBe(''); + }); + + it('FE-ATLAS2-PAINT-114: below the region zoom the country keeps its own name', () => { + const { engine } = fakeEngine({ + manifest: { countries: [US] }, + zoom: 17, + regionIndex: new Map([['US', usRegions()]]), + }); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Name US']); + }); + + it('FE-ATLAS2-PAINT-115: on a phone-wide view region names start earlier', () => { + const { engine } = fakeEngine({ + manifest: { countries: [US] }, + zoom: 14, + vp: { width: 600, height: 800 }, + regionIndex: new Map([['US', usRegions()]]), + regionAlpha: 1, + }); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Kansas', 'Texas (en)']); + }); + + it('FE-ATLAS2-PAINT-116: a region named by its plain name falls back to it, and one without any name shows empty', () => { + const { engine } = fakeEngine({ + manifest: { countries: [] }, + zoom: 20, + regionIndex: new Map([ + [ + 'FR', + index([ + feat({ code: 'FR-IDF', name: 'Île-de-France', anchor: [100, 100] }), + feat({ code: 'FR-X', anchor: [400, 400] }), + ]), + ], + ]), + regionAlpha: 1, + }); + placeLabels(host, pool, engine, nameOf); + expect(pool.map((l) => l.el.textContent).sort()).toEqual(['', 'Île-de-France']); + }); + + /** Two countries with one region each at nearly the same spot: only one of them can be named. */ + function rivals(focus: string | null, countries: ManifestCountry[]) { + return fakeEngine({ + manifest: { countries }, + zoom: 20, + focus, + regionIndex: new Map([ + // Mexico's region is right in the middle of the view. + ['MX', index([feat({ code: 'MX-SON', name: 'Sonora', anchor: [500, 400] })])], + ['US', index([feat({ code: 'US-AZ', name: 'Arizona', anchor: [510, 404] })])], + ]), + regionAlpha: 1, + }); + } + + it('FE-ATLAS2-PAINT-117: the regions of the country under the middle of the view come first', () => { + const { engine } = rivals('US', [mc('US', 520, 410), mc('MX', 480, 420)]); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Arizona']); + }); + + it('FE-ATLAS2-PAINT-118: a country under the middle without regions puts no country first, so the nearest region wins', () => { + const { engine } = rivals('ES', [mc('US', 520, 410), mc('MX', 480, 420)]); + placeLabels(host, pool, engine, nameOf); + expect(shownTexts()).toEqual(['Sonora']); + }); + + it('FE-ATLAS2-PAINT-119: over open water the country with regions whose anchor is nearest the middle comes first', () => { + // US's anchor is the nearer one; Mexico's lies behind the limb. + const near = rivals(null, [mc('US', 520, 410), mc('MX', 501, 401)]); + near.state.visibility.set('501,401', 0); + placeLabels(host, pool, near.engine, nameOf); + expect(shownTexts()).toEqual(['Arizona']); + + // No anchor near enough the middle (or none at all): nobody comes first. + pool = []; + const far = rivals(null, [mc('US', 950, 750), mc('MX', 0, 0, 1000, false)]); + placeLabels(host, pool, far.engine, nameOf); + expect(shownTexts()).toEqual(['Sonora']); + }); + + it('FE-ATLAS2-PAINT-120: shows at most 120 region names, leaving room for country names', () => { + const features: Feature[] = []; + for (let i = 0; i < 130; i++) { + features.push(feat({ code: `R${i}`, name: `R${i}`, anchor: [30 + (i % 13) * 70, 30 + Math.floor(i / 13) * 30] })); + } + const { engine } = fakeEngine({ + manifest: { countries: [mc('FR', 500, 700, 5000)] }, + zoom: 20, + regionIndex: new Map([['XX', index(features)]]), + regionAlpha: 1, + }); + placeLabels(host, pool, engine, nameOf); + const regions = pool.filter((l) => l.el.dataset.region === '1' && l.el.style.opacity !== '0'); + expect(regions).toHaveLength(120); + expect(labelOf('Name FR')).toBeDefined(); + }); +}); diff --git a/client/src/components/AtlasGlobe/globeMath.edge.test.ts b/client/src/components/AtlasGlobe/globeMath.edge.test.ts new file mode 100644 index 000000000..63304db54 --- /dev/null +++ b/client/src/components/AtlasGlobe/globeMath.edge.test.ts @@ -0,0 +1,131 @@ +// FE-ATLAS2-PAINT-401 to FE-ATLAS2-PAINT-412: the edges of the globe projection the +// main globeMath tests leave out (clamps, the far side, degenerate arcs). +import { describe, expect, it } from 'vitest'; +import { + arcSegments, + frameParams, + interpolateGreatCircle, + latLimits, + moonPhase, + MORPH_END, + morphOf, + projectPoint, + RAD, + smoothstep, + wrapPi, + xSqueeze, + type GlobeViewport, +} from './globeMath'; + +const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 300, flatY: 500 }; + +describe('globeMath edges', () => { + it('FE-ATLAS2-PAINT-401: smoothstep clamps below and above its range and eases in between', () => { + expect(smoothstep(0, 1, -2)).toBe(0); + expect(smoothstep(0, 1, 3)).toBe(1); + expect(smoothstep(0, 1, 0.5)).toBe(0.5); + expect(smoothstep(0, 1, 0.25)).toBeCloseTo(0.15625); + expect(morphOf(MORPH_END * 4)).toBe(1); + }); + + it('FE-ATLAS2-PAINT-402: wraps exactly pi onto minus pi and leaves small angles alone', () => { + expect(wrapPi(Math.PI)).toBeCloseTo(-Math.PI); + expect(wrapPi(-Math.PI)).toBeCloseTo(-Math.PI); + expect(wrapPi(1)).toBe(1); + expect(wrapPi(Math.PI * 4 + 0.5)).toBeCloseTo(0.5); + }); + + it('FE-ATLAS2-PAINT-403: moves the origin from the globe centre to the map centre as it unrolls', () => { + const globe = frameParams({ lon: 20, lat: 10, zoom: 1 }, VP); + expect(globe.t).toBe(0); + expect(globe.k).toBe(1); + expect(globe.originX).toBe(500); + expect(globe.originY).toBe(300); + expect(globe.scale).toBe(300); + expect(globe.centerLon).toBeCloseTo(20 * RAD); + expect(globe.centerLat).toBeCloseTo(10 * RAD); + + const flat = frameParams({ lon: 20, lat: 10, zoom: MORPH_END }, VP); + expect(flat.t).toBe(1); + expect(flat.k).toBeCloseTo(0.0005); + expect(flat.originY).toBe(500); + expect(flat.scale).toBeCloseTo(300 * MORPH_END); + }); + + it('FE-ATLAS2-PAINT-404: hides a point past the antimeridian of its reference on the far side', () => { + const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP); + const p = projectPoint(-179, 0, f, 179, 0); + expect(p.visible).toBe(-1); + }); + + it('FE-ATLAS2-PAINT-405: shades full in the middle, dark at the limb, and evenly once flat', () => { + const globe = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP); + expect(projectPoint(0, 0, globe).shade).toBeCloseTo(1); + expect(projectPoint(89.9, 0, globe).shade).toBeLessThan(0.01); + const flat = frameParams({ lon: 0, lat: 0, zoom: MORPH_END }, VP); + expect(projectPoint(80, 30, flat).shade).toBeCloseTo(1); + }); + + it('FE-ATLAS2-PAINT-406: never squeezes longitude more than 0.3 near the poles', () => { + const f = frameParams({ lon: 0, lat: 85, zoom: MORPH_END }, VP); + expect(xSqueeze(f)).toBeCloseTo(0.3); + const globe = frameParams({ lon: 0, lat: 85, zoom: 1 }, VP); + expect(xSqueeze(globe)).toBe(1); + }); + + it('FE-ATLAS2-PAINT-407: a great circle between one point and itself stays on that point', () => { + expect(interpolateGreatCircle(0, 0, 0, 0, 0.5)).toEqual([0, 0]); + const [lon, lat] = interpolateGreatCircle(13.4, 52.5, 13.4, 52.5, 0.5); + expect(lon).toBeCloseTo(13.4); + expect(lat).toBeCloseTo(52.5); + }); + + it('FE-ATLAS2-PAINT-408: a great circle starts and ends on its airports', () => { + const [lon0, lat0] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 0); + const [lon1, lat1] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 1); + expect(lon0).toBeCloseTo(8.57); + expect(lat0).toBeCloseTo(50.03); + expect(lon1).toBeCloseTo(-73.78); + expect(lat1).toBeCloseTo(40.64); + }); + + it('FE-ATLAS2-PAINT-409: no routes give no segments, and the default cuts each arc in 48', () => { + const none = arcSegments([]); + expect(none.count).toBe(0); + expect(none.data).toHaveLength(0); + const two = arcSegments([ + { a: [0, 0], b: [10, 0] }, + { a: [20, 0], b: [30, 0] }, + ]); + expect(two.count).toBe(96); + // The second arc starts at its own first airport. + expect(two.data[48 * 8]).toBeCloseTo(20 * RAD); + }); + + it('FE-ATLAS2-PAINT-410: a route to the same airport still lifts by the minimum peak', () => { + const { data, count } = arcSegments([{ a: [5, 5], b: [5, 5] }], 2); + expect(count).toBe(2); + // Lift at the middle of the arc is the minimum peak. + expect(data[5]).toBeCloseTo(0.015); + expect(data[0]).toBeCloseTo(5 * RAD); + expect(data[2]).toBeCloseTo(5 * RAD); + }); + + it('FE-ATLAS2-PAINT-411: knows the moon phase before its reference new moon too', () => { + const old = moonPhase(new Date(Date.UTC(1999, 0, 2))); + expect(old.phase).toBeGreaterThanOrEqual(0); + expect(old.phase).toBeLessThan(1); + expect(old.lit).toBeGreaterThan(0.95); + const ref = moonPhase(new Date(Date.UTC(2000, 0, 6, 18, 14))); + expect(ref.phase).toBe(0); + expect(ref.lit).toBe(0); + }); + + it('FE-ATLAS2-PAINT-412: an off-centre flat map gets different southern and northern limits', () => { + const [south, north] = latLimits(MORPH_END, VP); + const scale = VP.baseRadius * MORPH_END; + expect(north).toBeCloseTo(90 - VP.flatY / scale / RAD); + expect(south).toBeCloseTo(-90 + (VP.height - VP.flatY) / scale / RAD); + expect(north - south).toBeGreaterThan(0); + }); +}); diff --git a/client/src/components/AtlasGlobe/globeMesh.edge.test.ts b/client/src/components/AtlasGlobe/globeMesh.edge.test.ts new file mode 100644 index 000000000..c39a347a1 --- /dev/null +++ b/client/src/components/AtlasGlobe/globeMesh.edge.test.ts @@ -0,0 +1,214 @@ +// FE-ATLAS2-PAINT-501 to FE-ATLAS2-PAINT-510: the branches of the mesh builder the main +// globeMesh tests leave out (each split direction, holes, multipolygons, growth). +import type { Topology } from 'topojson-specification'; +import { describe, expect, it } from 'vitest'; +import { buildLayer, densify, tessellate } from './globeMesh'; + +const RAD = Math.PI / 180; + +/** A square with a hole, a two-part country, a sliver too thin to fill and a feature without geometry. */ +const SHAPES: Topology = { + type: 'Topology', + arcs: [ + [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + [0, 0], + ], + [ + [3, 3], + [3, 7], + [7, 7], + [7, 3], + [3, 3], + ], + [ + [20, 0], + [22, 0], + [22, 2], + [20, 2], + [20, 0], + ], + [ + [30, 0], + [32, 0], + [32, 2], + [30, 2], + [30, 0], + ], + [ + [40, 0], + [41, 1], + [40, 0], + ], + ], + objects: { + countries: { + type: 'GeometryCollection', + geometries: [ + { type: 'Polygon', id: 0, arcs: [[0], [1]] }, + { type: 'MultiPolygon', id: 1, arcs: [[[2]], [[3]]] }, + { type: 'Polygon', id: 2, arcs: [[4]] }, + { type: null, id: 3 }, + ], + }, + }, +}; + +/** A long, thin strip: cut fine it needs more vertices than the builders reserve up front. */ +const STRIP: Topology = { + type: 'Topology', + arcs: [ + [ + [0, 0], + [350, 0], + [350, 0.01], + [0, 0.01], + [0, 0], + ], + ], + objects: { strip: { type: 'GeometryCollection', geometries: [{ type: 'Polygon', id: 0, arcs: [[0]] }] } }, +}; + +function edgeLengths(coords: number[], tris: number[]): number[] { + const out: number[] = []; + for (let i = 0; i < tris.length; i += 3) { + const t = [tris[i], tris[i + 1], tris[i + 2]]; + for (const [p, q] of [ + [t[0], t[1]], + [t[1], t[2]], + [t[2], t[0]], + ]) { + out.push(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1])); + } + } + return out; +} + +describe('tessellate', () => { + it('FE-ATLAS2-PAINT-501: keeps a triangle that is already small enough as it is', () => { + const coords = [0, 0, 1, 0, 0, 1]; + expect(tessellate(coords, [0, 1, 2], 5)).toEqual([0, 1, 2]); + expect(coords).toHaveLength(6); + }); + + it('FE-ATLAS2-PAINT-502: splits the first edge when it is the longest', () => { + const coords = [0, 0, 10, 0, 5, 1]; + expect(tessellate(coords, [0, 1, 2], 9)).toEqual([3, 1, 2, 0, 3, 2]); + expect(coords.slice(6)).toEqual([5, 0]); + }); + + it('FE-ATLAS2-PAINT-503: splits the second edge when it is the longest', () => { + const coords = [0, 0, 1, 0, 0, 10]; + expect(tessellate(coords, [0, 1, 2], 10.01)).toEqual([0, 3, 2, 0, 1, 3]); + expect(coords.slice(6)).toEqual([0.5, 5]); + }); + + it('FE-ATLAS2-PAINT-504: splits the closing edge when it is the longest', () => { + const coords = [0, 0, 5, 1, 10, 0]; + expect(tessellate(coords, [0, 1, 2], 9)).toEqual([3, 1, 2, 0, 1, 3]); + expect(coords.slice(6)).toEqual([5, 0]); + }); + + it('FE-ATLAS2-PAINT-505: two triangles sharing a long edge share its midpoint', () => { + const coords = [0, 0, 10, 0, 10, 10, 0, 10]; + const tris = tessellate(coords, [0, 1, 2, 0, 2, 3], 12); + expect(tris).toHaveLength(12); + // One new vertex for the shared diagonal, not one per triangle. + expect(coords).toHaveLength(10); + expect(coords.slice(8)).toEqual([5, 5]); + expect(Math.max(...edgeLengths(coords, tris))).toBeLessThanOrEqual(12); + }); +}); + +describe('densify', () => { + it('FE-ATLAS2-PAINT-506: leaves a short line and a single point alone and cuts a diagonal evenly', () => { + expect( + densify( + [ + [0, 0], + [1, 1], + ], + 5 + ) + ).toEqual([ + [0, 0], + [1, 1], + ]); + expect(densify([[3, 4]], 1)).toEqual([[3, 4]]); + const d = densify( + [ + [0, 0], + [3, 4], + ], + 2 + ); + expect(d).toEqual([ + [0, 0], + [1, 4 / 3], + [2, 8 / 3], + [3, 4], + ]); + }); +}); + +describe('buildLayer', () => { + const layer = buildLayer(SHAPES, 'countries', 100, (n) => 10 + n); + + it('FE-ATLAS2-PAINT-507: fills a polygon with its hole, both parts of a multipolygon, and skips slivers and empty features', () => { + const fid = Array.from(layer.fill.fid); + // Square with hole: 4 + 4 vertices; the two parts: 4 each; the sliver and the empty feature: none. + expect(fid).toEqual([10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11]); + expect(layer.fill.ll).toHaveLength(32); + expect(layer.fill.ref).toHaveLength(32); + // A square with a hole takes eight triangles, each plain square two. + expect(layer.fill.index).toHaveLength((8 + 2 + 2) * 3); + expect(Math.min(...layer.fill.index)).toBe(0); + expect(Math.max(...layer.fill.index)).toBe(15); + }); + + it('FE-ATLAS2-PAINT-508: the hole stays empty and every vertex refers to the centre of its own outline', () => { + const idx = Array.from(layer.fill.index.slice(0, 24)); + // The hole's own vertices (4 to 7) never make up one triangle together. + for (let i = 0; i < idx.length; i += 3) { + expect(idx.slice(i, i + 3).every((v) => v >= 4)).toBe(false); + } + expect(layer.fill.ref[0]).toBeCloseTo(5 * RAD); + expect(layer.fill.ref[1]).toBeCloseTo(5 * RAD); + expect(layer.fill.ref[8 * 2]).toBeCloseTo(21 * RAD); + expect(layer.fill.ref[12 * 2]).toBeCloseTo(31 * RAD); + expect(layer.fill.ll[8 * 2]).toBeCloseTo(20 * RAD); + }); + + it('FE-ATLAS2-PAINT-509: draws every outline as coast when no border is shared', () => { + expect(layer.borders.count).toBe(0); + expect(layer.borders.seg).toHaveLength(0); + // Outer square, hole, two parts (four sides each) and the sliver's two sides. + expect(layer.coast.count).toBe(18); + expect(layer.coast.seg).toHaveLength(18 * 4); + }); + + it('FE-ATLAS2-PAINT-510: grows its buffers for a fine cut of a long strip and keeps every edge short', () => { + const strip = buildLayer(STRIP, 'strip', 0.02, () => 7); + const vertices = strip.fill.fid.length; + expect(vertices).toBeGreaterThan(1 << 15); + expect(strip.fill.ll).toHaveLength(vertices * 2); + expect(strip.fill.ref).toHaveLength(vertices * 2); + expect(strip.fill.fid.every((v) => v === 7)).toBe(true); + // Spread would overflow the argument list for an index this long. + expect(strip.fill.index.reduce((m, v) => Math.max(m, v), 0)).toBe(vertices - 1); + expect(strip.fill.index.length % 3).toBe(0); + // The outline: 700 degrees cut into steps of at most 0.02. + expect(strip.coast.count).toBeGreaterThanOrEqual(35000); + expect(strip.coast.seg).toHaveLength(strip.coast.count * 4); + let longest = 0; + for (let i = 0; i < strip.coast.seg.length; i += 4) { + const s = strip.coast.seg; + longest = Math.max(longest, Math.hypot(s[i + 2] - s[i], s[i + 3] - s[i + 1])); + } + // Float32 storage: a few millionths of slack on values up to six radians. + expect(longest).toBeLessThanOrEqual(0.02 * RAD + 1e-5); + }); +}); diff --git a/client/src/components/AtlasGlobe/globeMesh.worker.test.ts b/client/src/components/AtlasGlobe/globeMesh.worker.test.ts new file mode 100644 index 000000000..2714ef4e4 --- /dev/null +++ b/client/src/components/AtlasGlobe/globeMesh.worker.test.ts @@ -0,0 +1,119 @@ +// FE-ATLAS2-RENDER-500 to FE-ATLAS2-RENDER-503: the mesh worker, building a layer off the main thread and +// answering each job with the layer (buffers transferred) or the error. +import type { Topology } from 'topojson-specification'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { MeshRequest, MeshResponse } from './globeMesh.worker'; + +const h = vi.hoisted(() => ({ fail: null as unknown })); + +vi.mock('./globeMesh', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + buildLayer: (...args: Parameters) => { + if (h.fail !== null) throw h.fail; + return actual.buildLayer(...args); + }, + }; +}); + +/** Two squares sharing one edge. */ +const TWO_SQUARES: Topology = { + type: 'Topology', + arcs: [ + [ + [10, 0], + [10, 10], + ], + [ + [10, 10], + [0, 10], + [0, 0], + [10, 0], + ], + [ + [10, 0], + [20, 0], + [20, 10], + [10, 10], + ], + ], + objects: { + countries: { + type: 'GeometryCollection', + geometries: [ + { type: 'Polygon', id: 0, arcs: [[0, 1]] }, + { type: 'Polygon', id: 1, arcs: [[~0, 2]] }, + ], + }, + }, +}; + +type Posted = [MeshResponse, Transferable[] | undefined]; +let posted: Posted[]; + +function send(req: MeshRequest): void { + const handler = self.onmessage; + if (!handler) throw new Error('worker installed no message handler'); + handler.call(self, { data: req } as MessageEvent); +} + +beforeAll(async () => { + await import('./globeMesh.worker'); +}); + +beforeEach(() => { + h.fail = null; + posted = []; + vi.spyOn(self, 'postMessage').mockImplementation(((msg: MeshResponse, transfer?: Transferable[]) => { + posted.push([msg, transfer]); + }) as typeof self.postMessage); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('globeMesh.worker', () => { + it('FE-ATLAS2-RENDER-500: answers a job with the built layer, ids offset by idBase', () => { + send({ job: 7, topo: TWO_SQUARES, object: 'countries', maxEdge: 4, idBase: 100 }); + expect(posted).toHaveLength(1); + const [msg] = posted[0]; + expect(msg.job).toBe(7); + expect(msg.error).toBeUndefined(); + const fid = Array.from(msg.layer?.fill.fid ?? []); + expect(new Set(fid)).toEqual(new Set([100, 101])); + expect(msg.layer?.fill.index.length).toBeGreaterThan(0); + // The shared edge is a border, the outer ring the coast. + expect(msg.layer?.borders.count).toBeGreaterThan(0); + expect(msg.layer?.coast.count).toBeGreaterThan(0); + }); + + it('FE-ATLAS2-RENDER-501: transfers the six array buffers instead of copying them', () => { + send({ job: 1, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 }); + const [msg, transfer] = posted[0]; + const layer = msg.layer; + if (!layer) throw new Error('no layer'); + expect(transfer).toEqual([ + layer.fill.ll.buffer, + layer.fill.ref.buffer, + layer.fill.fid.buffer, + layer.fill.index.buffer, + layer.coast.seg.buffer, + layer.borders.seg.buffer, + ]); + }); + + it('FE-ATLAS2-RENDER-502: answers a failing job with its error message', () => { + h.fail = new Error('bad topology'); + send({ job: 3, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 }); + expect(posted).toEqual([[{ job: 3, error: 'bad topology' }, undefined]]); + }); + + it('FE-ATLAS2-RENDER-503: turns a thrown non-error into text', () => { + h.fail = 'out of memory'; + send({ job: 4, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 }); + expect(posted).toEqual([[{ job: 4, error: 'out of memory' }, undefined]]); + }); +}); diff --git a/client/src/components/AtlasGlobe/globeTheme.test.ts b/client/src/components/AtlasGlobe/globeTheme.test.ts new file mode 100644 index 000000000..e783d3c36 --- /dev/null +++ b/client/src/components/AtlasGlobe/globeTheme.test.ts @@ -0,0 +1,75 @@ +// FE-ATLAS2-RENDER-100 to FE-ATLAS2-RENDER-109: the globe's paint, light and dark, and the accent it reads. +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { globeTheme, hexToRgb, rgbToBytes } from './globeTheme'; + +/** What the live stylesheet answers for --accent. */ +function accentToken(value: string): void { + const read = vi.fn((name: string) => (name === '--accent' ? value : '')); + vi.stubGlobal('getComputedStyle', () => ({ getPropertyValue: read }) as unknown as CSSStyleDeclaration); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('hexToRgb', () => { + it('FE-ATLAS2-RENDER-100: reads a six-digit hex colour into 0..1 channels', () => { + expect(hexToRgb('#ff8000')).toEqual([1, 128 / 255, 0]); + }); + + it('FE-ATLAS2-RENDER-101: expands the three-digit short form', () => { + expect(hexToRgb('#0f8')).toEqual([0, 1, 136 / 255]); + }); + + it('FE-ATLAS2-RENDER-102: ignores an alpha channel and surrounding space', () => { + expect(hexToRgb(' #11223380 ')).toEqual([0x11 / 255, 0x22 / 255, 0x33 / 255]); + }); + + it('FE-ATLAS2-RENDER-103: falls back to mid grey for something that is no hex colour', () => { + expect(hexToRgb('#zzzzzz')).toEqual([0.5, 0.5, 0.5]); + }); +}); + +describe('rgbToBytes', () => { + it('FE-ATLAS2-RENDER-104: rounds channels to bytes', () => { + expect(rgbToBytes([1, 0.5, 0])).toEqual([255, 128, 0]); + expect(rgbToBytes(hexToRgb('#123456'))).toEqual([0x12, 0x34, 0x56]); + }); +}); + +describe('globeTheme', () => { + it('FE-ATLAS2-RENDER-105: dark mode is a dark globe with white selection and arcs', () => { + const th = globeTheme(true); + expect(th.dark).toBe(true); + expect(th.selection).toEqual([1, 1, 1, 0.95]); + expect(th.arc).toEqual([0.95, 0.95, 0.95, 0.95]); + expect(Math.max(...th.land)).toBeLessThan(0.3); + expect(Math.max(...th.space0)).toBeLessThan(0.05); + }); + + it('FE-ATLAS2-RENDER-106: dark mode does not take the accent for the selection', () => { + accentToken('#ff0000'); + expect(globeTheme(true).selection).toEqual([1, 1, 1, 0.95]); + }); + + it('FE-ATLAS2-RENDER-107: light mode is a bright globe whose selection is the default accent', () => { + const th = globeTheme(false); + expect(th.dark).toBe(false); + expect(Math.min(...th.land)).toBeGreaterThan(0.9); + const [r, g, b] = hexToRgb('#111827'); + expect(th.selection).toEqual([r, g, b, 0.95]); + }); + + it('FE-ATLAS2-RENDER-108: light mode follows the live --accent token', () => { + accentToken('#4f46e5'); + const [r, g, b] = hexToRgb('#4f46e5'); + expect(globeTheme(false).selection).toEqual([r, g, b, 0.95]); + }); + + it('FE-ATLAS2-RENDER-109: an accent token that is no hex colour keeps the default', () => { + accentToken('rgb(1 2 3)'); + const [r, g, b] = hexToRgb('#111827'); + expect(globeTheme(false).selection).toEqual([r, g, b, 0.95]); + }); +}); diff --git a/client/src/components/Dawarich/useDawarichAtlas.test.ts b/client/src/components/Dawarich/useDawarichAtlas.test.ts new file mode 100644 index 000000000..e984e8895 --- /dev/null +++ b/client/src/components/Dawarich/useDawarichAtlas.test.ts @@ -0,0 +1,435 @@ +// FE-ATLAS2-DATA-140 to FE-ATLAS2-DATA-162: the state behind the Atlas's Dawarich +// questions, "which wishes did I reach?" and "which countries was I in?". +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared'; +import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { DawarichOfflineError, dawarichRepo } from '../../repo/dawarichRepo'; +import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode'; +import { dawarichNotes, useDawarichAtlas } from './useDawarichAtlas'; + +const toast = vi.hoisted(() => ({ + success: vi.fn<(message: string) => void>(), + error: vi.fn<(message: string) => void>(), +})); +vi.mock('../shared/Toast', () => ({ useToast: () => toast })); + +const scan = (): DawarichBucketScan => ({ + matches: [ + { + itemId: 3, + name: 'Uluru', + match: { at: '2026-04-02T08:00:00Z', minutes: 95, distanceMeters: 120, points: 41 }, + alreadyVisited: false, + }, + { + itemId: 5, + name: 'Kata Tjuta', + match: { at: '2026-04-02T08:00:00Z', minutes: 40, distanceMeters: 300, points: 12 }, + alreadyVisited: false, + }, + { + itemId: 6, + name: 'Sydney', + match: { at: '2026-05-10T08:00:00Z', minutes: 60, distanceMeters: 50, points: 20 }, + alreadyVisited: false, + }, + { itemId: 4, name: 'Machu Picchu', match: null, alreadyVisited: false }, + { + itemId: 7, + name: 'Bali', + match: { at: '2025-01-01T08:00:00Z', minutes: 300, distanceMeters: 10, points: 99 }, + alreadyVisited: true, + }, + ], + skippedWithoutCoordinates: 2, + truncated: true, + fetchedAt: '2026-09-13T21:05:00Z', +}); + +const atlas = (): DawarichAtlasSuggestions => ({ + countries: [ + { countryCode: 'DE', sourceName: 'Germany', cities: [], alreadyVisited: false }, + { countryCode: 'FR', sourceName: 'France', cities: [], alreadyVisited: false }, + { countryCode: 'PT', sourceName: 'Portugal', cities: [], alreadyVisited: true }, + ], + unresolved: ['Kosovo', 'Atlantis'], + fetchedAt: '2026-09-13T21:05:00Z', +}); + +const echoT = (key: string, params?: Record): string => + params + ? `${key}:${Object.entries(params) + .map(([k, v]) => `${k}=${v}`) + .join(',')}` + : key; + +/** A promise the test settles by hand, for "while it is still running". */ +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +const toasts = (type: 'success' | 'error') => toast[type].mock.calls.map((c) => c[0]); + +beforeEach(() => { + toast.success.mockReset(); + toast.error.mockReset(); + _resetNetworkMode(); +}); + +afterEach(() => { + vi.restoreAllMocks(); + _resetNetworkMode(); +}); + +describe('before anything is asked', () => { + it('FE-ATLAS2-DATA-140: the wishes tab opens empty, idle and with nothing to confirm', () => { + const { result } = renderHook(() => useDawarichAtlas()); + expect(result.current).toMatchObject({ + tab: 'wishes', + scan: null, + countries: null, + busy: false, + loaded: false, + selected: 0, + anything: false, + writing: false, + }); + expect(result.current.matches).toEqual([]); + expect(result.current.offered).toEqual([]); + expect(dawarichNotes(result.current, echoT)).toEqual([ + `dawarich.bucket.rule:meters=${DAWARICH_BUCKET_MATCH_RADIUS_M},count=${DAWARICH_BUCKET_MATCH_MIN_MINUTES}`, + ]); + }); + + it('FE-ATLAS2-DATA-141: the countries tab can be the first one, with no notes before a read', () => { + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + expect(result.current.tab).toBe('countries'); + expect(result.current.loaded).toBe(false); + expect(dawarichNotes(result.current, echoT)).toEqual([]); + }); +}); + +describe('the wishes', () => { + it('FE-ATLAS2-DATA-142: a scan keeps the found wishes, open ones first, and preselects every open match', async () => { + const run = deferred(); + vi.spyOn(dawarichRepo, 'bucketScan').mockReturnValue(run.promise); + const { result } = renderHook(() => useDawarichAtlas()); + + let pending!: Promise; + act(() => { + pending = result.current.runScan(); + }); + expect(result.current.scanning).toBe(true); + expect(result.current.busy).toBe(true); + + await act(async () => { + run.resolve(scan()); + await pending; + }); + + expect(result.current.scanning).toBe(false); + expect(result.current.loaded).toBe(true); + expect(result.current.anything).toBe(true); + // Machu Picchu has no match and is left out; the latest open one leads, Bali (reached already) goes last. + const ids = result.current.matches.map((m) => m.itemId); + expect(ids).toHaveLength(4); + expect(ids[0]).toBe(6); + expect(ids[3]).toBe(7); + expect(result.current.openMatches.map((m) => m.itemId).sort((a, b) => a - b)).toEqual([3, 5, 6]); + expect([...result.current.picked].sort((a, b) => a - b)).toEqual([3, 5, 6]); + expect(result.current.selected).toBe(3); + }); + + it('FE-ATLAS2-DATA-143: the notes name skipped wishes, a truncated scan and the rule', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + expect(dawarichNotes(result.current, echoT)).toEqual([ + 'dawarich.bucket.skipped:count=2', + 'dawarich.bucket.truncated', + `dawarich.bucket.rule:meters=${DAWARICH_BUCKET_MATCH_RADIUS_M},count=${DAWARICH_BUCKET_MATCH_MIN_MINUTES}`, + ]); + }); + + it('FE-ATLAS2-DATA-144: a scan with nothing found has nothing to confirm and no skipped note', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue({ + matches: [{ itemId: 1, name: 'X', match: null, alreadyVisited: false }], + skippedWithoutCoordinates: 0, + truncated: false, + fetchedAt: 'now', + }); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + expect(result.current.loaded).toBe(true); + expect(result.current.anything).toBe(false); + expect(result.current.selected).toBe(0); + expect(dawarichNotes(result.current, echoT)).toHaveLength(1); + }); + + it('FE-ATLAS2-DATA-145: a wish can be unticked and ticked again', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + + act(() => result.current.togglePicked(3)); + expect(result.current.picked.has(3)).toBe(false); + expect(result.current.selected).toBe(2); + act(() => result.current.togglePicked(3)); + expect(result.current.picked.has(3)).toBe(true); + }); + + it('FE-ATLAS2-DATA-146: confirming ticks the wishes off once per day, says how many, and marks them reached', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const confirm = vi + .spyOn(dawarichRepo, 'confirmBucketVisits') + .mockImplementation(async (ids) => ({ updated: ids.length })); + const onChanged = vi.fn(); + const { result } = renderHook(() => useDawarichAtlas({ onChanged })); + await act(() => result.current.runScan()); + + await act(() => result.current.confirmWishes()); + + expect(confirm).toHaveBeenCalledTimes(2); + expect(confirm).toHaveBeenCalledWith([6], '2026-05-10T08:00:00Z'); + const april = confirm.mock.calls.find((c) => c[1] === '2026-04-02T08:00:00Z'); + expect([...(april?.[0] ?? [])].sort((a, b) => a - b)).toEqual([3, 5]); + expect(toasts('success')).toEqual(['dawarich.bucket.confirmed']); + expect(result.current.openMatches).toEqual([]); + expect(result.current.picked.size).toBe(0); + expect(result.current.writing).toBe(false); + expect(onChanged).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-DATA-147: only the ticked wishes are confirmed and marked', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const confirm = vi.spyOn(dawarichRepo, 'confirmBucketVisits').mockResolvedValue({ updated: 1 }); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + act(() => result.current.togglePicked(3)); + act(() => result.current.togglePicked(5)); + + await act(() => result.current.confirmWishes()); + + expect(confirm).toHaveBeenCalledTimes(1); + expect(confirm).toHaveBeenCalledWith([6], '2026-05-10T08:00:00Z'); + expect(result.current.openMatches.map((m) => m.itemId).sort((a, b) => a - b)).toEqual([3, 5]); + }); + + it('FE-ATLAS2-DATA-148: nothing ticked, nothing is sent', async () => { + const confirm = vi.spyOn(dawarichRepo, 'confirmBucketVisits'); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.confirmWishes()); + expect(confirm).not.toHaveBeenCalled(); + expect(toast.error).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-DATA-149: offline, confirming says so and sends nothing', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const confirm = vi.spyOn(dawarichRepo, 'confirmBucketVisits'); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + setForcedOffline(true); + + await act(() => result.current.confirmWishes()); + + expect(confirm).not.toHaveBeenCalled(); + expect(toasts('error')).toEqual(['dawarich.error.offline']); + expect(result.current.picked.size).toBe(3); + }); + + it('FE-ATLAS2-DATA-150: a failed confirmation shows the server text and keeps the selection', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + vi.spyOn(dawarichRepo, 'confirmBucketVisits').mockRejectedValue({ response: { data: { error: 'Item gone' } } }); + const onChanged = vi.fn(); + const { result } = renderHook(() => useDawarichAtlas({ onChanged })); + await act(() => result.current.runScan()); + + await act(() => result.current.confirmWishes()); + + expect(toasts('error')).toEqual(['Item gone']); + expect(result.current.picked.size).toBe(3); + expect(result.current.writing).toBe(false); + expect(onChanged).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-DATA-151: a second confirm while one is on its way is not sent', async () => { + vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const first = deferred<{ updated: number }>(); + const confirm = vi.spyOn(dawarichRepo, 'confirmBucketVisits').mockReturnValue(first.promise); + const { result } = renderHook(() => useDawarichAtlas()); + await act(() => result.current.runScan()); + + let pending!: Promise; + act(() => { + pending = result.current.confirmWishes(); + }); + expect(result.current.writing).toBe(true); + const callsBefore = confirm.mock.calls.length; + await act(() => result.current.confirmWishes()); + expect(confirm.mock.calls.length).toBe(callsBefore); + + await act(async () => { + first.resolve({ updated: 1 }); + await pending; + }); + expect(result.current.writing).toBe(false); + }); + + it('FE-ATLAS2-DATA-152: a failed scan names why: offline, the server text, or unknown', async () => { + const scanSpy = vi.spyOn(dawarichRepo, 'bucketScan'); + const { result } = renderHook(() => useDawarichAtlas()); + + scanSpy.mockRejectedValueOnce(new DawarichOfflineError()); + await act(() => result.current.runScan()); + scanSpy.mockRejectedValueOnce({ response: { data: { error: 'Dawarich said no' } } }); + await act(() => result.current.runScan()); + scanSpy.mockRejectedValueOnce({ response: { data: { error: 42 } } }); + await act(() => result.current.runScan()); + scanSpy.mockRejectedValueOnce(null); + await act(() => result.current.runScan()); + + expect(toasts('error')).toEqual([ + 'dawarich.error.offline', + 'Dawarich said no', + 'dawarich.error.unknown', + 'dawarich.error.unknown', + ]); + expect(result.current.scanning).toBe(false); + expect(result.current.scan).toBeNull(); + }); +}); + +describe('the countries', () => { + it('FE-ATLAS2-DATA-153: loading asks for the last year and preselects the countries not on the map yet', async () => { + const load = deferred(); + const suggest = vi.spyOn(dawarichRepo, 'atlasSuggestions').mockReturnValue(load.promise); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + + let pending!: Promise; + act(() => { + pending = result.current.loadCountries(); + }); + expect(result.current.loadingCountries).toBe(true); + expect(result.current.busy).toBe(true); + await act(async () => { + load.resolve(atlas()); + await pending; + }); + + const [from, to] = suggest.mock.calls[0]; + expect(Date.parse(to) - Date.parse(from)).toBe(365 * 24 * 60 * 60 * 1000); + expect(result.current.loadingCountries).toBe(false); + expect(result.current.loaded).toBe(true); + expect(result.current.offered.map((c) => c.countryCode)).toEqual(['DE', 'FR']); + expect([...result.current.pickedCountries]).toEqual(['DE', 'FR']); + expect(result.current.selected).toBe(2); + expect(result.current.anything).toBe(true); + expect(dawarichNotes(result.current, echoT)).toEqual([ + 'dawarich.atlas.unresolved:names=Kosovo, Atlantis', + 'dawarich.atlas.window', + ]); + }); + + it('FE-ATLAS2-DATA-154: without unresolved names only the window note shows', async () => { + vi.spyOn(dawarichRepo, 'atlasSuggestions').mockResolvedValue({ ...atlas(), unresolved: [] }); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + await act(() => result.current.loadCountries()); + expect(dawarichNotes(result.current, echoT)).toEqual(['dawarich.atlas.window']); + }); + + it('FE-ATLAS2-DATA-155: a country can be unticked', async () => { + vi.spyOn(dawarichRepo, 'atlasSuggestions').mockResolvedValue(atlas()); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + await act(() => result.current.loadCountries()); + act(() => result.current.togglePickedCountry('DE')); + expect([...result.current.pickedCountries]).toEqual(['FR']); + act(() => result.current.togglePickedCountry('DE')); + expect(result.current.pickedCountries.has('DE')).toBe(true); + }); + + it('FE-ATLAS2-DATA-156: accepting marks the ticked countries, says how many and puts them on the map', async () => { + vi.spyOn(dawarichRepo, 'atlasSuggestions').mockResolvedValue(atlas()); + const accept = vi.spyOn(dawarichRepo, 'acceptAtlasCountries').mockResolvedValue({ marked: 1 }); + const onChanged = vi.fn(); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries', onChanged })); + await act(() => result.current.loadCountries()); + act(() => result.current.togglePickedCountry('FR')); + + await act(() => result.current.confirmCountries()); + + expect(accept).toHaveBeenCalledWith(['DE']); + expect(toasts('success')).toEqual(['dawarich.atlas.accepted']); + expect(result.current.offered.map((c) => c.countryCode)).toEqual(['FR']); + expect(result.current.pickedCountries.size).toBe(0); + expect(onChanged).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-DATA-157: nothing ticked, or offline, nothing is accepted', async () => { + const accept = vi.spyOn(dawarichRepo, 'acceptAtlasCountries'); + vi.spyOn(dawarichRepo, 'atlasSuggestions').mockResolvedValue(atlas()); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + await act(() => result.current.confirmCountries()); + expect(toast.error).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + + await act(() => result.current.loadCountries()); + setForcedOffline(true); + await act(() => result.current.confirmCountries()); + + expect(accept).not.toHaveBeenCalled(); + expect(toasts('error')).toEqual(['dawarich.error.offline']); + }); + + it('FE-ATLAS2-DATA-158: a failed accept or load is reported and leaves the state as it was', async () => { + const suggest = vi.spyOn(dawarichRepo, 'atlasSuggestions').mockRejectedValueOnce(new DawarichOfflineError()); + const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' })); + await act(() => result.current.loadCountries()); + expect(result.current.countries).toBeNull(); + expect(result.current.loadingCountries).toBe(false); + + suggest.mockResolvedValueOnce(atlas()); + await act(() => result.current.loadCountries()); + vi.spyOn(dawarichRepo, 'acceptAtlasCountries').mockRejectedValue(new Error('boom')); + await act(() => result.current.confirmCountries()); + + expect(toasts('error')).toEqual(['dawarich.error.offline', 'dawarich.error.unknown']); + expect(result.current.pickedCountries.size).toBe(2); + expect(result.current.writing).toBe(false); + }); +}); + +describe('the open tab', () => { + it('FE-ATLAS2-DATA-159: run and confirm follow the open tab', async () => { + const scanSpy = vi.spyOn(dawarichRepo, 'bucketScan').mockResolvedValue(scan()); + const suggest = vi.spyOn(dawarichRepo, 'atlasSuggestions').mockResolvedValue(atlas()); + const confirm = vi.spyOn(dawarichRepo, 'confirmBucketVisits').mockResolvedValue({ updated: 1 }); + const accept = vi.spyOn(dawarichRepo, 'acceptAtlasCountries').mockResolvedValue({ marked: 2 }); + const { result } = renderHook(() => useDawarichAtlas()); + + act(() => result.current.run()); + await waitFor(() => expect(result.current.loaded).toBe(true)); + expect(scanSpy).toHaveBeenCalledTimes(1); + expect(suggest).not.toHaveBeenCalled(); + act(() => result.current.confirm()); + await waitFor(() => expect(result.current.picked.size).toBe(0)); + expect(confirm).toHaveBeenCalled(); + + act(() => result.current.setTab('countries')); + expect(result.current.loaded).toBe(false); + act(() => result.current.run()); + await waitFor(() => expect(result.current.loaded).toBe(true)); + expect(suggest).toHaveBeenCalledTimes(1); + act(() => result.current.confirm()); + await waitFor(() => expect(result.current.pickedCountries.size).toBe(0)); + expect(accept).toHaveBeenCalledWith(['DE', 'FR']); + }); +}); diff --git a/client/src/components/Packing/usePackingBags.kept.test.ts b/client/src/components/Packing/usePackingBags.kept.test.ts new file mode 100644 index 000000000..4f8e3a817 --- /dev/null +++ b/client/src/components/Packing/usePackingBags.kept.test.ts @@ -0,0 +1,94 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { packingApi } from '../../api/client'; +import { _resetNetworkMode } from '../../sync/networkMode'; +import type { PackingBag } from '../../types'; +import { BAG_COLORS } from './packingListPanel.constants'; +import { usePackingBags, warmPackingBags } from './usePackingBags'; + +vi.mock('./useBagTotalsPing', () => ({ useBagTotalsPing: vi.fn() })); + +// FE-ATLAS2-REST-020 to 024: bags read ahead per trip (warmPackingBags), taken once by the list. +// Each test uses its own trip id, since a warm read waits in the module until a list takes it. + +const t = (key: string) => key; +const bag = (over: Partial): PackingBag => ({ + id: 1, + trip_id: 1, + name: 'Backpack', + color: BAG_COLORS[0], + sort_order: 0, + ...over, +}); + +function setup(tripId: number, bagTrackingEnabled = true) { + const toast = { error: vi.fn() }; + return renderHook(() => usePackingBags({ tripId, bagTrackingEnabled, t, toast })); +} + +beforeEach(() => { + _resetNetworkMode(); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('kept packing bags', () => { + it('FE-ATLAS2-REST-020: a list opened after warmPackingBags starts with the bags read ahead', async () => { + const warm = bag({ id: 11, trip_id: 101, name: 'Ahead' }); + const list = vi.spyOn(packingApi, 'listBags').mockResolvedValue({ bags: [warm], unassigned_weight_grams: 300 }); + await warmPackingBags(101); + expect(list).toHaveBeenCalledWith(101); + + // The read that follows the mount never answers here: what shows comes from the warm read alone. + list.mockReturnValue(new Promise(() => {})); + const { result } = setup(101); + expect(result.current.bags).toEqual([warm]); + expect(result.current.unassignedWeightGrams).toBe(300); + }); + + it('FE-ATLAS2-REST-021: a warm read without bags or server sum keeps an empty list and an unknown sum', async () => { + vi.spyOn(packingApi, 'listBags').mockResolvedValue({} as Awaited>); + await warmPackingBags(102); + const { result } = setup(102, false); + expect(result.current.bags).toEqual([]); + expect(result.current.unassignedWeightGrams).toBeNull(); + }); + + it('FE-ATLAS2-REST-022: a failed warm read rejects and leaves nothing kept for the trip', async () => { + vi.spyOn(packingApi, 'listBags').mockRejectedValue(new Error('offline')); + await expect(warmPackingBags(103)).rejects.toThrow('offline'); + const { result } = setup(103, false); + expect(result.current.bags).toEqual([]); + expect(result.current.unassignedWeightGrams).toBeNull(); + }); + + it('FE-ATLAS2-REST-023: a warm read is taken once; the next list on the trip starts empty and reads afresh', async () => { + const ahead = bag({ id: 21, trip_id: 104, name: 'Duffel' }); + const list = vi.spyOn(packingApi, 'listBags').mockResolvedValue({ bags: [ahead], unassigned_weight_grams: 1200 }); + await warmPackingBags(104); + list.mockReturnValue(new Promise(() => {})); + const one = setup(104); + expect(one.result.current.bags).toEqual([ahead]); + one.unmount(); + + const again = setup(104, false); + await act(async () => {}); + expect(again.result.current.bags).toEqual([]); + expect(again.result.current.unassignedWeightGrams).toBeNull(); + }); + + it('FE-ATLAS2-REST-024: the kept bags belong to their trip and never show on another one', async () => { + const mine = bag({ id: 31, trip_id: 105 }); + vi.spyOn(packingApi, 'listBags').mockResolvedValue({ bags: [mine], unassigned_weight_grams: 5 }); + await warmPackingBags(105); + const other = setup(106, false); + // And a list with bag tracking off does not take them either. + const off = setup(105, false); + expect(off.result.current.bags).toEqual([]); + expect(other.result.current.bags).toEqual([]); + expect(other.result.current.unassignedWeightGrams).toBeNull(); + }); +}); diff --git a/client/src/mobile/screens/atlas/MAtlasCountrySheets.test.tsx b/client/src/mobile/screens/atlas/MAtlasCountrySheets.test.tsx new file mode 100644 index 000000000..12b1bf0ea --- /dev/null +++ b/client/src/mobile/screens/atlas/MAtlasCountrySheets.test.tsx @@ -0,0 +1,151 @@ +import { useLocation } from 'react-router'; +import { describe, expect, it, vi } from 'vitest'; +import { buildAtlasData } from '../../../../tests/helpers/atlas'; +import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen, within } from '../../../../tests/helpers/render'; +import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe'; +import MAtlasCountrySheets from './MAtlasCountrySheets'; + +type PopupAtlas = Record & { setConfirmAction: (v: unknown) => void }; + +// The popup has its own test; here what matters is what it is handed. +const popup = vi.hoisted(() => ({ atlas: null as PopupAtlas | null })); +vi.mock('./MAtlasCountryPopup', () => ({ + default: ({ atlas }: { atlas: PopupAtlas }) => { + popup.atlas = atlas; + return null; + }, +})); +vi.mock('../../../components/Atlas/AtlasCountryPlaces', () => ({ + default: ({ variant, onOpenTrip }: { variant: string; onOpenTrip: (id: number) => void }) => ( + + ), +})); + +function Where() { + return {useLocation().pathname}; +} + +function show(s: AtlasGlobeState) { + return render( + <> + + + + ); +} + +const DETAIL = { + a2: 'FR', + data: { + places: [{ trip_id: 1 }], + trips: [ + { id: 1, title: 'With places' }, + { id: 2, title: 'Without places' }, + ], + manually_marked: true, + }, +}; + +describe('MAtlasCountrySheets', () => { + it('FE-ATLAS2-MOBILE-180: the popup gets the globe state under the names it reads', () => { + const s = buildGlobeState({ regions: { FR: [] }, bucket: [{ id: 1 }] }); + show(s); + const atlas = popup.atlas as PopupAtlas; + expect(atlas.t).toBe(s.t); + expect(atlas.confirmAction).toBe(s.confirmAction); + expect(atlas.visitedRegions).toBe(s.regions); + expect(atlas.setVisitedRegions).toBe(s.setRegions); + expect(atlas.bucketList).toBe(s.bucket); + expect(atlas.setBucketList).toBe(s.setBucket); + expect(atlas.handleDeleteBucketItem).toBe(s.handleDeleteBucketItem); + expect(atlas.executeConfirmAction).toBe(s.executeConfirmAction); + expect(atlas.setData).toBe(s.setData); + }); + + it('FE-ATLAS2-MOBILE-181: closing the popup also closes the dialogs, a new action or an updater does not', () => { + const s = buildGlobeState(); + show(s); + const atlas = popup.atlas as PopupAtlas; + const next = { code: 'FR', name: 'France', type: 'choose' }; + atlas.setConfirmAction(next); + expect(s.setConfirmAction).toHaveBeenLastCalledWith(next); + const updater = () => null; + atlas.setConfirmAction(updater); + expect(s.setConfirmAction).toHaveBeenLastCalledWith(updater); + expect(s.closeDialogs).not.toHaveBeenCalled(); + atlas.setConfirmAction(null); + expect(s.setConfirmAction).toHaveBeenLastCalledWith(null); + expect(s.closeDialogs).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-182: no country open, no country sheet', () => { + show(buildGlobeState()); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-183: while the country loads it shows its name, its counts and a spinner', () => { + const s = buildGlobeState({ detail: { a2: 'FR', data: null } }); + show(s); + const sheet = screen.getByRole('dialog', { name: 'name-FR' }); + expect(within(sheet).getByText('name-FR')).toBeInTheDocument(); + expect(within(sheet).getByText('2 atlas.trips:2, 5 atlas.places:5')).toBeInTheDocument(); + expect(sheet.querySelector('.animate-spin')).not.toBeNull(); + // Visited, so not marked as planned; nothing marked by hand to take off. + expect(within(sheet).queryByText('atlas.planned')).toBeNull(); + expect(within(sheet).queryByText('atlas.unmark')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-184: a planned country carries the planned mark', () => { + const data = buildAtlasData({ + countries: [{ code: 'FR', tripCount: 1, placeCount: 0, firstVisit: null, lastVisit: null, status: 'planned' }], + }); + show(buildGlobeState({ data, detail: { a2: 'FR', data: null } })); + expect(screen.getByText('atlas.planned')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-185: a country the data does not list shows no counts', () => { + show(buildGlobeState({ detail: { a2: 'JP', data: null } })); + const sheet = screen.getByRole('dialog', { name: 'name-JP' }); + expect(within(sheet).queryByText(/atlas\.trips/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-186: the regions visited show as a share, none at all hide it', () => { + const { unmount } = show( + buildGlobeState({ detail: { a2: 'FR', data: null }, progress: { visited: 3, total: 12 } }) + ); + expect(screen.getByText('3 / 12')).toBeInTheDocument(); + expect(screen.getByText('atlas.regions')).toBeInTheDocument(); + unmount(); + show(buildGlobeState({ detail: { a2: 'FR', data: null }, progress: { visited: 0, total: 0 } })); + expect(screen.queryByText('atlas.regions')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-187: trips without places sit as chips that open the trip, the places list opens its own', () => { + show(buildGlobeState({ detail: DETAIL })); + expect(screen.queryByText('With places')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Without places' })); + expect(screen.getByTestId('where').textContent).toBe('/trips/2'); + fireEvent.click(screen.getByRole('button', { name: 'places:mobile' })); + expect(screen.getByTestId('where').textContent).toBe('/trips/5'); + }); + + it('FE-ATLAS2-MOBILE-188: a country marked by hand can have the mark taken off, the close button closes', () => { + const s = buildGlobeState({ detail: DETAIL }); + show(s); + fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' })); + expect(s.askUnmarkDetail).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(s.closeDialogs).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-189: every trip with places leaves no chip row', () => { + const detail = { a2: 'FR', data: { places: [{ trip_id: 1 }], trips: [{ id: 1, title: 'With places' }] } }; + show(buildGlobeState({ detail })); + const sheet = screen.getByRole('dialog', { name: 'name-FR' }); + expect(within(sheet).queryByRole('button', { name: 'With places' })).toBeNull(); + expect(within(sheet).getByRole('button', { name: 'places:mobile' })).toBeInTheDocument(); + }); +}); diff --git a/client/src/mobile/screens/atlas/MAtlasGlobe.test.tsx b/client/src/mobile/screens/atlas/MAtlasGlobe.test.tsx new file mode 100644 index 000000000..5617a4437 --- /dev/null +++ b/client/src/mobile/screens/atlas/MAtlasGlobe.test.tsx @@ -0,0 +1,216 @@ +import { useLocation } from 'react-router'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAtlasData } from '../../../../tests/helpers/atlas'; +import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState'; +import { act, fireEvent, render, screen } from '../../../../tests/helpers/render'; +import type { GlobeEngine } from '../../../components/AtlasGlobe/GlobeEngine'; +import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe'; +import MAtlasGlobe from './MAtlasGlobe'; + +interface GlobeProps { + fetchJson: unknown; + dark: boolean; + insetBottom: number; + paintKey: unknown; + onFrame: (e: GlobeEngine) => void; + onError: (err: unknown) => void; +} + +// jsdom has no WebGL: the globe, its sky and its pins are stand-ins that keep +// what they were handed, the overlays around them have their own tests. +const fake = vi.hoisted(() => ({ + state: null as unknown, + hookArgs: [] as Array>, + statsArg: null as unknown, + globe: null as GlobeProps | null, + skyLayout: [] as unknown[], + pinsLayout: [] as unknown[], + focus: [] as number[], +})); + +vi.mock('../../../pages/atlas/useAtlasGlobe', () => ({ + useAtlasGlobe: (refs: Record) => { + fake.hookArgs.push(refs); + return fake.state; + }, +})); +vi.mock('../../../pages/atlas/useGlobeStats', () => ({ + useGlobeStats: (s: unknown) => { + fake.statsArg = s; + return [{ key: 'countries' }]; + }, +})); +vi.mock('../../../components/AtlasGlobe/AtlasGlobe', () => ({ + default: (props: GlobeProps) => { + fake.globe = props; + return
; + }, +})); +vi.mock('../../../components/AtlasGlobe/GlobeSky', async () => { + const { forwardRef, useImperativeHandle } = await import('react'); + return { + default: forwardRef(function Sky(_props, ref) { + useImperativeHandle(ref, () => ({ layout: (e: unknown) => fake.skyLayout.push(e) })); + return null; + }), + }; +}); +vi.mock('../../../components/AtlasGlobe/GlobePins', async () => { + const { forwardRef, useImperativeHandle } = await import('react'); + return { + default: forwardRef(function Pins(_props, ref) { + useImperativeHandle(ref, () => ({ layout: (e: unknown) => fake.pinsLayout.push(e) })); + return null; + }), + }; +}); +vi.mock('../../../pages/atlas/AtlasGlobeSearch', () => ({ + default: ({ focusSignal }: { focusSignal: number }) => { + fake.focus.push(focusSignal); + return

search:{focusSignal}

; + }, +})); +vi.mock('../../../pages/atlas/AtlasGlobeStatus', () => ({ default: () => null })); +vi.mock('../../../pages/atlas/AtlasGlobeTimeline', () => ({ default: () => null })); +vi.mock('../../../pages/atlas/AtlasBadgeUnlock', () => ({ default: () => null })); +vi.mock('./MAtlasCountrySheets', () => ({ default: () => null })); +vi.mock('./hub/MAtlasHub', () => ({ default: () => null })); +vi.mock('./MAtlasStatsCard', () => ({ + default: ({ stats }: { stats: unknown[] }) =>

stats:{stats.length}

, +})); +vi.mock('./MAtlasLayersSheet', () => ({ + default: ({ open, onClose }: { open: boolean; onClose: () => void }) => + open ? ( + + ) : null, +})); + +function Where() { + const l = useLocation(); + return {`${l.pathname}${l.search}`}; +} + +function show(s: AtlasGlobeState, url = '/atlas') { + fake.state = s; + return render( + <> + + + , + { initialEntries: [url] } + ); +} + +beforeEach(() => { + fake.hookArgs = []; + fake.globe = null; + fake.skyLayout = []; + fake.pinsLayout = []; + fake.focus = []; +}); + +describe('MAtlasGlobe', () => { + it('FE-ATLAS2-MOBILE-200: the globe gets the state, dark and room for the cards at the foot', () => { + const s = buildGlobeState(); + show(s); + expect(screen.getByTestId('globe')).toBeInTheDocument(); + const globe = fake.globe as GlobeProps; + expect(globe.fetchJson).toBe(s.fetchJson); + expect(globe.paintKey).toBe('k'); + expect(globe.dark).toBe(true); + expect(globe.insetBottom).toBe(170); + expect(Object.keys(fake.hookArgs[0] ?? {}).sort()).toEqual(['globeRef', 'skyRef']); + expect(fake.statsArg).toBe(s); + expect(screen.getByText('stats:1')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-201: every frame lays out the sky and the pins on the engine', () => { + show(buildGlobeState()); + const engine = { id: 'engine' } as unknown as GlobeEngine; + act(() => (fake.globe as GlobeProps).onFrame(engine)); + expect(fake.skyLayout).toEqual([engine]); + expect(fake.pinsLayout).toEqual([engine]); + }); + + it('FE-ATLAS2-MOBILE-202: a globe error is kept as its message, whatever was thrown', () => { + const s = buildGlobeState(); + show(s); + const globe = fake.globe as GlobeProps; + globe.onError(new Error('no webgl')); + expect(s.setError).toHaveBeenLastCalledWith('no webgl'); + globe.onError('lost context'); + expect(s.setError).toHaveBeenLastCalledWith('lost context'); + }); + + it('FE-ATLAS2-MOBILE-203: the hub button opens the hub on its last tab and lights up while it is open', () => { + const s = buildGlobeState({ passportTab: 'badges' }); + const { unmount } = show(s); + const hub = screen.getByRole('button', { name: 'atlas.globe.hub' }); + expect(hub.className).toContain('text-content-secondary'); + fireEvent.click(hub); + expect(s.openPassport).toHaveBeenCalledWith('badges'); + unmount(); + show(buildGlobeState({ passportOpen: true })); + expect(screen.getByRole('button', { name: 'atlas.globe.hub' }).className).toContain('bg-accent'); + }); + + it('FE-ATLAS2-MOBILE-204: the layers button opens the layers sheet, which closes again', () => { + show(buildGlobeState()); + const layers = screen.getByRole('button', { name: 'atlas.globe.layers' }); + expect(screen.queryByText('close layers')).toBeNull(); + fireEvent.click(layers); + expect(layers.className).toContain('bg-accent'); + fireEvent.click(screen.getByText('close layers')); + expect(screen.queryByText('close layers')).toBeNull(); + expect(layers.className).not.toContain('bg-accent'); + }); + + it('FE-ATLAS2-MOBILE-205: ?search=1 from the dock is taken off the address and focuses the search', () => { + show(buildGlobeState(), '/atlas?search=1&year=2024'); + expect(screen.getByText('search:1')).toBeInTheDocument(); + expect(screen.getByTestId('where').textContent).toBe('/atlas?year=2024'); + }); + + it('FE-ATLAS2-MOBILE-206: without the hand-over the search is left alone', () => { + show(buildGlobeState(), '/atlas?year=2024'); + expect(screen.getByText('search:0')).toBeInTheDocument(); + expect(fake.focus.every((n) => n === 0)).toBe(true); + expect(screen.getByTestId('where').textContent).toBe('/atlas?year=2024'); + }); + + it('FE-ATLAS2-MOBILE-207: no comparison, no compare bar', () => { + show(buildGlobeState()); + expect(screen.queryByText(/atlas\.globe\.compareWith/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-208: comparing counts the countries shared, theirs alone and mine alone', () => { + const data = buildAtlasData({ + countries: [ + { code: 'FR', tripCount: 1, placeCount: 1, status: 'visited' }, + { code: 'DE', tripCount: 1, placeCount: 1 }, + { code: 'IT', tripCount: 1, placeCount: 0, status: 'planned' }, + ], + }); + const s = buildGlobeState({ data, compareWith: { username: 'ann', codes: ['FR', 'JP', 'IT'] } }); + show(s); + expect(screen.getByText('atlas.globe.compareWith:ann')).toBeInTheDocument(); + const count = (label: string) => screen.getByText(label).parentElement?.querySelector('b')?.textContent; + expect(count('atlas.globe.together')).toBe('1'); + expect(count('atlas.globe.onlyThem:ann')).toBe('2'); + expect(count('atlas.globe.onlyYou')).toBe('1'); + }); + + it('FE-ATLAS2-MOBILE-209: the gaps switch flips and the close button ends the comparison', () => { + const s = buildGlobeState({ compareWith: { username: 'ann', codes: [] }, gaps: true, data: null }); + show(s); + const gaps = screen.getByRole('button', { name: 'atlas.globe.gaps' }); + expect(gaps).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(gaps); + expect(s.setGaps).toHaveBeenCalledWith(false); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(s.stopCompare).toHaveBeenCalledOnce(); + expect(screen.getByText('atlas.globe.together').parentElement?.querySelector('b')?.textContent).toBe('0'); + }); +}); diff --git a/client/src/mobile/screens/atlas/MAtlasLayersSheet.test.tsx b/client/src/mobile/screens/atlas/MAtlasLayersSheet.test.tsx new file mode 100644 index 000000000..698ecedb0 --- /dev/null +++ b/client/src/mobile/screens/atlas/MAtlasLayersSheet.test.tsx @@ -0,0 +1,72 @@ +import { describe, expect, it, vi } from 'vitest'; +import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen } from '../../../../tests/helpers/render'; +import MAtlasLayersSheet from './MAtlasLayersSheet'; + +describe('MAtlasLayersSheet', () => { + it('FE-ATLAS2-MOBILE-220: closed, the sheet renders nothing', () => { + render(); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-221: without flights or plugins only the planned switch stands there, and it flips', () => { + const s = buildGlobeState({ showPlanned: true }); + render(); + expect(screen.getByRole('dialog', { name: 'atlas.globe.layers' })).toBeInTheDocument(); + const switches = screen.getAllByRole('switch'); + expect(switches).toHaveLength(1); + expect(switches[0]).toHaveAccessibleName('atlas.showPlanned'); + expect(switches[0]).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(switches[0] as HTMLElement); + expect(s.setShowPlanned).toHaveBeenCalledWith(false); + }); + + it('FE-ATLAS2-MOBILE-222: flights with routes add their switch, an empty flight list does not', () => { + const s = buildGlobeState({ flights: { routes: [{ id: 1 }] }, showFlights: false }); + const { unmount } = render(); + const flights = screen.getByRole('switch', { name: 'atlas.globe.flights' }); + expect(flights).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(flights); + expect(s.setShowFlights).toHaveBeenCalledWith(true); + unmount(); + render(); + expect(screen.queryByRole('switch', { name: 'atlas.globe.flights' })).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-223: every plugin layer is a switch by its name or id, off when hidden', () => { + const s = buildGlobeState({ + pluginLayers: [ + { pluginId: 'p', id: 'rain', name: 'Rain' }, + { pluginId: 'p', id: 'wind', name: '' }, + ], + hiddenPluginLayers: new Set(['p:wind']), + }); + render(); + expect(screen.getByRole('switch', { name: 'Rain' })).toHaveAttribute('aria-checked', 'true'); + const wind = screen.getByRole('switch', { name: 'wind' }); + expect(wind).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(wind); + expect(s.togglePluginLayer).toHaveBeenCalledWith('p:wind'); + }); + + it('FE-ATLAS2-MOBILE-224: the colouring is a segmented choice of country, status and year', () => { + const s = buildGlobeState({ colorMode: 'status' }); + render(); + expect(screen.getByText('atlas.globe.colorBy')).toBeInTheDocument(); + expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual([ + 'atlas.globe.colorCountry', + 'atlas.globe.colorStatus', + 'atlas.globe.colorYear', + ]); + expect(screen.getByRole('tab', { name: 'atlas.globe.colorStatus' })).toHaveAttribute('aria-selected', 'true'); + fireEvent.click(screen.getByRole('tab', { name: 'atlas.globe.colorYear' })); + expect(s.setColorMode).toHaveBeenCalledWith('year'); + }); + + it('FE-ATLAS2-MOBILE-225: the close button closes the sheet', () => { + const onClose = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(onClose).toHaveBeenCalledOnce(); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MAtlasHub.test.tsx b/client/src/mobile/screens/atlas/hub/MAtlasHub.test.tsx new file mode 100644 index 000000000..773f18ca7 --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MAtlasHub.test.tsx @@ -0,0 +1,85 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render'; +import { resetAllStores, seedInstanceAddons } from '../../../../../tests/helpers/store'; +import type { AtlasHubTab } from '../../../../pages/atlas/useAtlasGlobe'; +import MAtlasHub from './MAtlasHub'; + +// Each tab has its own test; the hub only decides which one stands in the sheet. +vi.mock('./MHubOverview', () => ({ default: () =>

tab:overview

})); +vi.mock('./MHubBadges', () => ({ default: () =>

tab:badges

})); +vi.mock('./MHubWishlist', () => ({ default: () =>

tab:wishlist

})); +vi.mock('./MHubDawarich', () => ({ default: () =>

tab:dawarich

})); +vi.mock('./MHubTours', () => ({ default: () =>

tab:tours

})); +vi.mock('./MHubTravellers', () => ({ default: () =>

tab:travellers

})); + +const BADGES = [{ earned: true }, { earned: false }]; + +afterEach(() => { + resetAllStores(); +}); + +describe('MAtlasHub', () => { + it('FE-ATLAS2-MOBILE-160: a closed hub renders nothing', () => { + render(); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-161: the open hub names itself, counts the badges and shows the three tabs every Atlas has', () => { + render(); + const sheet = screen.getByRole('dialog', { name: 'atlas.globe.hub' }); + expect(within(sheet).getByText('atlas.globe.collected:1,2')).toBeInTheDocument(); + const chips = within(within(sheet).getByRole('group', { name: 'atlas.globe.hub' })).getAllByRole('button'); + expect(chips.map((c) => c.textContent?.trim())).toEqual([ + 'atlas.statsTab', + 'atlas.globe.badges', + 'atlas.bucketTab', + ]); + expect(within(sheet).getByRole('button', { name: 'atlas.statsTab' })).toHaveAttribute('aria-pressed', 'true'); + }); + + it('FE-ATLAS2-MOBILE-162: Dawarich, tours and comparing each add their tab', () => { + seedInstanceAddons(['tours']); + render(); + const chips = within(screen.getByRole('group', { name: 'atlas.globe.hub' })).getAllByRole('button'); + expect(chips.map((c) => c.textContent?.trim())).toEqual([ + 'atlas.statsTab', + 'atlas.globe.badges', + 'atlas.bucketTab', + 'dawarich.title', + 'tours.mode.tours', + 'atlas.globe.travellers', + ]); + }); + + const TABS: Array<[string, AtlasHubTab]> = [ + ['163', 'overview'], + ['166', 'badges'], + ['167', 'wishlist'], + ['168', 'dawarich'], + ['169', 'tours'], + ['170', 'travellers'], + ]; + for (const [id, tab] of TABS) { + it(`FE-ATLAS2-MOBILE-${id}: the ${tab} tab stands in the sheet when it is the open one`, () => { + render(); + expect(screen.getByText(`tab:${tab}`)).toBeInTheDocument(); + expect(screen.getAllByText(/^tab:/)).toHaveLength(1); + }); + } + + it('FE-ATLAS2-MOBILE-164: a chip switches the tab and leaves any open profile', () => { + const s = buildGlobeState({ passportOpen: true }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.bucketTab' })); + expect(s.setPassportTab).toHaveBeenCalledWith('wishlist'); + expect(s.setProfileId).toHaveBeenCalledWith(null); + }); + + it('FE-ATLAS2-MOBILE-165: the close button closes the hub', () => { + const s = buildGlobeState({ passportOpen: true }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(s.setPassportOpen).toHaveBeenCalledWith(false); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubBadges.test.tsx b/client/src/mobile/screens/atlas/hub/MHubBadges.test.tsx new file mode 100644 index 000000000..4c39d2d8c --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubBadges.test.tsx @@ -0,0 +1,157 @@ +import type { Badge } from '@trek/shared'; +import { describe, expect, it } from 'vitest'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render'; +import MHubBadges from './MHubBadges'; + +function badge(over: Partial): Badge { + return { + id: 'b', + category: 'countries', + motif: 'countries', + tier: 'bronze', + titleKey: 'badge.title', + descKey: 'badge.desc', + earned: false, + current: 0, + target: 1, + ...over, + }; +} + +const FIVE = badge({ + id: 'c5', + titleKey: 'badge.c5', + descKey: 'badge.c5.desc', + earned: true, + current: 5, + target: 5, + year: 2021, + country: 'FR', +}); +const TEN = badge({ + id: 'c10', + tier: 'silver', + titleKey: 'badge.c10', + descKey: 'badge.c10.desc', + current: 7, + target: 10, +}); +const REGION = badge({ + id: 'r1', + category: 'regions', + motif: 'region', + tier: 'gold', + titleKey: 'badge.region', + descKey: 'badge.region.desc', + params: { country: 'DE' }, + current: 2, + target: 5, +}); +const NO_YEAR = badge({ + id: 'k1', + category: 'continents', + motif: 'continents', + titleKey: 'badge.k1', + earned: true, + current: 2, + target: 2, +}); + +const BADGES = [FIVE, TEN, REGION, NO_YEAR]; + +const dialog = () => screen.getByRole('dialog'); +const openBadge = (title: string) => fireEvent.click(screen.getByText(title).closest('button') as HTMLElement); + +describe('MHubBadges', () => { + it('FE-ATLAS2-MOBILE-080: every category with badges is a section counting the earned ones, empty ones are left out', () => { + render(); + const countries = screen.getByRole('heading', { name: 'atlas.badgeCat.countries' }).closest('section'); + expect(within(countries as HTMLElement).getByText('1 / 2')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'atlas.badgeCat.regions' })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'atlas.badgeCat.flights' })).toBeNull(); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-081: an earned badge shows its year, an open one how far it got, a country in its title by name', () => { + render(); + expect(screen.getByText('2021')).toBeInTheDocument(); + expect(screen.getByText('7 / 10')).toBeInTheDocument(); + expect(screen.getByText('badge.region:name-DE')).toBeInTheDocument(); + // Earned without a year: no figure under it. + const k1 = screen.getByText('badge.k1:').closest('button') as HTMLElement; + expect(k1.lastElementChild?.textContent).toBe(''); + }); + + it('FE-ATLAS2-MOBILE-082: a tap opens the badge sheet with its tier, how to earn it, the progress and its stages', () => { + render(); + openBadge('badge.c10:'); + const sheet = dialog(); + expect(sheet).toHaveAttribute('aria-label', 'badge.c10:'); + expect(within(sheet).getByText('atlas.badgeTier.silver')).toBeInTheDocument(); + expect(within(sheet).getByText('atlas.badgeCat.countries')).toBeInTheDocument(); + expect(within(sheet).getByText('atlas.globe.howTo')).toBeInTheDocument(); + expect(within(sheet).getByText('badge.c10.desc:,10')).toBeInTheDocument(); + expect(within(sheet).getByText('atlas.globe.toGo')).toBeInTheDocument(); + expect(within(sheet).getByText('3')).toBeInTheDocument(); + expect(within(sheet).queryByText('atlas.globe.reached')).toBeNull(); + expect(within(sheet).queryByText('atlas.globe.holders')).toBeNull(); + const stages = within(sheet).getByRole('heading', { name: 'atlas.globe.stages' }).closest('section') as HTMLElement; + expect(within(stages).getByText('1 / 2')).toBeInTheDocument(); + const current = within(stages) + .getAllByRole('button') + .find((b) => b.getAttribute('aria-current') === 'true'); + expect(current?.textContent).toContain('badge.c10:'); + }); + + it('FE-ATLAS2-MOBILE-083: a stage opens that badge, which as earned shows the year and the country it was made by', () => { + render(); + openBadge('badge.c10:'); + const stages = within(dialog()) + .getByRole('heading', { name: 'atlas.globe.stages' }) + .closest('section') as HTMLElement; + fireEvent.click(within(stages).getByText('badge.c5:').closest('button') as HTMLElement); + const sheet = dialog(); + expect(sheet).toHaveAttribute('aria-label', 'badge.c5:'); + expect(within(sheet).getAllByText('atlas.globe.reached')).toHaveLength(2); + expect(within(sheet).getAllByText('2021').length).toBeGreaterThan(0); + expect(within(sheet).getByText('atlas.globe.madeBy')).toBeInTheDocument(); + expect(within(sheet).getByText('name-FR')).toBeInTheDocument(); + expect(within(sheet).getByText('badge.c5.desc:name-FR,5')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-084: an earned badge without a year shows a tick, a region badge has no stages', () => { + render(); + openBadge('badge.k1:'); + expect(within(dialog()).getByText('✓')).toBeInTheDocument(); + expect(within(dialog()).queryByText('atlas.globe.stages')).toBeNull(); + fireEvent.click(within(dialog()).getByRole('button', { name: 'common.close' })); + expect(screen.queryByText('atlas.globe.howTo')).toBeNull(); + openBadge('badge.region:name-DE'); + expect(within(dialog()).queryByText('atlas.globe.stages')).toBeNull(); + expect(within(dialog()).getByText('badge.region.desc:,5')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-085: with comparing on, the sheet loads the travellers and shows how many hold the badge', () => { + const people = [{ badges: [{ id: 'c10' }] }, { badges: [] }]; + const s = buildGlobeState({ badges: BADGES, compareEnabled: true, people }); + render(); + expect(s.loadPeople).not.toHaveBeenCalled(); + openBadge('badge.c10:'); + expect(s.loadPeople).toHaveBeenCalledOnce(); + expect(within(dialog()).getByText('atlas.globe.holders')).toBeInTheDocument(); + expect(within(dialog()).getByText('1 / 3')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-086: with comparing off, no travellers are loaded', () => { + const s = buildGlobeState({ badges: BADGES }); + render(); + openBadge('badge.c10:'); + expect(s.loadPeople).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-MOBILE-087: no badges at all renders no section', () => { + render(); + expect(screen.queryByRole('heading')).toBeNull(); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubDawarich.test.tsx b/client/src/mobile/screens/atlas/hub/MHubDawarich.test.tsx new file mode 100644 index 000000000..0654ee339 --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubDawarich.test.tsx @@ -0,0 +1,198 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen } from '../../../../../tests/helpers/render'; +import MHubDawarich from './MHubDawarich'; + +// The Dawarich questions go to the server; the tab only lays out what the hook holds. +const hook = vi.hoisted(() => ({ + state: {} as Record, + options: [] as Array<{ initialTab?: string; onChanged?: () => void }>, +})); +vi.mock('../../../../components/Dawarich/useDawarichAtlas', async (importOriginal) => ({ + ...(await importOriginal>()), + useDawarichAtlas: (options: { initialTab?: string; onChanged?: () => void }) => { + hook.options.push(options); + return hook.state; + }, +})); + +function dawarich(over: Record = {}) { + hook.state = { + tab: 'wishes', + setTab: vi.fn(), + scan: null, + picked: new Set(), + togglePicked: vi.fn(), + countries: null, + pickedCountries: new Set(), + togglePickedCountry: vi.fn(), + writing: false, + matches: [], + openMatches: [], + offered: [], + run: vi.fn(), + confirm: vi.fn(), + busy: false, + loaded: false, + selected: 0, + anything: false, + ...over, + }; + return hook.state as Record>; +} + +const AT = '2025-05-04T10:00:00Z'; +const MATCHES = [ + { itemId: 1, name: 'Kyoto', alreadyVisited: false, match: { at: AT, minutes: 90, distanceMeters: 1500 } }, + { itemId: 2, name: 'Rome', alreadyVisited: true, match: null }, + { itemId: 3, name: 'Oslo', alreadyVisited: false, match: null }, +]; +const OFFERED = [ + { countryCode: 'PT', sourceName: 'Portugal', cities: [{ name: 'Porto' }, { name: 'Lisbon' }] }, + { countryCode: 'ES', sourceName: 'Spain', cities: [] }, +]; + +beforeEach(() => { + hook.options = []; +}); + +describe('MHubDawarich', () => { + it('FE-ATLAS2-MOBILE-100: opens on the question the hub asked for and reloads the Atlas after a write', () => { + const d = dawarich(); + const s = buildGlobeState({ dawarichSub: 'countries' }); + render(); + expect(hook.options[0]?.initialTab).toBe('countries'); + expect(d.setTab).toHaveBeenCalledWith('countries'); + hook.options[0]?.onChanged?.(); + expect(s.reload).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-101: the segments carry how many there are to look at and switch the question', () => { + const d = dawarich({ openMatches: [MATCHES[0], MATCHES[2]], offered: [OFFERED[0]] }); + render(); + expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.wishes 2' })).toHaveAttribute('aria-selected', 'true'); + fireEvent.click(screen.getByRole('tab', { name: 'dawarich.atlas.tab.countries 1' })); + expect(d.setTab).toHaveBeenLastCalledWith('countries'); + }); + + it('FE-ATLAS2-MOBILE-102: nothing to look at leaves the segment labels plain', () => { + dawarich(); + render(); + expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.wishes' })).toBeInTheDocument(); + expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.countries' })).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-103: while a question runs it says which one', () => { + dawarich({ busy: true }); + const { unmount } = render(); + expect(screen.getByText('dawarich.bucket.scanning')).toBeInTheDocument(); + unmount(); + dawarich({ busy: true, tab: 'countries' }); + render(); + expect(screen.getByText('dawarich.atlas.loading')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-104: before the first question it explains the wishes check and asks it on a tap', () => { + const d = dawarich(); + render(); + expect(screen.getByText('dawarich.bucket.title')).toBeInTheDocument(); + expect(screen.getByText('dawarich.bucket.description')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.scan' })); + expect(d.run).toHaveBeenCalledOnce(); + // No notes before anything was asked. + expect(screen.queryByText(/dawarich\.bucket\.rule/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-105: before the first question on countries it explains that one', () => { + const d = dawarich({ tab: 'countries' }); + render(); + expect(screen.getByText('dawarich.atlas.title')).toBeInTheDocument(); + expect(screen.getByText('dawarich.atlas.description')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.load' })); + expect(d.run).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-106: a scan without a match says so, offers it again and states the rule', () => { + const d = dawarich({ loaded: true, scan: { matches: [], skippedWithoutCoordinates: 0, truncated: false } }); + render(); + expect(screen.getByText('dawarich.bucket.noMatches')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' })); + expect(d.run).toHaveBeenCalledOnce(); + expect(screen.getByText(/dawarich\.bucket\.rule:/)).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-107: no new countries says so and names the time window', () => { + dawarich({ loaded: true, tab: 'countries', countries: { countries: [], unresolved: [] } }); + render(); + expect(screen.getByText('dawarich.atlas.empty')).toBeInTheDocument(); + expect(screen.getByText('dawarich.atlas.window')).toBeInTheDocument(); + expect(screen.queryByText(/dawarich\.atlas\.unresolved/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-108: each matched wish is a checkbox with when, how long and how far, a visited one locked', () => { + const d = dawarich({ + loaded: true, + anything: true, + matches: MATCHES, + picked: new Set([1]), + selected: 1, + scan: { matches: MATCHES, skippedWithoutCoordinates: 2, truncated: true }, + }); + render(); + const day = new Date(AT).toLocaleDateString('en', { day: 'numeric', month: 'short' }); + expect(screen.getByRole('checkbox', { name: 'Kyoto' })).toHaveAttribute('aria-checked', 'true'); + expect( + screen.getByText(`${day}, dawarich.duration.hoursMinutes:1,30, dawarich.bucket.kilometersAway:1.5`) + ).toBeInTheDocument(); + expect(screen.getByRole('checkbox', { name: 'Rome' })).toBeDisabled(); + expect(screen.getByText('dawarich.bucket.alreadyVisited')).toBeInTheDocument(); + expect(screen.getByRole('checkbox', { name: 'Oslo' })).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(screen.getByRole('checkbox', { name: 'Oslo' })); + expect(d.togglePicked).toHaveBeenCalledWith(3); + expect(screen.getByText('dawarich.bucket.skipped:2')).toBeInTheDocument(); + expect(screen.getByText('dawarich.bucket.truncated')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-109: the confirm writes what is ticked, the round button asks again', () => { + const d = dawarich({ loaded: true, anything: true, matches: MATCHES, picked: new Set([1]), selected: 1 }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.confirm:1' })); + expect(d.confirm).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' })); + expect(d.run).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-110: nothing ticked, or a write on its way, keeps the confirm off', () => { + dawarich({ loaded: true, anything: true, matches: MATCHES, selected: 0 }); + const { unmount } = render(); + expect(screen.getByRole('button', { name: 'dawarich.bucket.confirm:0' })).toBeDisabled(); + unmount(); + dawarich({ loaded: true, anything: true, matches: MATCHES, selected: 1, writing: true }); + render(); + expect(screen.getByRole('button', { name: 'dawarich.bucket.confirm:1' })).toBeDisabled(); + }); + + it('FE-ATLAS2-MOBILE-111: each new country is a checkbox under its own name with its cities, the confirm accepts them', () => { + const d = dawarich({ + loaded: true, + anything: true, + tab: 'countries', + offered: OFFERED, + pickedCountries: new Set(['PT']), + selected: 1, + countries: { countries: OFFERED, unresolved: ['Atlantis'] }, + }); + render(); + const portugal = screen.getByRole('checkbox', { name: 'Portugal' }); + expect(portugal).toHaveAttribute('aria-checked', 'true'); + expect(screen.getByText('Porto, Lisbon')).toBeInTheDocument(); + const spain = screen.getByRole('checkbox', { name: 'Spain' }); + expect(spain).toHaveAttribute('aria-checked', 'false'); + expect(spain.querySelectorAll('.text-caption')).toHaveLength(0); + fireEvent.click(spain); + expect(d.togglePickedCountry).toHaveBeenCalledWith('ES'); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.accept:1' })); + expect(d.confirm).toHaveBeenCalledOnce(); + expect(screen.getByText('dawarich.atlas.unresolved:Atlantis')).toBeInTheDocument(); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubOverview.test.tsx b/client/src/mobile/screens/atlas/hub/MHubOverview.test.tsx new file mode 100644 index 000000000..b04a6dde0 --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubOverview.test.tsx @@ -0,0 +1,114 @@ +import { useLocation } from 'react-router'; +import { describe, expect, it } from 'vitest'; +import { buildAtlasData } from '../../../../../tests/helpers/atlas'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen } from '../../../../../tests/helpers/render'; +import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe'; +import MHubOverview from './MHubOverview'; + +function Where() { + return {useLocation().pathname}; +} + +function show(s: AtlasGlobeState) { + return render( + <> + + + + ); +} + +const barOf = (key: string) => + (screen.getByText(key).parentElement as HTMLElement).querySelector('.h-full') as HTMLElement; + +describe('MHubOverview', () => { + it('FE-ATLAS2-MOBILE-020: the headline is the country count with the share of the world and the planned ones', () => { + const s = buildGlobeState({ + totals: { countries: 39, continents: 2, regions: 5 }, + data: buildAtlasData({ + stats: { + totalTrips: 3, + totalPlaces: 10, + totalCountries: 39, + totalDays: 14, + totalCities: 3, + totalCountriesPlanned: 2, + totalCountriesIdea: 1, + }, + }), + }); + show(s); + expect(screen.getByText('39')).toBeInTheDocument(); + expect(screen.getByText('atlas.countries:39')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.worldShare:20')).toBeInTheDocument(); + expect(screen.getByText('+3 atlas.planned')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-021: nothing planned leaves the planned figure out', () => { + show(buildGlobeState()); + expect(screen.queryByText(/atlas\.planned/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-022: the next trip shows its countdown and opens the trip', () => { + // The server sends the countdown beside the trip; the shared type does not name it. + const nextTrip = { id: 9, title: 'Lisbon', daysUntil: 12 }; + const s = buildGlobeState({ data: buildAtlasData({ nextTrip }) }); + show(s); + expect(screen.getByText('12')).toBeInTheDocument(); + expect(screen.getByText('atlas.daysLeft')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Lisbon/ })); + expect(screen.getByTestId('where').textContent).toBe('/trips/9'); + }); + + it('FE-ATLAS2-MOBILE-023: a next trip without a countdown shows only its title', () => { + show(buildGlobeState({ data: buildAtlasData({ nextTrip: { id: 9, title: 'Lisbon' } }) })); + expect(screen.getByText('Lisbon')).toBeInTheDocument(); + expect(screen.queryByText('atlas.daysLeft')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-024: continents are bars scaled to the largest, the empty ones at zero, Antarctica hidden', () => { + const s = buildGlobeState({ + totals: { countries: 6, continents: 2, regions: 0 }, + data: buildAtlasData({ continents: { Europe: 4, Asia: 2 } }), + }); + show(s); + expect(screen.getByText('2 / 6')).toBeInTheDocument(); + expect(barOf('atlas.europe').style.width).toBe('100%'); + expect(barOf('atlas.asia').style.width).toBe('50%'); + expect(barOf('atlas.africa').style.width).toBe('0%'); + expect(screen.queryByText('atlas.antarctica')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-025: a country in Antarctica adds its row, and a small share keeps a visible bar', () => { + const s = buildGlobeState({ + totals: { countries: 6, continents: 2, regions: 0 }, + data: buildAtlasData({ continents: { Europe: 50, Antarctica: 1 } }), + }); + show(s); + expect(screen.getByText('2 / 7')).toBeInTheDocument(); + expect(barOf('atlas.antarctica').style.width).toBe('6%'); + }); + + it('FE-ATLAS2-MOBILE-026: with Dawarich on, its entry opens the countries question', () => { + const s = buildGlobeState({ dawarichEnabled: true }); + show(s); + fireEvent.click(screen.getByRole('button', { name: /atlas\.globe\.dawarichCountries/ })); + expect(s.openDawarich).toHaveBeenCalledWith('countries'); + }); + + it('FE-ATLAS2-MOBILE-027: without Dawarich there is no entry, and the tiles carry the figures', () => { + show(buildGlobeState({ totals: { countries: 1, continents: 1, regions: 5 } })); + expect(screen.queryByText('atlas.globe.dawarichCountries')).toBeNull(); + expect(screen.getByText('atlas.regions:5')).toBeInTheDocument(); + expect(screen.getByText('atlas.trips:3')).toBeInTheDocument(); + expect(screen.getByText('atlas.days:14')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-028: without data every continent is empty and nothing breaks', () => { + show(buildGlobeState({ data: null, totals: { countries: 0, continents: 0, regions: 0 } })); + expect(screen.getByText('0 / 6')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.worldShare:0')).toBeInTheDocument(); + expect(barOf('atlas.europe').style.width).toBe('0%'); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubTours.test.tsx b/client/src/mobile/screens/atlas/hub/MHubTours.test.tsx new file mode 100644 index 000000000..e3ee1470e --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubTours.test.tsx @@ -0,0 +1,180 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen } from '../../../../../tests/helpers/render'; +import MHubTours from './MHubTours'; + +// The stats hook reads the server and the figures are covered by their own +// tests; here they are fixed so the tab's layout and wiring are what is tested. +const tours = vi.hoisted(() => ({ + stats: {} as Record, + active: [] as boolean[], + figures: {} as Record, +})); + +vi.mock('../../../../components/Atlas/tourActivity/useTourActivityStats', () => ({ + useTourActivityStats: (active: boolean) => { + tours.active.push(active); + return tours.stats; + }, +})); +vi.mock('../../../../components/Atlas/tourActivity/tourHubFigures', () => ({ + tourHubFigures: () => tours.figures, +})); +vi.mock('../../../../components/Atlas/tourActivity/tourActivityReading', async (importOriginal) => ({ + ...(await importOriginal>()), + useDistanceUnit: () => 'metric', + distanceReading: (x: { distanceKm: { value: number | null } }) => + x.distanceKm.value == null ? null : { text: `${x.distanceKm.value} km` }, +})); +vi.mock('../../../../components/Atlas/tourActivity/tourActivityParts', () => ({ + ActivityStatusLine: ({ stats }: { stats: { status: string } }) =>

status:{stats.status}

, + BasisBadges: ({ byBasis }: { byBasis: Record }) =>

basis:{JSON.stringify(byBasis)}

, + UncountedBadges: (p: { upcoming: number; unassigned: number; undated: number }) => ( +

+ uncounted:{p.upcoming}:{p.unassigned}:{p.undated} +

+ ), +})); +vi.mock('../../../../components/Atlas/tourActivity/TourActivityStatsDialog', () => ({ + TourActivityStatsDialog: ({ open, onClose }: { open: boolean; onClose: () => void }) => + open ? ( +
+ +
+ ) : null, +})); + +function statsWith(over: Record = {}) { + tours.stats = { + status: 'ready', + data: { entries: [], uncounted: { unassigned: 0, undated: 0 } }, + summary: null, + period: 'all', + setPeriod: vi.fn(), + periods: ['all', 'thisYear', 'last12', 'year:2023'], + type: 'all', + setType: vi.fn(), + types: ['all'], + ...over, + }; + return tours.stats as Record>; +} + +const TYPES = [ + { type: 'hike', count: 3, distanceKm: { value: 30 } }, + { type: 'bike', count: 2, distanceKm: { value: null } }, +]; + +function summary(count: number, done: unknown[] = []) { + return { + totals: { count, byBasis: { plan: 2, track: 3 } }, + types: TYPES, + done, + upcoming: 1, + }; +} + +beforeEach(() => { + tours.active = []; + tours.figures = { + hero: { value: '42', unit: 'km' }, + ascent: { text: '1200 m' }, + descent: null, + types: TYPES, + maxKm: 30, + uncounted: { unassigned: 2, undated: 4 }, + }; +}); + +describe('MHubTours', () => { + it('FE-ATLAS2-MOBILE-140: before the numbers are there it asks for them and shows where the read stands', () => { + statsWith({ status: 'loading' }); + render(); + expect(tours.active[0]).toBe(true); + expect(screen.getByText('status:loading')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-141: the periods are chips, the chosen one pressed, a tap picks another', () => { + const st = statsWith({ period: 'thisYear' }); + render(); + const periods = screen.getByRole('group', { name: 'tours.stats.period' }); + expect(periods.textContent).toContain('2023'); + expect(screen.getByRole('button', { name: 'tours.stats.period.thisYear' })).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(screen.getByRole('button', { name: 'tours.stats.period.last12' })); + expect(st.setPeriod).toHaveBeenCalledWith('last12'); + // One type only: no type chips. + expect(screen.queryByRole('group', { name: 'tours.filter.type' })).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-142: more than one type adds a row of type chips', () => { + const st = statsWith({ types: ['all', 'hike'] }); + render(); + expect(screen.getByRole('button', { name: 'tours.stats.allTypes' })).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(screen.getByRole('button', { name: 'tourTypes.hike' })); + expect(st.setType).toHaveBeenCalledWith('hike'); + }); + + it('FE-ATLAS2-MOBILE-143: no tour in the period says none counts when there are tours at all', () => { + statsWith({ summary: summary(0), data: { entries: [{ place_id: 1 }], uncounted: { unassigned: 0, undated: 0 } } }); + render(); + expect(screen.getByText('tours.stats.none')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-144: no tour at all says there are none yet', () => { + statsWith({ summary: summary(0), data: null }); + render(); + expect(screen.getByText('tours.stats.empty')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-145: the distance is the headline, tours, climb and descent the tiles', () => { + statsWith({ summary: summary(5) }); + render(); + expect(screen.getByText('42')).toBeInTheDocument(); + expect(screen.getByText('km')).toBeInTheDocument(); + expect(screen.getByText('basis:{"plan":2,"track":3}')).toBeInTheDocument(); + expect(screen.getByText('5')).toBeInTheDocument(); + expect(screen.getByText('tours.mode.tours')).toBeInTheDocument(); + expect(screen.getByText('1200 m')).toBeInTheDocument(); + expect(screen.getByText('0')).toBeInTheDocument(); + expect(screen.getByText('uncounted:1:2:4')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-146: every type is a row with its count and a bar scaled to the longest', () => { + statsWith({ summary: summary(5) }); + render(); + expect(screen.getByRole('heading', { name: 'atlas.globe.byType' })).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.tourCount:3')).toBeInTheDocument(); + expect(screen.getByText('30 km')).toBeInTheDocument(); + const bar = (label: string) => + (screen.getByText(label).closest('.flex-col') as HTMLElement).querySelector('.bg-m-act') as HTMLElement; + expect(bar('tourTypes.hike').style.width).toBe('100%'); + // A type without a known distance keeps a sliver. + expect(bar('tourTypes.bike').style.width).toBe('4%'); + }); + + it('FE-ATLAS2-MOBILE-147: one type picked leaves the rows by type out, a headline without unit shows the figure alone', () => { + tours.figures = { ...tours.figures, hero: { value: '5', unit: '' } }; + statsWith({ summary: summary(5), type: 'hike', types: ['all', 'hike'] }); + render(); + expect(screen.queryByRole('heading', { name: 'atlas.globe.byType' })).toBeNull(); + expect(screen.queryByText('km')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-148: done tours open their list in a dialog, which closes again', () => { + statsWith({ summary: summary(5, [{ place_id: 1 }]) }); + render(); + expect(screen.queryByRole('dialog')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'tours.stats.showTours' })); + expect(screen.getByRole('dialog', { name: 'tour list' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'close list' })); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-149: without done tours there is no list to open', () => { + statsWith({ summary: summary(5) }); + render(); + expect(screen.queryByRole('button', { name: 'tours.stats.showTours' })).toBeNull(); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubTravellers.test.tsx b/client/src/mobile/screens/atlas/hub/MHubTravellers.test.tsx new file mode 100644 index 000000000..0c6f92629 --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubTravellers.test.tsx @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest'; +import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render'; +import MHubTravellers from './MHubTravellers'; + +function person(id: number, username: string, countries: number, over: Record = {}) { + return { + id, + username, + avatar_url: null, + countries, + continents: 2, + regions: 9, + flightKm: 0, + codes: [], + badges: [], + ...over, + }; +} + +const RANKING = [ + person(2, 'ann', 20, { avatar_url: 'https://example.test/ann.png', continents: 4, regions: 31 }), + person(1, 'me', 12), + person(3, 'bob', 8), + person(4, 'cy', 3), +]; + +const rowOf = (name: string) => screen.getByText(name).closest('button') as HTMLElement; + +describe('MHubTravellers', () => { + it('FE-ATLAS2-MOBILE-120: loads the travellers and shows being visible as a switch that hides on a tap', () => { + const s = buildGlobeState(); + render(); + expect(s.loadPeople).toHaveBeenCalledOnce(); + const visible = screen.getByRole('switch', { name: 'atlas.globe.visibleToOthers' }); + expect(visible).toHaveAttribute('aria-checked', 'true'); + fireEvent.click(visible); + expect(s.setHidden).toHaveBeenCalledWith(true); + // Nothing loaded yet: no list and no empty state. + expect(screen.queryByText('atlas.globe.noTravellers')).toBeNull(); + expect(screen.queryByRole('list')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-121: a hidden traveller sees the switch off and turns it back on', () => { + const s = buildGlobeState({ hidden: true }); + render(); + const visible = screen.getByRole('switch', { name: 'atlas.globe.visibleToOthers' }); + expect(visible).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(visible); + expect(s.setHidden).toHaveBeenCalledWith(false); + }); + + it('FE-ATLAS2-MOBILE-122: alone on the instance there is nobody to rank', () => { + render(); + expect(screen.getByText('atlas.globe.noTravellers')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-123: the ranking numbers every traveller, marks the reader and opens the others', () => { + const s = buildGlobeState({ ranking: RANKING, me: { id: 1 } }); + render(); + const list = screen.getByRole('list'); + expect(within(list).getAllByRole('listitem')).toHaveLength(4); + expect(screen.getByRole('heading', { name: 'atlas.globe.ranking' }).parentElement?.textContent).toContain('4'); + expect(rowOf('me')).toBeDisabled(); + expect(within(rowOf('me')).getByText('atlas.globe.you')).toBeInTheDocument(); + expect(within(rowOf('bob')).queryByText('atlas.globe.you')).toBeNull(); + fireEvent.click(rowOf('bob')); + expect(s.setProfileId).toHaveBeenCalledWith(3); + expect(within(rowOf('ann')).getByText('20')).toBeInTheDocument(); + expect(within(rowOf('ann')).getByText('31')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-124: the first three wear the podium, the rest a plain number', () => { + render(); + const place = (name: string) => rowOf(name).firstElementChild as HTMLElement; + expect(place('ann').textContent).toBe('1'); + expect(place('ann').getAttribute('style')).toContain('box-shadow'); + expect(place('bob').getAttribute('style')).toContain('box-shadow'); + expect(place('cy').textContent).toBe('4'); + expect(place('cy').getAttribute('style')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-125: a picture where there is one, otherwise the first letter', () => { + render(); + expect(rowOf('ann').querySelector('img')?.getAttribute('src')).toBe('https://example.test/ann.png'); + expect(within(rowOf('bob')).getByText('B')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-126: a profile shows the figures and the badges and starts the comparison', () => { + const profile = person(3, 'bob', 8, { + flightKm: 52400, + badges: [ + { + id: 'x', + motif: 'countries', + tier: 'gold', + target: 10, + titleKey: 'badge.x', + params: { country: 'FR' }, + }, + { id: 'y', motif: 'earth', tier: 'bronze', target: 40075, titleKey: 'badge.y' }, + ], + }); + const s = buildGlobeState({ ranking: RANKING, profile, badges: [1, 2, 3, 4, 5] }); + render(); + const sheet = screen.getByRole('dialog', { name: 'bob' }); + expect(within(sheet).getByText('atlas.globe.collected:2,5')).toBeInTheDocument(); + expect(within(sheet).getByText('52k')).toBeInTheDocument(); + expect(within(sheet).getByText('badge.x:name-FR')).toBeInTheDocument(); + expect(within(sheet).getByText('badge.y:')).toBeInTheDocument(); + fireEvent.click(within(sheet).getByRole('button', { name: 'atlas.globe.compareOnGlobe' })); + expect(s.setProfileId).toHaveBeenCalledWith(null); + expect(s.startCompare).toHaveBeenCalledWith(profile); + }); + + it('FE-ATLAS2-MOBILE-127: a profile without badges says so and its close button closes it', () => { + const s = buildGlobeState({ profile: person(3, 'bob', 8) }); + render(); + const sheet = screen.getByRole('dialog', { name: 'bob' }); + expect(within(sheet).getByText('atlas.globe.noBadgesYet')).toBeInTheDocument(); + fireEvent.click(within(sheet).getByRole('button', { name: 'common.close' })); + expect(s.setProfileId).toHaveBeenCalledWith(null); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/MHubWishlist.test.tsx b/client/src/mobile/screens/atlas/hub/MHubWishlist.test.tsx new file mode 100644 index 000000000..8097e03a6 --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/MHubWishlist.test.tsx @@ -0,0 +1,405 @@ +import { getIntlLanguage } from '@trek/shared'; +import React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildBucketItem } from '../../../../../tests/helpers/atlas'; +import { buildBucketState, buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState'; +import { act, fireEvent, render, screen, within } from '../../../../../tests/helpers/render'; +import { visitedOn } from '../../../../pages/atlas/atlasHubModel'; +import type { BucketItem } from '../../../../pages/atlas/atlasModel'; +import type { GlobePlaceHit } from '../../../../pages/atlas/useGlobePlaceSearch'; +import MHubWishlist from './MHubWishlist'; + +// The place search asks the server; here it answers what the test puts in. +const search = vi.hoisted(() => ({ + hits: [] as Array<{ name: string; address: string | null; lat: number; lng: number }>, + loading: false, + asked: [] as Array<[string, string]>, +})); +vi.mock('../../../../pages/atlas/useGlobePlaceSearch', () => ({ + useGlobePlaceSearch: (query: string, lang: string) => { + search.asked.push([query, lang]); + return { placeHits: search.hits, placesLoading: search.loading }; + }, +})); + +interface Form { + name: string; + notes: string; + lat: string; + lng: string; + target_date: string; + address?: string; +} + +const EMPTY: Form = { name: '', notes: '', lat: '', lng: '', target_date: '' }; + +function spies() { + return { + setShowBucketAdd: vi.fn(), + setBucketForm: vi.fn(), + setBucketPoiYear: vi.fn(), + setBucketPoiMonth: vi.fn(), + resetBucketAdd: vi.fn(), + handleSelectBucketPoi: vi.fn(), + handleAddBucketItem: vi.fn(async () => undefined), + handleDeleteBucketItem: vi.fn(async () => undefined), + handleClearBucketVisit: vi.fn(async () => undefined), + flyToPoint: vi.fn(), + openDawarich: vi.fn(), + }; +} +type Spies = ReturnType; + +/** The wishlist over a bucket state that really changes, so the add sheet reacts as it does in the app. */ +function Harness({ + items = [], + spy, + open = false, + form = {}, + year: startYear = 0, + month: startMonth = 0, + dawarich = false, +}: { + items?: BucketItem[]; + spy: Spies; + open?: boolean; + form?: Partial
; + year?: number; + month?: number; + dawarich?: boolean; +}) { + const [show, setShow] = React.useState(open); + const [bucketForm, setForm] = React.useState({ ...EMPTY, ...form }); + const [year, setYear] = React.useState(startYear); + const [month, setMonth] = React.useState(startMonth); + const s = buildGlobeState({ + placeLang: 'de', + dawarichEnabled: dawarich, + openDawarich: spy.openDawarich, + flyToPoint: spy.flyToPoint, + bucketState: buildBucketState({ + bucketList: items, + showBucketAdd: show, + setShowBucketAdd: (v: boolean) => { + spy.setShowBucketAdd(v); + setShow(v); + }, + bucketForm, + setBucketForm: (v: Form) => { + spy.setBucketForm(v); + setForm(v); + }, + bucketPoiYear: year, + setBucketPoiYear: (v: number) => { + spy.setBucketPoiYear(v); + setYear(v); + }, + bucketPoiMonth: month, + setBucketPoiMonth: (v: number) => { + spy.setBucketPoiMonth(v); + setMonth(v); + }, + resetBucketAdd: () => { + spy.resetBucketAdd(); + setShow(false); + setForm(EMPTY); + }, + handleSelectBucketPoi: (hit: GlobePlaceHit) => { + spy.handleSelectBucketPoi(hit); + setForm((f) => ({ + ...f, + name: hit.name, + lat: String(hit.lat), + lng: String(hit.lng), + address: hit.address ?? '', + })); + }, + handleAddBucketItem: spy.handleAddBucketItem, + handleDeleteBucketItem: spy.handleDeleteBucketItem, + handleClearBucketVisit: spy.handleClearBucketVisit, + }), + }); + return ; +} + +const ITEMS: BucketItem[] = [ + buildBucketItem({ id: 1, name: 'Kyoto', country_code: 'JP', target_date: '2027-04', lat: 35, lng: 135 }), + buildBucketItem({ id: 2, name: 'Lisbon', country_code: 'PRT', notes: 'with Anna' }), + buildBucketItem({ + id: 3, + name: 'Iceland', + country_code: 'IS', + visited_at: '2025-06-03 10:00:00', + visited_source: 'dawarich', + }), + buildBucketItem({ id: 4, name: 'Somewhere', country_code: null, visited_at: '2024-01-02', visited_source: 'manual' }), +]; + +/** jsdom has no Touch: an Event with the touches set on it, as MSwipeRow's own test does. */ +function touch(el: Element, type: 'touchstart' | 'touchmove' | 'touchend', x = 0) { + const e = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: 100 }] }); + act(() => { + el.dispatchEvent(e); + }); +} + +function swipe(name: string, dx: number) { + const row = (screen.getByText(name).closest('button') as HTMLElement).parentElement?.parentElement as HTMLElement; + touch(row, 'touchstart', 200); + touch(row, 'touchmove', 200 + dx / 2); + touch(row, 'touchmove', 200 + dx); + touch(row, 'touchend'); +} + +const sheet = () => screen.getByRole('dialog', { name: 'atlas.globe.newWish' }); +const shortMonths = () => + Array.from({ length: 12 }, (_, i) => new Date(2000, i).toLocaleString(getIntlLanguage('en'), { month: 'short' })); + +beforeEach(() => { + search.hits = []; + search.loading = false; + search.asked = []; +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('MHubWishlist', () => { + it('FE-ATLAS2-MOBILE-040: an empty list says so and its button opens the add sheet', () => { + const spy = spies(); + render(); + expect(screen.getByText('atlas.bucketEmpty')).toBeInTheDocument(); + expect(screen.getByText('atlas.bucketEmptyHint')).toBeInTheDocument(); + expect(screen.queryByRole('dialog')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.newWish' })); + expect(spy.setShowBucketAdd).toHaveBeenCalledWith(true); + expect(sheet()).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-041: the headline counts the wishes, the reached ones, the countries and names the next date', () => { + render(); + expect(screen.getByText('atlas.globe.wishes:4')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.wishesReached:2,4')).toBeInTheDocument(); + // JP, PT (stored as PRT) and IS; the wish without a country counts none. + expect(screen.getByText('3')).toBeInTheDocument(); + // The next dated wish in the headline and on its own row. + expect(screen.getAllByText('Apr 2027')).toHaveLength(2); + expect(screen.getAllByText('Kyoto')).toHaveLength(2); + }); + + it('FE-ATLAS2-MOBILE-042: open wishes come soonest first, reached ones latest first, each section counted', () => { + render(); + const open = screen.getByRole('heading', { name: 'atlas.globe.wishesOpen' }).closest('section') as HTMLElement; + const done = screen.getByRole('heading', { name: 'atlas.globe.wishesDone' }).closest('section') as HTMLElement; + const names = (el: HTMLElement) => + within(el) + .getAllByRole('button') + .map((b) => b.querySelector('.font-semibold')?.textContent); + expect(names(open)).toEqual(['Kyoto', 'Lisbon']); + expect(names(done)).toEqual(['Iceland', 'Somewhere']); + expect(within(open).getByText('2')).toBeInTheDocument(); + expect(within(done).getByText('2')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-043: a row names the country and the note, but not a country that is the wish itself', () => { + render(); + expect(screen.getByText('name-JP')).toBeInTheDocument(); + expect(screen.getByText('name-PT, with Anna')).toBeInTheDocument(); + const iceland = screen.getByText('Iceland').closest('button') as HTMLElement; + expect(within(iceland).queryByText('Iceland', { selector: '.text-caption' })).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-044: a reached wish is struck through and carries the day it came true', () => { + render(); + expect(screen.getByText('Iceland').className).toContain('line-through'); + expect(screen.getByText('Kyoto', { selector: '.text-body' }).className).not.toContain('line-through'); + const day = visitedOn(ITEMS[2] as BucketItem, 'en') as string; + const badge = (screen.getByText('Iceland').closest('button') as HTMLElement).lastElementChild as HTMLElement; + expect(badge.textContent).toContain(day); + }); + + it('FE-ATLAS2-MOBILE-045: a tap on a wish with a place flies there, one without a place stays put', () => { + const spy = spies(); + render(); + fireEvent.click(screen.getByText('Lisbon').closest('button') as HTMLElement); + expect(spy.flyToPoint).not.toHaveBeenCalled(); + fireEvent.click(screen.getByText('Kyoto', { selector: '.text-body' }).closest('button') as HTMLElement); + expect(spy.flyToPoint).toHaveBeenCalledWith(135, 35); + }); + + it('FE-ATLAS2-MOBILE-046: swiped towards the start, a wish offers removal, which deletes it', () => { + const spy = spies(); + render(); + swipe('Lisbon', -100); + expect(screen.queryByLabelText('dawarich.bucket.clearVisit')).toBeNull(); + fireEvent.click(screen.getByLabelText('atlas.removeFromBucket')); + expect(spy.handleDeleteBucketItem).toHaveBeenCalledWith(2); + }); + + it('FE-ATLAS2-MOBILE-047: a wish a recording reached can also be undone from the swipe', () => { + const spy = spies(); + render(); + swipe('Iceland', -100); + fireEvent.click(screen.getByLabelText('dawarich.bucket.clearVisit')); + expect(spy.handleClearBucketVisit).toHaveBeenCalledWith(3); + }); + + it('FE-ATLAS2-MOBILE-048: a wish ticked off by hand offers no undo', () => { + render(); + swipe('Somewhere', -100); + expect(screen.getByLabelText('atlas.removeFromBucket')).toBeInTheDocument(); + expect(screen.queryByLabelText('dawarich.bucket.clearVisit')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-049: swiped the other way, a wish with a place shows it on the globe', () => { + const spy = spies(); + render(); + const kyoto = screen.getByText('Kyoto', { selector: '.text-body' }); + const row = (kyoto.closest('button') as HTMLElement).parentElement?.parentElement as HTMLElement; + touch(row, 'touchstart', 200); + touch(row, 'touchmove', 250); + touch(row, 'touchmove', 300); + touch(row, 'touchend'); + fireEvent.click(screen.getByLabelText('atlas.globe.showOnGlobe')); + expect(spy.flyToPoint).toHaveBeenCalledWith(135, 35); + }); + + it('FE-ATLAS2-MOBILE-050: with Dawarich on, its entry opens the wishes question', () => { + const spy = spies(); + render(); + fireEvent.click(screen.getByRole('button', { name: /atlas\.globe\.dawarichWishes/ })); + expect(spy.openDawarich).toHaveBeenCalledWith('wishes'); + }); + + it('FE-ATLAS2-MOBILE-051: only open wishes leave the reached section out, and no dated wish leaves the headline line out', () => { + render(); + expect(screen.getByRole('heading', { name: 'atlas.globe.wishesOpen' })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'atlas.globe.wishesDone' })).toBeNull(); + expect(screen.getAllByText('Rome')).toHaveLength(1); + }); + + it('FE-ATLAS2-MOBILE-052: the add button above the list opens the sheet, its close button resets it', () => { + const spy = spies(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.newWish' })); + expect(sheet()).toBeInTheDocument(); + fireEvent.click(within(sheet()).getByRole('button', { name: 'common.cancel' })); + expect(spy.resetBucketAdd).toHaveBeenCalledOnce(); + expect(screen.queryByPlaceholderText('atlas.globe.wishSearch')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-053: the search asks in the place language and lists no results before anything is typed', () => { + render(); + expect(screen.getByPlaceholderText('atlas.globe.wishSearch')).toBeInTheDocument(); + expect(search.asked.at(-1)).toEqual(['', 'de']); + expect(screen.queryByText(/atlas\.globe\.wishJustName/)).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-054: a hit from the search is picked as the wish, with its address', () => { + search.hits = [{ name: 'Porto', address: 'Portugal', lat: 41.1, lng: -8.6 }]; + const spy = spies(); + render(); + fireEvent.change(screen.getByPlaceholderText('atlas.globe.wishSearch'), { target: { value: 'Por' } }); + expect(search.asked.at(-1)).toEqual(['Por', 'de']); + expect(screen.getByText('Portugal')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Porto/ })); + expect(spy.handleSelectBucketPoi).toHaveBeenCalledWith(search.hits[0]); + expect(screen.getByLabelText('atlas.bucketNamePlaceholder')).toHaveValue('Porto'); + expect(within(sheet()).getByText('Portugal')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-055: what was typed can be taken as a plain name without a place', () => { + const spy = spies(); + render(); + fireEvent.change(screen.getByPlaceholderText('atlas.globe.wishSearch'), { target: { value: ' Patagonia ' } }); + fireEvent.click(screen.getByText('atlas.globe.wishJustName:Patagonia')); + expect(spy.setBucketForm).toHaveBeenCalledWith( + expect.objectContaining({ name: 'Patagonia', lat: '', lng: '', address: undefined }) + ); + expect(screen.getByLabelText('atlas.bucketNamePlaceholder')).toHaveValue('Patagonia'); + expect(screen.getByText('atlas.globe.wishNoPlace')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-056: a search on its way shows the spinner', () => { + search.loading = true; + render(); + expect(sheet().querySelector('.animate-spin')).not.toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-057: a picked place without an address reads as shown on the globe, renamed and changed back', () => { + const spy = spies(); + render(); + expect(within(sheet()).getByText('atlas.globe.showOnGlobe')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('atlas.bucketNamePlaceholder'), { target: { value: 'Porto old town' } }); + expect(spy.setBucketForm).toHaveBeenLastCalledWith( + expect.objectContaining({ name: 'Porto old town', lat: '41.1' }) + ); + fireEvent.click(screen.getByText('atlas.globe.change')); + expect(spy.setBucketForm).toHaveBeenLastCalledWith( + expect.objectContaining({ name: '', lat: '', lng: '', address: undefined }) + ); + expect(screen.getByPlaceholderText('atlas.globe.wishSearch')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-058: without a year the wish is someday and the months are switched off', () => { + render(); + expect(screen.getByRole('button', { name: 'atlas.globe.someday' })).toHaveAttribute('aria-pressed', 'true'); + const grid = screen.getByRole('button', { name: shortMonths()[0] }).parentElement as HTMLElement; + expect(grid).toHaveAttribute('aria-disabled', 'true'); + }); + + it('FE-ATLAS2-MOBILE-059: the year steps from this year and a month toggles on and off', () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(2026, 10, 29)); + const spy = spies(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearLater' })); + expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2027); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearEarlier' })); + expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2026); + fireEvent.click(screen.getByRole('button', { name: '2026' })); + expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2026); + expect(screen.getByRole('button', { name: 'atlas.globe.someday' })).toHaveAttribute('aria-pressed', 'false'); + const march = screen.getByRole('button', { name: shortMonths()[2] }); + fireEvent.click(march); + expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(3); + expect(march).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(march); + expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(0); + }); + + it('FE-ATLAS2-MOBILE-060: someday clears the year and the month again', () => { + const spy = spies(); + render(); + expect(screen.getByRole('button', { name: shortMonths()[4] })).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.someday' })); + expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(0); + expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(0); + }); + + it('FE-ATLAS2-MOBILE-061: from a chosen year the arrows step from that year', () => { + const spy = spies(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearLater' })); + expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2031); + }); + + it('FE-ATLAS2-MOBILE-062: the note goes into the form', () => { + const spy = spies(); + render(); + fireEvent.change(screen.getByPlaceholderText('atlas.bucketNotesPlaceholder'), { target: { value: 'in spring' } }); + expect(spy.setBucketForm).toHaveBeenLastCalledWith(expect.objectContaining({ notes: 'in spring' })); + }); + + it('FE-ATLAS2-MOBILE-063: save waits for a name, then adds the wish', () => { + const spy = spies(); + const { unmount } = render(); + expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeDisabled(); + unmount(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.wishSave' })); + expect(spy.handleAddBucketItem).toHaveBeenCalledOnce(); + }); +}); diff --git a/client/src/mobile/screens/atlas/hub/mHubKit.test.tsx b/client/src/mobile/screens/atlas/hub/mHubKit.test.tsx new file mode 100644 index 000000000..dea3841bd --- /dev/null +++ b/client/src/mobile/screens/atlas/hub/mHubKit.test.tsx @@ -0,0 +1,133 @@ +import { Flag, Globe2, Plane } from 'lucide-react'; +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '../../../../../tests/helpers/render'; +import { MHubAction, MHubDawarichEntry, MHubEmpty, MHubHero, MHubSection, MHubTiles } from './mHubKit'; + +describe('mHubKit', () => { + it('FE-ATLAS2-MOBILE-001: the hero shows its figure, the unit and what sits under it', () => { + render( + + under the figure + + ); + expect(screen.getByText('42')).toBeInTheDocument(); + expect(screen.getByText('countries')).toBeInTheDocument(); + expect(screen.getByText('under the figure')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-002: a hero without unit or children renders the figure alone', () => { + const { container } = render(); + expect(screen.getByText('7')).toBeInTheDocument(); + expect(container.querySelector('.text-subtitle')).toBeNull(); + expect(container.querySelector('.mt-3\\.5')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-003: two across, an odd last tile takes the whole row and every tile keeps its symbol', () => { + render( + + ); + const tile = (label: string) => screen.getByText(label).closest('div') as HTMLElement; + expect(tile('three').className).toContain('col-span-2'); + expect(tile('one').className).not.toContain('col-span-2'); + expect(tile('one').querySelector('svg')).not.toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-004: an even count leaves no tile wide', () => { + render( + + ); + expect(screen.getByText('two').closest('div')?.className).not.toContain('col-span-2'); + }); + + it('FE-ATLAS2-MOBILE-005: three across drops the symbols and shows value and label', () => { + const { container } = render( + + ); + expect(container.firstElementChild?.className).toContain('grid-cols-3'); + expect(screen.getByText('5 / 10')).toBeInTheDocument(); + expect(screen.getByText('holders')).toBeInTheDocument(); + expect(container.querySelector('svg')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-006: a section shows its title, a meta of zero and its action', () => { + render( + more}> +

body

+
+ ); + expect(screen.getByRole('heading', { name: 'Open' })).toBeInTheDocument(); + expect(screen.getByText('0')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'more' })).toBeInTheDocument(); + expect(screen.getByText('body')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-007: a section without meta renders no meta line', () => { + const { container } = render( + +

body

+
+ ); + expect(container.querySelector('.tabular-nums')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-008: the empty state shows title, hint and its action', () => { + render(add} />); + expect(screen.getByText('Nothing yet')).toBeInTheDocument(); + expect(screen.getByText('Add one')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'add' })).toBeInTheDocument(); + }); + + it('FE-ATLAS2-MOBILE-009: the empty state without hint or action is the title alone', () => { + render(); + expect(screen.getByText('Nothing yet')).toBeInTheDocument(); + expect(screen.queryByRole('button')).toBeNull(); + }); + + it('FE-ATLAS2-MOBILE-010: the Dawarich entry names what it does and opens on a tap', () => { + const onClick = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: /Countries from Dawarich/ })); + expect(screen.getByText('Find them')).toBeInTheDocument(); + expect(onClick).toHaveBeenCalledOnce(); + }); + + it('FE-ATLAS2-MOBILE-011: the action runs on a tap and stays still when disabled', () => { + const onClick = vi.fn(); + const { rerender } = render( + + Save + + ); + const button = screen.getByRole('button', { name: 'Save' }); + expect(button.querySelector('svg')).not.toBeNull(); + fireEvent.click(button); + expect(onClick).toHaveBeenCalledOnce(); + rerender( + + Save + + ); + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Save' }).querySelector('svg')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + expect(onClick).toHaveBeenCalledOnce(); + }); +}); diff --git a/client/src/pages/atlas/AtlasBadgeUnlock.test.tsx b/client/src/pages/atlas/AtlasBadgeUnlock.test.tsx new file mode 100644 index 000000000..0fb9dad02 --- /dev/null +++ b/client/src/pages/atlas/AtlasBadgeUnlock.test.tsx @@ -0,0 +1,185 @@ +// FE-ATLAS2-VIEWA-080 to FE-ATLAS2-VIEWA-089: the badge unlock moment over the globe. +import { act, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildViewBadge, buildViewState } from '../../../tests/helpers/atlasViewState'; +import AtlasBadgeUnlock from './AtlasBadgeUnlock'; + +const KEY = 'trek_atlas_badges_seen_7'; + +interface FakeAnimation { + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + onfinish: (() => void) | null; + cancel: ReturnType; +} + +let animations: FakeAnimation[]; +let vibrate: ReturnType; +const originalMatchMedia = window.matchMedia; +const originalAnimate = HTMLElement.prototype.animate; + +beforeEach(() => { + animations = []; + HTMLElement.prototype.animate = function animate(keyframes: Keyframe[], options: KeyframeAnimationOptions) { + const anim: FakeAnimation = { keyframes, options, onfinish: null, cancel: vi.fn() }; + animations.push(anim); + return anim as unknown as Animation; + } as unknown as HTMLElement['animate']; + vibrate = vi.fn(); + Object.defineProperty(navigator, 'vibrate', { value: vibrate, configurable: true, writable: true }); +}); + +afterEach(() => { + window.matchMedia = originalMatchMedia; + HTMLElement.prototype.animate = originalAnimate; + vi.useRealTimers(); +}); + +function lastFrame(anim: FakeAnimation | undefined): Keyframe | undefined { + return anim ? anim.keyframes[anim.keyframes.length - 1] : undefined; +} + +function seen(): string[] | null { + const raw = localStorage.getItem(KEY); + return raw ? (JSON.parse(raw) as string[]) : null; +} + +const EARNED = buildViewBadge({ id: 'countries-5', earned: true, current: 5, target: 5 }); +const OPEN = buildViewBadge({ id: 'countries-10', earned: false, current: 5, target: 10 }); +const REGION = buildViewBadge({ + id: 'region-fr', + motif: 'region', + category: 'regions', + titleKey: 'atlas.badge.region.title', + params: { country: 'FR' }, + earned: true, + current: 13, + target: 13, +}); + +describe('AtlasBadgeUnlock', () => { + it('FE-ATLAS2-VIEWA-080: the first visit only remembers what is earned and celebrates nothing', () => { + const s = buildViewState({ badges: [EARNED, OPEN] }); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + expect(seen()).toEqual(['countries-5']); + expect(animations).toHaveLength(0); + }); + + it('FE-ATLAS2-VIEWA-081: nothing happens before the data and the globe are there, or without a user', () => { + const { container, rerender } = render(); + expect(seen()).toBeNull(); + rerender(); + expect(seen()).toBeNull(); + rerender(); + expect(seen()).toBeNull(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-ATLAS2-VIEWA-082: a badge reached since the last visit rises, names itself and flies to the badges button', () => { + localStorage.setItem(KEY, JSON.stringify([])); + const target = document.createElement('button'); + target.setAttribute('data-atlas-badges-btn', ''); + target.getBoundingClientRect = () => ({ left: 100, top: 10, width: 20, height: 20 }) as DOMRect; + document.body.appendChild(target); + const s = buildViewState({ badges: [EARNED, OPEN] }); + render(); + expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument(); + expect(screen.getByText('atlas.badge.countries.title')).toBeInTheDocument(); + expect(animations).toHaveLength(1); + const last = lastFrame(animations[0]); + expect(last?.transform).toContain('translate(110px, 20px)'); + expect(animations[0]?.options.duration).toBe(3400); + expect(vibrate).toHaveBeenCalledWith(18); + act(() => animations[0]?.onfinish?.()); + expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument(); + expect(seen()).toEqual(['countries-5']); + target.remove(); + }); + + it('FE-ATLAS2-VIEWA-083: without a badges button the medal flies upwards', () => { + localStorage.setItem(KEY, JSON.stringify([])); + render(); + expect(lastFrame(animations[0])?.transform).toContain('translate(0px, -200px)'); + }); + + it('FE-ATLAS2-VIEWA-084: several new badges come one after the other, each remembered', () => { + localStorage.setItem(KEY, JSON.stringify(['old'])); + const s = buildViewState({ badges: [EARNED, REGION] }); + render(); + expect(screen.getByText('atlas.badge.countries.title')).toBeInTheDocument(); + act(() => animations[0]?.onfinish?.()); + // The region badge names its country by its name. + expect(screen.getByText('atlas.badge.region.title(country=France)')).toBeInTheDocument(); + expect(animations).toHaveLength(2); + act(() => animations[1]?.onfinish?.()); + expect(seen()).toEqual(['old', 'countries-5', 'region-fr']); + expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-085: a badge already seen is not celebrated again, and one queued is not queued twice', () => { + localStorage.setItem(KEY, JSON.stringify(['countries-5'])); + const { rerender, container } = render(); + expect(container).toBeEmptyDOMElement(); + localStorage.setItem(KEY, JSON.stringify([])); + const s = buildViewState({ badges: [EARNED] }); + rerender(); + rerender(); + expect(screen.getAllByText('atlas.globe.newBadge')).toHaveLength(1); + act(() => animations[animations.length - 1]?.onfinish?.()); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-ATLAS2-VIEWA-086: with reduced motion the medal stays and leaves after a pause, without animating', () => { + vi.useFakeTimers(); + localStorage.setItem(KEY, JSON.stringify([])); + window.matchMedia = vi.fn((query: string) => ({ + matches: query.includes('reduce'), + media: query, + })) as unknown as typeof window.matchMedia; + render(); + expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument(); + expect(animations).toHaveLength(0); + act(() => { + vi.advanceTimersByTime(2199); + }); + expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument(); + act(() => { + vi.advanceTimersByTime(1); + }); + expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument(); + expect(seen()).toEqual(['countries-5']); + }); + + it('FE-ATLAS2-VIEWA-087: leaving mid-flight cancels the animation', () => { + localStorage.setItem(KEY, JSON.stringify([])); + const { unmount } = render(); + unmount(); + expect(animations[0]?.cancel).toHaveBeenCalled(); + }); + + it('FE-ATLAS2-VIEWA-088: blocked storage counts as a first visit and nothing breaks', () => { + const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('blocked'); + }); + const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('blocked'); + }); + try { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + expect(setItem).toHaveBeenCalledWith(KEY, JSON.stringify(['countries-5'])); + } finally { + getItem.mockRestore(); + setItem.mockRestore(); + } + }); + + it('FE-ATLAS2-VIEWA-089: a country param without a known name keeps its code', () => { + localStorage.setItem(KEY, JSON.stringify([])); + const b = buildViewBadge({ id: 'x', earned: true, params: { country: 'XX', n: 3 } }); + render(); + expect(screen.getByText('atlas.badge.countries.title(country=XX,n=3)')).toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/atlas/AtlasCountryActionDialog.test.tsx b/client/src/pages/atlas/AtlasCountryActionDialog.test.tsx new file mode 100644 index 000000000..4439a0884 --- /dev/null +++ b/client/src/pages/atlas/AtlasCountryActionDialog.test.tsx @@ -0,0 +1,221 @@ +// FE-ATLAS2-VIEWA-100 to FE-ATLAS2-VIEWA-111: the desktop country / region action dialog over a faked +// useAtlasCountryActions (the hook has its own tests). +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { fireEvent, render, screen, within } from '../../../tests/helpers/render'; +import CountryActionDialog, { type CountryActionDialogProps } from './AtlasCountryActionDialog'; +import type { AtlasConfirmAction } from './useAtlasCountryActions'; + +const actions = vi.hoisted(() => ({ + onWishlist: false, + markCountry: vi.fn(), + markRegion: vi.fn(), + unmarkRegion: vi.fn(), + addBucket: vi.fn(), + removeBucket: vi.fn(), + received: [] as unknown[], +})); + +vi.mock('./useAtlasCountryActions', async (importOriginal) => ({ + ...(await importOriginal()), + useAtlasCountryActions: (opts: unknown) => { + actions.received.push(opts); + return actions; + }, +})); + +// The real select opens a portal menu; a native one shows the same options and change. +vi.mock('../../components/shared/CustomSelect', () => ({ + default: ({ + id, + value, + onChange, + options, + }: { + id: string; + value: string; + onChange: (v: string) => void; + options: Array<{ value: string; label: string }>; + }) => ( + + ), +})); + +const t = (k: string) => k; + +function props(confirmAction: AtlasConfirmAction | null, over: Partial = {}) { + return { + t, + language: 'en', + confirmAction, + setConfirmAction: vi.fn(), + executeConfirmAction: vi.fn(), + bucketMonth: 0, + setBucketMonth: vi.fn(), + bucketYear: 0, + setBucketYear: vi.fn(), + setData: vi.fn(), + visitedRegions: {}, + setVisitedRegions: vi.fn(), + bucketList: [], + setBucketList: vi.fn(), + handleDeleteBucketItem: vi.fn(async () => undefined), + ...over, + } satisfies CountryActionDialogProps; +} + +const FRANCE: AtlasConfirmAction = { type: 'choose', code: 'FR', name: 'France' }; +const BAVARIA: AtlasConfirmAction = { + type: 'choose-region', + code: 'DE', + name: 'Bavaria', + regionCode: 'DE-BY', + countryName: 'Germany', +}; + +beforeEach(() => { + actions.onWishlist = false; + actions.received = []; + for (const fn of [ + actions.markCountry, + actions.markRegion, + actions.unmarkRegion, + actions.addBucket, + actions.removeBucket, + ]) + fn.mockClear(); +}); + +describe('CountryActionDialog', () => { + it('FE-ATLAS2-VIEWA-100: without a confirm action nothing shows, the hook still runs', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(actions.received).toHaveLength(1); + }); + + it('FE-ATLAS2-VIEWA-101: a country offers to mark it or wish for it, with its flag and name', () => { + const p = props(FRANCE); + render(); + expect(screen.getByRole('heading', { name: 'France' })).toBeInTheDocument(); + expect(screen.getByRole('img', { name: 'FR' })).toHaveAttribute('src', 'https://flagcdn.com/w80/fr.png'); + expect(screen.getByText('atlas.markVisitedHint')).toBeInTheDocument(); + expect(screen.getByText('atlas.addToBucketHint')).toBeInTheDocument(); + expect(screen.queryByText('atlas.removeFromBucket')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /atlas\.markVisited/ })); + expect(actions.markCountry).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', { name: /atlas\.addToBucket/ })); + expect(p.setConfirmAction).toHaveBeenCalledWith({ ...FRANCE, type: 'bucket' }); + }); + + it('FE-ATLAS2-VIEWA-102: cancel and the close button both close the dialog', () => { + const p = props(FRANCE); + render(); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + expect(p.setConfirmAction).toHaveBeenCalledTimes(2); + expect(p.setConfirmAction).toHaveBeenNthCalledWith(1, null); + expect(p.setConfirmAction).toHaveBeenNthCalledWith(2, null); + }); + + it('FE-ATLAS2-VIEWA-103: a country already on the wishlist offers to remove it', () => { + actions.onWishlist = true; + render(); + expect(screen.getByText('atlas.removeFromBucketHint')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /atlas\.removeFromBucket/ })); + expect(actions.removeBucket).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWA-104: a code that is not ISO A2 gets no flag image', () => { + render(); + expect(screen.getByRole('heading', { name: 'Kosovo' })).toBeInTheDocument(); + expect(screen.queryByRole('img')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-105: a region names its country and offers to mark it or wish for it', () => { + const p = props(BAVARIA); + render(); + expect(screen.getByRole('heading', { name: 'Bavaria' })).toBeInTheDocument(); + expect(screen.getByText('Germany')).toBeInTheDocument(); + expect(screen.getByText('atlas.markRegionVisitedHint')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /atlas\.markVisited/ })); + expect(actions.markRegion).toHaveBeenCalledWith(); + fireEvent.click(screen.getByRole('button', { name: /atlas\.addToBucket/ })); + expect(p.setConfirmAction).toHaveBeenCalledWith({ ...BAVARIA, type: 'bucket' }); + }); + + it('FE-ATLAS2-VIEWA-106: marking asks to confirm and the primary button confirms', () => { + const p = props({ ...FRANCE, type: 'mark' }); + render(); + expect(screen.getByText('atlas.confirmMark')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.markVisited' })); + expect(p.executeConfirmAction).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWA-107: unmarking a country asks and the danger button confirms', () => { + const p = props({ ...FRANCE, type: 'unmark' }); + render(); + expect(screen.getByText('atlas.confirmUnmark')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' })); + expect(p.executeConfirmAction).toHaveBeenCalledTimes(1); + expect(actions.unmarkRegion).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-VIEWA-108: unmarking a region asks and the danger button unmarks the region', () => { + const p = props({ ...BAVARIA, type: 'unmark-region' }); + render(); + expect(screen.getByText('atlas.confirmUnmarkRegion')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' })); + expect(actions.unmarkRegion).toHaveBeenCalledTimes(1); + expect(p.executeConfirmAction).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-VIEWA-109: the wish step asks when, with months and twenty years, and goes back to the choice', () => { + const p = props({ ...FRANCE, type: 'bucket' }, { bucketMonth: 0, bucketYear: 0 }); + render(); + expect(screen.getByText('atlas.bucketWhen')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'common.cancel' })).not.toBeInTheDocument(); + const month = screen.getByLabelText('atlas.month'); + const year = screen.getByLabelText('atlas.year'); + expect(within(month).getAllByRole('option')).toHaveLength(13); + expect(within(month).getAllByRole('option')[0]).toHaveTextContent('common.none'); + expect(within(month).getAllByRole('option')[1]).toHaveTextContent('January'); + const years = within(year).getAllByRole('option'); + expect(years).toHaveLength(21); + const now = new Date().getFullYear(); + expect(years[1]).toHaveTextContent(String(now)); + expect(years[20]).toHaveTextContent(String(now + 19)); + fireEvent.change(month, { target: { value: '4' } }); + expect(p.setBucketMonth).toHaveBeenCalledWith(4); + fireEvent.change(year, { target: { value: String(now + 1) } }); + expect(p.setBucketYear).toHaveBeenCalledWith(now + 1); + fireEvent.click(screen.getByRole('button', { name: 'common.back' })); + expect(p.setConfirmAction).toHaveBeenCalledWith({ ...FRANCE, type: 'choose' }); + }); + + it('FE-ATLAS2-VIEWA-110: back from a region wish returns to the region choice', () => { + const p = props({ ...BAVARIA, type: 'bucket' }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'common.back' })); + expect(p.setConfirmAction).toHaveBeenCalledWith({ ...BAVARIA, type: 'choose-region' }); + }); + + it('FE-ATLAS2-VIEWA-111: adding the wish passes the month target and clears the picker once added', () => { + const p = props({ ...FRANCE, type: 'bucket' }, { bucketMonth: 4, bucketYear: 2027 }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'atlas.addToBucket' })); + expect(actions.addBucket).toHaveBeenCalledTimes(1); + const [target, onAdded] = actions.addBucket.mock.calls[0] as [string | null, () => void]; + expect(target).toBe('2027-04'); + expect(p.setBucketMonth).not.toHaveBeenCalled(); + onAdded(); + expect(p.setBucketMonth).toHaveBeenCalledWith(0); + expect(p.setBucketYear).toHaveBeenCalledWith(0); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobeBadges.test.tsx b/client/src/pages/atlas/AtlasGlobeBadges.test.tsx new file mode 100644 index 000000000..ba75417d0 --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobeBadges.test.tsx @@ -0,0 +1,171 @@ +// FE-ATLAS2-VIEWA-020 to FE-ATLAS2-VIEWA-031: the badges tab of the Atlas hub, overview and detail page. +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { buildViewBadge, buildViewState } from '../../../tests/helpers/atlasViewState'; +import AtlasGlobeBadges from './AtlasGlobeBadges'; + +const FIVE = buildViewBadge({ id: 'countries-5', target: 5, current: 5, earned: true, year: 2021, country: 'FR' }); +const TEN = buildViewBadge({ id: 'countries-10', target: 10, current: 5, tier: 'silver' }); +const REGION = buildViewBadge({ + id: 'region-fr', + category: 'regions', + motif: 'region', + titleKey: 'atlas.badge.region.title', + descKey: 'atlas.badge.region.desc', + params: { country: 'FR' }, + earned: true, + current: 13, + target: 13, +}); + +function tile(name: RegExp): HTMLElement { + return screen.getByRole('button', { name }); +} + +describe('AtlasGlobeBadges overview', () => { + it('FE-ATLAS2-VIEWA-020: one section per category that has badges, with its earned count', () => { + const s = buildViewState({ badges: [FIVE, TEN, REGION] }); + render(); + const headings = screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent); + expect(headings).toEqual(['atlas.badgeCat.countries', 'atlas.badgeCat.regions']); + const countries = screen.getByText('atlas.badgeCat.countries').closest('section') as HTMLElement; + expect(within(countries).getByText('1 / 2')).toBeInTheDocument(); + const regions = screen.getByText('atlas.badgeCat.regions').closest('section') as HTMLElement; + expect(within(regions).getByText('1 / 1')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-021: an earned tile names its year, an open one its progress, a country param its name', () => { + const s = buildViewState({ badges: [FIVE, TEN, REGION] }); + render(); + const buttons = screen.getAllByRole('button'); + expect(buttons[0]).toHaveAttribute('data-earned', '1'); + expect(buttons[0]).toHaveTextContent('2021'); + expect(buttons[1]).toHaveAttribute('data-earned', '0'); + expect(buttons[1]).toHaveTextContent('5 / 10'); + expect(buttons[2]).toHaveTextContent('atlas.badge.region.title(country=France)'); + }); + + it('FE-ATLAS2-VIEWA-022: an earned tile without a year shows no second line; unknown country codes stay', () => { + const b = buildViewBadge({ id: 'x', earned: true, year: null, params: { country: 'XX' } }); + const s = buildViewState({ badges: [b] }); + render(); + const button = screen.getAllByRole('button')[0]; + expect(button).toHaveTextContent('atlas.badge.countries.title(country=XX)'); + expect(button.querySelectorAll('span.tabular-nums')).toHaveLength(0); + }); + + it('FE-ATLAS2-VIEWA-023: the pointer tilts a medal and leaving straightens it', () => { + const s = buildViewState({ badges: [TEN] }); + render(); + const button = screen.getAllByRole('button')[0]; + button.getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect; + fireEvent.pointerMove(button, { clientX: 75, clientY: 25 }); + expect(button.style.getPropertyValue('--mx')).toBe('75%'); + expect(button.style.getPropertyValue('--my')).toBe('25%'); + expect(button.style.getPropertyValue('--rx')).toBe(`${25 / 9}deg`); + expect(button.style.getPropertyValue('--ry')).toBe(`${25 / 9}deg`); + fireEvent.pointerMove(button, { clientX: 1000, clientY: -1000 }); + expect(button.style.getPropertyValue('--rx')).toBe('12deg'); + expect(button.style.getPropertyValue('--ry')).toBe('12deg'); + fireEvent.pointerLeave(button); + expect(button.style.getPropertyValue('--rx')).toBe('0deg'); + expect(button.style.getPropertyValue('--ry')).toBe('0deg'); + }); + + it('FE-ATLAS2-VIEWA-024: no badges render no sections', () => { + const s = buildViewState({ badges: [] }); + render(); + expect(screen.queryByRole('heading')).not.toBeInTheDocument(); + }); +}); + +describe('AtlasGlobeBadges detail', () => { + it('FE-ATLAS2-VIEWA-025: an open badge shows tier, how-to, progress, what is left and its stages', () => { + const s = buildViewState({ badges: [FIVE, TEN, REGION] }); + render(); + fireEvent.click(screen.getAllByRole('button')[1]); + expect(screen.getByRole('heading', { level: 3, name: 'atlas.badge.countries.title' })).toBeInTheDocument(); + expect(screen.getByText('atlas.badgeTier.silver')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.howTo')).toBeInTheDocument(); + expect(screen.getByText('atlas.badge.countries.desc(count=10)')).toBeInTheDocument(); + expect(screen.getByText('5 / 10')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.toGo')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.toGo').previousElementSibling).toHaveTextContent('5'); + expect(screen.queryByText('atlas.globe.reached')).not.toBeInTheDocument(); + expect(screen.queryByText('atlas.globe.madeBy')).not.toBeInTheDocument(); + expect(screen.queryByText('atlas.globe.holders')).not.toBeInTheDocument(); + expect(screen.getByText('atlas.globe.stages')).toBeInTheDocument(); + expect(screen.getByText('1 / 2')).toBeInTheDocument(); + expect(s.loadPeople).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-VIEWA-026: an earned badge says when and which country made it', () => { + const s = buildViewState({ badges: [FIVE, TEN] }); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(screen.getAllByText('atlas.globe.reached')).toHaveLength(2); + expect(screen.getByText('2021')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.madeBy')).toBeInTheDocument(); + expect(screen.getByText('France')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-027: an earned badge without year shows a tick; a country without a name keeps its code', () => { + const b = buildViewBadge({ id: 'only', earned: true, current: 5, target: 5, year: null, country: 'XX' }); + const s = buildViewState({ badges: [b] }); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(screen.getByText('✓')).toBeInTheDocument(); + expect(screen.getByText('XX')).toBeInTheDocument(); + // A single stage has no ladder. + expect(screen.queryByText('atlas.globe.stages')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-028: with comparing on it loads the travellers and counts who holds the badge', () => { + const people = [{ badges: [{ id: 'countries-5' }] }, { badges: [] }]; + const s = buildViewState({ badges: [FIVE, TEN], compareEnabled: true, people }); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(s.loadPeople).toHaveBeenCalledTimes(1); + expect(screen.getByText('atlas.globe.holders')).toBeInTheDocument(); + // One other traveller plus the reader, out of two others plus the reader. + expect(screen.getByText('2 / 3')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-029: comparing on but travellers not loaded yet shows no holders tile', () => { + const s = buildViewState({ badges: [TEN], compareEnabled: true, people: null }); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(s.loadPeople).toHaveBeenCalled(); + expect(screen.queryByText('atlas.globe.holders')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-030: a stage in the ladder opens that stage, the open one is marked current', () => { + const s = buildViewState({ badges: [FIVE, TEN] }); + render(); + fireEvent.click(screen.getAllByRole('button')[1]); + const stages = screen.getAllByRole('button').filter((b) => b.hasAttribute('aria-current')); + expect(stages).toHaveLength(2); + expect(stages[1]).toHaveAttribute('aria-current', 'true'); + expect(stages[0]).toHaveAttribute('aria-current', 'false'); + fireEvent.click(stages[0]); + expect(screen.getByText('atlas.globe.madeBy')).toBeInTheDocument(); + expect(screen.getAllByRole('button').filter((b) => b.getAttribute('aria-current') === 'true')).toHaveLength(1); + }); + + it('FE-ATLAS2-VIEWA-031: the back button returns to the overview; the detail medal tilts too', () => { + const s = buildViewState({ badges: [FIVE, TEN] }); + const { container } = render(); + fireEvent.click(screen.getAllByRole('button')[1]); + const medal = container.querySelector('div.ag-medal') as HTMLElement; + medal.getBoundingClientRect = () => ({ left: 0, top: 0, width: 200, height: 200 }) as DOMRect; + fireEvent.pointerMove(medal, { clientX: 100, clientY: 100 }); + expect(medal.style.getPropertyValue('--rx')).toBe('0deg'); + expect(medal.style.getPropertyValue('--mx')).toBe('50%'); + fireEvent.pointerLeave(medal); + expect(medal.style.getPropertyValue('--ry')).toBe('0deg'); + fireEvent.click(tile(/atlas\.badgeCat\.countries/)); + expect(screen.getByRole('heading', { level: 3, name: 'atlas.badgeCat.countries' })).toBeInTheDocument(); + expect(screen.getByText('1 / 2')).toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobeDawarich.test.tsx b/client/src/pages/atlas/AtlasGlobeDawarich.test.tsx new file mode 100644 index 000000000..99353ec29 --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobeDawarich.test.tsx @@ -0,0 +1,225 @@ +// FE-ATLAS2-VIEWA-060 to FE-ATLAS2-VIEWA-070: the Dawarich tab of the Atlas hub over a faked useDawarichAtlas. +import { fireEvent, render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildViewState } from '../../../tests/helpers/atlasViewState'; +import type { DawarichAtlasState } from '../../components/Dawarich/useDawarichAtlas'; +import AtlasGlobeDawarich from './AtlasGlobeDawarich'; + +const hook = vi.hoisted(() => ({ + state: null as unknown, + calls: [] as Array<{ initialTab?: string; onChanged?: () => void }>, +})); + +vi.mock('../../components/Dawarich/useDawarichAtlas', async (importOriginal) => ({ + ...(await importOriginal()), + useDawarichAtlas: (opts: { initialTab?: string; onChanged?: () => void }) => { + hook.calls.push(opts); + return hook.state; + }, +})); + +function fakeDawarich(over: Record = {}): DawarichAtlasState { + const d: Record = { + tab: 'wishes', + setTab: vi.fn(), + busy: false, + loaded: false, + anything: false, + run: vi.fn(), + confirm: vi.fn(), + matches: [], + openMatches: [], + offered: [], + picked: new Set(), + pickedCountries: new Set(), + togglePicked: vi.fn(), + togglePickedCountry: vi.fn(), + selected: 0, + writing: false, + scan: null, + countries: null, + ...over, + }; + hook.state = d; + return d as unknown as DawarichAtlasState; +} + +const VISITED = { itemId: 1, name: 'Louvre', alreadyVisited: true, match: null }; +const FOUND = { + itemId: 2, + name: 'Colosseum', + alreadyVisited: false, + match: { distanceMeters: 1500, minutes: 90, at: '2025-03-04T12:00:00Z' }, +}; +const MISSED = { itemId: 3, name: 'Machu Picchu', alreadyVisited: false, match: null }; + +const FRANCE = { countryCode: 'FR', sourceName: 'France', cities: [{ name: 'Paris' }, { name: 'Lyon' }] }; +const ITALY = { countryCode: 'IT', sourceName: 'Italia', cities: [] }; + +beforeEach(() => { + hook.calls = []; +}); + +describe('AtlasGlobeDawarich', () => { + it('FE-ATLAS2-VIEWA-060: asks the hub tab first and reloads the Atlas after a write', () => { + const d = fakeDawarich(); + const s = buildViewState({ dawarichSub: 'countries' }); + render(); + expect(hook.calls[0]?.initialTab).toBe('countries'); + expect(d.setTab).toHaveBeenCalledWith('countries'); + hook.calls[0]?.onChanged?.(); + expect(s.reload).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWA-061: the two segments carry their counts and switch the tab', () => { + const d = fakeDawarich({ openMatches: [FOUND], offered: [] }); + render(); + const wishes = screen.getByRole('button', { name: /dawarich\.atlas\.tab\.wishes/ }); + const countries = screen.getByRole('button', { name: /dawarich\.atlas\.tab\.countries/ }); + expect(wishes).toHaveTextContent('1'); + expect(wishes).toHaveClass('bg-surface-card'); + expect(countries).not.toHaveTextContent(/\d/); + fireEvent.click(countries); + expect(d.setTab).toHaveBeenCalledWith('countries'); + }); + + it('FE-ATLAS2-VIEWA-062: while it asks it says what it does, per tab', () => { + fakeDawarich({ busy: true }); + const { unmount } = render(); + expect(screen.getByText(/dawarich\.bucket\.scanning/)).toBeInTheDocument(); + unmount(); + fakeDawarich({ busy: true, tab: 'countries' }); + render(); + expect(screen.getByText(/dawarich\.atlas\.loading/)).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-063: before the first question it explains and offers to ask (wishes)', () => { + const d = fakeDawarich(); + render(); + expect(screen.getByText('dawarich.bucket.title')).toBeInTheDocument(); + expect(screen.getByText('dawarich.bucket.description')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.scan' })); + expect(d.run).toHaveBeenCalledTimes(1); + // Notes only once something was asked. + expect(screen.queryByText(/dawarich\.bucket\.rule/)).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-064: before the first question it explains and offers to ask (countries)', () => { + const d = fakeDawarich({ tab: 'countries' }); + render(); + expect(screen.getByText('dawarich.atlas.title')).toBeInTheDocument(); + expect(screen.getByText('dawarich.atlas.description')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.load' })); + expect(d.run).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWA-065: nothing found says so, offers to ask again and lists the scan notes', () => { + const d = fakeDawarich({ + loaded: true, + scan: { matches: [], skippedWithoutCoordinates: 2, truncated: true, fetchedAt: '' }, + }); + render(); + expect(screen.getByText('dawarich.bucket.noMatches')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' })); + expect(d.run).toHaveBeenCalledTimes(1); + expect(screen.getByText(/dawarich\.bucket\.skipped\(count=2\)/)).toBeInTheDocument(); + expect(screen.getByText(/dawarich\.bucket\.truncated/)).toBeInTheDocument(); + expect(screen.getByText(/dawarich\.bucket\.rule\(meters=/)).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-066: countries found empty say so', () => { + fakeDawarich({ + tab: 'countries', + loaded: true, + countries: { countries: [], unresolved: [], fetchedAt: '' }, + }); + render(); + expect(screen.getByText('dawarich.atlas.empty')).toBeInTheDocument(); + expect(screen.getByText(/dawarich\.atlas\.window/)).toBeInTheDocument(); + expect(screen.queryByText(/dawarich\.atlas\.unresolved/)).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-067: wishes found list visited, matched and missed ones, each tickable unless visited', () => { + const d = fakeDawarich({ + loaded: true, + anything: true, + matches: [VISITED, FOUND, MISSED], + openMatches: [FOUND, MISSED], + picked: new Set([2]), + selected: 1, + scan: { matches: [], skippedWithoutCoordinates: 0, truncated: false, fetchedAt: '' }, + }); + render(); + const louvre = screen.getByRole('checkbox', { name: 'Louvre' }); + expect(louvre).toBeDisabled(); + expect(louvre).toHaveTextContent('dawarich.bucket.alreadyVisited'); + const colosseum = screen.getByRole('checkbox', { name: 'Colosseum' }); + expect(colosseum).toHaveAttribute('aria-checked', 'true'); + expect(colosseum).toHaveTextContent('dawarich.bucket.kilometersAway(km=1.5)'); + expect(colosseum).toHaveTextContent('dawarich.duration.hoursMinutes(hours=1,minutes=30)'); + expect(colosseum).toHaveTextContent('Mar 4, 2025'); + const machu = screen.getByRole('checkbox', { name: 'Machu Picchu' }); + expect(machu).toHaveAttribute('aria-checked', 'false'); + expect(machu).toHaveTextContent('dawarich.bucket.noMatches'); + fireEvent.click(machu); + expect(d.togglePicked).toHaveBeenCalledWith(3); + expect(screen.queryByText(/dawarich\.bucket\.skipped/)).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-068: the footer counts the ticks, asks again and confirms the wishes', () => { + const d = fakeDawarich({ + loaded: true, + anything: true, + matches: [FOUND], + openMatches: [FOUND], + picked: new Set([2]), + selected: 1, + }); + render(); + expect(screen.getByText('dawarich.selected(count=1)')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' })); + expect(d.run).toHaveBeenCalledTimes(1); + const confirm = screen.getByRole('button', { name: 'dawarich.bucket.confirm(count=1)' }); + expect(confirm).toBeEnabled(); + fireEvent.click(confirm); + expect(d.confirm).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWA-069: countries found list their cities and are tickable; nothing ticked keeps confirm off', () => { + const d = fakeDawarich({ + tab: 'countries', + loaded: true, + anything: true, + offered: [FRANCE, ITALY], + pickedCountries: new Set(['FR']), + selected: 0, + countries: { countries: [], unresolved: ['Narnia'], fetchedAt: '' }, + }); + render(); + const france = screen.getByRole('checkbox', { name: 'France' }); + expect(france).toHaveAttribute('aria-checked', 'true'); + expect(france).toHaveTextContent('dawarich.atlas.cities(count=2)'); + expect(france).toHaveTextContent('Paris, Lyon'); + const italy = screen.getByRole('checkbox', { name: 'Italy' }); + expect(italy).not.toHaveTextContent('dawarich.atlas.cities'); + fireEvent.click(italy); + expect(d.togglePickedCountry).toHaveBeenCalledWith('IT'); + expect(screen.getByRole('button', { name: 'dawarich.atlas.accept(count=0)' })).toBeDisabled(); + expect(screen.getByText(/dawarich\.atlas\.unresolved\(names=Narnia\)/)).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-070: a write in flight keeps confirm off even with ticks', () => { + fakeDawarich({ + tab: 'countries', + loaded: true, + anything: true, + offered: [FRANCE], + pickedCountries: new Set(['FR']), + selected: 1, + writing: true, + }); + render(); + expect(screen.getByRole('button', { name: 'dawarich.atlas.accept(count=1)' })).toBeDisabled(); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobeDialogs.test.tsx b/client/src/pages/atlas/AtlasGlobeDialogs.test.tsx new file mode 100644 index 000000000..fa6b34e9e --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobeDialogs.test.tsx @@ -0,0 +1,236 @@ +// FE-ATLAS2-VIEWB-090 to FE-ATLAS2-VIEWB-104: the globe's country dialogs and its layers dialog. +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildAtlasData } from '../../../tests/helpers/atlas'; +import { viewState } from '../../../tests/helpers/atlasGlobeViews'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import { GlobeCountryDialogs, GlobeLayersDialog } from './AtlasGlobeDialogs'; + +interface ActionProps { + setConfirmAction: (v: unknown) => void; + bucketList: unknown; + visitedRegions: unknown; +} + +const actionProps: { last: ActionProps | null } = { last: null }; +const placesProps: { last: { detail: unknown; onOpenTrip: (id: number) => void } | null } = { last: null }; + +vi.mock('./AtlasCountryActionDialog', () => ({ + default: (props: ActionProps) => { + actionProps.last = props; + return
action-dialog
; + }, +})); + +vi.mock('../../components/Atlas/AtlasCountryPlaces', () => ({ + default: (props: { detail: unknown; onOpenTrip: (id: number) => void }) => { + placesProps.last = props; + return
country-places
; + }, +})); + +beforeEach(() => { + actionProps.last = null; + placesProps.last = null; +}); + +function detailOf(data: Record | null) { + return { a2: 'FR', data }; +} + +describe('GlobeCountryDialogs', () => { + it('FE-ATLAS2-VIEWB-090: without a detail only the action dialog is there, wired to the globe state', () => { + const bucket = [{ id: 1 }]; + const regions = { FR: [] }; + render(); + expect(screen.getByText('action-dialog')).toBeInTheDocument(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(actionProps.last?.bucketList).toBe(bucket); + expect(actionProps.last?.visitedRegions).toBe(regions); + }); + + it('FE-ATLAS2-VIEWB-091: clearing the confirm step closes the dialogs, a new step or an updater does not', () => { + const setConfirmAction = vi.fn(); + const closeDialogs = vi.fn(); + render(); + const set = actionProps.last?.setConfirmAction; + if (!set) throw new Error('no setter'); + set({ type: 'mark', code: 'FR' }); + expect(setConfirmAction).toHaveBeenLastCalledWith({ type: 'mark', code: 'FR' }); + expect(closeDialogs).not.toHaveBeenCalled(); + const updater = () => null; + set(updater); + expect(setConfirmAction).toHaveBeenLastCalledWith(updater); + expect(closeDialogs).not.toHaveBeenCalled(); + set(null); + expect(setConfirmAction).toHaveBeenLastCalledWith(null); + expect(closeDialogs).toHaveBeenCalledTimes(1); + }); + + it('FE-ATLAS2-VIEWB-092: the detail names the country with its trip and place counts', () => { + const data = buildAtlasData(); + render( + + ); + expect(screen.getByRole('heading', { name: 'name-FR' })).toBeInTheDocument(); + expect(screen.getByText('2 atlas.trips[count=2], 5 atlas.places[count=5]')).toBeInTheDocument(); + expect(screen.getByText('country-places')).toBeInTheDocument(); + // A visited country is not marked as planned, and a country from trips cannot be unmarked. + expect(screen.queryByText('atlas.planned')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'atlas.unmark' })).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-093: a country not in the data has no counts in its header', () => { + render( + + ); + expect(screen.getByRole('heading', { name: 'name-JP' })).toBeInTheDocument(); + expect(screen.queryByText(/atlas\.trips/)).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-094: a planned country carries the planned pill', () => { + const data = buildAtlasData({ + countries: [{ code: 'FR', tripCount: 1, placeCount: 0, firstVisit: null, lastVisit: null, status: 'planned' }], + }); + render( + + ); + expect(screen.getByText('atlas.planned')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-095: trips without a place in the country get a chip that opens the trip', () => { + const onOpenTrip = vi.fn(); + const detail = detailOf({ + places: [{ id: 1, trip_id: 10 }], + trips: [ + { id: 10, title: 'Placed trip' }, + { id: 11, title: 'Flight only' }, + ], + }); + render(); + expect(screen.queryByRole('button', { name: /Placed trip/ })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Flight only/ })); + expect(onOpenTrip).toHaveBeenCalledWith(11); + expect(placesProps.last?.onOpenTrip).toBe(onOpenTrip); + }); + + it('FE-ATLAS2-VIEWB-096: the region progress shows the share visited', () => { + render( + + ); + expect(screen.getByText('atlas.regions')).toBeInTheDocument(); + expect(screen.getByText('3 / 12')).toBeInTheDocument(); + const fill = document.querySelector('.duration-700'); + expect(fill?.style.width).toBe('25%'); + }); + + it('FE-ATLAS2-VIEWB-097: a country without regions shows no progress', () => { + render( + + ); + expect(screen.queryByText('atlas.regions')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-098: while the detail loads it spins instead of listing places', () => { + render(); + expect(screen.queryByText('country-places')).not.toBeInTheDocument(); + expect(document.querySelector('.animate-spin')).not.toBeNull(); + }); + + it('FE-ATLAS2-VIEWB-099: a hand-marked country can be unmarked, and close closes', () => { + const askUnmarkDetail = vi.fn(); + const closeDialogs = vi.fn(); + render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' })); + expect(askUnmarkDetail).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(closeDialogs).toHaveBeenCalledTimes(1); + }); +}); + +describe('GlobeLayersDialog', () => { + it('FE-ATLAS2-VIEWB-100: the planned switch flips the planned countries', () => { + const setShowPlanned = vi.fn(); + render(); + expect(screen.getByRole('heading', { name: 'atlas.globe.layers' })).toBeInTheDocument(); + const sw = screen.getByRole('button', { name: 'atlas.showPlanned' }); + expect(sw).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(sw); + expect(setShowPlanned).toHaveBeenCalledWith(false); + // No flights, no flights switch. + expect(screen.queryByRole('button', { name: 'atlas.globe.flights' })).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-101: with flights there is a flights switch', () => { + const setShowFlights = vi.fn(); + render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.flights' })); + expect(setShowFlights).toHaveBeenCalledWith(true); + }); + + it('FE-ATLAS2-VIEWB-102: an empty flight list shows no flights switch', () => { + render(); + expect(screen.queryByRole('button', { name: 'atlas.globe.flights' })).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-103: each plugin layer gets a switch, on unless hidden, falling back to its id', () => { + const togglePluginLayer = vi.fn(); + render( + + ); + expect(screen.getByRole('button', { name: 'Rain radar' })).toHaveAttribute('aria-pressed', 'true'); + const snow = screen.getByRole('button', { name: 'snow' }); + expect(snow).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(snow); + expect(togglePluginLayer).toHaveBeenCalledWith('p:snow'); + }); + + it('FE-ATLAS2-VIEWB-104: the colour modes switch the globe paint, the current one is lit, close closes', () => { + const setColorMode = vi.fn(); + const onClose = vi.fn(); + render(); + expect(screen.getByRole('button', { name: 'atlas.globe.colorStatus' }).className).toContain('bg-surface-card'); + expect(screen.getByRole('button', { name: 'atlas.globe.colorYear' }).className).not.toContain('bg-surface-card'); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.colorYear' })); + expect(setColorMode).toHaveBeenCalledWith('year'); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.colorCountry' })); + expect(setColorMode).toHaveBeenCalledWith('country'); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(onClose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobeOverview.test.tsx b/client/src/pages/atlas/AtlasGlobeOverview.test.tsx new file mode 100644 index 000000000..ae6f739bb --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobeOverview.test.tsx @@ -0,0 +1,104 @@ +// FE-ATLAS2-VIEWB-060 to FE-ATLAS2-VIEWB-065: the statistics tab of the Atlas hub. +import { fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useParams } from 'react-router'; +import { describe, expect, it, vi } from 'vitest'; +import { buildAtlasData } from '../../../tests/helpers/atlas'; +import { viewState } from '../../../tests/helpers/atlasGlobeViews'; +import AtlasGlobeOverview from './AtlasGlobeOverview'; +import type { AtlasGlobeState } from './useAtlasGlobe'; + +function TripProbe() { + const { id } = useParams(); + return
trip page {id}
; +} + +function mount(s: AtlasGlobeState) { + return render( + + + } /> + } /> + + + ); +} + +const totals = { countries: 39, continents: 3, regions: 14, trips: 5, firstYear: 2020, perYear: new Map() }; + +describe('AtlasGlobeOverview', () => { + it('FE-ATLAS2-VIEWB-060: the headline gives the countries and their share of the world, with the planned ones', () => { + const data = buildAtlasData({ + stats: { + totalTrips: 3, + totalPlaces: 10, + totalCountries: 39, + totalDays: 14, + totalCities: 3, + totalCountriesPlanned: 2, + totalCountriesIdea: 1, + }, + }); + mount(viewState({ data, totals })); + expect(screen.getByText('39')).toBeInTheDocument(); + expect(screen.getByText('atlas.countries[count=39]')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.worldShare[share=20]')).toBeInTheDocument(); + expect(screen.getByText(/\+3/)).toHaveTextContent('+3 atlas.planned'); + }); + + it('FE-ATLAS2-VIEWB-061: with nothing planned and no data the headline leaves the planned count out', () => { + mount(viewState({ data: null, totals: { ...totals, countries: 0 } })); + expect(screen.getByText('atlas.globe.worldShare[share=0]')).toBeInTheDocument(); + expect(screen.queryByText(/atlas\.planned/)).not.toBeInTheDocument(); + // The figures still show, all zero. + expect(screen.getByText('atlas.trips[count=0]')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-062: the continents chart scales bars to the largest and leaves Antarctica out until visited', () => { + const data = buildAtlasData({ continents: { Europe: 4, Asia: 2 } }); + const { container } = mount(viewState({ data, totals })); + expect(screen.getByText('3 / 6')).toBeInTheDocument(); + expect(screen.queryByText('atlas.antarctica')).not.toBeInTheDocument(); + const europe = screen.getByTitle('atlas.europe').parentElement as HTMLElement; + expect(europe).toHaveTextContent('4'); + const bars = container.querySelectorAll('.rounded-t-\\[6px\\]'); + expect(bars).toHaveLength(6); + expect(bars[0].style.height).toBe('100%'); + expect(bars[0].className).toContain('bg-accent'); + expect(bars[1].style.height).toBe('50%'); + expect(bars[2].style.height).toBe('8%'); + expect(bars[2].className).toContain('bg-surface-tertiary'); + }); + + it('FE-ATLAS2-VIEWB-063: a visited Antarctica joins the chart', () => { + const data = buildAtlasData({ continents: { Antarctica: 1 } }); + mount(viewState({ data, totals })); + expect(screen.getByTitle('atlas.antarctica')).toBeInTheDocument(); + expect(screen.getByText('3 / 7')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-064: with Dawarich on, its entry opens the recorded countries', () => { + const openDawarich = vi.fn(); + mount(viewState({ data: buildAtlasData(), totals, dawarichEnabled: true, openDawarich })); + fireEvent.click(screen.getByRole('button', { name: /atlas.globe.dawarichCountries/ })); + expect(openDawarich).toHaveBeenCalledWith('countries'); + }); + + it('FE-ATLAS2-VIEWB-065: the next trip counts down and opens the trip', () => { + // The server sends the days left beside the trip, which the shared type does not list. + const nextTrip = { id: 42, title: 'Lisbon', daysUntil: 9 }; + const data = buildAtlasData({ nextTrip }); + mount(viewState({ data, totals })); + expect(screen.getByText('9')).toBeInTheDocument(); + expect(screen.getByText('atlas.daysLeft')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Lisbon/ })); + expect(screen.getByText('trip page 42')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-066: a next trip without a countdown shows only its title, and no Dawarich entry when off', () => { + const data = buildAtlasData({ nextTrip: { id: 5, title: 'Rome', countryCode: 'IT' } }); + mount(viewState({ data, totals })); + expect(screen.getByText('Rome')).toBeInTheDocument(); + expect(screen.queryByText('atlas.daysLeft')).not.toBeInTheDocument(); + expect(screen.queryByText('atlas.globe.dawarichCountries')).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobePassport.test.tsx b/client/src/pages/atlas/AtlasGlobePassport.test.tsx new file mode 100644 index 000000000..f455ced2d --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobePassport.test.tsx @@ -0,0 +1,202 @@ +// FE-ATLAS2-VIEWB-080 to FE-ATLAS2-VIEWB-089: the Atlas hub dialog and another traveller's page. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { viewBadge, viewState } from '../../../tests/helpers/atlasGlobeViews'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import { useAddonStore } from '../../store/addonStore'; +import AtlasGlobePassport from './AtlasGlobePassport'; + +vi.mock('./AtlasGlobeOverview', () => ({ default: () =>
tab-overview
})); +vi.mock('./AtlasGlobeWishlist', () => ({ default: () =>
tab-wishlist
})); +vi.mock('./AtlasGlobeDawarich', () => ({ default: () =>
tab-dawarich
})); +vi.mock('./AtlasGlobeTours', () => ({ default: () =>
tab-tours
})); +vi.mock('./AtlasGlobeBadges', () => ({ default: () =>
tab-badges
})); +vi.mock('./AtlasGlobeTravellers', () => ({ default: () =>
tab-travellers
})); + +type AddonList = ReturnType['addons']; + +afterEach(() => { + useAddonStore.setState({ addons: [], loaded: false }); +}); + +function profile(over: Record = {}) { + return { + id: 9, + username: 'zoe', + avatar_url: null, + countries: 21, + continents: 4, + regions: 33, + flightKm: 48_400, + codes: ['FR', 'JP'], + badges: [], + ...over, + }; +} + +describe('AtlasGlobePassport', () => { + it('FE-ATLAS2-VIEWB-080: closed, it renders nothing', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-081: open on statistics, it shows the hub title and the overview tab', () => { + render(); + expect(screen.getByRole('heading', { name: 'atlas.globe.hub' })).toBeInTheDocument(); + expect(screen.getByText('tab-overview')).toBeInTheDocument(); + expect(screen.queryByText(/atlas\.globe\.collected/)).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-082: on badges, the header counts the earned ones', () => { + const badges = [viewBadge({ id: 'a', earned: true }), viewBadge({ id: 'b' }), viewBadge({ id: 'c', earned: true })]; + render(); + expect(screen.getByText('tab-badges')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.collected[earned=2,total=3]')).toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-083: each tab shows its own view', () => { + const cases: Array<[string, string]> = [ + ['wishlist', 'tab-wishlist'], + ['dawarich', 'tab-dawarich'], + ['tours', 'tab-tours'], + ['travellers', 'tab-travellers'], + ]; + for (const [tab, text] of cases) { + const { unmount } = render(); + expect(screen.getByText(text)).toBeInTheDocument(); + unmount(); + } + }); + + it('FE-ATLAS2-VIEWB-084: the tab bar lists the enabled tabs; picking one switches and leaves a profile', () => { + useAddonStore.setState({ + addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: 'm', enabled: true }] as unknown as AddonList, + loaded: true, + }); + const setPassportTab = vi.fn(); + const setProfileId = vi.fn(); + render( + + ); + for (const label of [ + 'atlas.statsTab', + 'atlas.globe.badges', + 'atlas.bucketTab', + 'dawarich.title', + 'tours.mode.tours', + 'atlas.globe.travellers', + ]) { + expect(screen.getByRole('button', { name: label })).toBeInTheDocument(); + } + expect(screen.getByRole('button', { name: 'atlas.statsTab' }).className).toContain('bg-surface-card'); + fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.travellers' })); + expect(setPassportTab).toHaveBeenCalledWith('travellers'); + expect(setProfileId).toHaveBeenCalledWith(null); + }); + + it('FE-ATLAS2-VIEWB-085: the header close button closes the hub', () => { + const setPassportOpen = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + expect(setPassportOpen).toHaveBeenCalledWith(false); + }); + + it('FE-ATLAS2-VIEWB-086: a traveller profile shows their figures and initial, goes back and compares on the globe', () => { + const p = profile(); + const setProfileId = vi.fn(); + const startCompare = vi.fn(); + render( + + ); + expect(screen.queryByText('tab-travellers')).not.toBeInTheDocument(); + expect(screen.getByText('zoe')).toBeInTheDocument(); + expect(screen.getByText('Z')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.collected[earned=0,total=2]')).toBeInTheDocument(); + expect(screen.getByText('21')).toBeInTheDocument(); + expect(screen.getByText('33')).toBeInTheDocument(); + expect(screen.getByText('48k')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.noBadgesYet')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /atlas.globe.compareOnGlobe/ })); + expect(startCompare).toHaveBeenCalledWith(p); + fireEvent.click(screen.getByRole('button', { name: 'common.back' })); + expect(setProfileId).toHaveBeenCalledWith(null); + }); + + it('FE-ATLAS2-VIEWB-087: a profile with a picture shows it instead of the initial', () => { + render( + + ); + expect(document.querySelector('img[src="/z.png"]')).not.toBeNull(); + expect(screen.queryByText('Z')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-088: their medals carry the step, the country by name and the year reached', () => { + const resolveName = (code: string) => (code === 'FR' ? 'France' : ''); + const badges = [ + { + id: 'c10', + motif: 'countries', + tier: 'gold', + titleKey: 'atlas.badge.c', + params: { country: 'FR' }, + year: 2019, + target: 10, + }, + { + id: 'u', + motif: 'first', + tier: 'bronze', + titleKey: 'atlas.badge.u', + params: { country: 'XX' }, + year: null, + target: 1, + }, + { id: 'n', motif: 'moon', tier: 'silver', titleKey: 'atlas.badge.n', target: 1 }, + ]; + render( + + ); + expect(screen.getByText('atlas.badge.c[country=France]')).toBeInTheDocument(); + expect(screen.getByText('atlas.badge.u[country=XX]')).toBeInTheDocument(); + // A badge without params still gets an (empty) params object. + expect(screen.getByText('atlas.badge.n[]')).toBeInTheDocument(); + expect(screen.getByText('atlas.globe.reachedIn[year=2019]')).toBeInTheDocument(); + expect(screen.getAllByText(/atlas\.globe\.reachedIn/)).toHaveLength(1); + // The stepped medal carries its number; the ids keep each medal's gradients apart. + expect(screen.getByText('10')).toBeInTheDocument(); + expect(document.querySelector('#bm-p9-c10-r')).not.toBeNull(); + expect(screen.queryByText('atlas.globe.noBadgesYet')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWB-089: the travellers tab without a profile shows the list', () => { + render(); + expect(screen.getByText('tab-travellers')).toBeInTheDocument(); + }); +}); diff --git a/client/src/pages/atlas/AtlasGlobeSearch.test.tsx b/client/src/pages/atlas/AtlasGlobeSearch.test.tsx new file mode 100644 index 000000000..e488610f8 --- /dev/null +++ b/client/src/pages/atlas/AtlasGlobeSearch.test.tsx @@ -0,0 +1,146 @@ +// FE-ATLAS2-VIEWA-001 to FE-ATLAS2-VIEWA-012: the search pill over the globe. +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { buildViewState } from '../../../tests/helpers/atlasViewState'; +import AtlasGlobeSearch from './AtlasGlobeSearch'; + +const COUNTRY = { kind: 'country' as const, a2: 'FR', name: 'France' }; +const REGION = { kind: 'region' as const, a2: 'DE', code: 'DE-BY', name: 'Bavaria', lon: 11, lat: 48 }; +const PLACE = { name: 'Eiffel Tower', address: 'Champ de Mars, Paris', lat: 48.85, lng: 2.29 }; + +function input(): HTMLInputElement { + return screen.getByRole('textbox', { name: 'atlas.globe.search' }) as HTMLInputElement; +} + +describe('AtlasGlobeSearch', () => { + it('FE-ATLAS2-VIEWA-001: shows the query, the slash hint and no list while nothing matches', () => { + const s = buildViewState(); + render(); + expect(input()).toHaveAttribute('placeholder', 'atlas.globe.search'); + expect(screen.getByText('/')).toBeInTheDocument(); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-002: typing hands the text to setQuery and focusing loads the region search', () => { + const s = buildViewState(); + render(); + fireEvent.focus(input()); + expect(s.loadRegionSearch).toHaveBeenCalledTimes(1); + fireEvent.change(input(), { target: { value: 'fra' } }); + expect(s.setQuery).toHaveBeenCalledWith('fra'); + }); + + it('FE-ATLAS2-VIEWA-003: a query shows the clear button, which empties it', () => { + const s = buildViewState({ query: 'fra' }); + render(); + expect(input().value).toBe('fra'); + fireEvent.click(screen.getByRole('button', { name: 'Clear' })); + expect(s.setQuery).toHaveBeenCalledWith(''); + expect(screen.queryByText('/')).not.toBeInTheDocument(); + }); + + it('FE-ATLAS2-VIEWA-004: lists countries and regions, a region with its country, the first one active', () => { + const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] }); + render(); + const options = screen.getAllByRole('option'); + expect(options).toHaveLength(2); + expect(options[0]).toHaveTextContent('France'); + expect(options[0]).toHaveAttribute('aria-selected', 'true'); + expect(options[1]).toHaveTextContent('Bavaria'); + expect(options[1]).toHaveTextContent('Germany'); + expect(options[1]).toHaveAttribute('aria-selected', 'false'); + expect(s.resolveName).toHaveBeenCalledWith('DE'); + }); + + it('FE-ATLAS2-VIEWA-005: arrow keys move the active result and stop at both ends', () => { + const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] }); + render(); + fireEvent.keyDown(input(), { key: 'ArrowDown' }); + fireEvent.keyDown(input(), { key: 'ArrowDown' }); + expect(screen.getAllByRole('option')[1]).toHaveAttribute('aria-selected', 'true'); + fireEvent.keyDown(input(), { key: 'ArrowUp' }); + fireEvent.keyDown(input(), { key: 'ArrowUp' }); + expect(screen.getAllByRole('option')[0]).toHaveAttribute('aria-selected', 'true'); + }); + + it('FE-ATLAS2-VIEWA-006: Enter picks the active result; hovering a row makes it active', () => { + const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] }); + render(); + fireEvent.mouseEnter(screen.getAllByRole('option')[1]); + expect(screen.getAllByRole('option')[1]).toHaveAttribute('aria-selected', 'true'); + fireEvent.keyDown(input(), { key: 'Enter' }); + expect(s.pickResult).toHaveBeenCalledWith(REGION); + }); + + it('FE-ATLAS2-VIEWA-007: clicking a result picks it', () => { + const s = buildViewState({ query: 'a', results: [COUNTRY] }); + render(); + fireEvent.mouseDown(screen.getByRole('option')); + fireEvent.click(screen.getByRole('option')); + expect(s.pickResult).toHaveBeenCalledWith(COUNTRY); + }); + + it('FE-ATLAS2-VIEWA-008: places show under their heading with address, and a click picks the place', () => { + const s = buildViewState({ + query: 'eiffel', + placeHits: [PLACE, { ...PLACE, lat: 1, lng: 2, address: null, name: 'Other' }], + }); + render(); + expect(screen.getByText('atlas.searchPlaces')).toBeInTheDocument(); + expect(screen.getByText('Champ de Mars, Paris')).toBeInTheDocument(); + const rows = screen.getAllByRole('option'); + expect(rows).toHaveLength(2); + expect(rows[1]).toHaveTextContent('Other'); + fireEvent.click(rows[0]); + expect(s.pickPlace).toHaveBeenCalledWith(PLACE); + }); + + it('FE-ATLAS2-VIEWA-009: Enter with no region or country result picks the first place', () => { + const s = buildViewState({ query: 'eiffel', placeHits: [PLACE] }); + render(); + fireEvent.keyDown(input(), { key: 'Enter' }); + expect(s.pickPlace).toHaveBeenCalledWith(PLACE); + expect(s.pickResult).not.toHaveBeenCalled(); + }); + + it('FE-ATLAS2-VIEWA-010: while places load the heading shows alone; Escape clears; Enter with nothing does nothing', () => { + const s = buildViewState({ query: 'eif', placesLoading: true }); + render(); + expect(screen.getByRole('listbox')).toHaveTextContent('atlas.searchPlaces'); + fireEvent.keyDown(input(), { key: 'Enter' }); + expect(s.pickPlace).not.toHaveBeenCalled(); + expect(s.pickResult).not.toHaveBeenCalled(); + fireEvent.keyDown(input(), { key: 'Escape' }); + expect(s.setQuery).toHaveBeenCalledWith(''); + }); + + it('FE-ATLAS2-VIEWA-011: "/" outside a field focuses the search, inside a field it does not', () => { + const s = buildViewState(); + const { unmount } = render( + <> +