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.
This commit is contained in:
Maurice
2026-11-29 10:21:28 +01:00
parent 10ad92574d
commit 9018ee8980
69 changed files with 14979 additions and 0 deletions
@@ -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(<AddonManager />);
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(<AddonManager />);
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(
<>
<ToastContainer />
<AddonManager />
</>
);
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);
});
});
@@ -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<typeof vi.fn<() => Promise<void>>>;
beforeEach(() => {
toast.success.mockReset();
toast.error.mockReset();
loadAddons = vi.fn<() => Promise<void>>().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();
});
});
@@ -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, unknown>): 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> = {}): 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> = {}): 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');
});
});
@@ -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<typeof AtlasGlobe>;
const MANIFEST = {
version: 1,
lods: ['110m'],
regionLods: [],
world: {},
countries: [],
} as unknown as AtlasMeshManifest;
function baseProps(over: Partial<Props> = {}): 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<typeof h.FakeEngine> {
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<typeof h.FakeEngine>): 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(<AtlasGlobe {...baseProps({ className: 'globe-host' })} />);
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(<AtlasGlobe {...baseProps({ dark: false })} />);
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<AtlasGlobeHandle>();
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps()} />);
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<AtlasGlobeHandle>();
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps({ onError })} />);
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(<AtlasGlobe {...baseProps()} />)).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(<AtlasGlobe {...baseProps({ fetchJson: first })} />);
rerender(<AtlasGlobe {...baseProps({ fetchJson: second })} />);
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(<AtlasGlobe {...baseProps({ onHover, onSelect, onError })} />);
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(<AtlasGlobe {...baseProps()} />);
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(<AtlasGlobe {...baseProps({ paint, onReady })} />);
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(<AtlasGlobe {...baseProps({ paint, onReady })} />);
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(<AtlasGlobe {...baseProps({ paint, paintKey: undefined })} />);
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(<AtlasGlobe {...baseProps({ paint, paintKey: 'k1' })} />);
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(<AtlasGlobe {...baseProps({ paint, paintKey: 1 })} />);
act(() => engine().opts.onReady?.());
const before = paint.mock.calls.length;
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
expect(paint.mock.calls.length).toBe(before + 1);
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
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(<AtlasGlobe {...baseProps({ paint: first })} />);
rerender(<AtlasGlobe {...baseProps({ paint: second })} />);
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(<AtlasGlobe {...baseProps({ dark: true })} />);
rerender(<AtlasGlobe {...baseProps({ dark: false })} />);
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(<AtlasGlobe {...baseProps()} />);
expect(engine().insets).toEqual([0]);
rerender(<AtlasGlobe {...baseProps({ insetBottom: 120 })} />);
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(<AtlasGlobe {...baseProps({ onFrame, labelFor, labelRegionsOf })} />);
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(<AtlasGlobe {...baseProps()} />);
const e = engine();
unmount();
e.opts.onFrame?.(asEngine(e));
expect(h.placeLabels).not.toHaveBeenCalled();
});
});
File diff suppressed because it is too large Load Diff
@@ -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<string, ScreenPoint>, 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 | null>): 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(<GlobePins pins={[PARIS, KYOTO]} />);
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(<GlobePins pins={[{ ...PARIS, onClick }]} />);
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<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
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<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
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<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
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<GlobePinsHandle>();
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(<GlobePins ref={ref} pins={pins} />);
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<GlobePinsHandle>();
const { rerender } = render(<GlobePins ref={ref} pins={[PARIS]} />);
rerender(<GlobePins ref={ref} pins={[KYOTO]} />);
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');
});
});
@@ -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> = {}): 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;');
});
});
@@ -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<GlobeSkyHandle>();
const utils = render(<GlobeSky ref={ref} dark={dark} />);
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 | null>): 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(<GlobeSky dark={false} />);
expect(vi.getTimerCount()).toBe(0);
rerender(<GlobeSky dark />);
expect(vi.getTimerCount()).toBe(1);
unmount();
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -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(
<GlobeStatsBar
stats={[
{ key: 'countries', icon: Flag, value: 12, label: 'Countries', onClick },
{ key: 'continents', icon: Globe, value: 3, label: 'Continents' },
]}
/>
);
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(<GlobeStatsBar stats={[]} className="end-0 top-0" />);
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(<BadgeMedal id="x1" motif="first" tier="gold" earned />);
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(
<BadgeMedal id="p" motif="countries" tier="bronze" earned={false} progress={0.42} size={46} />
);
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(<BadgeMedal id="z" motif="moon" tier="silver" earned={false} />);
expect(container.querySelectorAll('polygon')).toHaveLength(2);
});
it('FE-ATLAS2-VIEWB-025: the seven-continents motif lights seven points', () => {
const { container } = render(<BadgeMedal id="s" motif="seven" tier="aurora" earned />);
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(<BadgeMedal id="l" motif="countries" tier="gold" earned label={label} />);
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(
<BadgeMedal id="b" motif="countries" tier="gold" earned label="5" back={<text data-testid="back">B</text>} />
);
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(<BadgeMedal id={motif} motif={motif} tier="bronze" earned />);
// 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(<DawarichMark />);
const box = container.firstElementChild as HTMLElement;
expect(box.style.width).toBe('18px');
expect(container.querySelector('img')).toHaveAttribute('width', '18');
rerender(<DawarichMark size={30} />);
expect((container.firstElementChild as HTMLElement).style.height).toBe('32px');
expect(container.querySelector('img')).toHaveAttribute('src', '/brands/dawarich.svg');
});
});
@@ -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<string, RegionIndex>;
regionAlpha: number;
focus: string | null;
/** Visibility by "x,y" of the anchor; 1 when not listed. */
visibility: Map<string, number>;
}
/**
* 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<FakeLabelEngine> = {}) {
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> = {}): 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();
});
});
@@ -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);
});
});
@@ -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);
});
});
@@ -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<typeof import('./globeMesh')>();
return {
...actual,
buildLayer: (...args: Parameters<typeof actual.buildLayer>) => {
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<MeshRequest>);
}
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]]);
});
});
@@ -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]);
});
});
@@ -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, string | number>): 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<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((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<DawarichBucketScan>();
vi.spyOn(dawarichRepo, 'bucketScan').mockReturnValue(run.promise);
const { result } = renderHook(() => useDawarichAtlas());
let pending!: Promise<void>;
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<void>;
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<DawarichAtlasSuggestions>();
const suggest = vi.spyOn(dawarichRepo, 'atlasSuggestions').mockReturnValue(load.promise);
const { result } = renderHook(() => useDawarichAtlas({ initialTab: 'countries' }));
let pending!: Promise<void>;
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']);
});
});
@@ -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>): 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<ReturnType<typeof packingApi.listBags>>);
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();
});
});