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();
});
});
@@ -0,0 +1,151 @@
import { useLocation } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
import { buildAtlasData } from '../../../../tests/helpers/atlas';
import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen, within } from '../../../../tests/helpers/render';
import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe';
import MAtlasCountrySheets from './MAtlasCountrySheets';
type PopupAtlas = Record<string, unknown> & { setConfirmAction: (v: unknown) => void };
// The popup has its own test; here what matters is what it is handed.
const popup = vi.hoisted(() => ({ atlas: null as PopupAtlas | null }));
vi.mock('./MAtlasCountryPopup', () => ({
default: ({ atlas }: { atlas: PopupAtlas }) => {
popup.atlas = atlas;
return null;
},
}));
vi.mock('../../../components/Atlas/AtlasCountryPlaces', () => ({
default: ({ variant, onOpenTrip }: { variant: string; onOpenTrip: (id: number) => void }) => (
<button type="button" onClick={() => onOpenTrip(5)}>
places:{variant}
</button>
),
}));
function Where() {
return <output data-testid="where">{useLocation().pathname}</output>;
}
function show(s: AtlasGlobeState) {
return render(
<>
<MAtlasCountrySheets s={s} />
<Where />
</>
);
}
const DETAIL = {
a2: 'FR',
data: {
places: [{ trip_id: 1 }],
trips: [
{ id: 1, title: 'With places' },
{ id: 2, title: 'Without places' },
],
manually_marked: true,
},
};
describe('MAtlasCountrySheets', () => {
it('FE-ATLAS2-MOBILE-180: the popup gets the globe state under the names it reads', () => {
const s = buildGlobeState({ regions: { FR: [] }, bucket: [{ id: 1 }] });
show(s);
const atlas = popup.atlas as PopupAtlas;
expect(atlas.t).toBe(s.t);
expect(atlas.confirmAction).toBe(s.confirmAction);
expect(atlas.visitedRegions).toBe(s.regions);
expect(atlas.setVisitedRegions).toBe(s.setRegions);
expect(atlas.bucketList).toBe(s.bucket);
expect(atlas.setBucketList).toBe(s.setBucket);
expect(atlas.handleDeleteBucketItem).toBe(s.handleDeleteBucketItem);
expect(atlas.executeConfirmAction).toBe(s.executeConfirmAction);
expect(atlas.setData).toBe(s.setData);
});
it('FE-ATLAS2-MOBILE-181: closing the popup also closes the dialogs, a new action or an updater does not', () => {
const s = buildGlobeState();
show(s);
const atlas = popup.atlas as PopupAtlas;
const next = { code: 'FR', name: 'France', type: 'choose' };
atlas.setConfirmAction(next);
expect(s.setConfirmAction).toHaveBeenLastCalledWith(next);
const updater = () => null;
atlas.setConfirmAction(updater);
expect(s.setConfirmAction).toHaveBeenLastCalledWith(updater);
expect(s.closeDialogs).not.toHaveBeenCalled();
atlas.setConfirmAction(null);
expect(s.setConfirmAction).toHaveBeenLastCalledWith(null);
expect(s.closeDialogs).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-182: no country open, no country sheet', () => {
show(buildGlobeState());
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ATLAS2-MOBILE-183: while the country loads it shows its name, its counts and a spinner', () => {
const s = buildGlobeState({ detail: { a2: 'FR', data: null } });
show(s);
const sheet = screen.getByRole('dialog', { name: 'name-FR' });
expect(within(sheet).getByText('name-FR')).toBeInTheDocument();
expect(within(sheet).getByText('2 atlas.trips:2, 5 atlas.places:5')).toBeInTheDocument();
expect(sheet.querySelector('.animate-spin')).not.toBeNull();
// Visited, so not marked as planned; nothing marked by hand to take off.
expect(within(sheet).queryByText('atlas.planned')).toBeNull();
expect(within(sheet).queryByText('atlas.unmark')).toBeNull();
});
it('FE-ATLAS2-MOBILE-184: a planned country carries the planned mark', () => {
const data = buildAtlasData({
countries: [{ code: 'FR', tripCount: 1, placeCount: 0, firstVisit: null, lastVisit: null, status: 'planned' }],
});
show(buildGlobeState({ data, detail: { a2: 'FR', data: null } }));
expect(screen.getByText('atlas.planned')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-185: a country the data does not list shows no counts', () => {
show(buildGlobeState({ detail: { a2: 'JP', data: null } }));
const sheet = screen.getByRole('dialog', { name: 'name-JP' });
expect(within(sheet).queryByText(/atlas\.trips/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-186: the regions visited show as a share, none at all hide it', () => {
const { unmount } = show(
buildGlobeState({ detail: { a2: 'FR', data: null }, progress: { visited: 3, total: 12 } })
);
expect(screen.getByText('3 / 12')).toBeInTheDocument();
expect(screen.getByText('atlas.regions')).toBeInTheDocument();
unmount();
show(buildGlobeState({ detail: { a2: 'FR', data: null }, progress: { visited: 0, total: 0 } }));
expect(screen.queryByText('atlas.regions')).toBeNull();
});
it('FE-ATLAS2-MOBILE-187: trips without places sit as chips that open the trip, the places list opens its own', () => {
show(buildGlobeState({ detail: DETAIL }));
expect(screen.queryByText('With places')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Without places' }));
expect(screen.getByTestId('where').textContent).toBe('/trips/2');
fireEvent.click(screen.getByRole('button', { name: 'places:mobile' }));
expect(screen.getByTestId('where').textContent).toBe('/trips/5');
});
it('FE-ATLAS2-MOBILE-188: a country marked by hand can have the mark taken off, the close button closes', () => {
const s = buildGlobeState({ detail: DETAIL });
show(s);
fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' }));
expect(s.askUnmarkDetail).toHaveBeenCalledOnce();
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(s.closeDialogs).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-189: every trip with places leaves no chip row', () => {
const detail = { a2: 'FR', data: { places: [{ trip_id: 1 }], trips: [{ id: 1, title: 'With places' }] } };
show(buildGlobeState({ detail }));
const sheet = screen.getByRole('dialog', { name: 'name-FR' });
expect(within(sheet).queryByRole('button', { name: 'With places' })).toBeNull();
expect(within(sheet).getByRole('button', { name: 'places:mobile' })).toBeInTheDocument();
});
});
@@ -0,0 +1,216 @@
import { useLocation } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAtlasData } from '../../../../tests/helpers/atlas';
import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState';
import { act, fireEvent, render, screen } from '../../../../tests/helpers/render';
import type { GlobeEngine } from '../../../components/AtlasGlobe/GlobeEngine';
import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe';
import MAtlasGlobe from './MAtlasGlobe';
interface GlobeProps {
fetchJson: unknown;
dark: boolean;
insetBottom: number;
paintKey: unknown;
onFrame: (e: GlobeEngine) => void;
onError: (err: unknown) => void;
}
// jsdom has no WebGL: the globe, its sky and its pins are stand-ins that keep
// what they were handed, the overlays around them have their own tests.
const fake = vi.hoisted(() => ({
state: null as unknown,
hookArgs: [] as Array<Record<string, unknown>>,
statsArg: null as unknown,
globe: null as GlobeProps | null,
skyLayout: [] as unknown[],
pinsLayout: [] as unknown[],
focus: [] as number[],
}));
vi.mock('../../../pages/atlas/useAtlasGlobe', () => ({
useAtlasGlobe: (refs: Record<string, unknown>) => {
fake.hookArgs.push(refs);
return fake.state;
},
}));
vi.mock('../../../pages/atlas/useGlobeStats', () => ({
useGlobeStats: (s: unknown) => {
fake.statsArg = s;
return [{ key: 'countries' }];
},
}));
vi.mock('../../../components/AtlasGlobe/AtlasGlobe', () => ({
default: (props: GlobeProps) => {
fake.globe = props;
return <div data-testid="globe" />;
},
}));
vi.mock('../../../components/AtlasGlobe/GlobeSky', async () => {
const { forwardRef, useImperativeHandle } = await import('react');
return {
default: forwardRef<unknown, { dark?: boolean }>(function Sky(_props, ref) {
useImperativeHandle(ref, () => ({ layout: (e: unknown) => fake.skyLayout.push(e) }));
return null;
}),
};
});
vi.mock('../../../components/AtlasGlobe/GlobePins', async () => {
const { forwardRef, useImperativeHandle } = await import('react');
return {
default: forwardRef<unknown, { pins: unknown }>(function Pins(_props, ref) {
useImperativeHandle(ref, () => ({ layout: (e: unknown) => fake.pinsLayout.push(e) }));
return null;
}),
};
});
vi.mock('../../../pages/atlas/AtlasGlobeSearch', () => ({
default: ({ focusSignal }: { focusSignal: number }) => {
fake.focus.push(focusSignal);
return <p>search:{focusSignal}</p>;
},
}));
vi.mock('../../../pages/atlas/AtlasGlobeStatus', () => ({ default: () => null }));
vi.mock('../../../pages/atlas/AtlasGlobeTimeline', () => ({ default: () => null }));
vi.mock('../../../pages/atlas/AtlasBadgeUnlock', () => ({ default: () => null }));
vi.mock('./MAtlasCountrySheets', () => ({ default: () => null }));
vi.mock('./hub/MAtlasHub', () => ({ default: () => null }));
vi.mock('./MAtlasStatsCard', () => ({
default: ({ stats }: { stats: unknown[] }) => <p>stats:{stats.length}</p>,
}));
vi.mock('./MAtlasLayersSheet', () => ({
default: ({ open, onClose }: { open: boolean; onClose: () => void }) =>
open ? (
<button type="button" onClick={onClose}>
close layers
</button>
) : null,
}));
function Where() {
const l = useLocation();
return <output data-testid="where">{`${l.pathname}${l.search}`}</output>;
}
function show(s: AtlasGlobeState, url = '/atlas') {
fake.state = s;
return render(
<>
<MAtlasGlobe />
<Where />
</>,
{ initialEntries: [url] }
);
}
beforeEach(() => {
fake.hookArgs = [];
fake.globe = null;
fake.skyLayout = [];
fake.pinsLayout = [];
fake.focus = [];
});
describe('MAtlasGlobe', () => {
it('FE-ATLAS2-MOBILE-200: the globe gets the state, dark and room for the cards at the foot', () => {
const s = buildGlobeState();
show(s);
expect(screen.getByTestId('globe')).toBeInTheDocument();
const globe = fake.globe as GlobeProps;
expect(globe.fetchJson).toBe(s.fetchJson);
expect(globe.paintKey).toBe('k');
expect(globe.dark).toBe(true);
expect(globe.insetBottom).toBe(170);
expect(Object.keys(fake.hookArgs[0] ?? {}).sort()).toEqual(['globeRef', 'skyRef']);
expect(fake.statsArg).toBe(s);
expect(screen.getByText('stats:1')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-201: every frame lays out the sky and the pins on the engine', () => {
show(buildGlobeState());
const engine = { id: 'engine' } as unknown as GlobeEngine;
act(() => (fake.globe as GlobeProps).onFrame(engine));
expect(fake.skyLayout).toEqual([engine]);
expect(fake.pinsLayout).toEqual([engine]);
});
it('FE-ATLAS2-MOBILE-202: a globe error is kept as its message, whatever was thrown', () => {
const s = buildGlobeState();
show(s);
const globe = fake.globe as GlobeProps;
globe.onError(new Error('no webgl'));
expect(s.setError).toHaveBeenLastCalledWith('no webgl');
globe.onError('lost context');
expect(s.setError).toHaveBeenLastCalledWith('lost context');
});
it('FE-ATLAS2-MOBILE-203: the hub button opens the hub on its last tab and lights up while it is open', () => {
const s = buildGlobeState({ passportTab: 'badges' });
const { unmount } = show(s);
const hub = screen.getByRole('button', { name: 'atlas.globe.hub' });
expect(hub.className).toContain('text-content-secondary');
fireEvent.click(hub);
expect(s.openPassport).toHaveBeenCalledWith('badges');
unmount();
show(buildGlobeState({ passportOpen: true }));
expect(screen.getByRole('button', { name: 'atlas.globe.hub' }).className).toContain('bg-accent');
});
it('FE-ATLAS2-MOBILE-204: the layers button opens the layers sheet, which closes again', () => {
show(buildGlobeState());
const layers = screen.getByRole('button', { name: 'atlas.globe.layers' });
expect(screen.queryByText('close layers')).toBeNull();
fireEvent.click(layers);
expect(layers.className).toContain('bg-accent');
fireEvent.click(screen.getByText('close layers'));
expect(screen.queryByText('close layers')).toBeNull();
expect(layers.className).not.toContain('bg-accent');
});
it('FE-ATLAS2-MOBILE-205: ?search=1 from the dock is taken off the address and focuses the search', () => {
show(buildGlobeState(), '/atlas?search=1&year=2024');
expect(screen.getByText('search:1')).toBeInTheDocument();
expect(screen.getByTestId('where').textContent).toBe('/atlas?year=2024');
});
it('FE-ATLAS2-MOBILE-206: without the hand-over the search is left alone', () => {
show(buildGlobeState(), '/atlas?year=2024');
expect(screen.getByText('search:0')).toBeInTheDocument();
expect(fake.focus.every((n) => n === 0)).toBe(true);
expect(screen.getByTestId('where').textContent).toBe('/atlas?year=2024');
});
it('FE-ATLAS2-MOBILE-207: no comparison, no compare bar', () => {
show(buildGlobeState());
expect(screen.queryByText(/atlas\.globe\.compareWith/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-208: comparing counts the countries shared, theirs alone and mine alone', () => {
const data = buildAtlasData({
countries: [
{ code: 'FR', tripCount: 1, placeCount: 1, status: 'visited' },
{ code: 'DE', tripCount: 1, placeCount: 1 },
{ code: 'IT', tripCount: 1, placeCount: 0, status: 'planned' },
],
});
const s = buildGlobeState({ data, compareWith: { username: 'ann', codes: ['FR', 'JP', 'IT'] } });
show(s);
expect(screen.getByText('atlas.globe.compareWith:ann')).toBeInTheDocument();
const count = (label: string) => screen.getByText(label).parentElement?.querySelector('b')?.textContent;
expect(count('atlas.globe.together')).toBe('1');
expect(count('atlas.globe.onlyThem:ann')).toBe('2');
expect(count('atlas.globe.onlyYou')).toBe('1');
});
it('FE-ATLAS2-MOBILE-209: the gaps switch flips and the close button ends the comparison', () => {
const s = buildGlobeState({ compareWith: { username: 'ann', codes: [] }, gaps: true, data: null });
show(s);
const gaps = screen.getByRole('button', { name: 'atlas.globe.gaps' });
expect(gaps).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(gaps);
expect(s.setGaps).toHaveBeenCalledWith(false);
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(s.stopCompare).toHaveBeenCalledOnce();
expect(screen.getByText('atlas.globe.together').parentElement?.querySelector('b')?.textContent).toBe('0');
});
});
@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from 'vitest';
import { buildGlobeState } from '../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
import MAtlasLayersSheet from './MAtlasLayersSheet';
describe('MAtlasLayersSheet', () => {
it('FE-ATLAS2-MOBILE-220: closed, the sheet renders nothing', () => {
render(<MAtlasLayersSheet s={buildGlobeState()} open={false} onClose={vi.fn()} />);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ATLAS2-MOBILE-221: without flights or plugins only the planned switch stands there, and it flips', () => {
const s = buildGlobeState({ showPlanned: true });
render(<MAtlasLayersSheet s={s} open onClose={vi.fn()} />);
expect(screen.getByRole('dialog', { name: 'atlas.globe.layers' })).toBeInTheDocument();
const switches = screen.getAllByRole('switch');
expect(switches).toHaveLength(1);
expect(switches[0]).toHaveAccessibleName('atlas.showPlanned');
expect(switches[0]).toHaveAttribute('aria-checked', 'true');
fireEvent.click(switches[0] as HTMLElement);
expect(s.setShowPlanned).toHaveBeenCalledWith(false);
});
it('FE-ATLAS2-MOBILE-222: flights with routes add their switch, an empty flight list does not', () => {
const s = buildGlobeState({ flights: { routes: [{ id: 1 }] }, showFlights: false });
const { unmount } = render(<MAtlasLayersSheet s={s} open onClose={vi.fn()} />);
const flights = screen.getByRole('switch', { name: 'atlas.globe.flights' });
expect(flights).toHaveAttribute('aria-checked', 'false');
fireEvent.click(flights);
expect(s.setShowFlights).toHaveBeenCalledWith(true);
unmount();
render(<MAtlasLayersSheet s={buildGlobeState({ flights: { routes: [] } })} open onClose={vi.fn()} />);
expect(screen.queryByRole('switch', { name: 'atlas.globe.flights' })).toBeNull();
});
it('FE-ATLAS2-MOBILE-223: every plugin layer is a switch by its name or id, off when hidden', () => {
const s = buildGlobeState({
pluginLayers: [
{ pluginId: 'p', id: 'rain', name: 'Rain' },
{ pluginId: 'p', id: 'wind', name: '' },
],
hiddenPluginLayers: new Set(['p:wind']),
});
render(<MAtlasLayersSheet s={s} open onClose={vi.fn()} />);
expect(screen.getByRole('switch', { name: 'Rain' })).toHaveAttribute('aria-checked', 'true');
const wind = screen.getByRole('switch', { name: 'wind' });
expect(wind).toHaveAttribute('aria-checked', 'false');
fireEvent.click(wind);
expect(s.togglePluginLayer).toHaveBeenCalledWith('p:wind');
});
it('FE-ATLAS2-MOBILE-224: the colouring is a segmented choice of country, status and year', () => {
const s = buildGlobeState({ colorMode: 'status' });
render(<MAtlasLayersSheet s={s} open onClose={vi.fn()} />);
expect(screen.getByText('atlas.globe.colorBy')).toBeInTheDocument();
expect(screen.getAllByRole('tab').map((t) => t.textContent)).toEqual([
'atlas.globe.colorCountry',
'atlas.globe.colorStatus',
'atlas.globe.colorYear',
]);
expect(screen.getByRole('tab', { name: 'atlas.globe.colorStatus' })).toHaveAttribute('aria-selected', 'true');
fireEvent.click(screen.getByRole('tab', { name: 'atlas.globe.colorYear' }));
expect(s.setColorMode).toHaveBeenCalledWith('year');
});
it('FE-ATLAS2-MOBILE-225: the close button closes the sheet', () => {
const onClose = vi.fn();
render(<MAtlasLayersSheet s={buildGlobeState()} open onClose={onClose} />);
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(onClose).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,85 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
import { resetAllStores, seedInstanceAddons } from '../../../../../tests/helpers/store';
import type { AtlasHubTab } from '../../../../pages/atlas/useAtlasGlobe';
import MAtlasHub from './MAtlasHub';
// Each tab has its own test; the hub only decides which one stands in the sheet.
vi.mock('./MHubOverview', () => ({ default: () => <p>tab:overview</p> }));
vi.mock('./MHubBadges', () => ({ default: () => <p>tab:badges</p> }));
vi.mock('./MHubWishlist', () => ({ default: () => <p>tab:wishlist</p> }));
vi.mock('./MHubDawarich', () => ({ default: () => <p>tab:dawarich</p> }));
vi.mock('./MHubTours', () => ({ default: () => <p>tab:tours</p> }));
vi.mock('./MHubTravellers', () => ({ default: () => <p>tab:travellers</p> }));
const BADGES = [{ earned: true }, { earned: false }];
afterEach(() => {
resetAllStores();
});
describe('MAtlasHub', () => {
it('FE-ATLAS2-MOBILE-160: a closed hub renders nothing', () => {
render(<MAtlasHub s={buildGlobeState()} />);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ATLAS2-MOBILE-161: the open hub names itself, counts the badges and shows the three tabs every Atlas has', () => {
render(<MAtlasHub s={buildGlobeState({ passportOpen: true, badges: BADGES })} />);
const sheet = screen.getByRole('dialog', { name: 'atlas.globe.hub' });
expect(within(sheet).getByText('atlas.globe.collected:1,2')).toBeInTheDocument();
const chips = within(within(sheet).getByRole('group', { name: 'atlas.globe.hub' })).getAllByRole('button');
expect(chips.map((c) => c.textContent?.trim())).toEqual([
'atlas.statsTab',
'atlas.globe.badges',
'atlas.bucketTab',
]);
expect(within(sheet).getByRole('button', { name: 'atlas.statsTab' })).toHaveAttribute('aria-pressed', 'true');
});
it('FE-ATLAS2-MOBILE-162: Dawarich, tours and comparing each add their tab', () => {
seedInstanceAddons(['tours']);
render(<MAtlasHub s={buildGlobeState({ passportOpen: true, dawarichEnabled: true, compareEnabled: true })} />);
const chips = within(screen.getByRole('group', { name: 'atlas.globe.hub' })).getAllByRole('button');
expect(chips.map((c) => c.textContent?.trim())).toEqual([
'atlas.statsTab',
'atlas.globe.badges',
'atlas.bucketTab',
'dawarich.title',
'tours.mode.tours',
'atlas.globe.travellers',
]);
});
const TABS: Array<[string, AtlasHubTab]> = [
['163', 'overview'],
['166', 'badges'],
['167', 'wishlist'],
['168', 'dawarich'],
['169', 'tours'],
['170', 'travellers'],
];
for (const [id, tab] of TABS) {
it(`FE-ATLAS2-MOBILE-${id}: the ${tab} tab stands in the sheet when it is the open one`, () => {
render(<MAtlasHub s={buildGlobeState({ passportOpen: true, passportTab: tab })} />);
expect(screen.getByText(`tab:${tab}`)).toBeInTheDocument();
expect(screen.getAllByText(/^tab:/)).toHaveLength(1);
});
}
it('FE-ATLAS2-MOBILE-164: a chip switches the tab and leaves any open profile', () => {
const s = buildGlobeState({ passportOpen: true });
render(<MAtlasHub s={s} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.bucketTab' }));
expect(s.setPassportTab).toHaveBeenCalledWith('wishlist');
expect(s.setProfileId).toHaveBeenCalledWith(null);
});
it('FE-ATLAS2-MOBILE-165: the close button closes the hub', () => {
const s = buildGlobeState({ passportOpen: true });
render(<MAtlasHub s={s} />);
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(s.setPassportOpen).toHaveBeenCalledWith(false);
});
});
@@ -0,0 +1,157 @@
import type { Badge } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
import MHubBadges from './MHubBadges';
function badge(over: Partial<Badge>): Badge {
return {
id: 'b',
category: 'countries',
motif: 'countries',
tier: 'bronze',
titleKey: 'badge.title',
descKey: 'badge.desc',
earned: false,
current: 0,
target: 1,
...over,
};
}
const FIVE = badge({
id: 'c5',
titleKey: 'badge.c5',
descKey: 'badge.c5.desc',
earned: true,
current: 5,
target: 5,
year: 2021,
country: 'FR',
});
const TEN = badge({
id: 'c10',
tier: 'silver',
titleKey: 'badge.c10',
descKey: 'badge.c10.desc',
current: 7,
target: 10,
});
const REGION = badge({
id: 'r1',
category: 'regions',
motif: 'region',
tier: 'gold',
titleKey: 'badge.region',
descKey: 'badge.region.desc',
params: { country: 'DE' },
current: 2,
target: 5,
});
const NO_YEAR = badge({
id: 'k1',
category: 'continents',
motif: 'continents',
titleKey: 'badge.k1',
earned: true,
current: 2,
target: 2,
});
const BADGES = [FIVE, TEN, REGION, NO_YEAR];
const dialog = () => screen.getByRole('dialog');
const openBadge = (title: string) => fireEvent.click(screen.getByText(title).closest('button') as HTMLElement);
describe('MHubBadges', () => {
it('FE-ATLAS2-MOBILE-080: every category with badges is a section counting the earned ones, empty ones are left out', () => {
render(<MHubBadges s={buildGlobeState({ badges: BADGES })} />);
const countries = screen.getByRole('heading', { name: 'atlas.badgeCat.countries' }).closest('section');
expect(within(countries as HTMLElement).getByText('1 / 2')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'atlas.badgeCat.regions' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'atlas.badgeCat.flights' })).toBeNull();
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ATLAS2-MOBILE-081: an earned badge shows its year, an open one how far it got, a country in its title by name', () => {
render(<MHubBadges s={buildGlobeState({ badges: BADGES })} />);
expect(screen.getByText('2021')).toBeInTheDocument();
expect(screen.getByText('7 / 10')).toBeInTheDocument();
expect(screen.getByText('badge.region:name-DE')).toBeInTheDocument();
// Earned without a year: no figure under it.
const k1 = screen.getByText('badge.k1:').closest('button') as HTMLElement;
expect(k1.lastElementChild?.textContent).toBe('');
});
it('FE-ATLAS2-MOBILE-082: a tap opens the badge sheet with its tier, how to earn it, the progress and its stages', () => {
render(<MHubBadges s={buildGlobeState({ badges: BADGES })} />);
openBadge('badge.c10:');
const sheet = dialog();
expect(sheet).toHaveAttribute('aria-label', 'badge.c10:');
expect(within(sheet).getByText('atlas.badgeTier.silver')).toBeInTheDocument();
expect(within(sheet).getByText('atlas.badgeCat.countries')).toBeInTheDocument();
expect(within(sheet).getByText('atlas.globe.howTo')).toBeInTheDocument();
expect(within(sheet).getByText('badge.c10.desc:,10')).toBeInTheDocument();
expect(within(sheet).getByText('atlas.globe.toGo')).toBeInTheDocument();
expect(within(sheet).getByText('3')).toBeInTheDocument();
expect(within(sheet).queryByText('atlas.globe.reached')).toBeNull();
expect(within(sheet).queryByText('atlas.globe.holders')).toBeNull();
const stages = within(sheet).getByRole('heading', { name: 'atlas.globe.stages' }).closest('section') as HTMLElement;
expect(within(stages).getByText('1 / 2')).toBeInTheDocument();
const current = within(stages)
.getAllByRole('button')
.find((b) => b.getAttribute('aria-current') === 'true');
expect(current?.textContent).toContain('badge.c10:');
});
it('FE-ATLAS2-MOBILE-083: a stage opens that badge, which as earned shows the year and the country it was made by', () => {
render(<MHubBadges s={buildGlobeState({ badges: BADGES })} />);
openBadge('badge.c10:');
const stages = within(dialog())
.getByRole('heading', { name: 'atlas.globe.stages' })
.closest('section') as HTMLElement;
fireEvent.click(within(stages).getByText('badge.c5:').closest('button') as HTMLElement);
const sheet = dialog();
expect(sheet).toHaveAttribute('aria-label', 'badge.c5:');
expect(within(sheet).getAllByText('atlas.globe.reached')).toHaveLength(2);
expect(within(sheet).getAllByText('2021').length).toBeGreaterThan(0);
expect(within(sheet).getByText('atlas.globe.madeBy')).toBeInTheDocument();
expect(within(sheet).getByText('name-FR')).toBeInTheDocument();
expect(within(sheet).getByText('badge.c5.desc:name-FR,5')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-084: an earned badge without a year shows a tick, a region badge has no stages', () => {
render(<MHubBadges s={buildGlobeState({ badges: BADGES })} />);
openBadge('badge.k1:');
expect(within(dialog()).getByText('✓')).toBeInTheDocument();
expect(within(dialog()).queryByText('atlas.globe.stages')).toBeNull();
fireEvent.click(within(dialog()).getByRole('button', { name: 'common.close' }));
expect(screen.queryByText('atlas.globe.howTo')).toBeNull();
openBadge('badge.region:name-DE');
expect(within(dialog()).queryByText('atlas.globe.stages')).toBeNull();
expect(within(dialog()).getByText('badge.region.desc:,5')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-085: with comparing on, the sheet loads the travellers and shows how many hold the badge', () => {
const people = [{ badges: [{ id: 'c10' }] }, { badges: [] }];
const s = buildGlobeState({ badges: BADGES, compareEnabled: true, people });
render(<MHubBadges s={s} />);
expect(s.loadPeople).not.toHaveBeenCalled();
openBadge('badge.c10:');
expect(s.loadPeople).toHaveBeenCalledOnce();
expect(within(dialog()).getByText('atlas.globe.holders')).toBeInTheDocument();
expect(within(dialog()).getByText('1 / 3')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-086: with comparing off, no travellers are loaded', () => {
const s = buildGlobeState({ badges: BADGES });
render(<MHubBadges s={s} />);
openBadge('badge.c10:');
expect(s.loadPeople).not.toHaveBeenCalled();
});
it('FE-ATLAS2-MOBILE-087: no badges at all renders no section', () => {
render(<MHubBadges s={buildGlobeState({ badges: [] })} />);
expect(screen.queryByRole('heading')).toBeNull();
});
});
@@ -0,0 +1,198 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import MHubDawarich from './MHubDawarich';
// The Dawarich questions go to the server; the tab only lays out what the hook holds.
const hook = vi.hoisted(() => ({
state: {} as Record<string, unknown>,
options: [] as Array<{ initialTab?: string; onChanged?: () => void }>,
}));
vi.mock('../../../../components/Dawarich/useDawarichAtlas', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useDawarichAtlas: (options: { initialTab?: string; onChanged?: () => void }) => {
hook.options.push(options);
return hook.state;
},
}));
function dawarich(over: Record<string, unknown> = {}) {
hook.state = {
tab: 'wishes',
setTab: vi.fn(),
scan: null,
picked: new Set<number>(),
togglePicked: vi.fn(),
countries: null,
pickedCountries: new Set<string>(),
togglePickedCountry: vi.fn(),
writing: false,
matches: [],
openMatches: [],
offered: [],
run: vi.fn(),
confirm: vi.fn(),
busy: false,
loaded: false,
selected: 0,
anything: false,
...over,
};
return hook.state as Record<string, ReturnType<typeof vi.fn>>;
}
const AT = '2025-05-04T10:00:00Z';
const MATCHES = [
{ itemId: 1, name: 'Kyoto', alreadyVisited: false, match: { at: AT, minutes: 90, distanceMeters: 1500 } },
{ itemId: 2, name: 'Rome', alreadyVisited: true, match: null },
{ itemId: 3, name: 'Oslo', alreadyVisited: false, match: null },
];
const OFFERED = [
{ countryCode: 'PT', sourceName: 'Portugal', cities: [{ name: 'Porto' }, { name: 'Lisbon' }] },
{ countryCode: 'ES', sourceName: 'Spain', cities: [] },
];
beforeEach(() => {
hook.options = [];
});
describe('MHubDawarich', () => {
it('FE-ATLAS2-MOBILE-100: opens on the question the hub asked for and reloads the Atlas after a write', () => {
const d = dawarich();
const s = buildGlobeState({ dawarichSub: 'countries' });
render(<MHubDawarich s={s} />);
expect(hook.options[0]?.initialTab).toBe('countries');
expect(d.setTab).toHaveBeenCalledWith('countries');
hook.options[0]?.onChanged?.();
expect(s.reload).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-101: the segments carry how many there are to look at and switch the question', () => {
const d = dawarich({ openMatches: [MATCHES[0], MATCHES[2]], offered: [OFFERED[0]] });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.wishes 2' })).toHaveAttribute('aria-selected', 'true');
fireEvent.click(screen.getByRole('tab', { name: 'dawarich.atlas.tab.countries 1' }));
expect(d.setTab).toHaveBeenLastCalledWith('countries');
});
it('FE-ATLAS2-MOBILE-102: nothing to look at leaves the segment labels plain', () => {
dawarich();
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.wishes' })).toBeInTheDocument();
expect(screen.getByRole('tab', { name: 'dawarich.atlas.tab.countries' })).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-103: while a question runs it says which one', () => {
dawarich({ busy: true });
const { unmount } = render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.bucket.scanning')).toBeInTheDocument();
unmount();
dawarich({ busy: true, tab: 'countries' });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.atlas.loading')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-104: before the first question it explains the wishes check and asks it on a tap', () => {
const d = dawarich();
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.bucket.title')).toBeInTheDocument();
expect(screen.getByText('dawarich.bucket.description')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.scan' }));
expect(d.run).toHaveBeenCalledOnce();
// No notes before anything was asked.
expect(screen.queryByText(/dawarich\.bucket\.rule/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-105: before the first question on countries it explains that one', () => {
const d = dawarich({ tab: 'countries' });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.atlas.title')).toBeInTheDocument();
expect(screen.getByText('dawarich.atlas.description')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.load' }));
expect(d.run).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-106: a scan without a match says so, offers it again and states the rule', () => {
const d = dawarich({ loaded: true, scan: { matches: [], skippedWithoutCoordinates: 0, truncated: false } });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.bucket.noMatches')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' }));
expect(d.run).toHaveBeenCalledOnce();
expect(screen.getByText(/dawarich\.bucket\.rule:/)).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-107: no new countries says so and names the time window', () => {
dawarich({ loaded: true, tab: 'countries', countries: { countries: [], unresolved: [] } });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByText('dawarich.atlas.empty')).toBeInTheDocument();
expect(screen.getByText('dawarich.atlas.window')).toBeInTheDocument();
expect(screen.queryByText(/dawarich\.atlas\.unresolved/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-108: each matched wish is a checkbox with when, how long and how far, a visited one locked', () => {
const d = dawarich({
loaded: true,
anything: true,
matches: MATCHES,
picked: new Set([1]),
selected: 1,
scan: { matches: MATCHES, skippedWithoutCoordinates: 2, truncated: true },
});
render(<MHubDawarich s={buildGlobeState()} />);
const day = new Date(AT).toLocaleDateString('en', { day: 'numeric', month: 'short' });
expect(screen.getByRole('checkbox', { name: 'Kyoto' })).toHaveAttribute('aria-checked', 'true');
expect(
screen.getByText(`${day}, dawarich.duration.hoursMinutes:1,30, dawarich.bucket.kilometersAway:1.5`)
).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: 'Rome' })).toBeDisabled();
expect(screen.getByText('dawarich.bucket.alreadyVisited')).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: 'Oslo' })).toHaveAttribute('aria-checked', 'false');
fireEvent.click(screen.getByRole('checkbox', { name: 'Oslo' }));
expect(d.togglePicked).toHaveBeenCalledWith(3);
expect(screen.getByText('dawarich.bucket.skipped:2')).toBeInTheDocument();
expect(screen.getByText('dawarich.bucket.truncated')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-109: the confirm writes what is ticked, the round button asks again', () => {
const d = dawarich({ loaded: true, anything: true, matches: MATCHES, picked: new Set([1]), selected: 1 });
render(<MHubDawarich s={buildGlobeState()} />);
fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.confirm:1' }));
expect(d.confirm).toHaveBeenCalledOnce();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' }));
expect(d.run).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-110: nothing ticked, or a write on its way, keeps the confirm off', () => {
dawarich({ loaded: true, anything: true, matches: MATCHES, selected: 0 });
const { unmount } = render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByRole('button', { name: 'dawarich.bucket.confirm:0' })).toBeDisabled();
unmount();
dawarich({ loaded: true, anything: true, matches: MATCHES, selected: 1, writing: true });
render(<MHubDawarich s={buildGlobeState()} />);
expect(screen.getByRole('button', { name: 'dawarich.bucket.confirm:1' })).toBeDisabled();
});
it('FE-ATLAS2-MOBILE-111: each new country is a checkbox under its own name with its cities, the confirm accepts them', () => {
const d = dawarich({
loaded: true,
anything: true,
tab: 'countries',
offered: OFFERED,
pickedCountries: new Set(['PT']),
selected: 1,
countries: { countries: OFFERED, unresolved: ['Atlantis'] },
});
render(<MHubDawarich s={buildGlobeState()} />);
const portugal = screen.getByRole('checkbox', { name: 'Portugal' });
expect(portugal).toHaveAttribute('aria-checked', 'true');
expect(screen.getByText('Porto, Lisbon')).toBeInTheDocument();
const spain = screen.getByRole('checkbox', { name: 'Spain' });
expect(spain).toHaveAttribute('aria-checked', 'false');
expect(spain.querySelectorAll('.text-caption')).toHaveLength(0);
fireEvent.click(spain);
expect(d.togglePickedCountry).toHaveBeenCalledWith('ES');
fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.accept:1' }));
expect(d.confirm).toHaveBeenCalledOnce();
expect(screen.getByText('dawarich.atlas.unresolved:Atlantis')).toBeInTheDocument();
});
});
@@ -0,0 +1,114 @@
import { useLocation } from 'react-router';
import { describe, expect, it } from 'vitest';
import { buildAtlasData } from '../../../../../tests/helpers/atlas';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
import MHubOverview from './MHubOverview';
function Where() {
return <output data-testid="where">{useLocation().pathname}</output>;
}
function show(s: AtlasGlobeState) {
return render(
<>
<MHubOverview s={s} />
<Where />
</>
);
}
const barOf = (key: string) =>
(screen.getByText(key).parentElement as HTMLElement).querySelector('.h-full') as HTMLElement;
describe('MHubOverview', () => {
it('FE-ATLAS2-MOBILE-020: the headline is the country count with the share of the world and the planned ones', () => {
const s = buildGlobeState({
totals: { countries: 39, continents: 2, regions: 5 },
data: buildAtlasData({
stats: {
totalTrips: 3,
totalPlaces: 10,
totalCountries: 39,
totalDays: 14,
totalCities: 3,
totalCountriesPlanned: 2,
totalCountriesIdea: 1,
},
}),
});
show(s);
expect(screen.getByText('39')).toBeInTheDocument();
expect(screen.getByText('atlas.countries:39')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.worldShare:20')).toBeInTheDocument();
expect(screen.getByText('+3 atlas.planned')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-021: nothing planned leaves the planned figure out', () => {
show(buildGlobeState());
expect(screen.queryByText(/atlas\.planned/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-022: the next trip shows its countdown and opens the trip', () => {
// The server sends the countdown beside the trip; the shared type does not name it.
const nextTrip = { id: 9, title: 'Lisbon', daysUntil: 12 };
const s = buildGlobeState({ data: buildAtlasData({ nextTrip }) });
show(s);
expect(screen.getByText('12')).toBeInTheDocument();
expect(screen.getByText('atlas.daysLeft')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Lisbon/ }));
expect(screen.getByTestId('where').textContent).toBe('/trips/9');
});
it('FE-ATLAS2-MOBILE-023: a next trip without a countdown shows only its title', () => {
show(buildGlobeState({ data: buildAtlasData({ nextTrip: { id: 9, title: 'Lisbon' } }) }));
expect(screen.getByText('Lisbon')).toBeInTheDocument();
expect(screen.queryByText('atlas.daysLeft')).toBeNull();
});
it('FE-ATLAS2-MOBILE-024: continents are bars scaled to the largest, the empty ones at zero, Antarctica hidden', () => {
const s = buildGlobeState({
totals: { countries: 6, continents: 2, regions: 0 },
data: buildAtlasData({ continents: { Europe: 4, Asia: 2 } }),
});
show(s);
expect(screen.getByText('2 / 6')).toBeInTheDocument();
expect(barOf('atlas.europe').style.width).toBe('100%');
expect(barOf('atlas.asia').style.width).toBe('50%');
expect(barOf('atlas.africa').style.width).toBe('0%');
expect(screen.queryByText('atlas.antarctica')).toBeNull();
});
it('FE-ATLAS2-MOBILE-025: a country in Antarctica adds its row, and a small share keeps a visible bar', () => {
const s = buildGlobeState({
totals: { countries: 6, continents: 2, regions: 0 },
data: buildAtlasData({ continents: { Europe: 50, Antarctica: 1 } }),
});
show(s);
expect(screen.getByText('2 / 7')).toBeInTheDocument();
expect(barOf('atlas.antarctica').style.width).toBe('6%');
});
it('FE-ATLAS2-MOBILE-026: with Dawarich on, its entry opens the countries question', () => {
const s = buildGlobeState({ dawarichEnabled: true });
show(s);
fireEvent.click(screen.getByRole('button', { name: /atlas\.globe\.dawarichCountries/ }));
expect(s.openDawarich).toHaveBeenCalledWith('countries');
});
it('FE-ATLAS2-MOBILE-027: without Dawarich there is no entry, and the tiles carry the figures', () => {
show(buildGlobeState({ totals: { countries: 1, continents: 1, regions: 5 } }));
expect(screen.queryByText('atlas.globe.dawarichCountries')).toBeNull();
expect(screen.getByText('atlas.regions:5')).toBeInTheDocument();
expect(screen.getByText('atlas.trips:3')).toBeInTheDocument();
expect(screen.getByText('atlas.days:14')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-028: without data every continent is empty and nothing breaks', () => {
show(buildGlobeState({ data: null, totals: { countries: 0, continents: 0, regions: 0 } }));
expect(screen.getByText('0 / 6')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.worldShare:0')).toBeInTheDocument();
expect(barOf('atlas.europe').style.width).toBe('0%');
});
});
@@ -0,0 +1,180 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import MHubTours from './MHubTours';
// The stats hook reads the server and the figures are covered by their own
// tests; here they are fixed so the tab's layout and wiring are what is tested.
const tours = vi.hoisted(() => ({
stats: {} as Record<string, unknown>,
active: [] as boolean[],
figures: {} as Record<string, unknown>,
}));
vi.mock('../../../../components/Atlas/tourActivity/useTourActivityStats', () => ({
useTourActivityStats: (active: boolean) => {
tours.active.push(active);
return tours.stats;
},
}));
vi.mock('../../../../components/Atlas/tourActivity/tourHubFigures', () => ({
tourHubFigures: () => tours.figures,
}));
vi.mock('../../../../components/Atlas/tourActivity/tourActivityReading', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useDistanceUnit: () => 'metric',
distanceReading: (x: { distanceKm: { value: number | null } }) =>
x.distanceKm.value == null ? null : { text: `${x.distanceKm.value} km` },
}));
vi.mock('../../../../components/Atlas/tourActivity/tourActivityParts', () => ({
ActivityStatusLine: ({ stats }: { stats: { status: string } }) => <p>status:{stats.status}</p>,
BasisBadges: ({ byBasis }: { byBasis: Record<string, number> }) => <p>basis:{JSON.stringify(byBasis)}</p>,
UncountedBadges: (p: { upcoming: number; unassigned: number; undated: number }) => (
<p>
uncounted:{p.upcoming}:{p.unassigned}:{p.undated}
</p>
),
}));
vi.mock('../../../../components/Atlas/tourActivity/TourActivityStatsDialog', () => ({
TourActivityStatsDialog: ({ open, onClose }: { open: boolean; onClose: () => void }) =>
open ? (
<div role="dialog" aria-label="tour list">
<button type="button" onClick={onClose}>
close list
</button>
</div>
) : null,
}));
function statsWith(over: Record<string, unknown> = {}) {
tours.stats = {
status: 'ready',
data: { entries: [], uncounted: { unassigned: 0, undated: 0 } },
summary: null,
period: 'all',
setPeriod: vi.fn(),
periods: ['all', 'thisYear', 'last12', 'year:2023'],
type: 'all',
setType: vi.fn(),
types: ['all'],
...over,
};
return tours.stats as Record<string, ReturnType<typeof vi.fn>>;
}
const TYPES = [
{ type: 'hike', count: 3, distanceKm: { value: 30 } },
{ type: 'bike', count: 2, distanceKm: { value: null } },
];
function summary(count: number, done: unknown[] = []) {
return {
totals: { count, byBasis: { plan: 2, track: 3 } },
types: TYPES,
done,
upcoming: 1,
};
}
beforeEach(() => {
tours.active = [];
tours.figures = {
hero: { value: '42', unit: 'km' },
ascent: { text: '1200 m' },
descent: null,
types: TYPES,
maxKm: 30,
uncounted: { unassigned: 2, undated: 4 },
};
});
describe('MHubTours', () => {
it('FE-ATLAS2-MOBILE-140: before the numbers are there it asks for them and shows where the read stands', () => {
statsWith({ status: 'loading' });
render(<MHubTours s={buildGlobeState()} />);
expect(tours.active[0]).toBe(true);
expect(screen.getByText('status:loading')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-141: the periods are chips, the chosen one pressed, a tap picks another', () => {
const st = statsWith({ period: 'thisYear' });
render(<MHubTours s={buildGlobeState()} />);
const periods = screen.getByRole('group', { name: 'tours.stats.period' });
expect(periods.textContent).toContain('2023');
expect(screen.getByRole('button', { name: 'tours.stats.period.thisYear' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'tours.stats.period.last12' }));
expect(st.setPeriod).toHaveBeenCalledWith('last12');
// One type only: no type chips.
expect(screen.queryByRole('group', { name: 'tours.filter.type' })).toBeNull();
});
it('FE-ATLAS2-MOBILE-142: more than one type adds a row of type chips', () => {
const st = statsWith({ types: ['all', 'hike'] });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.getByRole('button', { name: 'tours.stats.allTypes' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'tourTypes.hike' }));
expect(st.setType).toHaveBeenCalledWith('hike');
});
it('FE-ATLAS2-MOBILE-143: no tour in the period says none counts when there are tours at all', () => {
statsWith({ summary: summary(0), data: { entries: [{ place_id: 1 }], uncounted: { unassigned: 0, undated: 0 } } });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.getByText('tours.stats.none')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-144: no tour at all says there are none yet', () => {
statsWith({ summary: summary(0), data: null });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.getByText('tours.stats.empty')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-145: the distance is the headline, tours, climb and descent the tiles', () => {
statsWith({ summary: summary(5) });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('km')).toBeInTheDocument();
expect(screen.getByText('basis:{"plan":2,"track":3}')).toBeInTheDocument();
expect(screen.getByText('5')).toBeInTheDocument();
expect(screen.getByText('tours.mode.tours')).toBeInTheDocument();
expect(screen.getByText('1200 m')).toBeInTheDocument();
expect(screen.getByText('0')).toBeInTheDocument();
expect(screen.getByText('uncounted:1:2:4')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-146: every type is a row with its count and a bar scaled to the longest', () => {
statsWith({ summary: summary(5) });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.byType' })).toBeInTheDocument();
expect(screen.getByText('atlas.globe.tourCount:3')).toBeInTheDocument();
expect(screen.getByText('30 km')).toBeInTheDocument();
const bar = (label: string) =>
(screen.getByText(label).closest('.flex-col') as HTMLElement).querySelector('.bg-m-act') as HTMLElement;
expect(bar('tourTypes.hike').style.width).toBe('100%');
// A type without a known distance keeps a sliver.
expect(bar('tourTypes.bike').style.width).toBe('4%');
});
it('FE-ATLAS2-MOBILE-147: one type picked leaves the rows by type out, a headline without unit shows the figure alone', () => {
tours.figures = { ...tours.figures, hero: { value: '5', unit: '' } };
statsWith({ summary: summary(5), type: 'hike', types: ['all', 'hike'] });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.queryByRole('heading', { name: 'atlas.globe.byType' })).toBeNull();
expect(screen.queryByText('km')).toBeNull();
});
it('FE-ATLAS2-MOBILE-148: done tours open their list in a dialog, which closes again', () => {
statsWith({ summary: summary(5, [{ place_id: 1 }]) });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.queryByRole('dialog')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'tours.stats.showTours' }));
expect(screen.getByRole('dialog', { name: 'tour list' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'close list' }));
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ATLAS2-MOBILE-149: without done tours there is no list to open', () => {
statsWith({ summary: summary(5) });
render(<MHubTours s={buildGlobeState()} />);
expect(screen.queryByRole('button', { name: 'tours.stats.showTours' })).toBeNull();
});
});
@@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest';
import { buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
import MHubTravellers from './MHubTravellers';
function person(id: number, username: string, countries: number, over: Record<string, unknown> = {}) {
return {
id,
username,
avatar_url: null,
countries,
continents: 2,
regions: 9,
flightKm: 0,
codes: [],
badges: [],
...over,
};
}
const RANKING = [
person(2, 'ann', 20, { avatar_url: 'https://example.test/ann.png', continents: 4, regions: 31 }),
person(1, 'me', 12),
person(3, 'bob', 8),
person(4, 'cy', 3),
];
const rowOf = (name: string) => screen.getByText(name).closest('button') as HTMLElement;
describe('MHubTravellers', () => {
it('FE-ATLAS2-MOBILE-120: loads the travellers and shows being visible as a switch that hides on a tap', () => {
const s = buildGlobeState();
render(<MHubTravellers s={s} />);
expect(s.loadPeople).toHaveBeenCalledOnce();
const visible = screen.getByRole('switch', { name: 'atlas.globe.visibleToOthers' });
expect(visible).toHaveAttribute('aria-checked', 'true');
fireEvent.click(visible);
expect(s.setHidden).toHaveBeenCalledWith(true);
// Nothing loaded yet: no list and no empty state.
expect(screen.queryByText('atlas.globe.noTravellers')).toBeNull();
expect(screen.queryByRole('list')).toBeNull();
});
it('FE-ATLAS2-MOBILE-121: a hidden traveller sees the switch off and turns it back on', () => {
const s = buildGlobeState({ hidden: true });
render(<MHubTravellers s={s} />);
const visible = screen.getByRole('switch', { name: 'atlas.globe.visibleToOthers' });
expect(visible).toHaveAttribute('aria-checked', 'false');
fireEvent.click(visible);
expect(s.setHidden).toHaveBeenCalledWith(false);
});
it('FE-ATLAS2-MOBILE-122: alone on the instance there is nobody to rank', () => {
render(<MHubTravellers s={buildGlobeState({ ranking: [person(1, 'me', 3)] })} />);
expect(screen.getByText('atlas.globe.noTravellers')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-123: the ranking numbers every traveller, marks the reader and opens the others', () => {
const s = buildGlobeState({ ranking: RANKING, me: { id: 1 } });
render(<MHubTravellers s={s} />);
const list = screen.getByRole('list');
expect(within(list).getAllByRole('listitem')).toHaveLength(4);
expect(screen.getByRole('heading', { name: 'atlas.globe.ranking' }).parentElement?.textContent).toContain('4');
expect(rowOf('me')).toBeDisabled();
expect(within(rowOf('me')).getByText('atlas.globe.you')).toBeInTheDocument();
expect(within(rowOf('bob')).queryByText('atlas.globe.you')).toBeNull();
fireEvent.click(rowOf('bob'));
expect(s.setProfileId).toHaveBeenCalledWith(3);
expect(within(rowOf('ann')).getByText('20')).toBeInTheDocument();
expect(within(rowOf('ann')).getByText('31')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-124: the first three wear the podium, the rest a plain number', () => {
render(<MHubTravellers s={buildGlobeState({ ranking: RANKING, me: { id: 1 } })} />);
const place = (name: string) => rowOf(name).firstElementChild as HTMLElement;
expect(place('ann').textContent).toBe('1');
expect(place('ann').getAttribute('style')).toContain('box-shadow');
expect(place('bob').getAttribute('style')).toContain('box-shadow');
expect(place('cy').textContent).toBe('4');
expect(place('cy').getAttribute('style')).toBeNull();
});
it('FE-ATLAS2-MOBILE-125: a picture where there is one, otherwise the first letter', () => {
render(<MHubTravellers s={buildGlobeState({ ranking: RANKING, me: { id: 1 } })} />);
expect(rowOf('ann').querySelector('img')?.getAttribute('src')).toBe('https://example.test/ann.png');
expect(within(rowOf('bob')).getByText('B')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-126: a profile shows the figures and the badges and starts the comparison', () => {
const profile = person(3, 'bob', 8, {
flightKm: 52400,
badges: [
{
id: 'x',
motif: 'countries',
tier: 'gold',
target: 10,
titleKey: 'badge.x',
params: { country: 'FR' },
},
{ id: 'y', motif: 'earth', tier: 'bronze', target: 40075, titleKey: 'badge.y' },
],
});
const s = buildGlobeState({ ranking: RANKING, profile, badges: [1, 2, 3, 4, 5] });
render(<MHubTravellers s={s} />);
const sheet = screen.getByRole('dialog', { name: 'bob' });
expect(within(sheet).getByText('atlas.globe.collected:2,5')).toBeInTheDocument();
expect(within(sheet).getByText('52k')).toBeInTheDocument();
expect(within(sheet).getByText('badge.x:name-FR')).toBeInTheDocument();
expect(within(sheet).getByText('badge.y:')).toBeInTheDocument();
fireEvent.click(within(sheet).getByRole('button', { name: 'atlas.globe.compareOnGlobe' }));
expect(s.setProfileId).toHaveBeenCalledWith(null);
expect(s.startCompare).toHaveBeenCalledWith(profile);
});
it('FE-ATLAS2-MOBILE-127: a profile without badges says so and its close button closes it', () => {
const s = buildGlobeState({ profile: person(3, 'bob', 8) });
render(<MHubTravellers s={s} />);
const sheet = screen.getByRole('dialog', { name: 'bob' });
expect(within(sheet).getByText('atlas.globe.noBadgesYet')).toBeInTheDocument();
fireEvent.click(within(sheet).getByRole('button', { name: 'common.close' }));
expect(s.setProfileId).toHaveBeenCalledWith(null);
});
});
@@ -0,0 +1,405 @@
import { getIntlLanguage } from '@trek/shared';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildBucketItem } from '../../../../../tests/helpers/atlas';
import { buildBucketState, buildGlobeState } from '../../../../../tests/helpers/atlasGlobeState';
import { act, fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
import { visitedOn } from '../../../../pages/atlas/atlasHubModel';
import type { BucketItem } from '../../../../pages/atlas/atlasModel';
import type { GlobePlaceHit } from '../../../../pages/atlas/useGlobePlaceSearch';
import MHubWishlist from './MHubWishlist';
// The place search asks the server; here it answers what the test puts in.
const search = vi.hoisted(() => ({
hits: [] as Array<{ name: string; address: string | null; lat: number; lng: number }>,
loading: false,
asked: [] as Array<[string, string]>,
}));
vi.mock('../../../../pages/atlas/useGlobePlaceSearch', () => ({
useGlobePlaceSearch: (query: string, lang: string) => {
search.asked.push([query, lang]);
return { placeHits: search.hits, placesLoading: search.loading };
},
}));
interface Form {
name: string;
notes: string;
lat: string;
lng: string;
target_date: string;
address?: string;
}
const EMPTY: Form = { name: '', notes: '', lat: '', lng: '', target_date: '' };
function spies() {
return {
setShowBucketAdd: vi.fn(),
setBucketForm: vi.fn(),
setBucketPoiYear: vi.fn(),
setBucketPoiMonth: vi.fn(),
resetBucketAdd: vi.fn(),
handleSelectBucketPoi: vi.fn(),
handleAddBucketItem: vi.fn(async () => undefined),
handleDeleteBucketItem: vi.fn(async () => undefined),
handleClearBucketVisit: vi.fn(async () => undefined),
flyToPoint: vi.fn(),
openDawarich: vi.fn(),
};
}
type Spies = ReturnType<typeof spies>;
/** The wishlist over a bucket state that really changes, so the add sheet reacts as it does in the app. */
function Harness({
items = [],
spy,
open = false,
form = {},
year: startYear = 0,
month: startMonth = 0,
dawarich = false,
}: {
items?: BucketItem[];
spy: Spies;
open?: boolean;
form?: Partial<Form>;
year?: number;
month?: number;
dawarich?: boolean;
}) {
const [show, setShow] = React.useState(open);
const [bucketForm, setForm] = React.useState<Form>({ ...EMPTY, ...form });
const [year, setYear] = React.useState(startYear);
const [month, setMonth] = React.useState(startMonth);
const s = buildGlobeState({
placeLang: 'de',
dawarichEnabled: dawarich,
openDawarich: spy.openDawarich,
flyToPoint: spy.flyToPoint,
bucketState: buildBucketState({
bucketList: items,
showBucketAdd: show,
setShowBucketAdd: (v: boolean) => {
spy.setShowBucketAdd(v);
setShow(v);
},
bucketForm,
setBucketForm: (v: Form) => {
spy.setBucketForm(v);
setForm(v);
},
bucketPoiYear: year,
setBucketPoiYear: (v: number) => {
spy.setBucketPoiYear(v);
setYear(v);
},
bucketPoiMonth: month,
setBucketPoiMonth: (v: number) => {
spy.setBucketPoiMonth(v);
setMonth(v);
},
resetBucketAdd: () => {
spy.resetBucketAdd();
setShow(false);
setForm(EMPTY);
},
handleSelectBucketPoi: (hit: GlobePlaceHit) => {
spy.handleSelectBucketPoi(hit);
setForm((f) => ({
...f,
name: hit.name,
lat: String(hit.lat),
lng: String(hit.lng),
address: hit.address ?? '',
}));
},
handleAddBucketItem: spy.handleAddBucketItem,
handleDeleteBucketItem: spy.handleDeleteBucketItem,
handleClearBucketVisit: spy.handleClearBucketVisit,
}),
});
return <MHubWishlist s={s} />;
}
const ITEMS: BucketItem[] = [
buildBucketItem({ id: 1, name: 'Kyoto', country_code: 'JP', target_date: '2027-04', lat: 35, lng: 135 }),
buildBucketItem({ id: 2, name: 'Lisbon', country_code: 'PRT', notes: 'with Anna' }),
buildBucketItem({
id: 3,
name: 'Iceland',
country_code: 'IS',
visited_at: '2025-06-03 10:00:00',
visited_source: 'dawarich',
}),
buildBucketItem({ id: 4, name: 'Somewhere', country_code: null, visited_at: '2024-01-02', visited_source: 'manual' }),
];
/** jsdom has no Touch: an Event with the touches set on it, as MSwipeRow's own test does. */
function touch(el: Element, type: 'touchstart' | 'touchmove' | 'touchend', x = 0) {
const e = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: 100 }] });
act(() => {
el.dispatchEvent(e);
});
}
function swipe(name: string, dx: number) {
const row = (screen.getByText(name).closest('button') as HTMLElement).parentElement?.parentElement as HTMLElement;
touch(row, 'touchstart', 200);
touch(row, 'touchmove', 200 + dx / 2);
touch(row, 'touchmove', 200 + dx);
touch(row, 'touchend');
}
const sheet = () => screen.getByRole('dialog', { name: 'atlas.globe.newWish' });
const shortMonths = () =>
Array.from({ length: 12 }, (_, i) => new Date(2000, i).toLocaleString(getIntlLanguage('en'), { month: 'short' }));
beforeEach(() => {
search.hits = [];
search.loading = false;
search.asked = [];
});
afterEach(() => {
vi.useRealTimers();
});
describe('MHubWishlist', () => {
it('FE-ATLAS2-MOBILE-040: an empty list says so and its button opens the add sheet', () => {
const spy = spies();
render(<Harness spy={spy} />);
expect(screen.getByText('atlas.bucketEmpty')).toBeInTheDocument();
expect(screen.getByText('atlas.bucketEmptyHint')).toBeInTheDocument();
expect(screen.queryByRole('dialog')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.newWish' }));
expect(spy.setShowBucketAdd).toHaveBeenCalledWith(true);
expect(sheet()).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-041: the headline counts the wishes, the reached ones, the countries and names the next date', () => {
render(<Harness spy={spies()} items={ITEMS} />);
expect(screen.getByText('atlas.globe.wishes:4')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.wishesReached:2,4')).toBeInTheDocument();
// JP, PT (stored as PRT) and IS; the wish without a country counts none.
expect(screen.getByText('3')).toBeInTheDocument();
// The next dated wish in the headline and on its own row.
expect(screen.getAllByText('Apr 2027')).toHaveLength(2);
expect(screen.getAllByText('Kyoto')).toHaveLength(2);
});
it('FE-ATLAS2-MOBILE-042: open wishes come soonest first, reached ones latest first, each section counted', () => {
render(<Harness spy={spies()} items={ITEMS} />);
const open = screen.getByRole('heading', { name: 'atlas.globe.wishesOpen' }).closest('section') as HTMLElement;
const done = screen.getByRole('heading', { name: 'atlas.globe.wishesDone' }).closest('section') as HTMLElement;
const names = (el: HTMLElement) =>
within(el)
.getAllByRole('button')
.map((b) => b.querySelector('.font-semibold')?.textContent);
expect(names(open)).toEqual(['Kyoto', 'Lisbon']);
expect(names(done)).toEqual(['Iceland', 'Somewhere']);
expect(within(open).getByText('2')).toBeInTheDocument();
expect(within(done).getByText('2')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-043: a row names the country and the note, but not a country that is the wish itself', () => {
render(<Harness spy={spies()} items={ITEMS} />);
expect(screen.getByText('name-JP')).toBeInTheDocument();
expect(screen.getByText('name-PT, with Anna')).toBeInTheDocument();
const iceland = screen.getByText('Iceland').closest('button') as HTMLElement;
expect(within(iceland).queryByText('Iceland', { selector: '.text-caption' })).toBeNull();
});
it('FE-ATLAS2-MOBILE-044: a reached wish is struck through and carries the day it came true', () => {
render(<Harness spy={spies()} items={ITEMS} />);
expect(screen.getByText('Iceland').className).toContain('line-through');
expect(screen.getByText('Kyoto', { selector: '.text-body' }).className).not.toContain('line-through');
const day = visitedOn(ITEMS[2] as BucketItem, 'en') as string;
const badge = (screen.getByText('Iceland').closest('button') as HTMLElement).lastElementChild as HTMLElement;
expect(badge.textContent).toContain(day);
});
it('FE-ATLAS2-MOBILE-045: a tap on a wish with a place flies there, one without a place stays put', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} />);
fireEvent.click(screen.getByText('Lisbon').closest('button') as HTMLElement);
expect(spy.flyToPoint).not.toHaveBeenCalled();
fireEvent.click(screen.getByText('Kyoto', { selector: '.text-body' }).closest('button') as HTMLElement);
expect(spy.flyToPoint).toHaveBeenCalledWith(135, 35);
});
it('FE-ATLAS2-MOBILE-046: swiped towards the start, a wish offers removal, which deletes it', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} />);
swipe('Lisbon', -100);
expect(screen.queryByLabelText('dawarich.bucket.clearVisit')).toBeNull();
fireEvent.click(screen.getByLabelText('atlas.removeFromBucket'));
expect(spy.handleDeleteBucketItem).toHaveBeenCalledWith(2);
});
it('FE-ATLAS2-MOBILE-047: a wish a recording reached can also be undone from the swipe', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} />);
swipe('Iceland', -100);
fireEvent.click(screen.getByLabelText('dawarich.bucket.clearVisit'));
expect(spy.handleClearBucketVisit).toHaveBeenCalledWith(3);
});
it('FE-ATLAS2-MOBILE-048: a wish ticked off by hand offers no undo', () => {
render(<Harness spy={spies()} items={ITEMS} />);
swipe('Somewhere', -100);
expect(screen.getByLabelText('atlas.removeFromBucket')).toBeInTheDocument();
expect(screen.queryByLabelText('dawarich.bucket.clearVisit')).toBeNull();
});
it('FE-ATLAS2-MOBILE-049: swiped the other way, a wish with a place shows it on the globe', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} />);
const kyoto = screen.getByText('Kyoto', { selector: '.text-body' });
const row = (kyoto.closest('button') as HTMLElement).parentElement?.parentElement as HTMLElement;
touch(row, 'touchstart', 200);
touch(row, 'touchmove', 250);
touch(row, 'touchmove', 300);
touch(row, 'touchend');
fireEvent.click(screen.getByLabelText('atlas.globe.showOnGlobe'));
expect(spy.flyToPoint).toHaveBeenCalledWith(135, 35);
});
it('FE-ATLAS2-MOBILE-050: with Dawarich on, its entry opens the wishes question', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} dawarich />);
fireEvent.click(screen.getByRole('button', { name: /atlas\.globe\.dawarichWishes/ }));
expect(spy.openDawarich).toHaveBeenCalledWith('wishes');
});
it('FE-ATLAS2-MOBILE-051: only open wishes leave the reached section out, and no dated wish leaves the headline line out', () => {
render(<Harness spy={spies()} items={[buildBucketItem({ id: 5, name: 'Rome', country_code: 'IT' })]} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.wishesOpen' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'atlas.globe.wishesDone' })).toBeNull();
expect(screen.getAllByText('Rome')).toHaveLength(1);
});
it('FE-ATLAS2-MOBILE-052: the add button above the list opens the sheet, its close button resets it', () => {
const spy = spies();
render(<Harness spy={spy} items={ITEMS} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.newWish' }));
expect(sheet()).toBeInTheDocument();
fireEvent.click(within(sheet()).getByRole('button', { name: 'common.cancel' }));
expect(spy.resetBucketAdd).toHaveBeenCalledOnce();
expect(screen.queryByPlaceholderText('atlas.globe.wishSearch')).toBeNull();
});
it('FE-ATLAS2-MOBILE-053: the search asks in the place language and lists no results before anything is typed', () => {
render(<Harness spy={spies()} open />);
expect(screen.getByPlaceholderText('atlas.globe.wishSearch')).toBeInTheDocument();
expect(search.asked.at(-1)).toEqual(['', 'de']);
expect(screen.queryByText(/atlas\.globe\.wishJustName/)).toBeNull();
});
it('FE-ATLAS2-MOBILE-054: a hit from the search is picked as the wish, with its address', () => {
search.hits = [{ name: 'Porto', address: 'Portugal', lat: 41.1, lng: -8.6 }];
const spy = spies();
render(<Harness spy={spy} open />);
fireEvent.change(screen.getByPlaceholderText('atlas.globe.wishSearch'), { target: { value: 'Por' } });
expect(search.asked.at(-1)).toEqual(['Por', 'de']);
expect(screen.getByText('Portugal')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Porto/ }));
expect(spy.handleSelectBucketPoi).toHaveBeenCalledWith(search.hits[0]);
expect(screen.getByLabelText('atlas.bucketNamePlaceholder')).toHaveValue('Porto');
expect(within(sheet()).getByText('Portugal')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-055: what was typed can be taken as a plain name without a place', () => {
const spy = spies();
render(<Harness spy={spy} open />);
fireEvent.change(screen.getByPlaceholderText('atlas.globe.wishSearch'), { target: { value: ' Patagonia ' } });
fireEvent.click(screen.getByText('atlas.globe.wishJustName:Patagonia'));
expect(spy.setBucketForm).toHaveBeenCalledWith(
expect.objectContaining({ name: 'Patagonia', lat: '', lng: '', address: undefined })
);
expect(screen.getByLabelText('atlas.bucketNamePlaceholder')).toHaveValue('Patagonia');
expect(screen.getByText('atlas.globe.wishNoPlace')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-056: a search on its way shows the spinner', () => {
search.loading = true;
render(<Harness spy={spies()} open />);
expect(sheet().querySelector('.animate-spin')).not.toBeNull();
});
it('FE-ATLAS2-MOBILE-057: a picked place without an address reads as shown on the globe, renamed and changed back', () => {
const spy = spies();
render(<Harness spy={spy} open form={{ name: 'Porto', lat: '41.1', lng: '-8.6' }} />);
expect(within(sheet()).getByText('atlas.globe.showOnGlobe')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('atlas.bucketNamePlaceholder'), { target: { value: 'Porto old town' } });
expect(spy.setBucketForm).toHaveBeenLastCalledWith(
expect.objectContaining({ name: 'Porto old town', lat: '41.1' })
);
fireEvent.click(screen.getByText('atlas.globe.change'));
expect(spy.setBucketForm).toHaveBeenLastCalledWith(
expect.objectContaining({ name: '', lat: '', lng: '', address: undefined })
);
expect(screen.getByPlaceholderText('atlas.globe.wishSearch')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-058: without a year the wish is someday and the months are switched off', () => {
render(<Harness spy={spies()} open />);
expect(screen.getByRole('button', { name: 'atlas.globe.someday' })).toHaveAttribute('aria-pressed', 'true');
const grid = screen.getByRole('button', { name: shortMonths()[0] }).parentElement as HTMLElement;
expect(grid).toHaveAttribute('aria-disabled', 'true');
});
it('FE-ATLAS2-MOBILE-059: the year steps from this year and a month toggles on and off', () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 10, 29));
const spy = spies();
render(<Harness spy={spy} open />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearLater' }));
expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2027);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearEarlier' }));
expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2026);
fireEvent.click(screen.getByRole('button', { name: '2026' }));
expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2026);
expect(screen.getByRole('button', { name: 'atlas.globe.someday' })).toHaveAttribute('aria-pressed', 'false');
const march = screen.getByRole('button', { name: shortMonths()[2] });
fireEvent.click(march);
expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(3);
expect(march).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(march);
expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(0);
});
it('FE-ATLAS2-MOBILE-060: someday clears the year and the month again', () => {
const spy = spies();
render(<Harness spy={spy} open year={2030} month={5} />);
expect(screen.getByRole('button', { name: shortMonths()[4] })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.someday' }));
expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(0);
expect(spy.setBucketPoiMonth).toHaveBeenLastCalledWith(0);
});
it('FE-ATLAS2-MOBILE-061: from a chosen year the arrows step from that year', () => {
const spy = spies();
render(<Harness spy={spy} open year={2030} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearLater' }));
expect(spy.setBucketPoiYear).toHaveBeenLastCalledWith(2031);
});
it('FE-ATLAS2-MOBILE-062: the note goes into the form', () => {
const spy = spies();
render(<Harness spy={spy} open />);
fireEvent.change(screen.getByPlaceholderText('atlas.bucketNotesPlaceholder'), { target: { value: 'in spring' } });
expect(spy.setBucketForm).toHaveBeenLastCalledWith(expect.objectContaining({ notes: 'in spring' }));
});
it('FE-ATLAS2-MOBILE-063: save waits for a name, then adds the wish', () => {
const spy = spies();
const { unmount } = render(<Harness spy={spy} open />);
expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeDisabled();
unmount();
render(<Harness spy={spy} open form={{ name: 'Porto' }} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.wishSave' }));
expect(spy.handleAddBucketItem).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,133 @@
import { Flag, Globe2, Plane } from 'lucide-react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { MHubAction, MHubDawarichEntry, MHubEmpty, MHubHero, MHubSection, MHubTiles } from './mHubKit';
describe('mHubKit', () => {
it('FE-ATLAS2-MOBILE-001: the hero shows its figure, the unit and what sits under it', () => {
render(
<MHubHero value={42} unit="countries">
<span>under the figure</span>
</MHubHero>
);
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('countries')).toBeInTheDocument();
expect(screen.getByText('under the figure')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-002: a hero without unit or children renders the figure alone', () => {
const { container } = render(<MHubHero value="7" />);
expect(screen.getByText('7')).toBeInTheDocument();
expect(container.querySelector('.text-subtitle')).toBeNull();
expect(container.querySelector('.mt-3\\.5')).toBeNull();
});
it('FE-ATLAS2-MOBILE-003: two across, an odd last tile takes the whole row and every tile keeps its symbol', () => {
render(
<MHubTiles
tiles={[
{ Icon: Flag, value: 1, label: 'one' },
{ Icon: Globe2, value: 2, label: 'two' },
{ Icon: Plane, value: 3, label: 'three' },
]}
/>
);
const tile = (label: string) => screen.getByText(label).closest('div') as HTMLElement;
expect(tile('three').className).toContain('col-span-2');
expect(tile('one').className).not.toContain('col-span-2');
expect(tile('one').querySelector('svg')).not.toBeNull();
});
it('FE-ATLAS2-MOBILE-004: an even count leaves no tile wide', () => {
render(
<MHubTiles
tiles={[
{ Icon: Flag, value: 1, label: 'one' },
{ Icon: Globe2, value: 2, label: 'two' },
]}
/>
);
expect(screen.getByText('two').closest('div')?.className).not.toContain('col-span-2');
});
it('FE-ATLAS2-MOBILE-005: three across drops the symbols and shows value and label', () => {
const { container } = render(
<MHubTiles
cols={3}
tiles={[
{ Icon: Flag, value: '5 / 10', label: 'progress' },
{ Icon: Globe2, value: 4, label: 'to go' },
{ Icon: Plane, value: '1 / 3', label: 'holders' },
]}
/>
);
expect(container.firstElementChild?.className).toContain('grid-cols-3');
expect(screen.getByText('5 / 10')).toBeInTheDocument();
expect(screen.getByText('holders')).toBeInTheDocument();
expect(container.querySelector('svg')).toBeNull();
});
it('FE-ATLAS2-MOBILE-006: a section shows its title, a meta of zero and its action', () => {
render(
<MHubSection title="Open" meta={0} action={<button type="button">more</button>}>
<p>body</p>
</MHubSection>
);
expect(screen.getByRole('heading', { name: 'Open' })).toBeInTheDocument();
expect(screen.getByText('0')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'more' })).toBeInTheDocument();
expect(screen.getByText('body')).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-007: a section without meta renders no meta line', () => {
const { container } = render(
<MHubSection title="Done">
<p>body</p>
</MHubSection>
);
expect(container.querySelector('.tabular-nums')).toBeNull();
});
it('FE-ATLAS2-MOBILE-008: the empty state shows title, hint and its action', () => {
render(<MHubEmpty Icon={Flag} title="Nothing yet" hint="Add one" action={<button type="button">add</button>} />);
expect(screen.getByText('Nothing yet')).toBeInTheDocument();
expect(screen.getByText('Add one')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'add' })).toBeInTheDocument();
});
it('FE-ATLAS2-MOBILE-009: the empty state without hint or action is the title alone', () => {
render(<MHubEmpty Icon={Flag} title="Nothing yet" />);
expect(screen.getByText('Nothing yet')).toBeInTheDocument();
expect(screen.queryByRole('button')).toBeNull();
});
it('FE-ATLAS2-MOBILE-010: the Dawarich entry names what it does and opens on a tap', () => {
const onClick = vi.fn();
render(<MHubDawarichEntry title="Countries from Dawarich" hint="Find them" onClick={onClick} />);
fireEvent.click(screen.getByRole('button', { name: /Countries from Dawarich/ }));
expect(screen.getByText('Find them')).toBeInTheDocument();
expect(onClick).toHaveBeenCalledOnce();
});
it('FE-ATLAS2-MOBILE-011: the action runs on a tap and stays still when disabled', () => {
const onClick = vi.fn();
const { rerender } = render(
<MHubAction Icon={Flag} onClick={onClick}>
Save
</MHubAction>
);
const button = screen.getByRole('button', { name: 'Save' });
expect(button.querySelector('svg')).not.toBeNull();
fireEvent.click(button);
expect(onClick).toHaveBeenCalledOnce();
rerender(
<MHubAction onClick={onClick} disabled>
Save
</MHubAction>
);
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Save' }).querySelector('svg')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
expect(onClick).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,185 @@
// FE-ATLAS2-VIEWA-080 to FE-ATLAS2-VIEWA-089: the badge unlock moment over the globe.
import { act, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildViewBadge, buildViewState } from '../../../tests/helpers/atlasViewState';
import AtlasBadgeUnlock from './AtlasBadgeUnlock';
const KEY = 'trek_atlas_badges_seen_7';
interface FakeAnimation {
keyframes: Keyframe[];
options: KeyframeAnimationOptions;
onfinish: (() => void) | null;
cancel: ReturnType<typeof vi.fn>;
}
let animations: FakeAnimation[];
let vibrate: ReturnType<typeof vi.fn>;
const originalMatchMedia = window.matchMedia;
const originalAnimate = HTMLElement.prototype.animate;
beforeEach(() => {
animations = [];
HTMLElement.prototype.animate = function animate(keyframes: Keyframe[], options: KeyframeAnimationOptions) {
const anim: FakeAnimation = { keyframes, options, onfinish: null, cancel: vi.fn() };
animations.push(anim);
return anim as unknown as Animation;
} as unknown as HTMLElement['animate'];
vibrate = vi.fn();
Object.defineProperty(navigator, 'vibrate', { value: vibrate, configurable: true, writable: true });
});
afterEach(() => {
window.matchMedia = originalMatchMedia;
HTMLElement.prototype.animate = originalAnimate;
vi.useRealTimers();
});
function lastFrame(anim: FakeAnimation | undefined): Keyframe | undefined {
return anim ? anim.keyframes[anim.keyframes.length - 1] : undefined;
}
function seen(): string[] | null {
const raw = localStorage.getItem(KEY);
return raw ? (JSON.parse(raw) as string[]) : null;
}
const EARNED = buildViewBadge({ id: 'countries-5', earned: true, current: 5, target: 5 });
const OPEN = buildViewBadge({ id: 'countries-10', earned: false, current: 5, target: 10 });
const REGION = buildViewBadge({
id: 'region-fr',
motif: 'region',
category: 'regions',
titleKey: 'atlas.badge.region.title',
params: { country: 'FR' },
earned: true,
current: 13,
target: 13,
});
describe('AtlasBadgeUnlock', () => {
it('FE-ATLAS2-VIEWA-080: the first visit only remembers what is earned and celebrates nothing', () => {
const s = buildViewState({ badges: [EARNED, OPEN] });
const { container } = render(<AtlasBadgeUnlock s={s} />);
expect(container).toBeEmptyDOMElement();
expect(seen()).toEqual(['countries-5']);
expect(animations).toHaveLength(0);
});
it('FE-ATLAS2-VIEWA-081: nothing happens before the data and the globe are there, or without a user', () => {
const { container, rerender } = render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED], data: null })} />);
expect(seen()).toBeNull();
rerender(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED], manifest: null })} />);
expect(seen()).toBeNull();
rerender(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED], me: null })} />);
expect(seen()).toBeNull();
expect(container).toBeEmptyDOMElement();
});
it('FE-ATLAS2-VIEWA-082: a badge reached since the last visit rises, names itself and flies to the badges button', () => {
localStorage.setItem(KEY, JSON.stringify([]));
const target = document.createElement('button');
target.setAttribute('data-atlas-badges-btn', '');
target.getBoundingClientRect = () => ({ left: 100, top: 10, width: 20, height: 20 }) as DOMRect;
document.body.appendChild(target);
const s = buildViewState({ badges: [EARNED, OPEN] });
render(<AtlasBadgeUnlock s={s} />);
expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument();
expect(screen.getByText('atlas.badge.countries.title')).toBeInTheDocument();
expect(animations).toHaveLength(1);
const last = lastFrame(animations[0]);
expect(last?.transform).toContain('translate(110px, 20px)');
expect(animations[0]?.options.duration).toBe(3400);
expect(vibrate).toHaveBeenCalledWith(18);
act(() => animations[0]?.onfinish?.());
expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument();
expect(seen()).toEqual(['countries-5']);
target.remove();
});
it('FE-ATLAS2-VIEWA-083: without a badges button the medal flies upwards', () => {
localStorage.setItem(KEY, JSON.stringify([]));
render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED] })} />);
expect(lastFrame(animations[0])?.transform).toContain('translate(0px, -200px)');
});
it('FE-ATLAS2-VIEWA-084: several new badges come one after the other, each remembered', () => {
localStorage.setItem(KEY, JSON.stringify(['old']));
const s = buildViewState({ badges: [EARNED, REGION] });
render(<AtlasBadgeUnlock s={s} />);
expect(screen.getByText('atlas.badge.countries.title')).toBeInTheDocument();
act(() => animations[0]?.onfinish?.());
// The region badge names its country by its name.
expect(screen.getByText('atlas.badge.region.title(country=France)')).toBeInTheDocument();
expect(animations).toHaveLength(2);
act(() => animations[1]?.onfinish?.());
expect(seen()).toEqual(['old', 'countries-5', 'region-fr']);
expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-085: a badge already seen is not celebrated again, and one queued is not queued twice', () => {
localStorage.setItem(KEY, JSON.stringify(['countries-5']));
const { rerender, container } = render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED] })} />);
expect(container).toBeEmptyDOMElement();
localStorage.setItem(KEY, JSON.stringify([]));
const s = buildViewState({ badges: [EARNED] });
rerender(<AtlasBadgeUnlock s={s} />);
rerender(<AtlasBadgeUnlock s={{ ...s, badges: [...s.badges] }} />);
expect(screen.getAllByText('atlas.globe.newBadge')).toHaveLength(1);
act(() => animations[animations.length - 1]?.onfinish?.());
expect(container).toBeEmptyDOMElement();
});
it('FE-ATLAS2-VIEWA-086: with reduced motion the medal stays and leaves after a pause, without animating', () => {
vi.useFakeTimers();
localStorage.setItem(KEY, JSON.stringify([]));
window.matchMedia = vi.fn((query: string) => ({
matches: query.includes('reduce'),
media: query,
})) as unknown as typeof window.matchMedia;
render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED] })} />);
expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument();
expect(animations).toHaveLength(0);
act(() => {
vi.advanceTimersByTime(2199);
});
expect(screen.getByText('atlas.globe.newBadge')).toBeInTheDocument();
act(() => {
vi.advanceTimersByTime(1);
});
expect(screen.queryByText('atlas.globe.newBadge')).not.toBeInTheDocument();
expect(seen()).toEqual(['countries-5']);
});
it('FE-ATLAS2-VIEWA-087: leaving mid-flight cancels the animation', () => {
localStorage.setItem(KEY, JSON.stringify([]));
const { unmount } = render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED] })} />);
unmount();
expect(animations[0]?.cancel).toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWA-088: blocked storage counts as a first visit and nothing breaks', () => {
const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('blocked');
});
try {
const { container } = render(<AtlasBadgeUnlock s={buildViewState({ badges: [EARNED] })} />);
expect(container).toBeEmptyDOMElement();
expect(setItem).toHaveBeenCalledWith(KEY, JSON.stringify(['countries-5']));
} finally {
getItem.mockRestore();
setItem.mockRestore();
}
});
it('FE-ATLAS2-VIEWA-089: a country param without a known name keeps its code', () => {
localStorage.setItem(KEY, JSON.stringify([]));
const b = buildViewBadge({ id: 'x', earned: true, params: { country: 'XX', n: 3 } });
render(<AtlasBadgeUnlock s={buildViewState({ badges: [b] })} />);
expect(screen.getByText('atlas.badge.countries.title(country=XX,n=3)')).toBeInTheDocument();
});
});
@@ -0,0 +1,221 @@
// FE-ATLAS2-VIEWA-100 to FE-ATLAS2-VIEWA-111: the desktop country / region action dialog over a faked
// useAtlasCountryActions (the hook has its own tests).
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import CountryActionDialog, { type CountryActionDialogProps } from './AtlasCountryActionDialog';
import type { AtlasConfirmAction } from './useAtlasCountryActions';
const actions = vi.hoisted(() => ({
onWishlist: false,
markCountry: vi.fn(),
markRegion: vi.fn(),
unmarkRegion: vi.fn(),
addBucket: vi.fn(),
removeBucket: vi.fn(),
received: [] as unknown[],
}));
vi.mock('./useAtlasCountryActions', async (importOriginal) => ({
...(await importOriginal<typeof import('./useAtlasCountryActions')>()),
useAtlasCountryActions: (opts: unknown) => {
actions.received.push(opts);
return actions;
},
}));
// The real select opens a portal menu; a native one shows the same options and change.
vi.mock('../../components/shared/CustomSelect', () => ({
default: ({
id,
value,
onChange,
options,
}: {
id: string;
value: string;
onChange: (v: string) => void;
options: Array<{ value: string; label: string }>;
}) => (
<select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
{options.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
),
}));
const t = (k: string) => k;
function props(confirmAction: AtlasConfirmAction | null, over: Partial<CountryActionDialogProps> = {}) {
return {
t,
language: 'en',
confirmAction,
setConfirmAction: vi.fn(),
executeConfirmAction: vi.fn(),
bucketMonth: 0,
setBucketMonth: vi.fn(),
bucketYear: 0,
setBucketYear: vi.fn(),
setData: vi.fn(),
visitedRegions: {},
setVisitedRegions: vi.fn(),
bucketList: [],
setBucketList: vi.fn(),
handleDeleteBucketItem: vi.fn(async () => undefined),
...over,
} satisfies CountryActionDialogProps;
}
const FRANCE: AtlasConfirmAction = { type: 'choose', code: 'FR', name: 'France' };
const BAVARIA: AtlasConfirmAction = {
type: 'choose-region',
code: 'DE',
name: 'Bavaria',
regionCode: 'DE-BY',
countryName: 'Germany',
};
beforeEach(() => {
actions.onWishlist = false;
actions.received = [];
for (const fn of [
actions.markCountry,
actions.markRegion,
actions.unmarkRegion,
actions.addBucket,
actions.removeBucket,
])
fn.mockClear();
});
describe('CountryActionDialog', () => {
it('FE-ATLAS2-VIEWA-100: without a confirm action nothing shows, the hook still runs', () => {
const { container } = render(<CountryActionDialog {...props(null)} />);
expect(container).toBeEmptyDOMElement();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(actions.received).toHaveLength(1);
});
it('FE-ATLAS2-VIEWA-101: a country offers to mark it or wish for it, with its flag and name', () => {
const p = props(FRANCE);
render(<CountryActionDialog {...p} />);
expect(screen.getByRole('heading', { name: 'France' })).toBeInTheDocument();
expect(screen.getByRole('img', { name: 'FR' })).toHaveAttribute('src', 'https://flagcdn.com/w80/fr.png');
expect(screen.getByText('atlas.markVisitedHint')).toBeInTheDocument();
expect(screen.getByText('atlas.addToBucketHint')).toBeInTheDocument();
expect(screen.queryByText('atlas.removeFromBucket')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas\.markVisited/ }));
expect(actions.markCountry).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: /atlas\.addToBucket/ }));
expect(p.setConfirmAction).toHaveBeenCalledWith({ ...FRANCE, type: 'bucket' });
});
it('FE-ATLAS2-VIEWA-102: cancel and the close button both close the dialog', () => {
const p = props(FRANCE);
render(<CountryActionDialog {...p} />);
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }));
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(p.setConfirmAction).toHaveBeenCalledTimes(2);
expect(p.setConfirmAction).toHaveBeenNthCalledWith(1, null);
expect(p.setConfirmAction).toHaveBeenNthCalledWith(2, null);
});
it('FE-ATLAS2-VIEWA-103: a country already on the wishlist offers to remove it', () => {
actions.onWishlist = true;
render(<CountryActionDialog {...props(FRANCE)} />);
expect(screen.getByText('atlas.removeFromBucketHint')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas\.removeFromBucket/ }));
expect(actions.removeBucket).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-104: a code that is not ISO A2 gets no flag image', () => {
render(<CountryActionDialog {...props({ type: 'choose', code: 'XKX', name: 'Kosovo' })} />);
expect(screen.getByRole('heading', { name: 'Kosovo' })).toBeInTheDocument();
expect(screen.queryByRole('img')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-105: a region names its country and offers to mark it or wish for it', () => {
const p = props(BAVARIA);
render(<CountryActionDialog {...p} />);
expect(screen.getByRole('heading', { name: 'Bavaria' })).toBeInTheDocument();
expect(screen.getByText('Germany')).toBeInTheDocument();
expect(screen.getByText('atlas.markRegionVisitedHint')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas\.markVisited/ }));
expect(actions.markRegion).toHaveBeenCalledWith();
fireEvent.click(screen.getByRole('button', { name: /atlas\.addToBucket/ }));
expect(p.setConfirmAction).toHaveBeenCalledWith({ ...BAVARIA, type: 'bucket' });
});
it('FE-ATLAS2-VIEWA-106: marking asks to confirm and the primary button confirms', () => {
const p = props({ ...FRANCE, type: 'mark' });
render(<CountryActionDialog {...p} />);
expect(screen.getByText('atlas.confirmMark')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'atlas.markVisited' }));
expect(p.executeConfirmAction).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-107: unmarking a country asks and the danger button confirms', () => {
const p = props({ ...FRANCE, type: 'unmark' });
render(<CountryActionDialog {...p} />);
expect(screen.getByText('atlas.confirmUnmark')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' }));
expect(p.executeConfirmAction).toHaveBeenCalledTimes(1);
expect(actions.unmarkRegion).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWA-108: unmarking a region asks and the danger button unmarks the region', () => {
const p = props({ ...BAVARIA, type: 'unmark-region' });
render(<CountryActionDialog {...p} />);
expect(screen.getByText('atlas.confirmUnmarkRegion')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' }));
expect(actions.unmarkRegion).toHaveBeenCalledTimes(1);
expect(p.executeConfirmAction).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWA-109: the wish step asks when, with months and twenty years, and goes back to the choice', () => {
const p = props({ ...FRANCE, type: 'bucket' }, { bucketMonth: 0, bucketYear: 0 });
render(<CountryActionDialog {...p} />);
expect(screen.getByText('atlas.bucketWhen')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'common.cancel' })).not.toBeInTheDocument();
const month = screen.getByLabelText('atlas.month');
const year = screen.getByLabelText('atlas.year');
expect(within(month).getAllByRole('option')).toHaveLength(13);
expect(within(month).getAllByRole('option')[0]).toHaveTextContent('common.none');
expect(within(month).getAllByRole('option')[1]).toHaveTextContent('January');
const years = within(year).getAllByRole('option');
expect(years).toHaveLength(21);
const now = new Date().getFullYear();
expect(years[1]).toHaveTextContent(String(now));
expect(years[20]).toHaveTextContent(String(now + 19));
fireEvent.change(month, { target: { value: '4' } });
expect(p.setBucketMonth).toHaveBeenCalledWith(4);
fireEvent.change(year, { target: { value: String(now + 1) } });
expect(p.setBucketYear).toHaveBeenCalledWith(now + 1);
fireEvent.click(screen.getByRole('button', { name: 'common.back' }));
expect(p.setConfirmAction).toHaveBeenCalledWith({ ...FRANCE, type: 'choose' });
});
it('FE-ATLAS2-VIEWA-110: back from a region wish returns to the region choice', () => {
const p = props({ ...BAVARIA, type: 'bucket' });
render(<CountryActionDialog {...p} />);
fireEvent.click(screen.getByRole('button', { name: 'common.back' }));
expect(p.setConfirmAction).toHaveBeenCalledWith({ ...BAVARIA, type: 'choose-region' });
});
it('FE-ATLAS2-VIEWA-111: adding the wish passes the month target and clears the picker once added', () => {
const p = props({ ...FRANCE, type: 'bucket' }, { bucketMonth: 4, bucketYear: 2027 });
render(<CountryActionDialog {...p} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.addToBucket' }));
expect(actions.addBucket).toHaveBeenCalledTimes(1);
const [target, onAdded] = actions.addBucket.mock.calls[0] as [string | null, () => void];
expect(target).toBe('2027-04');
expect(p.setBucketMonth).not.toHaveBeenCalled();
onAdded();
expect(p.setBucketMonth).toHaveBeenCalledWith(0);
expect(p.setBucketYear).toHaveBeenCalledWith(0);
});
});
@@ -0,0 +1,171 @@
// FE-ATLAS2-VIEWA-020 to FE-ATLAS2-VIEWA-031: the badges tab of the Atlas hub, overview and detail page.
import { fireEvent, render, screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { buildViewBadge, buildViewState } from '../../../tests/helpers/atlasViewState';
import AtlasGlobeBadges from './AtlasGlobeBadges';
const FIVE = buildViewBadge({ id: 'countries-5', target: 5, current: 5, earned: true, year: 2021, country: 'FR' });
const TEN = buildViewBadge({ id: 'countries-10', target: 10, current: 5, tier: 'silver' });
const REGION = buildViewBadge({
id: 'region-fr',
category: 'regions',
motif: 'region',
titleKey: 'atlas.badge.region.title',
descKey: 'atlas.badge.region.desc',
params: { country: 'FR' },
earned: true,
current: 13,
target: 13,
});
function tile(name: RegExp): HTMLElement {
return screen.getByRole('button', { name });
}
describe('AtlasGlobeBadges overview', () => {
it('FE-ATLAS2-VIEWA-020: one section per category that has badges, with its earned count', () => {
const s = buildViewState({ badges: [FIVE, TEN, REGION] });
render(<AtlasGlobeBadges s={s} />);
const headings = screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent);
expect(headings).toEqual(['atlas.badgeCat.countries', 'atlas.badgeCat.regions']);
const countries = screen.getByText('atlas.badgeCat.countries').closest('section') as HTMLElement;
expect(within(countries).getByText('1 / 2')).toBeInTheDocument();
const regions = screen.getByText('atlas.badgeCat.regions').closest('section') as HTMLElement;
expect(within(regions).getByText('1 / 1')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-021: an earned tile names its year, an open one its progress, a country param its name', () => {
const s = buildViewState({ badges: [FIVE, TEN, REGION] });
render(<AtlasGlobeBadges s={s} />);
const buttons = screen.getAllByRole('button');
expect(buttons[0]).toHaveAttribute('data-earned', '1');
expect(buttons[0]).toHaveTextContent('2021');
expect(buttons[1]).toHaveAttribute('data-earned', '0');
expect(buttons[1]).toHaveTextContent('5 / 10');
expect(buttons[2]).toHaveTextContent('atlas.badge.region.title(country=France)');
});
it('FE-ATLAS2-VIEWA-022: an earned tile without a year shows no second line; unknown country codes stay', () => {
const b = buildViewBadge({ id: 'x', earned: true, year: null, params: { country: 'XX' } });
const s = buildViewState({ badges: [b] });
render(<AtlasGlobeBadges s={s} />);
const button = screen.getAllByRole('button')[0];
expect(button).toHaveTextContent('atlas.badge.countries.title(country=XX)');
expect(button.querySelectorAll('span.tabular-nums')).toHaveLength(0);
});
it('FE-ATLAS2-VIEWA-023: the pointer tilts a medal and leaving straightens it', () => {
const s = buildViewState({ badges: [TEN] });
render(<AtlasGlobeBadges s={s} />);
const button = screen.getAllByRole('button')[0];
button.getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 100 }) as DOMRect;
fireEvent.pointerMove(button, { clientX: 75, clientY: 25 });
expect(button.style.getPropertyValue('--mx')).toBe('75%');
expect(button.style.getPropertyValue('--my')).toBe('25%');
expect(button.style.getPropertyValue('--rx')).toBe(`${25 / 9}deg`);
expect(button.style.getPropertyValue('--ry')).toBe(`${25 / 9}deg`);
fireEvent.pointerMove(button, { clientX: 1000, clientY: -1000 });
expect(button.style.getPropertyValue('--rx')).toBe('12deg');
expect(button.style.getPropertyValue('--ry')).toBe('12deg');
fireEvent.pointerLeave(button);
expect(button.style.getPropertyValue('--rx')).toBe('0deg');
expect(button.style.getPropertyValue('--ry')).toBe('0deg');
});
it('FE-ATLAS2-VIEWA-024: no badges render no sections', () => {
const s = buildViewState({ badges: [] });
render(<AtlasGlobeBadges s={s} />);
expect(screen.queryByRole('heading')).not.toBeInTheDocument();
});
});
describe('AtlasGlobeBadges detail', () => {
it('FE-ATLAS2-VIEWA-025: an open badge shows tier, how-to, progress, what is left and its stages', () => {
const s = buildViewState({ badges: [FIVE, TEN, REGION] });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[1]);
expect(screen.getByRole('heading', { level: 3, name: 'atlas.badge.countries.title' })).toBeInTheDocument();
expect(screen.getByText('atlas.badgeTier.silver')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.howTo')).toBeInTheDocument();
expect(screen.getByText('atlas.badge.countries.desc(count=10)')).toBeInTheDocument();
expect(screen.getByText('5 / 10')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.toGo')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.toGo').previousElementSibling).toHaveTextContent('5');
expect(screen.queryByText('atlas.globe.reached')).not.toBeInTheDocument();
expect(screen.queryByText('atlas.globe.madeBy')).not.toBeInTheDocument();
expect(screen.queryByText('atlas.globe.holders')).not.toBeInTheDocument();
expect(screen.getByText('atlas.globe.stages')).toBeInTheDocument();
expect(screen.getByText('1 / 2')).toBeInTheDocument();
expect(s.loadPeople).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWA-026: an earned badge says when and which country made it', () => {
const s = buildViewState({ badges: [FIVE, TEN] });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(screen.getAllByText('atlas.globe.reached')).toHaveLength(2);
expect(screen.getByText('2021')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.madeBy')).toBeInTheDocument();
expect(screen.getByText('France')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-027: an earned badge without year shows a tick; a country without a name keeps its code', () => {
const b = buildViewBadge({ id: 'only', earned: true, current: 5, target: 5, year: null, country: 'XX' });
const s = buildViewState({ badges: [b] });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(screen.getByText('✓')).toBeInTheDocument();
expect(screen.getByText('XX')).toBeInTheDocument();
// A single stage has no ladder.
expect(screen.queryByText('atlas.globe.stages')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-028: with comparing on it loads the travellers and counts who holds the badge', () => {
const people = [{ badges: [{ id: 'countries-5' }] }, { badges: [] }];
const s = buildViewState({ badges: [FIVE, TEN], compareEnabled: true, people });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(s.loadPeople).toHaveBeenCalledTimes(1);
expect(screen.getByText('atlas.globe.holders')).toBeInTheDocument();
// One other traveller plus the reader, out of two others plus the reader.
expect(screen.getByText('2 / 3')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-029: comparing on but travellers not loaded yet shows no holders tile', () => {
const s = buildViewState({ badges: [TEN], compareEnabled: true, people: null });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[0]);
expect(s.loadPeople).toHaveBeenCalled();
expect(screen.queryByText('atlas.globe.holders')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-030: a stage in the ladder opens that stage, the open one is marked current', () => {
const s = buildViewState({ badges: [FIVE, TEN] });
render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[1]);
const stages = screen.getAllByRole('button').filter((b) => b.hasAttribute('aria-current'));
expect(stages).toHaveLength(2);
expect(stages[1]).toHaveAttribute('aria-current', 'true');
expect(stages[0]).toHaveAttribute('aria-current', 'false');
fireEvent.click(stages[0]);
expect(screen.getByText('atlas.globe.madeBy')).toBeInTheDocument();
expect(screen.getAllByRole('button').filter((b) => b.getAttribute('aria-current') === 'true')).toHaveLength(1);
});
it('FE-ATLAS2-VIEWA-031: the back button returns to the overview; the detail medal tilts too', () => {
const s = buildViewState({ badges: [FIVE, TEN] });
const { container } = render(<AtlasGlobeBadges s={s} />);
fireEvent.click(screen.getAllByRole('button')[1]);
const medal = container.querySelector('div.ag-medal') as HTMLElement;
medal.getBoundingClientRect = () => ({ left: 0, top: 0, width: 200, height: 200 }) as DOMRect;
fireEvent.pointerMove(medal, { clientX: 100, clientY: 100 });
expect(medal.style.getPropertyValue('--rx')).toBe('0deg');
expect(medal.style.getPropertyValue('--mx')).toBe('50%');
fireEvent.pointerLeave(medal);
expect(medal.style.getPropertyValue('--ry')).toBe('0deg');
fireEvent.click(tile(/atlas\.badgeCat\.countries/));
expect(screen.getByRole('heading', { level: 3, name: 'atlas.badgeCat.countries' })).toBeInTheDocument();
expect(screen.getByText('1 / 2')).toBeInTheDocument();
});
});
@@ -0,0 +1,225 @@
// FE-ATLAS2-VIEWA-060 to FE-ATLAS2-VIEWA-070: the Dawarich tab of the Atlas hub over a faked useDawarichAtlas.
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildViewState } from '../../../tests/helpers/atlasViewState';
import type { DawarichAtlasState } from '../../components/Dawarich/useDawarichAtlas';
import AtlasGlobeDawarich from './AtlasGlobeDawarich';
const hook = vi.hoisted(() => ({
state: null as unknown,
calls: [] as Array<{ initialTab?: string; onChanged?: () => void }>,
}));
vi.mock('../../components/Dawarich/useDawarichAtlas', async (importOriginal) => ({
...(await importOriginal<typeof import('../../components/Dawarich/useDawarichAtlas')>()),
useDawarichAtlas: (opts: { initialTab?: string; onChanged?: () => void }) => {
hook.calls.push(opts);
return hook.state;
},
}));
function fakeDawarich(over: Record<string, unknown> = {}): DawarichAtlasState {
const d: Record<string, unknown> = {
tab: 'wishes',
setTab: vi.fn(),
busy: false,
loaded: false,
anything: false,
run: vi.fn(),
confirm: vi.fn(),
matches: [],
openMatches: [],
offered: [],
picked: new Set<number>(),
pickedCountries: new Set<string>(),
togglePicked: vi.fn(),
togglePickedCountry: vi.fn(),
selected: 0,
writing: false,
scan: null,
countries: null,
...over,
};
hook.state = d;
return d as unknown as DawarichAtlasState;
}
const VISITED = { itemId: 1, name: 'Louvre', alreadyVisited: true, match: null };
const FOUND = {
itemId: 2,
name: 'Colosseum',
alreadyVisited: false,
match: { distanceMeters: 1500, minutes: 90, at: '2025-03-04T12:00:00Z' },
};
const MISSED = { itemId: 3, name: 'Machu Picchu', alreadyVisited: false, match: null };
const FRANCE = { countryCode: 'FR', sourceName: 'France', cities: [{ name: 'Paris' }, { name: 'Lyon' }] };
const ITALY = { countryCode: 'IT', sourceName: 'Italia', cities: [] };
beforeEach(() => {
hook.calls = [];
});
describe('AtlasGlobeDawarich', () => {
it('FE-ATLAS2-VIEWA-060: asks the hub tab first and reloads the Atlas after a write', () => {
const d = fakeDawarich();
const s = buildViewState({ dawarichSub: 'countries' });
render(<AtlasGlobeDawarich s={s} />);
expect(hook.calls[0]?.initialTab).toBe('countries');
expect(d.setTab).toHaveBeenCalledWith('countries');
hook.calls[0]?.onChanged?.();
expect(s.reload).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-061: the two segments carry their counts and switch the tab', () => {
const d = fakeDawarich({ openMatches: [FOUND], offered: [] });
render(<AtlasGlobeDawarich s={buildViewState()} />);
const wishes = screen.getByRole('button', { name: /dawarich\.atlas\.tab\.wishes/ });
const countries = screen.getByRole('button', { name: /dawarich\.atlas\.tab\.countries/ });
expect(wishes).toHaveTextContent('1');
expect(wishes).toHaveClass('bg-surface-card');
expect(countries).not.toHaveTextContent(/\d/);
fireEvent.click(countries);
expect(d.setTab).toHaveBeenCalledWith('countries');
});
it('FE-ATLAS2-VIEWA-062: while it asks it says what it does, per tab', () => {
fakeDawarich({ busy: true });
const { unmount } = render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText(/dawarich\.bucket\.scanning/)).toBeInTheDocument();
unmount();
fakeDawarich({ busy: true, tab: 'countries' });
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText(/dawarich\.atlas\.loading/)).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-063: before the first question it explains and offers to ask (wishes)', () => {
const d = fakeDawarich();
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText('dawarich.bucket.title')).toBeInTheDocument();
expect(screen.getByText('dawarich.bucket.description')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.bucket.scan' }));
expect(d.run).toHaveBeenCalledTimes(1);
// Notes only once something was asked.
expect(screen.queryByText(/dawarich\.bucket\.rule/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-064: before the first question it explains and offers to ask (countries)', () => {
const d = fakeDawarich({ tab: 'countries' });
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText('dawarich.atlas.title')).toBeInTheDocument();
expect(screen.getByText('dawarich.atlas.description')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.atlas.load' }));
expect(d.run).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-065: nothing found says so, offers to ask again and lists the scan notes', () => {
const d = fakeDawarich({
loaded: true,
scan: { matches: [], skippedWithoutCoordinates: 2, truncated: true, fetchedAt: '' },
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText('dawarich.bucket.noMatches')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' }));
expect(d.run).toHaveBeenCalledTimes(1);
expect(screen.getByText(/dawarich\.bucket\.skipped\(count=2\)/)).toBeInTheDocument();
expect(screen.getByText(/dawarich\.bucket\.truncated/)).toBeInTheDocument();
expect(screen.getByText(/dawarich\.bucket\.rule\(meters=/)).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-066: countries found empty say so', () => {
fakeDawarich({
tab: 'countries',
loaded: true,
countries: { countries: [], unresolved: [], fetchedAt: '' },
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText('dawarich.atlas.empty')).toBeInTheDocument();
expect(screen.getByText(/dawarich\.atlas\.window/)).toBeInTheDocument();
expect(screen.queryByText(/dawarich\.atlas\.unresolved/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-067: wishes found list visited, matched and missed ones, each tickable unless visited', () => {
const d = fakeDawarich({
loaded: true,
anything: true,
matches: [VISITED, FOUND, MISSED],
openMatches: [FOUND, MISSED],
picked: new Set([2]),
selected: 1,
scan: { matches: [], skippedWithoutCoordinates: 0, truncated: false, fetchedAt: '' },
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
const louvre = screen.getByRole('checkbox', { name: 'Louvre' });
expect(louvre).toBeDisabled();
expect(louvre).toHaveTextContent('dawarich.bucket.alreadyVisited');
const colosseum = screen.getByRole('checkbox', { name: 'Colosseum' });
expect(colosseum).toHaveAttribute('aria-checked', 'true');
expect(colosseum).toHaveTextContent('dawarich.bucket.kilometersAway(km=1.5)');
expect(colosseum).toHaveTextContent('dawarich.duration.hoursMinutes(hours=1,minutes=30)');
expect(colosseum).toHaveTextContent('Mar 4, 2025');
const machu = screen.getByRole('checkbox', { name: 'Machu Picchu' });
expect(machu).toHaveAttribute('aria-checked', 'false');
expect(machu).toHaveTextContent('dawarich.bucket.noMatches');
fireEvent.click(machu);
expect(d.togglePicked).toHaveBeenCalledWith(3);
expect(screen.queryByText(/dawarich\.bucket\.skipped/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-068: the footer counts the ticks, asks again and confirms the wishes', () => {
const d = fakeDawarich({
loaded: true,
anything: true,
matches: [FOUND],
openMatches: [FOUND],
picked: new Set([2]),
selected: 1,
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByText('dawarich.selected(count=1)')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'dawarich.again' }));
expect(d.run).toHaveBeenCalledTimes(1);
const confirm = screen.getByRole('button', { name: 'dawarich.bucket.confirm(count=1)' });
expect(confirm).toBeEnabled();
fireEvent.click(confirm);
expect(d.confirm).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-069: countries found list their cities and are tickable; nothing ticked keeps confirm off', () => {
const d = fakeDawarich({
tab: 'countries',
loaded: true,
anything: true,
offered: [FRANCE, ITALY],
pickedCountries: new Set(['FR']),
selected: 0,
countries: { countries: [], unresolved: ['Narnia'], fetchedAt: '' },
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
const france = screen.getByRole('checkbox', { name: 'France' });
expect(france).toHaveAttribute('aria-checked', 'true');
expect(france).toHaveTextContent('dawarich.atlas.cities(count=2)');
expect(france).toHaveTextContent('Paris, Lyon');
const italy = screen.getByRole('checkbox', { name: 'Italy' });
expect(italy).not.toHaveTextContent('dawarich.atlas.cities');
fireEvent.click(italy);
expect(d.togglePickedCountry).toHaveBeenCalledWith('IT');
expect(screen.getByRole('button', { name: 'dawarich.atlas.accept(count=0)' })).toBeDisabled();
expect(screen.getByText(/dawarich\.atlas\.unresolved\(names=Narnia\)/)).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-070: a write in flight keeps confirm off even with ticks', () => {
fakeDawarich({
tab: 'countries',
loaded: true,
anything: true,
offered: [FRANCE],
pickedCountries: new Set(['FR']),
selected: 1,
writing: true,
});
render(<AtlasGlobeDawarich s={buildViewState()} />);
expect(screen.getByRole('button', { name: 'dawarich.atlas.accept(count=1)' })).toBeDisabled();
});
});
@@ -0,0 +1,236 @@
// FE-ATLAS2-VIEWB-090 to FE-ATLAS2-VIEWB-104: the globe's country dialogs and its layers dialog.
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAtlasData } from '../../../tests/helpers/atlas';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { GlobeCountryDialogs, GlobeLayersDialog } from './AtlasGlobeDialogs';
interface ActionProps {
setConfirmAction: (v: unknown) => void;
bucketList: unknown;
visitedRegions: unknown;
}
const actionProps: { last: ActionProps | null } = { last: null };
const placesProps: { last: { detail: unknown; onOpenTrip: (id: number) => void } | null } = { last: null };
vi.mock('./AtlasCountryActionDialog', () => ({
default: (props: ActionProps) => {
actionProps.last = props;
return <div>action-dialog</div>;
},
}));
vi.mock('../../components/Atlas/AtlasCountryPlaces', () => ({
default: (props: { detail: unknown; onOpenTrip: (id: number) => void }) => {
placesProps.last = props;
return <div>country-places</div>;
},
}));
beforeEach(() => {
actionProps.last = null;
placesProps.last = null;
});
function detailOf(data: Record<string, unknown> | null) {
return { a2: 'FR', data };
}
describe('GlobeCountryDialogs', () => {
it('FE-ATLAS2-VIEWB-090: without a detail only the action dialog is there, wired to the globe state', () => {
const bucket = [{ id: 1 }];
const regions = { FR: [] };
render(<GlobeCountryDialogs s={viewState({ bucket, regions })} onOpenTrip={vi.fn()} />);
expect(screen.getByText('action-dialog')).toBeInTheDocument();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(actionProps.last?.bucketList).toBe(bucket);
expect(actionProps.last?.visitedRegions).toBe(regions);
});
it('FE-ATLAS2-VIEWB-091: clearing the confirm step closes the dialogs, a new step or an updater does not', () => {
const setConfirmAction = vi.fn();
const closeDialogs = vi.fn();
render(<GlobeCountryDialogs s={viewState({ setConfirmAction, closeDialogs })} onOpenTrip={vi.fn()} />);
const set = actionProps.last?.setConfirmAction;
if (!set) throw new Error('no setter');
set({ type: 'mark', code: 'FR' });
expect(setConfirmAction).toHaveBeenLastCalledWith({ type: 'mark', code: 'FR' });
expect(closeDialogs).not.toHaveBeenCalled();
const updater = () => null;
set(updater);
expect(setConfirmAction).toHaveBeenLastCalledWith(updater);
expect(closeDialogs).not.toHaveBeenCalled();
set(null);
expect(setConfirmAction).toHaveBeenLastCalledWith(null);
expect(closeDialogs).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWB-092: the detail names the country with its trip and place counts', () => {
const data = buildAtlasData();
render(
<GlobeCountryDialogs
s={viewState({ data, detail: detailOf({ places: [], trips: [], manually_marked: false }) })}
onOpenTrip={vi.fn()}
/>
);
expect(screen.getByRole('heading', { name: 'name-FR' })).toBeInTheDocument();
expect(screen.getByText('2 atlas.trips[count=2], 5 atlas.places[count=5]')).toBeInTheDocument();
expect(screen.getByText('country-places')).toBeInTheDocument();
// A visited country is not marked as planned, and a country from trips cannot be unmarked.
expect(screen.queryByText('atlas.planned')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'atlas.unmark' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-093: a country not in the data has no counts in its header', () => {
render(
<GlobeCountryDialogs
s={viewState({ data: null, detail: { a2: 'JP', data: { places: [], trips: [] } } })}
onOpenTrip={vi.fn()}
/>
);
expect(screen.getByRole('heading', { name: 'name-JP' })).toBeInTheDocument();
expect(screen.queryByText(/atlas\.trips/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-094: a planned country carries the planned pill', () => {
const data = buildAtlasData({
countries: [{ code: 'FR', tripCount: 1, placeCount: 0, firstVisit: null, lastVisit: null, status: 'planned' }],
});
render(
<GlobeCountryDialogs s={viewState({ data, detail: detailOf({ places: [], trips: [] }) })} onOpenTrip={vi.fn()} />
);
expect(screen.getByText('atlas.planned')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-095: trips without a place in the country get a chip that opens the trip', () => {
const onOpenTrip = vi.fn();
const detail = detailOf({
places: [{ id: 1, trip_id: 10 }],
trips: [
{ id: 10, title: 'Placed trip' },
{ id: 11, title: 'Flight only' },
],
});
render(<GlobeCountryDialogs s={viewState({ detail })} onOpenTrip={onOpenTrip} />);
expect(screen.queryByRole('button', { name: /Placed trip/ })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Flight only/ }));
expect(onOpenTrip).toHaveBeenCalledWith(11);
expect(placesProps.last?.onOpenTrip).toBe(onOpenTrip);
});
it('FE-ATLAS2-VIEWB-096: the region progress shows the share visited', () => {
render(
<GlobeCountryDialogs
s={viewState({ detail: detailOf({ places: [], trips: [] }), progress: { visited: 3, total: 12 } })}
onOpenTrip={vi.fn()}
/>
);
expect(screen.getByText('atlas.regions')).toBeInTheDocument();
expect(screen.getByText('3 / 12')).toBeInTheDocument();
const fill = document.querySelector<HTMLElement>('.duration-700');
expect(fill?.style.width).toBe('25%');
});
it('FE-ATLAS2-VIEWB-097: a country without regions shows no progress', () => {
render(
<GlobeCountryDialogs
s={viewState({ detail: detailOf({ places: [], trips: [] }), progress: { visited: 0, total: 0 } })}
onOpenTrip={vi.fn()}
/>
);
expect(screen.queryByText('atlas.regions')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-098: while the detail loads it spins instead of listing places', () => {
render(<GlobeCountryDialogs s={viewState({ detail: detailOf(null) })} onOpenTrip={vi.fn()} />);
expect(screen.queryByText('country-places')).not.toBeInTheDocument();
expect(document.querySelector('.animate-spin')).not.toBeNull();
});
it('FE-ATLAS2-VIEWB-099: a hand-marked country can be unmarked, and close closes', () => {
const askUnmarkDetail = vi.fn();
const closeDialogs = vi.fn();
render(
<GlobeCountryDialogs
s={viewState({
detail: detailOf({ places: [], trips: [], manually_marked: true }),
askUnmarkDetail,
closeDialogs,
})}
onOpenTrip={vi.fn()}
/>
);
fireEvent.click(screen.getByRole('button', { name: 'atlas.unmark' }));
expect(askUnmarkDetail).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(closeDialogs).toHaveBeenCalledTimes(1);
});
});
describe('GlobeLayersDialog', () => {
it('FE-ATLAS2-VIEWB-100: the planned switch flips the planned countries', () => {
const setShowPlanned = vi.fn();
render(<GlobeLayersDialog s={viewState({ showPlanned: true, setShowPlanned })} onClose={vi.fn()} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.layers' })).toBeInTheDocument();
const sw = screen.getByRole('button', { name: 'atlas.showPlanned' });
expect(sw).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(sw);
expect(setShowPlanned).toHaveBeenCalledWith(false);
// No flights, no flights switch.
expect(screen.queryByRole('button', { name: 'atlas.globe.flights' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-101: with flights there is a flights switch', () => {
const setShowFlights = vi.fn();
render(
<GlobeLayersDialog
s={viewState({ flights: { routes: [{ id: 1 }] }, showFlights: false, setShowFlights })}
onClose={vi.fn()}
/>
);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.flights' }));
expect(setShowFlights).toHaveBeenCalledWith(true);
});
it('FE-ATLAS2-VIEWB-102: an empty flight list shows no flights switch', () => {
render(<GlobeLayersDialog s={viewState({ flights: { routes: [] } })} onClose={vi.fn()} />);
expect(screen.queryByRole('button', { name: 'atlas.globe.flights' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-103: each plugin layer gets a switch, on unless hidden, falling back to its id', () => {
const togglePluginLayer = vi.fn();
render(
<GlobeLayersDialog
s={viewState({
pluginLayers: [
{ pluginId: 'p', id: 'rain', name: 'Rain radar' },
{ pluginId: 'p', id: 'snow', name: '' },
],
hiddenPluginLayers: new Set(['p:snow']),
togglePluginLayer,
})}
onClose={vi.fn()}
/>
);
expect(screen.getByRole('button', { name: 'Rain radar' })).toHaveAttribute('aria-pressed', 'true');
const snow = screen.getByRole('button', { name: 'snow' });
expect(snow).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(snow);
expect(togglePluginLayer).toHaveBeenCalledWith('p:snow');
});
it('FE-ATLAS2-VIEWB-104: the colour modes switch the globe paint, the current one is lit, close closes', () => {
const setColorMode = vi.fn();
const onClose = vi.fn();
render(<GlobeLayersDialog s={viewState({ colorMode: 'status', setColorMode })} onClose={onClose} />);
expect(screen.getByRole('button', { name: 'atlas.globe.colorStatus' }).className).toContain('bg-surface-card');
expect(screen.getByRole('button', { name: 'atlas.globe.colorYear' }).className).not.toContain('bg-surface-card');
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.colorYear' }));
expect(setColorMode).toHaveBeenCalledWith('year');
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.colorCountry' }));
expect(setColorMode).toHaveBeenCalledWith('country');
fireEvent.click(screen.getByRole('button', { name: 'common.close' }));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,104 @@
// FE-ATLAS2-VIEWB-060 to FE-ATLAS2-VIEWB-065: the statistics tab of the Atlas hub.
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useParams } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
import { buildAtlasData } from '../../../tests/helpers/atlas';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeOverview from './AtlasGlobeOverview';
import type { AtlasGlobeState } from './useAtlasGlobe';
function TripProbe() {
const { id } = useParams();
return <div>trip page {id}</div>;
}
function mount(s: AtlasGlobeState) {
return render(
<MemoryRouter initialEntries={['/atlas']}>
<Routes>
<Route path="/atlas" element={<AtlasGlobeOverview s={s} />} />
<Route path="/trips/:id" element={<TripProbe />} />
</Routes>
</MemoryRouter>
);
}
const totals = { countries: 39, continents: 3, regions: 14, trips: 5, firstYear: 2020, perYear: new Map() };
describe('AtlasGlobeOverview', () => {
it('FE-ATLAS2-VIEWB-060: the headline gives the countries and their share of the world, with the planned ones', () => {
const data = buildAtlasData({
stats: {
totalTrips: 3,
totalPlaces: 10,
totalCountries: 39,
totalDays: 14,
totalCities: 3,
totalCountriesPlanned: 2,
totalCountriesIdea: 1,
},
});
mount(viewState({ data, totals }));
expect(screen.getByText('39')).toBeInTheDocument();
expect(screen.getByText('atlas.countries[count=39]')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.worldShare[share=20]')).toBeInTheDocument();
expect(screen.getByText(/\+3/)).toHaveTextContent('+3 atlas.planned');
});
it('FE-ATLAS2-VIEWB-061: with nothing planned and no data the headline leaves the planned count out', () => {
mount(viewState({ data: null, totals: { ...totals, countries: 0 } }));
expect(screen.getByText('atlas.globe.worldShare[share=0]')).toBeInTheDocument();
expect(screen.queryByText(/atlas\.planned/)).not.toBeInTheDocument();
// The figures still show, all zero.
expect(screen.getByText('atlas.trips[count=0]')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-062: the continents chart scales bars to the largest and leaves Antarctica out until visited', () => {
const data = buildAtlasData({ continents: { Europe: 4, Asia: 2 } });
const { container } = mount(viewState({ data, totals }));
expect(screen.getByText('3 / 6')).toBeInTheDocument();
expect(screen.queryByText('atlas.antarctica')).not.toBeInTheDocument();
const europe = screen.getByTitle('atlas.europe').parentElement as HTMLElement;
expect(europe).toHaveTextContent('4');
const bars = container.querySelectorAll<HTMLElement>('.rounded-t-\\[6px\\]');
expect(bars).toHaveLength(6);
expect(bars[0].style.height).toBe('100%');
expect(bars[0].className).toContain('bg-accent');
expect(bars[1].style.height).toBe('50%');
expect(bars[2].style.height).toBe('8%');
expect(bars[2].className).toContain('bg-surface-tertiary');
});
it('FE-ATLAS2-VIEWB-063: a visited Antarctica joins the chart', () => {
const data = buildAtlasData({ continents: { Antarctica: 1 } });
mount(viewState({ data, totals }));
expect(screen.getByTitle('atlas.antarctica')).toBeInTheDocument();
expect(screen.getByText('3 / 7')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-064: with Dawarich on, its entry opens the recorded countries', () => {
const openDawarich = vi.fn();
mount(viewState({ data: buildAtlasData(), totals, dawarichEnabled: true, openDawarich }));
fireEvent.click(screen.getByRole('button', { name: /atlas.globe.dawarichCountries/ }));
expect(openDawarich).toHaveBeenCalledWith('countries');
});
it('FE-ATLAS2-VIEWB-065: the next trip counts down and opens the trip', () => {
// The server sends the days left beside the trip, which the shared type does not list.
const nextTrip = { id: 42, title: 'Lisbon', daysUntil: 9 };
const data = buildAtlasData({ nextTrip });
mount(viewState({ data, totals }));
expect(screen.getByText('9')).toBeInTheDocument();
expect(screen.getByText('atlas.daysLeft')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Lisbon/ }));
expect(screen.getByText('trip page 42')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-066: a next trip without a countdown shows only its title, and no Dawarich entry when off', () => {
const data = buildAtlasData({ nextTrip: { id: 5, title: 'Rome', countryCode: 'IT' } });
mount(viewState({ data, totals }));
expect(screen.getByText('Rome')).toBeInTheDocument();
expect(screen.queryByText('atlas.daysLeft')).not.toBeInTheDocument();
expect(screen.queryByText('atlas.globe.dawarichCountries')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,202 @@
// FE-ATLAS2-VIEWB-080 to FE-ATLAS2-VIEWB-089: the Atlas hub dialog and another traveller's page.
import { afterEach, describe, expect, it, vi } from 'vitest';
import { viewBadge, viewState } from '../../../tests/helpers/atlasGlobeViews';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { useAddonStore } from '../../store/addonStore';
import AtlasGlobePassport from './AtlasGlobePassport';
vi.mock('./AtlasGlobeOverview', () => ({ default: () => <div>tab-overview</div> }));
vi.mock('./AtlasGlobeWishlist', () => ({ default: () => <div>tab-wishlist</div> }));
vi.mock('./AtlasGlobeDawarich', () => ({ default: () => <div>tab-dawarich</div> }));
vi.mock('./AtlasGlobeTours', () => ({ default: () => <div>tab-tours</div> }));
vi.mock('./AtlasGlobeBadges', () => ({ default: () => <div>tab-badges</div> }));
vi.mock('./AtlasGlobeTravellers', () => ({ default: () => <div>tab-travellers</div> }));
type AddonList = ReturnType<typeof useAddonStore.getState>['addons'];
afterEach(() => {
useAddonStore.setState({ addons: [], loaded: false });
});
function profile(over: Record<string, unknown> = {}) {
return {
id: 9,
username: 'zoe',
avatar_url: null,
countries: 21,
continents: 4,
regions: 33,
flightKm: 48_400,
codes: ['FR', 'JP'],
badges: [],
...over,
};
}
describe('AtlasGlobePassport', () => {
it('FE-ATLAS2-VIEWB-080: closed, it renders nothing', () => {
const { container } = render(<AtlasGlobePassport s={viewState({ passportOpen: false })} />);
expect(container).toBeEmptyDOMElement();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-081: open on statistics, it shows the hub title and the overview tab', () => {
render(<AtlasGlobePassport s={viewState({ passportOpen: true, passportTab: 'overview' })} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.hub' })).toBeInTheDocument();
expect(screen.getByText('tab-overview')).toBeInTheDocument();
expect(screen.queryByText(/atlas\.globe\.collected/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-082: on badges, the header counts the earned ones', () => {
const badges = [viewBadge({ id: 'a', earned: true }), viewBadge({ id: 'b' }), viewBadge({ id: 'c', earned: true })];
render(<AtlasGlobePassport s={viewState({ passportOpen: true, passportTab: 'badges', badges })} />);
expect(screen.getByText('tab-badges')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.collected[earned=2,total=3]')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-083: each tab shows its own view', () => {
const cases: Array<[string, string]> = [
['wishlist', 'tab-wishlist'],
['dawarich', 'tab-dawarich'],
['tours', 'tab-tours'],
['travellers', 'tab-travellers'],
];
for (const [tab, text] of cases) {
const { unmount } = render(<AtlasGlobePassport s={viewState({ passportOpen: true, passportTab: tab })} />);
expect(screen.getByText(text)).toBeInTheDocument();
unmount();
}
});
it('FE-ATLAS2-VIEWB-084: the tab bar lists the enabled tabs; picking one switches and leaves a profile', () => {
useAddonStore.setState({
addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: 'm', enabled: true }] as unknown as AddonList,
loaded: true,
});
const setPassportTab = vi.fn();
const setProfileId = vi.fn();
render(
<AtlasGlobePassport
s={viewState({
passportOpen: true,
passportTab: 'overview',
dawarichEnabled: true,
compareEnabled: true,
setPassportTab,
setProfileId,
})}
/>
);
for (const label of [
'atlas.statsTab',
'atlas.globe.badges',
'atlas.bucketTab',
'dawarich.title',
'tours.mode.tours',
'atlas.globe.travellers',
]) {
expect(screen.getByRole('button', { name: label })).toBeInTheDocument();
}
expect(screen.getByRole('button', { name: 'atlas.statsTab' }).className).toContain('bg-surface-card');
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.travellers' }));
expect(setPassportTab).toHaveBeenCalledWith('travellers');
expect(setProfileId).toHaveBeenCalledWith(null);
});
it('FE-ATLAS2-VIEWB-085: the header close button closes the hub', () => {
const setPassportOpen = vi.fn();
render(<AtlasGlobePassport s={viewState({ passportOpen: true, setPassportOpen })} />);
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(setPassportOpen).toHaveBeenCalledWith(false);
});
it('FE-ATLAS2-VIEWB-086: a traveller profile shows their figures and initial, goes back and compares on the globe', () => {
const p = profile();
const setProfileId = vi.fn();
const startCompare = vi.fn();
render(
<AtlasGlobePassport
s={viewState({
passportOpen: true,
passportTab: 'travellers',
profile: p,
badges: [viewBadge(), viewBadge({ id: 'x' })],
setProfileId,
startCompare,
})}
/>
);
expect(screen.queryByText('tab-travellers')).not.toBeInTheDocument();
expect(screen.getByText('zoe')).toBeInTheDocument();
expect(screen.getByText('Z')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.collected[earned=0,total=2]')).toBeInTheDocument();
expect(screen.getByText('21')).toBeInTheDocument();
expect(screen.getByText('33')).toBeInTheDocument();
expect(screen.getByText('48k')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.noBadgesYet')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas.globe.compareOnGlobe/ }));
expect(startCompare).toHaveBeenCalledWith(p);
fireEvent.click(screen.getByRole('button', { name: 'common.back' }));
expect(setProfileId).toHaveBeenCalledWith(null);
});
it('FE-ATLAS2-VIEWB-087: a profile with a picture shows it instead of the initial', () => {
render(
<AtlasGlobePassport
s={viewState({ passportOpen: true, passportTab: 'travellers', profile: profile({ avatar_url: '/z.png' }) })}
/>
);
expect(document.querySelector('img[src="/z.png"]')).not.toBeNull();
expect(screen.queryByText('Z')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-088: their medals carry the step, the country by name and the year reached', () => {
const resolveName = (code: string) => (code === 'FR' ? 'France' : '');
const badges = [
{
id: 'c10',
motif: 'countries',
tier: 'gold',
titleKey: 'atlas.badge.c',
params: { country: 'FR' },
year: 2019,
target: 10,
},
{
id: 'u',
motif: 'first',
tier: 'bronze',
titleKey: 'atlas.badge.u',
params: { country: 'XX' },
year: null,
target: 1,
},
{ id: 'n', motif: 'moon', tier: 'silver', titleKey: 'atlas.badge.n', target: 1 },
];
render(
<AtlasGlobePassport
s={viewState({
passportOpen: true,
passportTab: 'travellers',
profile: profile({ badges }),
resolveName,
})}
/>
);
expect(screen.getByText('atlas.badge.c[country=France]')).toBeInTheDocument();
expect(screen.getByText('atlas.badge.u[country=XX]')).toBeInTheDocument();
// A badge without params still gets an (empty) params object.
expect(screen.getByText('atlas.badge.n[]')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.reachedIn[year=2019]')).toBeInTheDocument();
expect(screen.getAllByText(/atlas\.globe\.reachedIn/)).toHaveLength(1);
// The stepped medal carries its number; the ids keep each medal's gradients apart.
expect(screen.getByText('10')).toBeInTheDocument();
expect(document.querySelector('#bm-p9-c10-r')).not.toBeNull();
expect(screen.queryByText('atlas.globe.noBadgesYet')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-089: the travellers tab without a profile shows the list', () => {
render(<AtlasGlobePassport s={viewState({ passportOpen: true, passportTab: 'travellers', profile: null })} />);
expect(screen.getByText('tab-travellers')).toBeInTheDocument();
});
});
@@ -0,0 +1,146 @@
// FE-ATLAS2-VIEWA-001 to FE-ATLAS2-VIEWA-012: the search pill over the globe.
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { buildViewState } from '../../../tests/helpers/atlasViewState';
import AtlasGlobeSearch from './AtlasGlobeSearch';
const COUNTRY = { kind: 'country' as const, a2: 'FR', name: 'France' };
const REGION = { kind: 'region' as const, a2: 'DE', code: 'DE-BY', name: 'Bavaria', lon: 11, lat: 48 };
const PLACE = { name: 'Eiffel Tower', address: 'Champ de Mars, Paris', lat: 48.85, lng: 2.29 };
function input(): HTMLInputElement {
return screen.getByRole('textbox', { name: 'atlas.globe.search' }) as HTMLInputElement;
}
describe('AtlasGlobeSearch', () => {
it('FE-ATLAS2-VIEWA-001: shows the query, the slash hint and no list while nothing matches', () => {
const s = buildViewState();
render(<AtlasGlobeSearch s={s} />);
expect(input()).toHaveAttribute('placeholder', 'atlas.globe.search');
expect(screen.getByText('/')).toBeInTheDocument();
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-002: typing hands the text to setQuery and focusing loads the region search', () => {
const s = buildViewState();
render(<AtlasGlobeSearch s={s} />);
fireEvent.focus(input());
expect(s.loadRegionSearch).toHaveBeenCalledTimes(1);
fireEvent.change(input(), { target: { value: 'fra' } });
expect(s.setQuery).toHaveBeenCalledWith('fra');
});
it('FE-ATLAS2-VIEWA-003: a query shows the clear button, which empties it', () => {
const s = buildViewState({ query: 'fra' });
render(<AtlasGlobeSearch s={s} />);
expect(input().value).toBe('fra');
fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
expect(s.setQuery).toHaveBeenCalledWith('');
expect(screen.queryByText('/')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-004: lists countries and regions, a region with its country, the first one active', () => {
const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] });
render(<AtlasGlobeSearch s={s} />);
const options = screen.getAllByRole('option');
expect(options).toHaveLength(2);
expect(options[0]).toHaveTextContent('France');
expect(options[0]).toHaveAttribute('aria-selected', 'true');
expect(options[1]).toHaveTextContent('Bavaria');
expect(options[1]).toHaveTextContent('Germany');
expect(options[1]).toHaveAttribute('aria-selected', 'false');
expect(s.resolveName).toHaveBeenCalledWith('DE');
});
it('FE-ATLAS2-VIEWA-005: arrow keys move the active result and stop at both ends', () => {
const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] });
render(<AtlasGlobeSearch s={s} />);
fireEvent.keyDown(input(), { key: 'ArrowDown' });
fireEvent.keyDown(input(), { key: 'ArrowDown' });
expect(screen.getAllByRole('option')[1]).toHaveAttribute('aria-selected', 'true');
fireEvent.keyDown(input(), { key: 'ArrowUp' });
fireEvent.keyDown(input(), { key: 'ArrowUp' });
expect(screen.getAllByRole('option')[0]).toHaveAttribute('aria-selected', 'true');
});
it('FE-ATLAS2-VIEWA-006: Enter picks the active result; hovering a row makes it active', () => {
const s = buildViewState({ query: 'a', results: [COUNTRY, REGION] });
render(<AtlasGlobeSearch s={s} />);
fireEvent.mouseEnter(screen.getAllByRole('option')[1]);
expect(screen.getAllByRole('option')[1]).toHaveAttribute('aria-selected', 'true');
fireEvent.keyDown(input(), { key: 'Enter' });
expect(s.pickResult).toHaveBeenCalledWith(REGION);
});
it('FE-ATLAS2-VIEWA-007: clicking a result picks it', () => {
const s = buildViewState({ query: 'a', results: [COUNTRY] });
render(<AtlasGlobeSearch s={s} />);
fireEvent.mouseDown(screen.getByRole('option'));
fireEvent.click(screen.getByRole('option'));
expect(s.pickResult).toHaveBeenCalledWith(COUNTRY);
});
it('FE-ATLAS2-VIEWA-008: places show under their heading with address, and a click picks the place', () => {
const s = buildViewState({
query: 'eiffel',
placeHits: [PLACE, { ...PLACE, lat: 1, lng: 2, address: null, name: 'Other' }],
});
render(<AtlasGlobeSearch s={s} />);
expect(screen.getByText('atlas.searchPlaces')).toBeInTheDocument();
expect(screen.getByText('Champ de Mars, Paris')).toBeInTheDocument();
const rows = screen.getAllByRole('option');
expect(rows).toHaveLength(2);
expect(rows[1]).toHaveTextContent('Other');
fireEvent.click(rows[0]);
expect(s.pickPlace).toHaveBeenCalledWith(PLACE);
});
it('FE-ATLAS2-VIEWA-009: Enter with no region or country result picks the first place', () => {
const s = buildViewState({ query: 'eiffel', placeHits: [PLACE] });
render(<AtlasGlobeSearch s={s} />);
fireEvent.keyDown(input(), { key: 'Enter' });
expect(s.pickPlace).toHaveBeenCalledWith(PLACE);
expect(s.pickResult).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWA-010: while places load the heading shows alone; Escape clears; Enter with nothing does nothing', () => {
const s = buildViewState({ query: 'eif', placesLoading: true });
render(<AtlasGlobeSearch s={s} />);
expect(screen.getByRole('listbox')).toHaveTextContent('atlas.searchPlaces');
fireEvent.keyDown(input(), { key: 'Enter' });
expect(s.pickPlace).not.toHaveBeenCalled();
expect(s.pickResult).not.toHaveBeenCalled();
fireEvent.keyDown(input(), { key: 'Escape' });
expect(s.setQuery).toHaveBeenCalledWith('');
});
it('FE-ATLAS2-VIEWA-011: "/" outside a field focuses the search, inside a field it does not', () => {
const s = buildViewState();
const { unmount } = render(
<>
<textarea aria-label="notes" />
<AtlasGlobeSearch s={s} />
</>
);
fireEvent.keyDown(window, { key: '/' });
expect(document.activeElement).toBe(input());
const notes = screen.getByRole('textbox', { name: 'notes' });
notes.focus();
fireEvent.keyDown(window, { key: '/' });
expect(document.activeElement).toBe(notes);
fireEvent.keyDown(window, { key: 'a' });
expect(document.activeElement).toBe(notes);
unmount();
});
it('FE-ATLAS2-VIEWA-012: a focus signal from outside focuses the field and a custom class is used', () => {
const s = buildViewState();
const { rerender, container } = render(<AtlasGlobeSearch s={s} className="phone-pos" focusSignal={0} />);
expect(container.firstElementChild).toHaveClass('phone-pos');
expect(document.activeElement).not.toBe(input());
rerender(<AtlasGlobeSearch s={s} className="phone-pos" focusSignal={1} />);
expect(document.activeElement).toBe(input());
});
});
@@ -0,0 +1,59 @@
// FE-ATLAS2-VIEWB-030 to FE-ATLAS2-VIEWB-035: what the globe shows while it is not ready.
import { fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeStatus from './AtlasGlobeStatus';
afterEach(() => {
vi.unstubAllGlobals();
});
describe('AtlasGlobeStatus', () => {
it('FE-ATLAS2-VIEWB-030: a load failure says so, quotes the reason and retries the load', () => {
const retryLoad = vi.fn();
render(<AtlasGlobeStatus s={viewState({ error: 'HTTP 500 on manifest', retryLoad })} />);
expect(screen.getByText('atlas.globe.loadFailed')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.loadFailedHint')).toBeInTheDocument();
expect(screen.getByText('HTTP 500 on manifest')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas.globe.retry/ }));
expect(retryLoad).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWB-031: a WebGL failure says the browser cannot draw and reloads the page', () => {
const reload = vi.fn();
vi.stubGlobal('location', { ...window.location, reload });
const retryLoad = vi.fn();
render(<AtlasGlobeStatus s={viewState({ error: 'WebGL2 not supported', retryLoad })} />);
expect(screen.getByText('atlas.globe.noWebgl')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.noWebglHint')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /atlas.globe.retry/ }));
expect(reload).toHaveBeenCalledTimes(1);
expect(retryLoad).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWB-032: a lost context and a shader error count as WebGL failures too', () => {
for (const error of ['Context lost', 'shader compile failed']) {
const { unmount } = render(<AtlasGlobeStatus s={viewState({ error })} />);
expect(screen.getByText('atlas.globe.noWebgl')).toBeInTheDocument();
unmount();
}
});
it('FE-ATLAS2-VIEWB-033: while data or map are missing it shows the spinner', () => {
const { rerender } = render(<AtlasGlobeStatus s={viewState({ data: null, manifest: {} })} />);
expect(screen.getByText('atlas.globe.loading')).toBeInTheDocument();
rerender(<AtlasGlobeStatus s={viewState({ data: {}, manifest: null })} />);
expect(screen.getByText('atlas.globe.loading')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-034: once data and map are there it shows nothing', () => {
const { container } = render(<AtlasGlobeStatus s={viewState({ data: {}, manifest: {} })} />);
expect(container).toBeEmptyDOMElement();
});
it('FE-ATLAS2-VIEWB-035: an error wins over a globe that has its data', () => {
render(<AtlasGlobeStatus s={viewState({ data: {}, manifest: {}, error: 'boom' })} />);
expect(screen.getByText('atlas.globe.loadFailed')).toBeInTheDocument();
expect(screen.queryByText('atlas.globe.loading')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,151 @@
// FE-ATLAS2-VIEWB-040 to FE-ATLAS2-VIEWB-047: the time scrubber over the years travelled.
import { act, fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeTimeline from './AtlasGlobeTimeline';
const PER_YEAR = new Map<number, number>([
[2022, 3],
[2024, 2],
[2026, 1],
]);
interface Probe {
year: number | null;
open: boolean;
}
/** The scrubber over real year state, so play and drag move what it shows. */
function Harness({
probe,
initialYear = null,
firstYear = 2022,
open = true,
}: {
probe: Probe;
initialYear?: number | null;
firstYear?: number | null;
open?: boolean;
}): React.ReactElement {
const [year, setYear] = React.useState<number | null>(initialYear);
const [timelineOpen, setTimelineOpen] = React.useState(open);
probe.year = year;
probe.open = timelineOpen;
const s = viewState({
year,
setYear,
timelineOpen,
setTimelineOpen,
totals: { countries: 6, continents: 2, regions: 0, trips: 4, firstYear, perYear: PER_YEAR },
});
return <AtlasGlobeTimeline s={s} className="pos" />;
}
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 5, 1));
});
afterEach(() => {
vi.useRealTimers();
});
describe('AtlasGlobeTimeline', () => {
it('FE-ATLAS2-VIEWB-040: closed, or with no first year, it shows nothing', () => {
const probe: Probe = { year: null, open: false };
const closed = render(<Harness probe={probe} open={false} />);
expect(closed.container).toBeEmptyDOMElement();
closed.unmount();
const noYear = render(<Harness probe={probe} firstYear={null} />);
expect(noYear.container).toBeEmptyDOMElement();
});
it('FE-ATLAS2-VIEWB-041: with no year picked it stands on this year and counts every country', () => {
const probe: Probe = { year: null, open: true };
const { container } = render(<Harness probe={probe} />);
const slider = screen.getByRole('slider', { name: 'atlas.year' });
expect(slider).toHaveAttribute('min', '2022');
expect(slider).toHaveAttribute('max', '2026');
expect((slider as HTMLInputElement).value).toBe('2026');
expect(screen.getByText('6')).toBeInTheDocument();
expect(screen.getByText('+1')).toBeInTheDocument();
expect(container.firstElementChild?.className).toContain('pos');
});
it('FE-ATLAS2-VIEWB-042: a year sums the countries up to it and shows no gain when none came that year', () => {
const probe: Probe = { year: null, open: true };
render(<Harness probe={probe} initialYear={2023} />);
expect(screen.getByText('2023')).toBeInTheDocument();
expect(screen.getByText('3')).toBeInTheDocument();
expect(screen.queryByText(/^\+/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-043: dragging the slider picks that year', () => {
const probe: Probe = { year: null, open: true };
render(<Harness probe={probe} />);
fireEvent.change(screen.getByRole('slider'), { target: { value: '2024' } });
expect(probe.year).toBe(2024);
expect(screen.getByText('5')).toBeInTheDocument();
expect(screen.getByText('+2')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-044: play from the end starts over at the first year and runs year by year to the end', () => {
const probe: Probe = { year: null, open: true };
render(<Harness probe={probe} />);
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
expect(probe.year).toBe(2022);
expect(screen.getByRole('button', { name: 'Pause' })).toBeInTheDocument();
act(() => {
vi.advanceTimersByTime(700);
});
expect(probe.year).toBe(2023);
act(() => {
vi.advanceTimersByTime(700 * 3);
});
expect(probe.year).toBe(2026);
// Reaching this year stops the film.
expect(screen.getByRole('button', { name: 'Play' })).toBeInTheDocument();
act(() => {
vi.advanceTimersByTime(700 * 3);
});
expect(probe.year).toBe(2026);
});
it('FE-ATLAS2-VIEWB-045: play from a past year carries on from it, pause holds it', () => {
const probe: Probe = { year: null, open: true };
render(<Harness probe={probe} initialYear={2023} />);
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
expect(probe.year).toBe(2023);
act(() => {
vi.advanceTimersByTime(700);
});
expect(probe.year).toBe(2024);
fireEvent.click(screen.getByRole('button', { name: 'Pause' }));
act(() => {
vi.advanceTimersByTime(700 * 4);
});
expect(probe.year).toBe(2024);
});
it('FE-ATLAS2-VIEWB-046: dragging while playing stops the film', () => {
const probe: Probe = { year: null, open: true };
render(<Harness probe={probe} initialYear={2022} />);
fireEvent.click(screen.getByRole('button', { name: 'Play' }));
fireEvent.change(screen.getByRole('slider'), { target: { value: '2023' } });
expect(screen.getByRole('button', { name: 'Play' })).toBeInTheDocument();
act(() => {
vi.advanceTimersByTime(700 * 2);
});
expect(probe.year).toBe(2023);
});
it('FE-ATLAS2-VIEWB-047: close clears the year and closes the scrubber', () => {
const probe: Probe = { year: null, open: true };
const { container } = render(<Harness probe={probe} initialYear={2024} />);
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(probe.year).toBeNull();
expect(probe.open).toBe(false);
expect(container).toBeEmptyDOMElement();
});
});
@@ -0,0 +1,195 @@
// FE-ATLAS2-VIEWB-110 to FE-ATLAS2-VIEWB-117: the tours tab of the Atlas hub.
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeTours from './AtlasGlobeTours';
interface FakeType {
type: string;
count: number;
distanceKm: { value: number | null; known: number; of: number };
}
interface FakeFigures {
hero: { value: string; unit: string };
ascent: { text: string } | null;
descent: { text: string } | null;
types: FakeType[];
maxKm: number;
uncounted: { unassigned: number; undated: number };
}
const fake = vi.hoisted(() => ({
stats: {} as Record<string, unknown>,
figures: null as FakeFigures | null,
statsActive: [] as boolean[],
uncounted: [] as Array<Record<string, unknown>>,
basis: [] as unknown[],
dialog: [] as Array<{ open: boolean; onClose: () => void }>,
}));
vi.mock('../../components/Atlas/tourActivity/useTourActivityStats', () => ({
useTourActivityStats: (active: boolean) => {
fake.statsActive.push(active);
return fake.stats;
},
}));
vi.mock('../../components/Atlas/tourActivity/tourHubFigures', () => ({
tourHubFigures: () => fake.figures,
}));
vi.mock('../../components/Atlas/tourActivity/tourActivityReading', async () => {
const { Footprints } = await import('lucide-react');
return {
useDistanceUnit: () => 'metric',
typeLabel: (type: string) => `label-${type}`,
typeIcon: () => Footprints,
distanceReading: (x: FakeType) => (x.distanceKm.value === null ? null : { text: `${x.distanceKm.value} km` }),
};
});
vi.mock('../../components/Atlas/tourActivity/tourActivityParts', () => ({
ActivityFilters: () => <div>filters</div>,
ActivityStatusLine: () => <div>status-line</div>,
BasisBadges: (props: { byBasis: unknown }) => {
fake.basis.push(props.byBasis);
return <div>basis</div>;
},
UncountedBadges: (props: Record<string, unknown>) => {
fake.uncounted.push(props);
return <div>uncounted</div>;
},
}));
vi.mock('../../components/Atlas/tourActivity/TourActivityStatsDialog', () => ({
TourActivityStatsDialog: (props: { open: boolean; onClose: () => void }) => {
fake.dialog.push(props);
return props.open ? (
<button type="button" onClick={props.onClose}>
close-list
</button>
) : null;
},
}));
vi.mock('../../components/Tours/tourParts', () => ({
InfoDot: (props: { label: string; description: string }) => <span>{`${props.label}|${props.description}`}</span>,
}));
const byBasis = { plan: 2, track: 1 };
function summary(count: number, done: unknown[] = []) {
return {
totals: { count, byBasis },
types: [],
done,
upcoming: 4,
};
}
function figures(over: Partial<FakeFigures> = {}): FakeFigures {
return {
hero: { value: '128.4', unit: 'km' },
ascent: { text: '2,300 m' },
descent: { text: '2,100 m' },
types: [],
maxKm: 100,
uncounted: { unassigned: 1, undated: 2 },
...over,
};
}
beforeEach(() => {
fake.stats = { summary: null, data: null, type: 'all' };
fake.figures = figures();
fake.statsActive = [];
fake.uncounted = [];
fake.basis = [];
fake.dialog = [];
});
describe('AtlasGlobeTours', () => {
it('FE-ATLAS2-VIEWB-110: before the first read it shows the filters and the status line, reading live', () => {
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getByText('filters')).toBeInTheDocument();
expect(screen.getByText('status-line')).toBeInTheDocument();
expect(fake.statsActive.every(Boolean)).toBe(true);
expect(fake.statsActive.length).toBeGreaterThan(0);
});
it('FE-ATLAS2-VIEWB-111: with no tours at all it says there are none yet', () => {
fake.stats = { summary: summary(0), data: { entries: [] }, type: 'all' };
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getByText('tours.stats.empty')).toBeInTheDocument();
expect(screen.queryByText('status-line')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-112: with tours but none in the filter it says none match', () => {
fake.stats = { summary: summary(0), data: { entries: [{ place_id: 1 }] }, type: 'all' };
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getByText('tours.stats.none')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-113: the headline is the distance with its unit, the tiles the count and the climbs', () => {
fake.stats = { summary: summary(7), data: { entries: [] }, type: 'all' };
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getByText('128.4')).toBeInTheDocument();
expect(screen.getByText('km')).toBeInTheDocument();
expect(screen.getByText('7')).toBeInTheDocument();
expect(screen.getByText('tours.mode.tours')).toBeInTheDocument();
expect(screen.getByText('2,300 m')).toBeInTheDocument();
expect(screen.getByText('2,100 m')).toBeInTheDocument();
expect(screen.getByText('tours.stats.title|tours.stats.basisInfo')).toBeInTheDocument();
expect(fake.basis.at(-1)).toBe(byBasis);
expect(fake.uncounted.at(-1)).toEqual({ upcoming: 4, unassigned: 1, undated: 2 });
// No type bars without types, and no list button without done tours.
expect(screen.queryByText('atlas.globe.byType')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'tours.stats.showTours' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-114: a count-only headline has no unit and missing climbs read zero', () => {
fake.stats = { summary: summary(3), data: null, type: 'all' };
fake.figures = figures({ hero: { value: '3', unit: '' }, ascent: null, descent: null });
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getAllByText('0')).toHaveLength(2);
expect(screen.queryByText('km')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-115: every type gets a bar scaled to the longest, at least a sliver', () => {
fake.stats = { summary: summary(5), data: null, type: 'all' };
fake.figures = figures({
maxKm: 80,
types: [
{ type: 'hiking', count: 3, distanceKm: { value: 80, known: 3, of: 3 } },
{ type: 'cycling', count: 1, distanceKm: { value: 20, known: 1, of: 1 } },
{ type: 'paddling', count: 1, distanceKm: { value: null, known: 0, of: 1 } },
],
});
const { container } = render(<AtlasGlobeTours s={viewState()} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.byType' })).toBeInTheDocument();
expect(screen.getByText('label-hiking')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.tourCount[count=3]')).toBeInTheDocument();
expect(screen.getByText('80 km')).toBeInTheDocument();
expect(screen.getByText('20 km')).toBeInTheDocument();
const bars = container.querySelectorAll<HTMLElement>('.h-2 > div');
expect([...bars].map((b) => b.style.width)).toEqual(['100%', '25%', '4%']);
});
it('FE-ATLAS2-VIEWB-116: narrowed to one type it leaves the type bars out', () => {
fake.stats = { summary: summary(5), data: null, type: 'hiking' };
fake.figures = figures({ types: [{ type: 'hiking', count: 5, distanceKm: { value: 9, known: 5, of: 5 } }] });
render(<AtlasGlobeTours s={viewState()} />);
expect(screen.queryByText('atlas.globe.byType')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-117: with done tours the list opens in its dialog and closes again', () => {
fake.stats = { summary: summary(2, [{ place_id: 1 }]), data: null, type: 'all' };
render(<AtlasGlobeTours s={viewState()} />);
expect(fake.dialog.at(-1)?.open).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'tours.stats.showTours' }));
expect(fake.dialog.at(-1)?.open).toBe(true);
fireEvent.click(screen.getByRole('button', { name: 'close-list' }));
expect(fake.dialog.at(-1)?.open).toBe(false);
});
});
@@ -0,0 +1,94 @@
// FE-ATLAS2-VIEWB-050 to FE-ATLAS2-VIEWB-055: the travellers of this instance, ranked.
import { fireEvent, render, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeTravellers from './AtlasGlobeTravellers';
function person(id: number, username: string, over: Record<string, unknown> = {}) {
return {
id,
username,
avatar_url: null,
countries: 10 - id,
continents: 2,
regions: 5,
flightKm: 12_600,
codes: [],
badges: [],
...over,
};
}
describe('AtlasGlobeTravellers', () => {
it('FE-ATLAS2-VIEWB-050: it loads the people once and shows a placeholder until the ranking is there', () => {
const loadPeople = vi.fn();
render(<AtlasGlobeTravellers s={viewState({ loadPeople, ranking: null })} />);
expect(loadPeople).toHaveBeenCalledTimes(1);
expect(screen.getByText('…')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-051: alone on the instance it shows the empty state', () => {
render(<AtlasGlobeTravellers s={viewState({ ranking: [person(1, 'me')], me: { id: 1 } })} />);
expect(screen.getByText('atlas.globe.noTravellers')).toBeInTheDocument();
expect(screen.queryByRole('list')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-052: the visibility switch reflects and flips the hidden flag', () => {
const setHidden = vi.fn();
const { rerender } = render(<AtlasGlobeTravellers s={viewState({ hidden: false, setHidden, ranking: [] })} />);
const sw = screen.getByRole('button', { name: 'atlas.globe.visibleToOthers' });
expect(sw).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(sw);
expect(setHidden).toHaveBeenCalledWith(true);
rerender(<AtlasGlobeTravellers s={viewState({ hidden: true, setHidden, ranking: [] })} />);
const off = screen.getByRole('button', { name: 'atlas.globe.visibleToOthers' });
expect(off).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(off);
expect(setHidden).toHaveBeenLastCalledWith(false);
});
it('FE-ATLAS2-VIEWB-053: the ranking lists everyone with place, figures and flight thousands; your row is marked and closed', () => {
const setProfileId = vi.fn();
const ranking = [
person(1, 'anna', { avatar_url: '/a.png' }),
person(2, 'bob'),
person(3, 'carla'),
person(4, 'dave'),
];
render(<AtlasGlobeTravellers s={viewState({ ranking, me: { id: 2 }, setProfileId })} />);
expect(screen.getByRole('heading', { name: 'atlas.globe.ranking' })).toBeInTheDocument();
const items = screen.getAllByRole('listitem');
expect(items).toHaveLength(4);
const first = within(items[0]).getByRole('button');
expect(first.querySelector('img')).toHaveAttribute('src', '/a.png');
expect(within(first).getByText('1')).toHaveStyle({ color: 'var(--accent)' });
expect(within(first).getByText('9')).toBeInTheDocument();
expect(within(first).getByText('13k')).toBeInTheDocument();
fireEvent.click(first);
expect(setProfileId).toHaveBeenCalledWith(1);
const mine = within(items[1]).getByRole('button');
expect(mine).toBeDisabled();
expect(mine).toHaveTextContent('bob (atlas.globe.you)');
expect(within(mine).getByText('B')).toBeInTheDocument();
const fourth = within(items[3]).getByRole('button');
expect(within(fourth).getByText('4')).toHaveStyle({ color: 'var(--text-muted)' });
expect(within(fourth).getByText('D')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-054: the ranking count stands beside its title', () => {
render(<AtlasGlobeTravellers s={viewState({ ranking: [person(1, 'a'), person(2, 'b')] })} />);
const section = screen.getByRole('heading', { name: 'atlas.globe.ranking' }).closest('section');
expect(section).not.toBeNull();
expect(within(section as HTMLElement).getAllByText('2').length).toBeGreaterThan(0);
});
it('FE-ATLAS2-VIEWB-055: with nobody signed in no row is taken as yours', () => {
render(<AtlasGlobeTravellers s={viewState({ ranking: [person(1, 'a'), person(2, 'b')], me: null })} />);
for (const btn of screen.getAllByRole('listitem').map((li) => within(li).getByRole('button'))) {
expect(btn).toBeEnabled();
}
expect(screen.queryByText(/atlas.globe.you/)).not.toBeInTheDocument();
});
});
@@ -0,0 +1,404 @@
// FE-ATLAS2-VIEWA-120 to FE-ATLAS2-VIEWA-143: the desktop globe Atlas layout over a faked useAtlasGlobe,
// with the WebGL globe and the hub surfaces stubbed (each has its own tests).
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAtlasData } from '../../../tests/helpers/atlas';
import { buildViewState } from '../../../tests/helpers/atlasViewState';
import type { GlobeEngine } from '../../components/AtlasGlobe/GlobeEngine';
import AtlasGlobeView from './AtlasGlobeView';
import { countryColor } from './atlasModel';
import type { AtlasGlobeState } from './useAtlasGlobe';
interface GlobeProps {
dark: boolean;
fetchJson: unknown;
paint: unknown;
paintKey: unknown;
onHover: unknown;
onSelect: unknown;
onReady: unknown;
labelFor: unknown;
labelRegionsOf: unknown;
onFrame: (e: GlobeEngine) => void;
onError: (err: unknown) => void;
}
const view = vi.hoisted(() => ({
state: null as unknown,
stats: { countries: 3 } as unknown,
hookArgs: [] as Array<{ globeRef: unknown; skyRef: unknown }>,
globeProps: null as unknown,
statsProp: null as unknown,
skyLayout: vi.fn(),
pinsLayout: vi.fn(),
navigate: vi.fn(),
}));
vi.mock('./useAtlasGlobe', () => ({
useAtlasGlobe: (args: { globeRef: unknown; skyRef: unknown }) => {
view.hookArgs.push(args);
return view.state;
},
}));
vi.mock('./useGlobeStats', () => ({ useGlobeStats: () => view.stats }));
vi.mock('react-router', async (importOriginal) => ({
...(await importOriginal<typeof import('react-router')>()),
useNavigate: () => view.navigate,
}));
vi.mock('../../components/AtlasGlobe/AtlasGlobe', () => ({
default: (props: unknown) => {
view.globeProps = props;
return <div data-testid="globe" />;
},
}));
vi.mock('../../components/AtlasGlobe/GlobeSky', async () => {
const { useImperativeHandle } = await import('react');
return {
default: ({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) => {
useImperativeHandle(ref, () => ({ layout: view.skyLayout }));
return null;
},
};
});
vi.mock('../../components/AtlasGlobe/GlobePins', async () => {
const { useImperativeHandle } = await import('react');
return {
default: ({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) => {
useImperativeHandle(ref, () => ({ layout: view.pinsLayout }));
return null;
},
};
});
vi.mock('../../components/AtlasGlobe/GlobeStatsBar', () => ({
default: ({ stats }: { stats: unknown }) => {
view.statsProp = stats;
return <div data-testid="stats-bar" />;
},
}));
vi.mock('../../components/Layout/Navbar', () => ({ default: () => <nav data-testid="navbar" /> }));
vi.mock('./AtlasGlobeSearch', () => ({ default: () => <div data-testid="search" /> }));
vi.mock('./AtlasHubRail', () => ({ default: () => <div data-testid="hub-rail" /> }));
vi.mock('./AtlasGlobeTimeline', () => ({ default: () => <div data-testid="timeline" /> }));
vi.mock('./AtlasBadgeUnlock', () => ({ default: () => <div data-testid="badge-unlock" /> }));
vi.mock('./AtlasGlobePassport', () => ({ default: () => <div data-testid="passport" /> }));
vi.mock('./AtlasGlobeStatus', () => ({ default: () => <div data-testid="status" /> }));
vi.mock('./AtlasGlobeDialogs', () => ({
GlobeCountryDialogs: ({ onOpenTrip }: { onOpenTrip: (id: number) => void }) => (
<button type="button" onClick={() => onOpenTrip(42)}>
open-trip
</button>
),
GlobeLayersDialog: ({ onClose }: { onClose: () => void }) => (
<div data-testid="layers-dialog">
<button type="button" onClick={onClose}>
close-layers
</button>
</div>
),
}));
const MANIFEST = {
countries: [
{ a2: 'FR', a3: 'FRA', name: 'France' },
{ a2: 'DE', a3: 'DEU', name: 'Germany' },
],
attribution: ['Natural Earth', 'geoBoundaries'],
};
function mount(over: Record<string, unknown> = {}): AtlasGlobeState {
const s = buildViewState({ manifest: MANIFEST, ...over });
view.state = s;
render(<AtlasGlobeView />);
return s;
}
function globeProps(): GlobeProps {
return view.globeProps as GlobeProps;
}
function engine(morphing: boolean): GlobeEngine {
return { isMorphing: () => morphing } as unknown as GlobeEngine;
}
/** The hover chip: the one absolutely placed box at the pointer. */
function chip(): HTMLElement | null {
return document.querySelector<HTMLElement>('.atlas-globe .z-30.whitespace-nowrap.rounded-xl');
}
/** How jsdom writes a colour back, so a hex and its rgb() compare equal. */
function cssColor(c: string): string {
const probe = document.createElement('span');
probe.style.background = c;
return probe.style.background;
}
beforeEach(() => {
view.hookArgs = [];
view.globeProps = null;
view.skyLayout.mockClear();
view.pinsLayout.mockClear();
view.navigate.mockClear();
});
describe('AtlasGlobeView layout', () => {
it('FE-ATLAS2-VIEWA-120: hands the hook its refs and the globe the state it paints with', () => {
const s = mount();
expect(view.hookArgs[0]).toHaveProperty('globeRef');
expect(view.hookArgs[0]).toHaveProperty('skyRef');
const p = globeProps();
expect(p.dark).toBe(true);
expect(p.fetchJson).toBe(s.fetchJson);
expect(p.paint).toBe(s.paint);
expect(p.paintKey).toBe('k');
expect(p.onHover).toBe(s.onHover);
expect(p.onSelect).toBe(s.onSelect);
expect(p.onReady).toBe(s.onReady);
expect(p.labelFor).toBe(s.labelFor);
expect(p.labelRegionsOf).toBe(s.labelRegionsOf);
expect(view.statsProp).toBe(view.stats);
for (const id of [
'navbar',
'globe',
'stats-bar',
'search',
'hub-rail',
'timeline',
'badge-unlock',
'passport',
'status',
])
expect(screen.getByTestId(id)).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-121: names the map data sources', () => {
mount();
expect(screen.getByText('Natural Earth')).toBeInTheDocument();
expect(screen.getByText('geoBoundaries')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-122: no manifest yet means no attribution', () => {
mount({ manifest: null });
expect(screen.queryByText('Natural Earth')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-123: a globe error is reported as text, an Error by its message', () => {
const s = mount();
globeProps().onError(new Error('WebGL lost'));
globeProps().onError('no context');
expect(s.setError).toHaveBeenNthCalledWith(1, 'WebGL lost');
expect(s.setError).toHaveBeenNthCalledWith(2, 'no context');
});
it('FE-ATLAS2-VIEWA-124: every frame lays out sky and pins and marks the root while the globe moves', () => {
mount();
const root = document.querySelector<HTMLElement>('.atlas-globe') as HTMLElement;
const moving = engine(true);
globeProps().onFrame(moving);
expect(view.skyLayout).toHaveBeenCalledWith(moving);
expect(view.pinsLayout).toHaveBeenCalledWith(moving);
expect(root.dataset.moving).toBe('1');
globeProps().onFrame(moving);
expect(root.dataset.moving).toBe('1');
globeProps().onFrame(engine(false));
expect(root.dataset.moving).toBe('0');
expect(view.skyLayout).toHaveBeenCalledTimes(3);
});
it('FE-ATLAS2-VIEWA-125: the layers button opens and closes the layers dialog', () => {
mount();
const button = screen.getByTitle('atlas.globe.layers');
expect(button).toHaveAttribute('aria-expanded', 'false');
expect(screen.queryByTestId('layers-dialog')).not.toBeInTheDocument();
fireEvent.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByTestId('layers-dialog')).toBeInTheDocument();
fireEvent.click(screen.getByText('close-layers'));
expect(screen.queryByTestId('layers-dialog')).not.toBeInTheDocument();
fireEvent.click(button);
fireEvent.click(button);
expect(screen.queryByTestId('layers-dialog')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-126: the zoom buttons zoom in and out', () => {
const s = mount();
fireEvent.click(screen.getByRole('button', { name: '+' }));
fireEvent.click(screen.getByRole('button', { name: '-' }));
expect(s.zoomIn).toHaveBeenCalledTimes(1);
expect(s.zoomOut).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-127: opening a trip from a country dialog navigates to it', () => {
mount();
fireEvent.click(screen.getByText('open-trip'));
expect(view.navigate).toHaveBeenCalledWith('/trips/42');
});
});
describe('AtlasGlobeView hover chip', () => {
it('FE-ATLAS2-VIEWA-128: nothing hovered shows no chip', () => {
mount();
expect(chip()).toBeNull();
});
it('FE-ATLAS2-VIEWA-129: a visited country names itself, its trips, places and years, at the pointer', () => {
mount({ hover: { hit: { kind: 'country', index: 0, a2: 'FR' }, x: 120, y: 80 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('France');
expect(c).toHaveTextContent('atlas.globe.visited');
expect(c).toHaveTextContent('2 atlas.trips(count=2), 5 atlas.places(count=5)');
expect(c).toHaveTextContent('2023 → 2024');
expect(c.style.left).toBe('120px');
expect(c.style.top).toBe('80px');
expect(c.querySelector('img')).toHaveAttribute('alt', 'FR');
const dot = c.querySelector<HTMLElement>('.rounded-full') as HTMLElement;
expect(dot.style.background).toBe(cssColor(countryColor('FRA')));
});
it('FE-ATLAS2-VIEWA-130: first and last visit in one year show that year alone', () => {
const data = buildAtlasData({
countries: [
{
code: 'FR',
tripCount: 1,
placeCount: 0,
firstVisit: '2023-03-01',
lastVisit: '2023-09-01',
status: 'visited',
},
],
});
mount({ data, hover: { hit: { kind: 'country', index: 0, a2: 'FR' }, x: 0, y: 0 } });
expect(chip()).toHaveTextContent('2023');
expect(chip()).not.toHaveTextContent('→');
});
it('FE-ATLAS2-VIEWA-131: a first visit without a last one shows the first year', () => {
const data = buildAtlasData({
countries: [{ code: 'DE', tripCount: 0, placeCount: 2, firstVisit: '2021-01-01', lastVisit: null }],
});
mount({ data, hover: { hit: { kind: 'country', index: 1, a2: 'DE' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('Germany');
// No status on the row reads as visited.
expect(c).toHaveTextContent('atlas.globe.visited');
expect(c).toHaveTextContent('0 atlas.trips(count=0), 2 atlas.places(count=2)');
expect(c).toHaveTextContent('2021');
});
it('FE-ATLAS2-VIEWA-132: a planned country says planned in the planned colour; no counts mean no facts', () => {
const data = buildAtlasData({
countries: [{ code: 'FR', tripCount: 0, placeCount: 0, status: 'planned' }],
});
mount({ data, hover: { hit: { kind: 'country', index: 0, a2: 'FR' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('atlas.planned');
expect(c).not.toHaveTextContent('atlas.trips');
expect(c.querySelectorAll('.ag-muted')).toHaveLength(0);
const dot = c.querySelector<HTMLElement>('.rounded-full') as HTMLElement;
expect(dot.style.background).toBe(cssColor('#818cf8'));
});
it('FE-ATLAS2-VIEWA-133: a country not in the Atlas shows only its name', () => {
mount({ hover: { hit: { kind: 'country', index: 1, a2: 'DE' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('Germany');
expect(c).not.toHaveTextContent('atlas.globe.visited');
expect(c).not.toHaveTextContent('atlas.planned');
});
it('FE-ATLAS2-VIEWA-134: a visited country outside the manifest falls back to the accent dot', () => {
mount({ hover: { hit: { kind: 'country', index: 9, a2: 'FR' }, x: 0, y: 0 } });
const dot = (chip() as HTMLElement).querySelector<HTMLElement>('.rounded-full') as HTMLElement;
expect(dot.style.background).toBe('var(--ag-accent)');
});
it('FE-ATLAS2-VIEWA-135: water or a country without a code or name shows no chip', () => {
mount({ hover: { hit: { kind: 'country', index: 0, a2: null }, x: 0, y: 0 } });
expect(chip()).toBeNull();
});
it('FE-ATLAS2-VIEWA-136: a region names its country, its places and its status', () => {
const regions = { DE: [{ code: 'DE-BY', name: 'Bayern', placeCount: 3, status: 'planned' }] };
mount({ regions, hover: { hit: { kind: 'region', a2: 'DE', code: 'DE-BY', name: 'Bavaria' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('Bavaria');
expect(c).toHaveTextContent('atlas.planned');
expect(c).toHaveTextContent('Germany');
expect(c).toHaveTextContent('3 atlas.places(count=3)');
// Regions get no flag.
expect(c.querySelector('img')).toBeNull();
});
it('FE-ATLAS2-VIEWA-137: a region row without status is visited; one without places or row shows just its country', () => {
const regions = { DE: [{ code: 'DE-BY', name: 'Bayern', placeCount: 0 }] };
mount({ regions, hover: { hit: { kind: 'region', a2: 'DE', code: 'DE-BY', name: 'Bavaria' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('atlas.globe.visited');
expect(c).not.toHaveTextContent('atlas.places');
const dot = c.querySelector<HTMLElement>('.rounded-full') as HTMLElement;
expect(dot.style.background).toBe('var(--ag-accent)');
});
it('FE-ATLAS2-VIEWA-138: an unvisited region shows its name and country only', () => {
mount({ hover: { hit: { kind: 'region', a2: 'DE', code: 'DE-BE', name: 'Berlin' }, x: 0, y: 0 } });
const c = chip() as HTMLElement;
expect(c).toHaveTextContent('Berlin');
expect(c).toHaveTextContent('Germany');
expect(c).not.toHaveTextContent('atlas.globe.visited');
});
it('FE-ATLAS2-VIEWA-139: a region without a name shows no chip', () => {
mount({ hover: { hit: { kind: 'region', a2: 'DE', code: null, name: null }, x: 0, y: 0 } });
expect(chip()).toBeNull();
});
});
describe('AtlasGlobeView compare banner', () => {
const ALICE = { username: 'alice', codes: ['FR', 'IT'] };
const MINE = buildAtlasData({
countries: [
{ code: 'FR', tripCount: 1, placeCount: 1, status: 'visited' },
{ code: 'DE', tripCount: 1, placeCount: 1 },
{ code: 'JP', tripCount: 1, placeCount: 0, status: 'planned' },
],
});
it('FE-ATLAS2-VIEWA-140: no comparison shows no banner', () => {
mount();
expect(screen.queryByText('atlas.globe.together')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-141: comparing counts the countries both, only they and only I visited', () => {
mount({ data: MINE, compareWith: ALICE });
expect(screen.getByText('A')).toBeInTheDocument();
expect(screen.getByText('alice')).toBeInTheDocument();
const count = (label: string) => screen.getByText(label).previousElementSibling?.textContent;
expect(count('atlas.globe.together')).toBe('1');
expect(count('atlas.globe.onlyThem(name=alice)')).toBe('1');
// Planned countries are not mine to compare.
expect(count('atlas.globe.onlyYou')).toBe('1');
});
it('FE-ATLAS2-VIEWA-142: the gaps switch flips and the close button stops comparing', () => {
const s = mount({ data: MINE, compareWith: ALICE, gaps: false });
const gaps = screen.getByRole('button', { name: 'atlas.globe.gaps' });
expect(gaps).toHaveAttribute('data-on', '0');
fireEvent.click(gaps);
expect(s.setGaps).toHaveBeenCalledWith(true);
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(s.stopCompare).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWA-143: with gaps on the switch shows on and turns them off; no data counts nothing as mine', () => {
const s = mount({ data: null, compareWith: ALICE, gaps: true });
const gaps = screen.getByRole('button', { name: 'atlas.globe.gaps' });
expect(gaps).toHaveAttribute('data-on', '1');
fireEvent.click(gaps);
expect(s.setGaps).toHaveBeenCalledWith(false);
const count = (label: string) => screen.getByText(label).previousElementSibling?.textContent;
expect(count('atlas.globe.together')).toBe('0');
expect(count('atlas.globe.onlyThem(name=alice)')).toBe('2');
expect(count('atlas.globe.onlyYou')).toBe('0');
});
});
@@ -0,0 +1,257 @@
// FE-ATLAS2-VIEWB-120 to FE-ATLAS2-VIEWB-134: adding a wish in the Atlas hub.
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { viewState, type ViewBucketForm } from '../../../tests/helpers/atlasGlobeViews';
import AtlasGlobeWishAdd from './AtlasGlobeWishAdd';
import type { GlobePlaceHit } from './useGlobePlaceSearch';
const search = vi.hoisted(() => ({
hits: [] as Array<{ name: string; address: string | null; lat: number; lng: number }>,
loading: false,
asked: [] as Array<[string, string]>,
}));
vi.mock('./useGlobePlaceSearch', () => ({
useGlobePlaceSearch: (query: string, lang: string) => {
search.asked.push([query, lang]);
return { placeHits: search.hits, placesLoading: search.loading };
},
}));
const EMPTY: ViewBucketForm = { name: '', notes: '', lat: '', lng: '', target_date: '' };
interface Spies {
form: ViewBucketForm;
year: number;
month: number;
select: ReturnType<typeof vi.fn>;
add: ReturnType<typeof vi.fn>;
reset: ReturnType<typeof vi.fn>;
}
/** The card over real form state, as useAtlasBucket holds it. */
function Harness({
spies,
initial = EMPTY,
initialYear = 0,
initialMonth = 0,
}: {
spies: Spies;
initial?: ViewBucketForm;
initialYear?: number;
initialMonth?: number;
}): React.ReactElement {
const [form, setForm] = React.useState<ViewBucketForm>(initial);
const [year, setYear] = React.useState(initialYear);
const [month, setMonth] = React.useState(initialMonth);
spies.form = form;
spies.year = year;
spies.month = month;
const bucketState = {
bucketForm: form,
setBucketForm: setForm,
bucketPoiYear: year,
setBucketPoiYear: setYear,
bucketPoiMonth: month,
setBucketPoiMonth: setMonth,
handleSelectBucketPoi: (p: GlobePlaceHit) => {
spies.select(p);
setForm((f) => ({ ...f, name: p.name, lat: String(p.lat), lng: String(p.lng), address: p.address ?? undefined }));
},
handleAddBucketItem: spies.add,
resetBucketAdd: () => {
spies.reset();
setForm(EMPTY);
},
};
return <AtlasGlobeWishAdd s={viewState({ bucketState, placeLang: 'de' })} />;
}
function spiesOf(): Spies {
return { form: EMPTY, year: 0, month: 0, select: vi.fn(), add: vi.fn(async () => undefined), reset: vi.fn() };
}
const HIT = { name: 'Kyoto', address: 'Kyoto, Japan', lat: 35.0116, lng: 135.7681 };
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 10, 29));
search.hits = [];
search.loading = false;
search.asked = [];
});
afterEach(() => {
vi.useRealTimers();
});
function searchBox(): HTMLElement {
return screen.getByPlaceholderText('atlas.globe.wishSearch');
}
describe('AtlasGlobeWishAdd', () => {
it('FE-ATLAS2-VIEWB-120: it opens on the search, asks the geocoder in the place language and cannot save yet', () => {
render(<Harness spies={spiesOf()} />);
expect(screen.getByText('atlas.globe.newWish')).toBeInTheDocument();
expect(searchBox()).toHaveFocus();
expect(search.asked.at(-1)).toEqual(['', 'de']);
expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeDisabled();
// Nothing typed, no result list.
expect(screen.queryByText(/atlas\.globe\.wishJustName/)).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-121: while the geocoder looks it spins', () => {
search.loading = true;
const { container } = render(<Harness spies={spiesOf()} />);
expect(container.querySelector('.animate-spin')).not.toBeNull();
});
it('FE-ATLAS2-VIEWB-122: typed text offers itself as a plain name, which takes it and empties the search', () => {
const spies = spiesOf();
render(<Harness spies={spies} />);
fireEvent.change(searchBox(), { target: { value: ' Hokkaido ' } });
expect(search.asked.at(-1)).toEqual([' Hokkaido ', 'de']);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.wishJustName[name=Hokkaido]' }));
expect(spies.form).toMatchObject({ name: 'Hokkaido', lat: '', lng: '' });
// Picked: the name is editable and there is no place under it.
expect(screen.getByRole('textbox', { name: 'atlas.bucketNamePlaceholder' })).toHaveValue('Hokkaido');
expect(screen.getByText('atlas.globe.wishNoPlace')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeEnabled();
});
it('FE-ATLAS2-VIEWB-123: the hits list each place with its address, a click picks it', () => {
search.hits = [HIT, { name: 'Osaka', address: null, lat: 34.69, lng: 135.5 }];
const spies = spiesOf();
render(<Harness spies={spies} />);
expect(screen.getByText('Kyoto, Japan')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Osaka/ }));
expect(spies.select).toHaveBeenCalledWith({ name: 'Osaka', address: null, lat: 34.69, lng: 135.5 });
// A place without an address shows its coordinates.
expect(screen.getByText('34.690, 135.500')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-124: Enter picks the first hit', () => {
search.hits = [HIT];
const spies = spiesOf();
render(<Harness spies={spies} />);
fireEvent.change(searchBox(), { target: { value: 'Kyo' } });
fireEvent.keyDown(searchBox(), { key: 'Enter' });
expect(spies.select).toHaveBeenCalledWith(HIT);
expect(screen.getByText('Kyoto, Japan')).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-125: Enter without hits takes the text as a name; other keys and an empty box do nothing', () => {
const spies = spiesOf();
render(<Harness spies={spies} />);
fireEvent.keyDown(searchBox(), { key: 'Enter' });
expect(spies.form.name).toBe('');
fireEvent.change(searchBox(), { target: { value: 'Lofoten' } });
fireEvent.keyDown(searchBox(), { key: 'a' });
expect(spies.form.name).toBe('');
fireEvent.keyDown(searchBox(), { key: 'Enter' });
expect(spies.form.name).toBe('Lofoten');
expect(spies.select).not.toHaveBeenCalled();
});
it('FE-ATLAS2-VIEWB-126: a picked place can be renamed and changed back to the search, the note survives', () => {
const spies = spiesOf();
render(
<Harness
spies={spies}
initial={{ ...EMPTY, name: 'Kyoto', lat: '35', lng: '135', address: 'Kyoto, Japan', notes: 'temples' }}
/>
);
fireEvent.change(screen.getByRole('textbox', { name: 'atlas.bucketNamePlaceholder' }), {
target: { value: 'Kyoto old town' },
});
expect(spies.form.name).toBe('Kyoto old town');
expect(spies.form.address).toBe('Kyoto, Japan');
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.change' }));
expect(spies.form).toEqual({ ...EMPTY, notes: 'temples', address: undefined });
expect(searchBox()).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-127: "some day" is the default when; it clears year and month', () => {
const spies = spiesOf();
render(<Harness spies={spies} initialYear={2027} initialMonth={4} />);
const someday = screen.getByRole('button', { name: 'atlas.globe.someday' });
expect(someday).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(someday);
expect(spies.year).toBe(0);
expect(spies.month).toBe(0);
expect(screen.getByRole('button', { name: 'atlas.globe.someday' })).toHaveAttribute('aria-pressed', 'true');
});
it('FE-ATLAS2-VIEWB-128: the year stepper starts from this year and goes back into past years too', () => {
const spies = spiesOf();
render(<Harness spies={spies} />);
expect(screen.getByRole('button', { name: '2026' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearLater' }));
expect(spies.year).toBe(2027);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearEarlier' }));
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearEarlier' }));
expect(spies.year).toBe(2025);
});
it('FE-ATLAS2-VIEWB-129: from "some day" the year earlier step lands a year before this one, a tap on the year picks it', () => {
const spies = spiesOf();
const first = render(<Harness spies={spies} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.yearEarlier' }));
expect(spies.year).toBe(2025);
first.unmount();
const again = spiesOf();
render(<Harness spies={again} />);
fireEvent.click(screen.getByRole('button', { name: '2026' }));
expect(again.year).toBe(2026);
});
it('FE-ATLAS2-VIEWB-130: the months are greyed out without a year and in the reader language', () => {
render(<Harness spies={spiesOf()} />);
const jan = screen.getByRole('button', { name: 'Jan' });
expect(jan.parentElement).toHaveAttribute('aria-disabled', 'true');
expect(jan.parentElement?.className).toContain('pointer-events-none');
expect(jan.parentElement?.children).toHaveLength(12);
expect(screen.getByRole('button', { name: 'Dec' })).toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-131: with a year a month can be picked and picked again to clear it', () => {
const spies = spiesOf();
render(<Harness spies={spies} initialYear={2027} />);
const apr = screen.getByRole('button', { name: 'Apr' });
expect(apr.parentElement).toHaveAttribute('aria-disabled', 'false');
fireEvent.click(apr);
expect(spies.month).toBe(4);
expect(screen.getByRole('button', { name: 'Apr' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: 'Apr' }));
expect(spies.month).toBe(0);
});
it('FE-ATLAS2-VIEWB-132: the note is written into the form', () => {
const spies = spiesOf();
render(<Harness spies={spies} />);
fireEvent.change(screen.getByPlaceholderText('atlas.bucketNotesPlaceholder'), {
target: { value: 'cherry blossom' },
});
expect(spies.form.notes).toBe('cherry blossom');
});
it('FE-ATLAS2-VIEWB-133: save adds the wish once a name is there', () => {
const spies = spiesOf();
render(<Harness spies={spies} initial={{ ...EMPTY, name: 'Kyoto' }} />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.wishSave' }));
expect(spies.add).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWB-134: both cancel buttons reset the form; a name of blanks cannot be saved', () => {
const spies = spiesOf();
render(<Harness spies={spies} initial={{ ...EMPTY, name: ' ' }} />);
expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeDisabled();
const cancels = screen.getAllByRole('button', { name: 'common.cancel' });
expect(cancels).toHaveLength(2);
fireEvent.click(cancels[0]);
fireEvent.click(screen.getAllByRole('button', { name: 'common.cancel' })[1]);
expect(spies.reset).toHaveBeenCalledTimes(2);
expect(spies.form).toEqual(EMPTY);
});
});
@@ -0,0 +1,161 @@
// FE-ATLAS2-VIEWA-040 to FE-ATLAS2-VIEWA-049: the wishlist tab of the Atlas hub.
import { fireEvent, render, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { buildBucketItem } from '../../../tests/helpers/atlas';
import { buildViewState } from '../../../tests/helpers/atlasViewState';
import AtlasGlobeWishlist from './AtlasGlobeWishlist';
import type { BucketItem } from './atlasModel';
vi.mock('./AtlasGlobeWishAdd', () => ({
default: () => <div data-testid="wish-add" />,
}));
const KYOTO = buildBucketItem({
id: 1,
name: 'Kyoto',
country_code: 'JP',
target_date: '2027-04',
notes: 'cherry blossoms',
lat: 35,
lng: 135,
});
const SOMEWHERE = buildBucketItem({ id: 2, name: 'Somewhere', country_code: null, target_date: null });
const PARIS = buildBucketItem({
id: 3,
name: 'Paris',
country_code: 'FRA',
visited_at: '2025-06-01 10:00:00',
visited_source: 'manual',
});
const GERMANY = buildBucketItem({
id: 4,
name: 'Germany',
country_code: 'DE',
visited_at: '2026-01-02 09:00:00',
visited_source: 'dawarich',
});
function stateWith(bucketList: BucketItem[], over: Record<string, unknown> = {}) {
const bucketState = {
bucketList,
showBucketAdd: false,
setShowBucketAdd: vi.fn(),
handleClearBucketVisit: vi.fn(async () => undefined),
handleDeleteBucketItem: vi.fn(async () => undefined),
...((over.bucketState as Record<string, unknown> | undefined) ?? {}),
};
const s = buildViewState({ ...over, bucketState });
return { s, b: bucketState };
}
function section(title: string): HTMLElement {
return screen.getByRole('heading', { name: title }).closest('section') as HTMLElement;
}
describe('AtlasGlobeWishlist', () => {
it('FE-ATLAS2-VIEWA-040: an empty list offers the first wish', () => {
const { s, b } = stateWith([]);
render(<AtlasGlobeWishlist s={s} />);
expect(screen.getByText('atlas.bucketEmpty')).toBeInTheDocument();
expect(screen.getByText('atlas.bucketEmptyHint')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.newWish' }));
expect(b.setShowBucketAdd).toHaveBeenCalledWith(true);
expect(screen.queryByTestId('wish-add')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-041: an empty list with the form open shows only the form', () => {
const { s } = stateWith([], { bucketState: { showBucketAdd: true } });
render(<AtlasGlobeWishlist s={s} />);
expect(screen.getByTestId('wish-add')).toBeInTheDocument();
expect(screen.queryByText('atlas.bucketEmpty')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-042: the headline counts wishes, reached ones, countries and the next dated wish', () => {
const { s } = stateWith([KYOTO, SOMEWHERE, PARIS, GERMANY]);
render(<AtlasGlobeWishlist s={s} />);
expect(screen.getByText('4')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.wishes(count=4)')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.wishesReached(done=2,count=4)')).toBeInTheDocument();
expect(screen.getByText('atlas.countries(count=3)')).toBeInTheDocument();
expect(screen.getByText('atlas.globe.nextWish')).toBeInTheDocument();
expect(screen.getAllByText(/Apr 2027/).length).toBeGreaterThanOrEqual(2);
});
it('FE-ATLAS2-VIEWA-043: open wishes come soonest first with country, notes and a way to the globe', () => {
const { s } = stateWith([SOMEWHERE, KYOTO, PARIS]);
render(<AtlasGlobeWishlist s={s} />);
const open = section('atlas.globe.wishesOpen');
const rows = within(open).getAllByRole('listitem');
expect(rows).toHaveLength(2);
expect(rows[0]).toHaveTextContent('Kyoto');
expect(rows[0]).toHaveTextContent('Japan, cherry blossoms');
expect(rows[1]).toHaveTextContent('Somewhere');
expect(within(rows[1]).queryByRole('button', { name: 'atlas.globe.showOnGlobe' })).not.toBeInTheDocument();
fireEvent.click(within(rows[0]).getByRole('button', { name: 'atlas.globe.showOnGlobe' }));
expect(s.flyToPoint).toHaveBeenCalledWith(135, 35);
// The open section carries the add action; the reached one does not then.
expect(within(open).getByRole('button', { name: 'atlas.globe.newWish' })).toBeInTheDocument();
expect(
within(section('atlas.globe.wishesDone')).queryByRole('button', { name: 'atlas.globe.newWish' })
).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-044: reached wishes are struck through, dated, and a recorded one can be undone', () => {
const { s, b } = stateWith([PARIS, GERMANY]);
render(<AtlasGlobeWishlist s={s} />);
const done = section('atlas.globe.wishesDone');
const rows = within(done).getAllByRole('listitem');
// Latest reached first.
expect(rows[0]).toHaveTextContent('Germany');
expect(rows[0]).toHaveTextContent('2026');
expect(rows[1]).toHaveTextContent('Paris');
expect(rows[1]).toHaveTextContent('France');
expect(rows[1]).toHaveTextContent('2025');
expect(within(rows[0]).getByText('Germany')).toHaveClass('line-through');
// A wish named like its country does not repeat the country underneath.
expect(rows[0].textContent?.match(/Germany/g)).toHaveLength(1);
expect(within(rows[1]).queryByRole('button', { name: 'dawarich.bucket.clearVisit' })).not.toBeInTheDocument();
fireEvent.click(within(rows[0]).getByRole('button', { name: 'dawarich.bucket.clearVisit' }));
expect(b.handleClearBucketVisit).toHaveBeenCalledWith(4);
});
it('FE-ATLAS2-VIEWA-045: with only reached wishes the reached section offers a new wish', () => {
const { s, b } = stateWith([PARIS]);
render(<AtlasGlobeWishlist s={s} />);
expect(screen.queryByRole('heading', { name: 'atlas.globe.wishesOpen' })).not.toBeInTheDocument();
fireEvent.click(within(section('atlas.globe.wishesDone')).getByRole('button', { name: 'atlas.globe.newWish' }));
expect(b.setShowBucketAdd).toHaveBeenCalledWith(true);
// No dated open wish: only the countries tile.
expect(screen.queryByText('atlas.globe.nextWish')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-046: every row can be removed', () => {
const { s, b } = stateWith([KYOTO, PARIS]);
render(<AtlasGlobeWishlist s={s} />);
const remove = screen.getAllByRole('button', { name: 'atlas.removeFromBucket' });
expect(remove).toHaveLength(2);
fireEvent.click(remove[1]);
expect(b.handleDeleteBucketItem).toHaveBeenCalledWith(3);
});
it('FE-ATLAS2-VIEWA-047: with the form open the add actions hide and the form shows above the list', () => {
const { s } = stateWith([KYOTO, PARIS], { bucketState: { showBucketAdd: true } });
render(<AtlasGlobeWishlist s={s} />);
expect(screen.getByTestId('wish-add')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'atlas.globe.newWish' })).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWA-048: with Dawarich on and wishes listed, the Dawarich entry opens its wishes question', () => {
const { s } = stateWith([KYOTO], { dawarichEnabled: true });
render(<AtlasGlobeWishlist s={s} />);
fireEvent.click(screen.getByRole('button', { name: /atlas\.globe\.dawarichWishes/ }));
expect(s.openDawarich).toHaveBeenCalledWith('wishes');
});
it('FE-ATLAS2-VIEWA-049: without wishes there is no Dawarich entry even when it is on', () => {
const { s } = stateWith([], { dawarichEnabled: true });
render(<AtlasGlobeWishlist s={s} />);
expect(screen.queryByText('atlas.globe.dawarichWishes')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,63 @@
// FE-ATLAS2-VIEWB-070 to FE-ATLAS2-VIEWB-073: the column of hub buttons on the map.
import { fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { viewState } from '../../../tests/helpers/atlasGlobeViews';
import { useAddonStore } from '../../store/addonStore';
import AtlasHubRail from './AtlasHubRail';
type AddonList = ReturnType<typeof useAddonStore.getState>['addons'];
function toursOn(enabled: boolean) {
const addons = [{ id: 'tours', name: 'Tours', type: 'trip', icon: 'mountain', enabled }] as unknown as AddonList;
useAddonStore.setState({ addons, loaded: true });
}
afterEach(() => {
useAddonStore.setState({ addons: [], loaded: false });
});
describe('AtlasHubRail', () => {
it('FE-ATLAS2-VIEWB-070: the base rail holds statistics, badges and wishlist, labelled by the hub', () => {
render(<AtlasHubRail s={viewState()} className="end-4" />);
const nav = screen.getByRole('navigation', { name: 'atlas.globe.hub' });
expect(nav.className).toContain('end-4');
const labels = screen.getAllByRole('button').map((b) => b.getAttribute('aria-label'));
expect(labels).toEqual(['atlas.statsTab', 'atlas.globe.badges', 'atlas.bucketTab']);
});
it('FE-ATLAS2-VIEWB-071: Dawarich, tours and travellers join when they are on', () => {
toursOn(true);
render(<AtlasHubRail s={viewState({ dawarichEnabled: true, compareEnabled: true })} className="" />);
const labels = screen.getAllByRole('button').map((b) => b.getAttribute('aria-label'));
expect(labels).toEqual([
'atlas.statsTab',
'atlas.globe.badges',
'atlas.bucketTab',
'dawarich.title',
'tours.mode.tours',
'atlas.globe.travellers',
]);
});
it('FE-ATLAS2-VIEWB-072: a click opens that tab, and the badges button is the one a new badge flies into', () => {
toursOn(false);
const openPassport = vi.fn();
render(<AtlasHubRail s={viewState({ openPassport })} className="" />);
expect(screen.queryByRole('button', { name: 'tours.mode.tours' })).not.toBeInTheDocument();
const badges = screen.getByRole('button', { name: 'atlas.globe.badges' });
expect(badges).toHaveAttribute('data-atlas-badges-btn', 'true');
expect(screen.getByRole('button', { name: 'atlas.statsTab' })).not.toHaveAttribute('data-atlas-badges-btn');
fireEvent.click(badges);
expect(openPassport).toHaveBeenCalledWith('badges');
});
it('FE-ATLAS2-VIEWB-073: only the open tab of an open hub is lit', () => {
const { rerender } = render(
<AtlasHubRail s={viewState({ passportOpen: true, passportTab: 'wishlist' })} className="" />
);
expect(screen.getByRole('button', { name: 'atlas.bucketTab' }).className).toContain('bg-accent');
expect(screen.getByRole('button', { name: 'atlas.statsTab' }).className).not.toContain('bg-accent');
rerender(<AtlasHubRail s={viewState({ passportOpen: false, passportTab: 'wishlist' })} className="" />);
expect(screen.getByRole('button', { name: 'atlas.bucketTab' }).className).not.toContain('bg-accent');
});
});
@@ -0,0 +1,458 @@
// FE-ATLAS2-PAINT-001 to FE-ATLAS2-PAINT-030: what the Atlas globe paints from the
// Atlas data, the comparison overlay and the region progress figures.
import { describe, expect, it } from 'vitest';
import { buildAtlasData, buildBucketItem } from '../../../tests/helpers/atlas';
import type { AtlasMeshManifest, GlobeEngine, RegionIndex } from '../../components/AtlasGlobe/GlobeEngine';
import { hexToRgb, rgbToBytes } from '../../components/AtlasGlobe/globeTheme';
import type { AtlasRegionRow } from '../../repo/atlasRepo';
import {
COMPARE_COLORS,
compareCounts,
paintGlobe,
PLUGIN_TONES,
regionProgress,
type GlobePaintInput,
} from './atlasGlobePaint';
import { countryColor, type AtlasCountry, type AtlasData, type BucketItem } from './atlasModel';
type Quad = [number, number, number, number];
interface StatusCall {
i: number;
color: Quad;
fx?: Quad;
}
type ManifestCountry = AtlasMeshManifest['countries'][number];
type Feature = RegionIndex['features'][number];
interface FakeOptions {
countries?: ManifestCountry[];
regionIndex?: Record<string, Feature[]>;
regionBase?: Record<string, number>;
regions?: AtlasMeshManifest['regions'];
/** Region layer keys the renderer reports as loaded, like "FR:r0". */
loadedRegions?: string[];
noManifest?: boolean;
}
/** A globe engine with just what the paint reads, and a renderer that records its writes. */
function fakeEngine(opts: FakeOptions = {}) {
const calls: StatusCall[] = [];
const cleared: Array<[number, number]> = [];
const loaded = new Set(opts.loadedRegions ?? []);
const renderer = {
setStatus: (i: number, color: Quad, fx?: Quad) => {
calls.push(fx === undefined ? { i, color } : { i, color, fx });
},
clearStatus: (from: number, to: number) => {
cleared.push([from, to]);
},
hasRegion: (key: string) => loaded.has(key),
};
const regionIndex = new Map<string, RegionIndex>(
Object.entries(opts.regionIndex ?? {}).map(([a2, features]) => [
a2,
{ bbox: [], counted: features.filter((f) => f.counted).length, features, files: {} },
])
);
const manifest: AtlasMeshManifest | null = opts.noManifest
? null
: {
version: 1,
lods: [],
regionLods: [],
world: {},
countries: opts.countries ?? [],
regions: opts.regions ?? {},
attribution: [],
};
const engine = {
manifest,
renderer,
regionIndex,
regionBase: new Map<string, number>(Object.entries(opts.regionBase ?? {})),
} as unknown as GlobeEngine;
const at = (i: number) => calls.find((c) => c.i === i);
return { engine, calls, cleared, at };
}
function mc(a2: string | null, a3: string): ManifestCountry {
return { a2, a3, name: a3, anchor: [0, 0], bbox: [], area: 100 };
}
function feat(over: Partial<Feature> = {}): Feature {
return { code: null, name: null, nameEn: null, anchor: null, counted: true, ...over };
}
function country(code: string, over: Partial<AtlasCountry> = {}): AtlasCountry {
return { code, tripCount: 1, placeCount: 1, firstVisit: null, lastVisit: null, status: 'visited', ...over };
}
function region(code: string, name: string, status?: AtlasRegionRow['status']): AtlasRegionRow {
return status ? { code, name, placeCount: 1, status } : { code, name, placeCount: 1 };
}
function input(over: Partial<GlobePaintInput> = {}): GlobePaintInput {
return { data: null, regions: {}, bucket: [], showPlanned: false, colorMode: 'country', year: null, ...over };
}
function data(countries: AtlasCountry[]): AtlasData {
return buildAtlasData({ countries });
}
const bytes = (hex: string) => rgbToBytes(hexToRgb(hex));
const lighten = (hex: string, f: number) => {
const [r, g, b] = hexToRgb(hex);
return rgbToBytes([r + (1 - r) * f, g + (1 - g) * f, b + (1 - b) * f]);
};
const STATUS_VISITED = '#38bdf8';
const PLANNED = '#818cf8';
const WISH = '#fbbf24';
const CLEAR: Quad = [0, 0, 0, 0];
describe('paintGlobe: countries', () => {
it('FE-ATLAS2-PAINT-001: paints nothing before the manifest has loaded', () => {
const { engine, calls } = fakeEngine({ noManifest: true });
paintGlobe(engine, input({ data: data([country('FR')]) }));
expect(calls).toEqual([]);
});
it('FE-ATLAS2-PAINT-002: fills a visited country with its own colour and reveals countries in visit order', () => {
const { engine, at } = fakeEngine({
countries: [mc('FR', 'FRA'), mc('DE', 'DEU')],
loadedRegions: ['FR:r1'],
});
paintGlobe(
engine,
input({
data: data([country('DE', { firstVisit: '2021-05-01' }), country('FR', { firstVisit: '2019-03-01' })]),
})
);
// France came first: reveal 0, and its regions are loaded.
expect(at(0)).toEqual({ i: 0, color: [...bytes(countryColor('FRA')), 235], fx: [0, 0, 255, 0] });
// Germany second of two: half way through the reveal, no regions.
expect(at(1)).toEqual({ i: 1, color: [...bytes(countryColor('DEU')), 235], fx: [0, 128, 0, 0] });
});
it('FE-ATLAS2-PAINT-003: notices regions loaded at the first region detail too', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA')], loadedRegions: ['FR:r0'] });
paintGlobe(engine, input({ data: data([country('FR')]) }));
expect(at(0)?.fx?.[2]).toBe(255);
});
it('FE-ATLAS2-PAINT-004: colours every visited country alike when colouring by status', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA'), mc('DE', 'DEU')] });
paintGlobe(engine, input({ colorMode: 'status', data: data([country('FR'), country('DE')]) }));
expect(at(0)?.color).toEqual([...bytes(STATUS_VISITED), 235]);
expect(at(1)?.color).toEqual([...bytes(STATUS_VISITED), 235]);
});
it('FE-ATLAS2-PAINT-005: runs the year colours from blue for the first year to magenta for the last', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA'), mc('DE', 'DEU'), mc('IT', 'ITA')] });
paintGlobe(
engine,
input({
colorMode: 'year',
data: data([
country('FR', { firstVisit: '2010-01-01' }),
country('DE', { firstVisit: '2020-01-01' }),
// No first visit: no year to colour by, so its country colour.
country('IT', { firstVisit: null }),
]),
})
);
expect(at(0)?.color).toEqual([80, 177, 226, 235]);
expect(at(1)?.color).toEqual([226, 80, 177, 235]);
expect(at(2)?.color).toEqual([...bytes(countryColor('ITA')), 235]);
});
it('FE-ATLAS2-PAINT-006: a single visit year takes the last colour of the scale', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA')] });
paintGlobe(engine, input({ colorMode: 'year', data: data([country('FR', { firstVisit: '2015-06-01' })]) }));
expect(at(0)?.color).toEqual([226, 80, 177, 235]);
});
it('FE-ATLAS2-PAINT-007: the time scrubber hides countries first visited after the chosen year', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA'), mc('DE', 'DEU'), mc('IT', 'ITA')] });
paintGlobe(
engine,
input({
year: 2020,
data: data([
country('FR', { firstVisit: '2019-01-01' }),
country('DE', { firstVisit: '2021-01-01' }),
country('IT', { firstVisit: null }),
]),
})
);
expect(at(0)?.color).toEqual([...bytes(countryColor('FRA')), 235]);
expect(at(1)?.color).toEqual(CLEAR);
// Without a year it cannot be placed on the scrubber, so it stays hidden too.
expect(at(2)?.color).toEqual(CLEAR);
});
it('FE-ATLAS2-PAINT-008: planned and idea countries show only with the planned switch on', () => {
const countries = [mc('FR', 'FRA'), mc('ES', 'ESP')];
const rows = data([country('FR', { status: 'planned' }), country('ES', { status: 'idea' })]);
const on = fakeEngine({ countries });
paintGlobe(on.engine, input({ showPlanned: true, data: rows }));
expect(on.at(0)?.color).toEqual([...bytes(PLANNED), 95]);
expect(on.at(1)?.color).toEqual([...bytes(PLANNED), 95]);
const off = fakeEngine({ countries });
paintGlobe(off.engine, input({ showPlanned: false, data: rows }));
expect(off.at(0)?.color).toEqual(CLEAR);
expect(off.at(1)?.color).toEqual(CLEAR);
});
it('FE-ATLAS2-PAINT-009: a plugin tint colours a country the user has no visit for', () => {
const { engine, at } = fakeEngine({ countries: [mc('FR', 'FRA'), mc('PT', 'PRT')] });
paintGlobe(
engine,
input({
data: data([country('FR')]),
pluginTint: new Map([
['PT', PLUGIN_TONES.success],
['FR', PLUGIN_TONES.danger],
]),
})
);
expect(at(1)?.color).toEqual([...bytes(PLUGIN_TONES.success), 90]);
// A visit wins over the plugin's tint.
expect(at(0)?.color).toEqual([...bytes(countryColor('FRA')), 235]);
});
it('FE-ATLAS2-PAINT-010: a wished-for country hatches, a wished-for region does not hatch its country', () => {
const { engine, at } = fakeEngine({
countries: [mc('JP', 'JPN'), mc('US', 'USA'), mc('FR', 'FRA')],
loadedRegions: ['JP:r0'],
});
const bucket: BucketItem[] = [
buildBucketItem({ id: 1, country_code: 'JP' }),
buildBucketItem({ id: 2, country_code: 'US', region_code: 'US-CA' }),
buildBucketItem({ id: 3, country_code: null }),
];
paintGlobe(engine, input({ bucket, data: data([country('FR', { firstVisit: '2020-01-01' })]) }));
expect(at(0)).toEqual({ i: 0, color: [...bytes(WISH), 0], fx: [255, 0, 255, 0] });
expect(at(1)).toEqual({ i: 1, color: CLEAR, fx: [0, 0, 0, 0] });
});
it('FE-ATLAS2-PAINT-011: a manifest country without an ISO code is left blank', () => {
const { engine, at } = fakeEngine({ countries: [mc(null, 'XNC')] });
paintGlobe(engine, input({ data: data([country('FR')]), pluginTint: new Map([['FR', '#ffffff']]) }));
expect(at(0)).toEqual({ i: 0, color: CLEAR, fx: [0, 0, 0, 0] });
});
it('FE-ATLAS2-PAINT-012: paints from no data at all without a single coloured country', () => {
const { engine, calls } = fakeEngine({ countries: [mc('FR', 'FRA'), mc('DE', 'DEU')] });
paintGlobe(engine, input({ colorMode: 'year', data: null }));
expect(calls.map((c) => c.color)).toEqual([CLEAR, CLEAR]);
});
});
describe('paintGlobe: regions', () => {
const US = mc('US', 'USA');
it('FE-ATLAS2-PAINT-013: fills visited regions a shade lighter than their country, matched by code, name or English name', () => {
const { engine, at } = fakeEngine({
countries: [US],
regionIndex: {
US: [
feat({ code: 'US-CA', name: 'California' }),
feat({ code: null, name: 'Téxas' }),
feat({ code: 'US-NY', name: 'Nouvelle-York', nameEn: 'New York' }),
feat({ code: 'US-OR', name: 'Oregon' }),
],
},
regionBase: { US: 300 },
});
paintGlobe(
engine,
input({
regions: {
US: [region('US-CA', 'California', 'visited'), region('X-1', 'Texas'), region('X-2', 'New York')],
},
})
);
const fill = [...lighten(countryColor('USA'), 0.18), 245];
expect(at(300)?.color).toEqual(fill);
expect(at(301)?.color).toEqual(fill);
expect(at(302)?.color).toEqual(fill);
expect(at(303)).toEqual({ i: 303, color: CLEAR });
});
it('FE-ATLAS2-PAINT-014: planned regions show with the switch on and hatch as a wish otherwise', () => {
const features = [feat({ code: 'US-TX', name: 'Texas' }), feat({ code: 'US-WA', name: 'Washington' })];
const regions = { US: [region('US-TX', 'Texas', 'planned')] };
const bucket = [buildBucketItem({ country_code: 'US', region_code: 'us-wa' })];
const on = fakeEngine({ countries: [US], regionIndex: { US: features }, regionBase: { US: 10 } });
paintGlobe(on.engine, input({ regions, bucket, showPlanned: true }));
expect(on.at(10)?.color).toEqual([...bytes(PLANNED), 110]);
expect(on.at(11)).toEqual({ i: 11, color: [...bytes(WISH), 0], fx: [255, 0, 0, 0] });
const off = fakeEngine({ countries: [US], regionIndex: { US: features }, regionBase: { US: 10 } });
paintGlobe(off.engine, input({ regions, bucket, showPlanned: false }));
expect(off.at(10)?.color).toEqual(CLEAR);
});
it('FE-ATLAS2-PAINT-015: regions of a country missing from the manifest fall back to the status colour', () => {
const { engine, at } = fakeEngine({
countries: [US],
regionIndex: { GL: [feat({ code: 'GL-AV', name: 'Avannaata' })] },
regionBase: { GL: 50 },
});
paintGlobe(engine, input({ regions: { GL: [region('GL-AV', 'Avannaata')] } }));
expect(at(50)?.color).toEqual([...lighten(STATUS_VISITED, 0.18), 245]);
});
it('FE-ATLAS2-PAINT-016: skips a region index that has no status block reserved yet', () => {
const { engine, calls } = fakeEngine({
countries: [US],
regionIndex: { US: [feat({ code: 'US-CA', name: 'California' })] },
});
paintGlobe(engine, input({ regions: { US: [region('US-CA', 'California')] } }));
// Only the one country write, nothing for the region.
expect(calls).toHaveLength(1);
expect(calls[0].i).toBe(0);
});
it('FE-ATLAS2-PAINT-017: a country with a region index but no region rows leaves every region blank', () => {
const { engine, at } = fakeEngine({
countries: [US],
regionIndex: { US: [feat({ code: 'US-CA' }), feat({ name: null })] },
regionBase: { US: 20 },
});
paintGlobe(engine, input());
expect(at(20)?.color).toEqual(CLEAR);
expect(at(21)?.color).toEqual(CLEAR);
});
});
describe('paintGlobe: comparison overlay', () => {
const countries = [mc('FR', 'FRA'), mc('DE', 'DEU'), mc('IT', 'ITA'), mc('ES', 'ESP'), mc(null, 'XNC')];
const mine = data([country('FR'), country('IT'), country('ES', { status: 'planned' })]);
it('FE-ATLAS2-PAINT-018: shared countries mint, theirs only hatched violet, yours only blue', () => {
const { engine, at } = fakeEngine({ countries });
paintGlobe(engine, input({ data: mine, compare: ['FR', 'DE'] }));
expect(at(0)).toEqual({ i: 0, color: [...bytes(COMPARE_COLORS.both), 240] });
expect(at(1)).toEqual({ i: 1, color: [...bytes(COMPARE_COLORS.theirs), 60], fx: [255, 0, 0, 0] });
expect(at(2)).toEqual({ i: 2, color: [...bytes(COMPARE_COLORS.mine), 150] });
// A planned country is not one of yours in the comparison.
expect(at(3)?.color).toEqual(CLEAR);
expect(at(4)?.color).toEqual(CLEAR);
});
it('FE-ATLAS2-PAINT-019: the gaps view shows only the countries neither has been to', () => {
const { engine, at } = fakeEngine({ countries });
paintGlobe(engine, input({ data: mine, compare: ['FR', 'DE'], gaps: true }));
expect(at(0)?.color).toEqual(CLEAR);
expect(at(1)?.color).toEqual(CLEAR);
expect(at(2)?.color).toEqual(CLEAR);
expect(at(3)?.color).toEqual([...bytes(WISH), 70]);
// No ISO code: not a country anyone could go to.
expect(at(4)?.color).toEqual(CLEAR);
});
it('FE-ATLAS2-PAINT-020: clears every loaded region block while comparing and ignores the region rows', () => {
const { engine, cleared, calls } = fakeEngine({
countries,
regionIndex: { FR: [feat({ code: 'FR-IDF' }), feat({ code: 'FR-PAC' })], DE: [feat({ code: 'DE-BY' })] },
regionBase: { FR: 100 },
});
paintGlobe(engine, input({ data: null, compare: [], regions: { FR: [region('FR-IDF', 'Île-de-France')] } }));
expect(cleared).toEqual([[100, 102]]);
expect(calls).toHaveLength(countries.length);
expect(calls.every((c) => c.color.every((v) => v === 0))).toBe(true);
});
});
describe('compareCounts', () => {
it('FE-ATLAS2-PAINT-021: counts shared, theirs only and yours only, each country once', () => {
expect(compareCounts(['FR', 'DE', 'IT', 'FR'], ['FR', 'ES', 'PT', 'ES'])).toEqual({
both: 1,
theirsOnly: 2,
mineOnly: 2,
});
});
it('FE-ATLAS2-PAINT-022: two empty lists share nothing', () => {
expect(compareCounts([], [])).toEqual({ both: 0, theirsOnly: 0, mineOnly: 0 });
});
it('FE-ATLAS2-PAINT-023: exposes the overlay and plugin palettes as hex colours', () => {
for (const hex of [...Object.values(COMPARE_COLORS), ...Object.values(PLUGIN_TONES)]) {
expect(hex).toMatch(/^#[0-9a-f]{6}$/);
}
expect(Object.keys(PLUGIN_TONES).sort()).toEqual(['danger', 'default', 'success', 'warn']);
});
});
describe('regionProgress', () => {
const regions: AtlasMeshManifest['regions'] = {
US: { bbox: [], counted: 3, total: 4, index: 'us.json' },
DE: { bbox: [], counted: 2, total: 2, index: 'de.json' },
};
it('FE-ATLAS2-PAINT-024: has no answer for a country without region files', () => {
const { engine } = fakeEngine({ regions });
expect(regionProgress(engine, 'FR', [region('FR-IDF', 'Île-de-France')])).toBeNull();
});
it('FE-ATLAS2-PAINT-025: has no answer before the manifest has loaded', () => {
const { engine } = fakeEngine({ noManifest: true });
expect(regionProgress(engine, 'US', [])).toBeNull();
});
it('FE-ATLAS2-PAINT-026: before the index loads it counts the visited rows, at most the counted total', () => {
const { engine } = fakeEngine({ regions });
expect(
regionProgress(engine, 'DE', [
region('DE-BY', 'Bayern'),
region('DE-BE', 'Berlin', 'visited'),
region('DE-HH', 'Hamburg', 'visited'),
region('DE-NW', 'NRW', 'planned'),
])
).toEqual({ visited: 2, total: 2 });
expect(regionProgress(engine, 'DE', [region('DE-BY', 'Bayern'), region('DE-NW', 'NRW', 'idea')])).toEqual({
visited: 1,
total: 2,
});
});
it('FE-ATLAS2-PAINT-027: with the index it counts only counted regions, matched by code, name or English name', () => {
const { engine } = fakeEngine({
regions,
regionIndex: {
US: [
feat({ code: 'US-CA', name: 'California' }),
feat({ code: null, name: 'Téxas' }),
feat({ code: 'US-NY', name: 'Nouvelle-York', nameEn: 'New York' }),
feat({ code: 'US-OR', name: 'Oregon' }),
// Not counted (a territory): never in the figure even when visited.
feat({ code: 'US-PR', name: 'Puerto Rico', counted: false }),
feat({ code: null, name: null, nameEn: null }),
],
},
});
const rows = [
region('US-CA', 'California'),
region('X-1', 'texas', 'visited'),
region('X-2', 'New York'),
region('US-OR', 'Oregon', 'planned'),
region('US-PR', 'Puerto Rico'),
];
expect(regionProgress(engine, 'US', rows, 3)).toEqual({ visited: 3, total: 3 });
});
it('FE-ATLAS2-PAINT-028: with the index and no visited rows the figure is zero of the total', () => {
const { engine } = fakeEngine({ regions, regionIndex: { US: [feat({ code: 'US-CA', name: 'California' })] } });
expect(regionProgress(engine, 'US', [region('US-CA', 'California', 'planned')])).toEqual({
visited: 0,
total: 3,
});
});
});
@@ -0,0 +1,239 @@
// FE-ATLAS2-HOOK-201 to FE-ATLAS2-HOOK-216: the small hooks over the globe state:
// the numbers bar (useGlobeStats), the hub tabs (useHubTabs) and the add-a-wish form (useWishAddForm).
import { act, renderHook } from '@testing-library/react';
import { Award, BarChart3, Mountain, Star, Trophy } from 'lucide-react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildBucketItem } from '../../../tests/helpers/atlas';
import { resetAllStores, seedInstanceAddons } from '../../../tests/helpers/store';
import DawarichMark from '../../components/AtlasGlobe/DawarichMark';
import { atlasBucketRepo } from '../../repo/atlasBucketRepo';
import type { AtlasGlobeState } from './useAtlasGlobe';
import { useGlobeStats } from './useGlobeStats';
import { useHubTabs } from './useHubTabs';
import { useWishAddForm } from './useWishAddForm';
vi.mock('../../repo/atlasBucketRepo', () => ({
atlasBucketRepo: { searchPlaces: vi.fn(), locate: vi.fn() },
}));
const t = (k: string) => k;
function badge(earned: boolean) {
return { earned };
}
function statsState(over: Record<string, unknown> = {}) {
const base = {
t,
totals: { countries: 3, continents: 2, regions: 5, trips: 4, firstYear: null as number | null },
flights: null as unknown,
setShowFlights: vi.fn(),
badges: [badge(true), badge(false), badge(true)],
openPassport: vi.fn(),
setTimelineOpen: vi.fn(),
bucket: [
buildBucketItem({ id: 1 }),
buildBucketItem({ id: 2, visited_at: '2024-01-01' }),
buildBucketItem({ id: 3 }),
],
...over,
};
return { base, state: base as unknown as AtlasGlobeState };
}
/** Calls the updater a setter was handed with `prev` and answers what it returns. */
function appliedUpdater(setter: ReturnType<typeof vi.fn>, prev: boolean): unknown {
const updater = setter.mock.lastCall?.[0] as (v: boolean) => boolean;
return updater(prev);
}
beforeEach(() => {
resetAllStores();
});
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});
describe('useGlobeStats', () => {
it('FE-ATLAS2-HOOK-201: without flights or a first year it shows countries, continents, regions, trips, badges and wishes', () => {
const { state } = statsState();
const { result } = renderHook(() => useGlobeStats(state));
expect(result.current.map((s) => [s.key, s.value, s.label])).toEqual([
['countries', 3, 'atlas.countries'],
['continents', 2, 'atlas.globe.continents'],
['regions', 5, 'atlas.regions'],
['trips', 4, 'atlas.trips'],
['badges', 2, 'atlas.globe.badges'],
['wishlist', 2, 'atlas.bucketTab'],
]);
});
it('FE-ATLAS2-HOOK-202: each number opens the passport on its tab', () => {
const { base, state } = statsState();
const { result } = renderHook(() => useGlobeStats(state));
const byKey = Object.fromEntries(result.current.map((s) => [s.key, s]));
byKey.countries.onClick?.();
byKey.continents.onClick?.();
byKey.regions.onClick?.();
byKey.trips.onClick?.();
expect(base.openPassport).toHaveBeenCalledTimes(4);
expect(base.openPassport).toHaveBeenLastCalledWith('overview');
byKey.badges.onClick?.();
expect(base.openPassport).toHaveBeenLastCalledWith('badges');
byKey.wishlist.onClick?.();
expect(base.openPassport).toHaveBeenLastCalledWith('wishlist');
});
it('FE-ATLAS2-HOOK-203: with flights the trips give way to flown kilometres, which toggle the arcs', () => {
const { base, state } = statsState({
flights: { totals: { flights: 7, km: 12_499, airports: 4, longestKm: 9000 } },
});
const { result } = renderHook(() => useGlobeStats(state));
const keys = result.current.map((s) => s.key);
expect(keys).toContain('flights');
expect(keys).not.toContain('trips');
const flights = result.current.find((s) => s.key === 'flights');
expect(flights?.value).toBe('12k');
expect(flights?.label).toBe('atlas.globe.flightKm');
flights?.onClick?.();
expect(appliedUpdater(base.setShowFlights, false)).toBe(true);
expect(appliedUpdater(base.setShowFlights, true)).toBe(false);
});
it('FE-ATLAS2-HOOK-204: flights with no flight keep the trips', () => {
const { state } = statsState({ flights: { totals: { flights: 0, km: 0, airports: 0, longestKm: 0 } } });
const { result } = renderHook(() => useGlobeStats(state));
expect(result.current.map((s) => s.key)).toContain('trips');
});
it('FE-ATLAS2-HOOK-205: a first year adds the years travelled, which toggle the timeline', () => {
const firstYear = new Date().getFullYear() - 4;
const { base, state } = statsState({
totals: { countries: 3, continents: 2, regions: 5, trips: 4, firstYear },
});
const { result } = renderHook(() => useGlobeStats(state));
const years = result.current[result.current.length - 1];
expect(years?.key).toBe('years');
expect(years?.value).toBe(5);
expect(years?.label).toBe('atlas.years');
years?.onClick?.();
expect(appliedUpdater(base.setTimelineOpen, false)).toBe(true);
});
});
describe('useHubTabs', () => {
function tabsState(dawarichEnabled: boolean, compareEnabled: boolean) {
return { t, dawarichEnabled, compareEnabled } as unknown as AtlasGlobeState;
}
it('FE-ATLAS2-HOOK-206: overview, badges and wishlist are always there, in that order', () => {
const { result } = renderHook(() => useHubTabs(tabsState(false, false)));
expect(result.current).toEqual([
{ tab: 'overview', label: 'atlas.statsTab', Icon: BarChart3 },
{ tab: 'badges', label: 'atlas.globe.badges', Icon: Award },
{ tab: 'wishlist', label: 'atlas.bucketTab', Icon: Star },
]);
});
it('FE-ATLAS2-HOOK-207: Dawarich, tours and travellers join when their switches are on', () => {
seedInstanceAddons(['tours']);
const { result } = renderHook(() => useHubTabs(tabsState(true, true)));
expect(result.current.slice(3)).toEqual([
{ tab: 'dawarich', label: 'dawarich.title', Icon: DawarichMark },
{ tab: 'tours', label: 'tours.mode.tours', Icon: Mountain },
{ tab: 'travellers', label: 'atlas.globe.travellers', Icon: Trophy },
]);
});
it('FE-ATLAS2-HOOK-208: the tours tab follows the tours addon alone', () => {
seedInstanceAddons(['tours']);
const { result } = renderHook(() => useHubTabs(tabsState(false, false)));
expect(result.current.map((e) => e.tab)).toEqual(['overview', 'badges', 'wishlist', 'tours']);
});
});
describe('useWishAddForm', () => {
const EMPTY = { name: '', notes: 'keep me', lat: '1', lng: '2', target_date: '', address: 'old' };
function formState(form = EMPTY, language = 'en') {
const setBucketForm = vi.fn();
const bucketState = { bucketForm: form, setBucketForm, bucketPoiYear: 2027, bucketPoiMonth: 3 };
const state = { bucketState, language, placeLang: 'fr' } as unknown as AtlasGlobeState;
return { state, setBucketForm, bucketState };
}
beforeEach(() => {
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue([]);
});
it('FE-ATLAS2-HOOK-209: it hands out the bucket state, the year and month and the month names', () => {
const { state, bucketState } = formState();
const { result } = renderHook(() => useWishAddForm(state));
expect(result.current.b).toBe(bucketState);
expect(result.current.year).toBe(2027);
expect(result.current.month).toBe(3);
expect(result.current.thisYear).toBe(new Date().getFullYear());
expect(result.current.months).toHaveLength(12);
expect(result.current.months[0]).toBe('Jan');
expect(result.current.months[2]).toBe('Mar');
expect(result.current.months[11]).toBe('Dec');
expect(result.current.picked).toBe(false);
expect(result.current.query).toBe('');
});
it('FE-ATLAS2-HOOK-210: the month names follow the reader language', () => {
const { state } = formState(EMPTY, 'de');
const { result } = renderHook(() => useWishAddForm(state));
expect(result.current.months[0]).not.toBe('Jan');
expect(new Set(result.current.months).size).toBe(12);
});
it('FE-ATLAS2-HOOK-211: a picked place counts once the form has a name', () => {
const { state } = formState({ ...EMPTY, name: 'Kyoto' });
const { result } = renderHook(() => useWishAddForm(state));
expect(result.current.picked).toBe(true);
});
it('FE-ATLAS2-HOOK-212: takeName takes the typed text as a plain name, dropping coordinates', () => {
const { state, setBucketForm } = formState();
const { result } = renderHook(() => useWishAddForm(state));
act(() => result.current.setQuery(' Kyoto '));
act(() => result.current.takeName());
expect(setBucketForm).toHaveBeenCalledWith({
name: 'Kyoto',
notes: 'keep me',
lat: '',
lng: '',
target_date: '',
address: undefined,
});
expect(result.current.query).toBe('');
});
it('FE-ATLAS2-HOOK-213: takeName with nothing typed does nothing', () => {
const { state, setBucketForm } = formState();
const { result } = renderHook(() => useWishAddForm(state));
act(() => result.current.setQuery(' '));
act(() => result.current.takeName());
expect(setBucketForm).not.toHaveBeenCalled();
expect(result.current.query).toBe(' ');
});
it('FE-ATLAS2-HOOK-214: the query searches places in the place language', async () => {
vi.useFakeTimers();
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue([{ name: 'Kyoto', lat: 35, lng: 135.7 }]);
const { state } = formState();
const { result } = renderHook(() => useWishAddForm(state));
act(() => result.current.setQuery('kyo'));
expect(result.current.placesLoading).toBe(true);
await act(async () => {
await vi.advanceTimersByTimeAsync(350);
});
expect(atlasBucketRepo.searchPlaces).toHaveBeenCalledWith('kyo', 'fr');
expect(result.current.placeHits).toEqual([{ name: 'Kyoto', address: null, lat: 35, lng: 135.7 }]);
expect(result.current.placesLoading).toBe(false);
});
});
+216
View File
@@ -0,0 +1,216 @@
// FE-ATLAS2-VIEWB-001 to FE-ATLAS2-VIEWB-014: the building blocks of the Atlas hub tabs.
import { fireEvent, render, screen } from '@testing-library/react';
import { Flag, MapPin, Star } from 'lucide-react';
import { describe, expect, it, vi } from 'vitest';
import {
HUB_CARD,
HubBar,
HubDawarichEntry,
HubEmpty,
HubGhost,
HubGlow,
HubHero,
HubIconButton,
HubPill,
HubPrimary,
HubRow,
HubRows,
HubSection,
HubTiles,
} from './atlasHubKit';
function bar(container: HTMLElement): HTMLElement {
const inner = container.firstElementChild?.firstElementChild;
if (!(inner instanceof HTMLElement)) throw new Error('no bar');
return inner;
}
describe('atlasHubKit', () => {
it('FE-ATLAS2-VIEWB-001: HubGlow paints the accent by default and a given colour otherwise', () => {
const { container, rerender } = render(<HubGlow />);
const glow = container.firstElementChild as HTMLElement;
expect(glow).toHaveAttribute('aria-hidden', 'true');
expect(glow.style.background).toContain('var(--accent)');
rerender(<HubGlow color="var(--warning)" />);
expect((container.firstElementChild as HTMLElement).style.background).toContain('var(--warning)');
});
it('FE-ATLAS2-VIEWB-002: HubHero shows the figure, its unit and what explains it', () => {
const { container } = render(
<HubHero value={42} unit="countries" className="extra">
<span>explained</span>
</HubHero>
);
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('countries')).toBeInTheDocument();
expect(screen.getByText('explained')).toBeInTheDocument();
expect(container.firstElementChild?.className).toContain('extra');
expect(container.firstElementChild?.className).toContain(HUB_CARD);
});
it('FE-ATLAS2-VIEWB-003: HubHero without unit or children renders only the figure', () => {
const { container } = render(<HubHero value="7" />);
expect(screen.getByText('7')).toBeInTheDocument();
// The glow and the figure row, nothing beneath.
expect(container.firstElementChild?.children).toHaveLength(2);
});
it('FE-ATLAS2-VIEWB-004: HubBar clamps its share between 0 and 100 percent', () => {
const half = render(<HubBar share={0.5} />);
expect(bar(half.container).style.width).toBe('50%');
expect(bar(half.container).className).toContain('bg-accent');
half.unmount();
const over = render(<HubBar share={3} />);
expect(bar(over.container).style.width).toBe('100%');
over.unmount();
const under = render(<HubBar share={-1} color="red" />);
expect(bar(under.container).style.width).toBe('0%');
expect(bar(under.container).className).not.toContain('bg-accent');
expect(bar(under.container).style.background).toBe('red');
});
it('FE-ATLAS2-VIEWB-005: HubTiles draws one tile per figure with its label', () => {
const { container } = render(
<HubTiles
cols="grid-cols-3"
className="wide"
tiles={[
{ Icon: Flag, value: 3, label: 'Flags' },
{ Icon: MapPin, value: 12, label: 'Pins' },
]}
/>
);
expect(screen.getByText('Flags')).toBeInTheDocument();
expect(screen.getByText('12')).toBeInTheDocument();
expect(container.firstElementChild?.className).toContain('grid-cols-3');
expect(container.firstElementChild?.className).toContain('wide');
expect(container.firstElementChild?.children).toHaveLength(2);
});
it('FE-ATLAS2-VIEWB-006: HubSection shows its title, count and action, and leaves the count out when absent', () => {
const { rerender } = render(
<HubSection title="Ranking" meta={5} action={<button type="button">Go</button>}>
<p>body</p>
</HubSection>
);
expect(screen.getByRole('heading', { name: 'Ranking' })).toBeInTheDocument();
expect(screen.getByText('5')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Go' })).toBeInTheDocument();
expect(screen.getByText('body')).toBeInTheDocument();
rerender(
<HubSection title="Ranking">
<p>body</p>
</HubSection>
);
expect(screen.queryByText('5')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-007: HubRows and HubRow build a list, a muted row is dimmed', () => {
render(
<HubRows>
<HubRow>first</HubRow>
<HubRow muted className="mine">
second
</HubRow>
</HubRows>
);
const items = screen.getAllByRole('listitem');
expect(items).toHaveLength(2);
expect(items[0].className).not.toContain('opacity-70');
expect(items[1].className).toContain('opacity-70');
expect(items[1].className).toContain('mine');
});
it('FE-ATLAS2-VIEWB-008: HubIconButton is labelled, clicks through and turns red on hover when dangerous', () => {
const onClick = vi.fn();
const { rerender } = render(
<HubIconButton label="Delete" onClick={onClick}>
x
</HubIconButton>
);
const btn = screen.getByRole('button', { name: 'Delete' });
expect(btn).toHaveAttribute('title', 'Delete');
expect(btn.className).toContain('hover:text-content');
fireEvent.click(btn);
expect(onClick).toHaveBeenCalledTimes(1);
rerender(
<HubIconButton label="Delete" onClick={onClick} danger>
x
</HubIconButton>
);
expect(screen.getByRole('button', { name: 'Delete' }).className).toContain('hover:text-danger');
});
it('FE-ATLAS2-VIEWB-009: HubPill takes a tone as its text colour', () => {
render(<HubPill tone="rgb(1, 2, 3)">Apr 2027</HubPill>);
expect(screen.getByText('Apr 2027').style.color).toBe('rgb(1, 2, 3)');
});
it('FE-ATLAS2-VIEWB-010: HubEmpty shows what is missing, the hint and the action', () => {
const { rerender } = render(
<HubEmpty Icon={Star} title="Nothing yet" hint="Add one" action={<button type="button">Add</button>} />
);
expect(screen.getByText('Nothing yet')).toBeInTheDocument();
expect(screen.getByText('Add one')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Add' })).toBeInTheDocument();
rerender(<HubEmpty Icon={Star} title="Nothing yet" />);
expect(screen.queryByText('Add one')).not.toBeInTheDocument();
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
it('FE-ATLAS2-VIEWB-011: HubDawarichEntry shows the logo, title and hint and opens on click', () => {
const onClick = vi.fn();
const { container } = render(
<HubDawarichEntry title="Dawarich" hint="Your recorded countries" onClick={onClick} />
);
expect(screen.getByText('Dawarich')).toBeInTheDocument();
expect(screen.getByText('Your recorded countries')).toBeInTheDocument();
expect(container.querySelector('img')?.getAttribute('src')).toBe('/brands/dawarich.svg');
fireEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWB-012: HubPrimary carries its icon, stays a button by default and does nothing disabled', () => {
const onClick = vi.fn();
const { container, rerender } = render(
<HubPrimary Icon={Star} onClick={onClick}>
Save
</HubPrimary>
);
const btn = screen.getByRole('button', { name: 'Save' });
expect(btn).toHaveAttribute('type', 'button');
expect(container.querySelector('svg')).not.toBeNull();
fireEvent.click(btn);
expect(onClick).toHaveBeenCalledTimes(1);
rerender(
<HubPrimary disabled onClick={onClick} type="submit">
Save
</HubPrimary>
);
const disabled = screen.getByRole('button', { name: 'Save' });
expect(disabled).toBeDisabled();
expect(disabled).toHaveAttribute('type', 'submit');
expect(container.querySelector('svg')).toBeNull();
fireEvent.click(disabled);
expect(onClick).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-VIEWB-013: HubGhost clicks through, with and without an icon', () => {
const onClick = vi.fn();
const { container, rerender } = render(<HubGhost onClick={onClick}>Change</HubGhost>);
expect(container.querySelector('svg')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Change' }));
expect(onClick).toHaveBeenCalledTimes(1);
rerender(
<HubGhost onClick={onClick} Icon={Star}>
Change
</HubGhost>
);
expect(container.querySelector('svg')).not.toBeNull();
});
it('FE-ATLAS2-VIEWB-014: HubTiles with the default columns lays out two then four', () => {
const { container } = render(<HubTiles tiles={[{ Icon: Flag, value: 1, label: 'One' }]} />);
expect(container.firstElementChild?.className).toContain('grid-cols-2 sm:grid-cols-4');
});
});
@@ -0,0 +1,241 @@
// FE-ATLAS2-PAINT-201 to FE-ATLAS2-PAINT-222: what the Atlas hub derives from its
// data for both shells (continents, figures, wishes, badges, medals).
import type { Badge } from '@trek/shared';
import { Briefcase, Building2, CalendarDays, Flame, Map as MapIcon, MapPin, Plane } from 'lucide-react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { buildAtlasData, buildBucketItem } from '../../../tests/helpers/atlas';
import {
badgeHolders,
badgeLadder,
continentCounts,
formatNum,
medalLabel,
overviewFigures,
splitWishes,
visitedOn,
whenLabeller,
wishCountry,
WORLD_COUNTRIES,
} from './atlasHubModel';
const echoT = (key: string, params?: Record<string, string | number>): string =>
params ? `${key}:${Object.values(params).join(',')}` : key;
function badge(over: Partial<Badge> = {}): Badge {
return {
id: 'countries-5',
category: 'countries',
motif: 'countries',
tier: 'bronze',
titleKey: 'badge.title',
descKey: 'badge.desc',
earned: false,
current: 0,
target: 5,
...over,
};
}
afterEach(() => {
vi.useRealTimers();
});
describe('continentCounts', () => {
it('FE-ATLAS2-PAINT-201: lists the six inhabited continents with zero before any data', () => {
expect(continentCounts(null)).toEqual([
{ name: 'Europe', key: 'atlas.europe', n: 0 },
{ name: 'Asia', key: 'atlas.asia', n: 0 },
{ name: 'North America', key: 'atlas.northAmerica', n: 0 },
{ name: 'South America', key: 'atlas.southAmerica', n: 0 },
{ name: 'Africa', key: 'atlas.africa', n: 0 },
{ name: 'Oceania', key: 'atlas.oceania', n: 0 },
]);
});
it('FE-ATLAS2-PAINT-202: takes the counts from the data and adds Antarctica once it has a country', () => {
const without = continentCounts(buildAtlasData({ continents: { Europe: 4, Asia: 2 } }));
expect(without.map((c) => c.n)).toEqual([4, 2, 0, 0, 0, 0]);
const withIce = continentCounts(buildAtlasData({ continents: { Antarctica: 1 } }));
expect(withIce).toHaveLength(7);
expect(withIce[6]).toEqual({ name: 'Antarctica', key: 'atlas.antarctica', n: 1 });
});
it('FE-ATLAS2-PAINT-203: counts the world share against the 195 sovereign states', () => {
expect(WORLD_COUNTRIES).toBe(195);
});
it('FE-ATLAS2-PAINT-204: data without any continents counts every continent as zero', () => {
expect(continentCounts(buildAtlasData({ continents: undefined })).every((c) => c.n === 0)).toBe(true);
});
});
describe('overviewFigures', () => {
it('FE-ATLAS2-PAINT-205: gives each figure its icon, value and counted label', () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 5, 15, 12));
const figures = overviewFigures(echoT, 12, buildAtlasData());
expect(figures.map((f) => f.Icon)).toEqual([MapIcon, Briefcase, MapPin, Building2, CalendarDays, Flame, Plane]);
expect(figures.map((f) => f.value)).toEqual([12, 3, 10, 3, 14, 2, 1]);
expect(figures.map((f) => f.label)).toEqual([
'atlas.regions:12',
'atlas.trips:3',
'atlas.places:10',
'atlas.cities:3',
'atlas.days:14',
'atlas.yearsInRow:2',
'atlas.tripsIn:1 2026',
]);
});
it('FE-ATLAS2-PAINT-206: shows zeros before the data has loaded and for figures an older server leaves out', () => {
expect(overviewFigures(echoT, 0, null).map((f) => f.value)).toEqual([0, 0, 0, 0, 0, 0, 0]);
const partial = buildAtlasData({
stats: { totalTrips: 2, totalPlaces: 1, totalCountries: 1, totalDays: 3 },
streak: undefined,
tripsThisYear: undefined,
});
expect(overviewFigures(echoT, 1, partial).map((f) => f.value)).toEqual([1, 2, 1, 0, 3, 0, 0]);
});
});
describe('formatNum', () => {
it('FE-ATLAS2-PAINT-207: rounds ten thousand and more to thousands', () => {
expect(formatNum(12400)).toBe('12k');
expect(formatNum(10000)).toBe('10k');
expect(formatNum(15600)).toBe('16k');
});
it('FE-ATLAS2-PAINT-208: writes smaller numbers in the reader grouping', () => {
expect(formatNum(42)).toBe('42');
expect(formatNum(9999)).toBe((9999).toLocaleString());
});
});
describe('wishCountry', () => {
it('FE-ATLAS2-PAINT-209: reads a two-letter code as the flag code, upper case', () => {
expect(wishCountry('de')).toBe('DE');
expect(wishCountry('JP')).toBe('JP');
});
it('FE-ATLAS2-PAINT-210: maps a three-letter code to its two-letter one', () => {
expect(wishCountry('DEU')).toBe('DE');
expect(wishCountry('jpn')).toBe('JP');
});
it('FE-ATLAS2-PAINT-211: has no flag for a missing or unknown code', () => {
expect(wishCountry(null)).toBeNull();
expect(wishCountry(undefined)).toBeNull();
expect(wishCountry('')).toBeNull();
expect(wishCountry('ZZZ')).toBeNull();
});
});
describe('whenLabeller', () => {
const when = whenLabeller('en');
it('FE-ATLAS2-PAINT-212: says a month with its year, a year alone as the year', () => {
expect(when('2027-04-10')).toBe('Apr 2027');
expect(when('2027-12')).toBe('Dec 2027');
expect(when('2027')).toBe('2027');
});
it('FE-ATLAS2-PAINT-213: has no label for no date or one it cannot read', () => {
expect(when(null)).toBeNull();
expect(when(undefined)).toBeNull();
expect(when('')).toBeNull();
expect(when('soon')).toBeNull();
});
it('FE-ATLAS2-PAINT-214: speaks the reader language', () => {
expect(whenLabeller('de')('2027-03')).toBe(
new Date(2027, 2).toLocaleString('de', { month: 'short', year: 'numeric' })
);
});
});
describe('visitedOn', () => {
it('FE-ATLAS2-PAINT-215: says the day a wish came true, also from a SQLite timestamp', () => {
expect(visitedOn(buildBucketItem({ visited_at: '2025-03-04 12:00:00' }), 'en')).toBe('Mar 4, 2025');
expect(visitedOn(buildBucketItem({ visited_at: '2025-03-04T12:00:00' }), 'en')).toBe('Mar 4, 2025');
});
it('FE-ATLAS2-PAINT-216: has nothing to say for an open wish', () => {
expect(visitedOn(buildBucketItem({ visited_at: null }), 'en')).toBeNull();
expect(visitedOn(buildBucketItem(), 'en')).toBeNull();
});
});
describe('splitWishes', () => {
it('FE-ATLAS2-PAINT-217: sorts open wishes soonest first, reached ones latest first, and counts their countries', () => {
const items = [
buildBucketItem({ id: 1, country_code: 'JP', target_date: null }),
buildBucketItem({ id: 2, country_code: 'JPN', target_date: '2027-05' }),
buildBucketItem({ id: 3, country_code: 'fr', target_date: '2026-12' }),
buildBucketItem({ id: 4, country_code: 'IT', visited_at: '2024-01-02 10:00:00' }),
buildBucketItem({ id: 5, country_code: null, visited_at: '2025-06-01 10:00:00' }),
buildBucketItem({ id: 6, country_code: 'ZZZ' }),
];
const split = splitWishes(items);
expect(split.open.map((i) => i.id)).toEqual([3, 2, 1, 6]);
expect(split.reached.map((i) => i.id)).toEqual([5, 4]);
// JP and JPN are one country; no code and an unknown code are none.
expect(split.countries).toBe(3);
expect(split.nextDated?.id).toBe(3);
});
it('FE-ATLAS2-PAINT-218: has no next date when no open wish carries one', () => {
const split = splitWishes([buildBucketItem({ id: 1 }), buildBucketItem({ id: 2, visited_at: '2025-01-01' })]);
expect(split.nextDated).toBeNull();
expect(splitWishes([])).toEqual({ open: [], reached: [], countries: 0, nextDated: null });
});
});
describe('badges', () => {
it('FE-ATLAS2-PAINT-219: a badge ladder holds the stages of its own series, smallest first', () => {
const b5 = badge({ id: 'c5', target: 5 });
const b25 = badge({ id: 'c25', target: 25 });
const b10 = badge({ id: 'c10', target: 10 });
const other = badge({ id: 'cont3', category: 'continents', motif: 'continents', target: 3 });
const sameCategoryOtherMotif = badge({ id: 'first', motif: 'first', target: 1 });
expect(badgeLadder([b25, other, b5, sameCategoryOtherMotif, b10], b10).map((b) => b.id)).toEqual([
'c5',
'c10',
'c25',
]);
});
it('FE-ATLAS2-PAINT-220: region badges stand alone, without a ladder', () => {
const r1 = badge({ id: 'r1', category: 'regions', motif: 'region', target: 3 });
const r2 = badge({ id: 'r2', category: 'regions', motif: 'region', target: 5 });
expect(badgeLadder([r1, r2], r1)).toEqual([]);
});
it('FE-ATLAS2-PAINT-221: counts the travellers holding a badge, the reader included', () => {
const b = badge({ id: 'c5' });
const people = [{ badges: [{ id: 'c5' }, { id: 'x' }] }, { badges: [] }, { badges: [{ id: 'c5' }] }];
expect(badgeHolders(people, b)).toEqual({ holders: 2, of: 4 });
expect(badgeHolders(people, { ...b, earned: true })).toEqual({ holders: 3, of: 4 });
expect(badgeHolders([], { ...b, earned: true })).toEqual({ holders: 1, of: 1 });
expect(badgeHolders(null, b)).toBeNull();
});
it('FE-ATLAS2-PAINT-222: puts the right number under each medal', () => {
for (const motif of [
'countries',
'continents',
'flights',
'airports',
'streak',
'burst',
'wish',
'islands',
] as const) {
expect(medalLabel({ motif, target: 25, current: 7 })).toBe('25');
}
expect(medalLabel({ motif: 'region', target: 5, current: 3 })).toBe('3/5');
expect(medalLabel({ motif: 'earth', target: 40075 * 5, current: 0 })).toBe('5×');
expect(medalLabel({ motif: 'earth', target: 40075, current: 0 })).toBeUndefined();
expect(medalLabel({ motif: 'first', target: 1, current: 1 })).toBeUndefined();
expect(medalLabel({ motif: 'moon', target: 384400, current: 0 })).toBeUndefined();
});
});
@@ -0,0 +1,275 @@
// FE-ATLAS2-DATA-170 to FE-ATLAS2-DATA-189: the Atlas bucket list - the add form
// with its place search and target month, deleting, and undoing a Dawarich tick.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildBucketItem } from '../../../tests/helpers/atlas';
import { atlasBucketRepo } from '../../repo/atlasBucketRepo';
import { atlasRepo } from '../../repo/atlasRepo';
import type { BucketItem } from './atlasModel';
import { useAtlasBucket } from './useAtlasBucket';
const toast = vi.hoisted(() => ({
success: vi.fn<(message: string) => void>(),
error: vi.fn<(message: string) => void>(),
}));
vi.mock('../../components/shared/Toast', () => ({ useToast: () => toast }));
const t = (key: string) => key;
function setup(list: BucketItem[] = []) {
const hook = renderHook(() => useAtlasBucket({ t, placeLang: 'de' }));
if (list.length) act(() => hook.result.current.setBucketList(list));
return hook;
}
type Hook = ReturnType<typeof setup>['result'];
/** Fill the add form the way the user types into it. */
function fill(result: Hook, form: Partial<ReturnType<typeof useAtlasBucket>['bucketForm']>): void {
act(() => result.current.setBucketForm((prev) => ({ ...prev, ...form })));
}
beforeEach(() => {
toast.success.mockReset();
toast.error.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('adding a wish', () => {
it('FE-ATLAS2-DATA-170: a blank name sends nothing', async () => {
const add = vi.spyOn(atlasRepo, 'addBucketItem');
const { result } = setup();
fill(result, { name: ' ' });
await act(() => result.current.handleAddBucketItem());
expect(add).not.toHaveBeenCalled();
});
it('FE-ATLAS2-DATA-171: a full form sends the trimmed fields, the target month, and resets once the wish is added', async () => {
const created = buildBucketItem({ id: 9, name: 'Azores', country_code: null, lat: 38.7, lng: -27.2 });
const add = vi.spyOn(atlasRepo, 'addBucketItem').mockResolvedValue(created);
const old = buildBucketItem({ id: 1, name: 'Kyoto' });
const { result } = setup([old]);
act(() => result.current.setShowBucketAdd(true));
act(() => result.current.setBucketSearch('azo'));
fill(result, { name: ' Azores ', notes: ' whales ', lat: '38.7', lng: '-27.2', target_date: '2020-01' });
act(() => result.current.setBucketPoiMonth(3));
act(() => result.current.setBucketPoiYear(2027));
await act(() => result.current.handleAddBucketItem());
expect(add).toHaveBeenCalledWith({
name: 'Azores',
notes: 'whales',
lat: 38.7,
lng: -27.2,
target_date: '2027-03',
});
expect(result.current.bucketList).toEqual([created, old]);
expect(result.current.bucketForm).toEqual({ name: '', notes: '', lat: '', lng: '', target_date: '' });
expect(result.current.bucketSearch).toBe('');
expect(result.current.bucketPoiMonth).toBe(0);
expect(result.current.bucketPoiYear).toBe(0);
expect(result.current.showBucketAdd).toBe(false);
});
it('FE-ATLAS2-DATA-172: a year without a month targets the year alone', async () => {
const add = vi.spyOn(atlasRepo, 'addBucketItem').mockResolvedValue(buildBucketItem({ id: 2 }));
const { result } = setup();
fill(result, { name: 'Lapland' });
act(() => result.current.setBucketPoiYear(2028));
await act(() => result.current.handleAddBucketItem());
expect(add).toHaveBeenCalledWith({ name: 'Lapland', target_date: '2028' });
});
it('FE-ATLAS2-DATA-173: without a picked year the typed target date is used; without both, none is sent', async () => {
const add = vi.spyOn(atlasRepo, 'addBucketItem').mockResolvedValue(buildBucketItem({ id: 3 }));
const { result } = setup();
fill(result, { name: 'Iceland', target_date: '2029-06' });
act(() => result.current.setBucketPoiMonth(4));
await act(() => result.current.handleAddBucketItem());
expect(add).toHaveBeenLastCalledWith({ name: 'Iceland', target_date: '2029-06' });
fill(result, { name: 'Faroe', lat: '62', lng: '' });
await act(() => result.current.handleAddBucketItem());
// Half a coordinate pair is no coordinate.
expect(add).toHaveBeenLastCalledWith({ name: 'Faroe' });
});
it('FE-ATLAS2-DATA-174: a wish already on the list is refused before sending, and the form stays filled', async () => {
const add = vi.spyOn(atlasRepo, 'addBucketItem');
const { result } = setup([buildBucketItem({ id: 1, name: 'Azores', country_code: null, lat: 38.7, lng: -27.2 })]);
fill(result, { name: 'azores', lat: '38.7', lng: '-27.2' });
await act(() => result.current.handleAddBucketItem());
expect(add).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith('atlas.bucketDuplicate');
expect(result.current.bucketForm.name).toBe('azores');
});
it('FE-ATLAS2-DATA-175: a duplicate the server finds (409) says so', async () => {
vi.spyOn(atlasRepo, 'addBucketItem').mockRejectedValue({ response: { status: 409, data: { error: 'dup' } } });
const { result } = setup();
fill(result, { name: 'Azores' });
await act(() => result.current.handleAddBucketItem());
expect(toast.error).toHaveBeenCalledWith('atlas.bucketDuplicate');
expect(result.current.bucketForm.name).toBe('Azores');
});
it('FE-ATLAS2-DATA-176: another failure shows the server text, or the common error', async () => {
const add = vi.spyOn(atlasRepo, 'addBucketItem');
const { result } = setup();
fill(result, { name: 'Azores' });
add.mockRejectedValueOnce({ response: { status: 500, data: { error: 'Server broke' } } });
await act(() => result.current.handleAddBucketItem());
add.mockRejectedValueOnce({ response: { status: 500 } });
await act(() => result.current.handleAddBucketItem());
expect(toast.error.mock.calls.map((c) => c[0])).toEqual(['Server broke', 'common.error']);
expect(result.current.bucketList).toEqual([]);
});
});
describe('deleting and undoing', () => {
it('FE-ATLAS2-DATA-177: a deleted wish leaves the list', async () => {
const del = vi.spyOn(atlasRepo, 'deleteBucketItem').mockResolvedValue(undefined);
const { result } = setup([buildBucketItem({ id: 1 }), buildBucketItem({ id: 2, name: 'Lima' })]);
await act(() => result.current.handleDeleteBucketItem(1));
expect(del).toHaveBeenCalledWith(1);
expect(result.current.bucketList.map((i) => i.id)).toEqual([2]);
});
it('FE-ATLAS2-DATA-178: a failed delete keeps the wish and says why', async () => {
vi.spyOn(atlasRepo, 'deleteBucketItem').mockRejectedValue(new Error('offline queue full'));
const { result } = setup([buildBucketItem({ id: 1 })]);
await act(() => result.current.handleDeleteBucketItem(1));
expect(result.current.bucketList).toHaveLength(1);
expect(toast.error).toHaveBeenCalledWith('offline queue full');
});
it('FE-ATLAS2-DATA-179: undoing a Dawarich tick clears the visit and keeps the wish', async () => {
const clear = vi.spyOn(atlasBucketRepo, 'clearVisit').mockResolvedValue(undefined);
const reached = buildBucketItem({ id: 1, visited_at: '2026-04-02', visited_source: 'dawarich' });
const other = buildBucketItem({ id: 2, visited_at: '2025-01-01', visited_source: 'manual' });
const { result } = setup([reached, other]);
await act(() => result.current.handleClearBucketVisit(1));
expect(clear).toHaveBeenCalledWith(1);
expect(result.current.bucketList[0]).toMatchObject({ id: 1, visited_at: null, visited_source: null });
expect(result.current.bucketList[1]).toBe(other);
});
it('FE-ATLAS2-DATA-180: a failed undo leaves the tick and says so', async () => {
vi.spyOn(atlasBucketRepo, 'clearVisit').mockRejectedValue({ response: { data: { error: 'Not yours' } } });
const reached = buildBucketItem({ id: 1, visited_at: '2026-04-02', visited_source: 'dawarich' });
const { result } = setup([reached]);
await act(() => result.current.handleClearBucketVisit(1));
expect(result.current.bucketList[0]).toBe(reached);
expect(toast.error).toHaveBeenCalledWith('Not yours');
});
});
describe('the place search', () => {
it('FE-ATLAS2-DATA-181: an empty search asks nothing', async () => {
const search = vi.spyOn(atlasBucketRepo, 'searchPlaces');
const { result } = setup();
act(() => result.current.setBucketSearch(' '));
await act(() => result.current.handleBucketPoiSearch());
expect(search).not.toHaveBeenCalled();
});
it('FE-ATLAS2-DATA-182: a search shows its hits in the place language and is busy while it runs', async () => {
let finish!: (hits: Array<{ name: string }>) => void;
const search = vi.spyOn(atlasBucketRepo, 'searchPlaces').mockReturnValue(
new Promise((resolve) => {
finish = resolve;
})
);
const { result } = setup();
act(() => result.current.setBucketSearch('azores'));
let pending!: Promise<void>;
act(() => {
pending = result.current.handleBucketPoiSearch();
});
expect(result.current.bucketSearching).toBe(true);
await act(async () => {
finish([{ name: 'Azores' }]);
await pending;
});
expect(search).toHaveBeenCalledWith('azores', 'de');
expect(result.current.bucketSearchResults).toEqual([{ name: 'Azores' }]);
expect(result.current.bucketSearching).toBe(false);
});
it('FE-ATLAS2-DATA-183: a failed search says so and stops being busy', async () => {
vi.spyOn(atlasBucketRepo, 'searchPlaces').mockRejectedValue('nope');
const { result } = setup();
act(() => result.current.setBucketSearch('azores'));
await act(() => result.current.handleBucketPoiSearch());
expect(toast.error).toHaveBeenCalledWith('common.error');
expect(result.current.bucketSearching).toBe(false);
});
it('FE-ATLAS2-DATA-184: picking a hit fills the form, keeps the notes and clears the search', () => {
const { result } = setup();
fill(result, { notes: 'go in May', target_date: '2027-05' });
act(() => result.current.setBucketSearch('azo'));
act(() => result.current.setBucketSearchResults([{ name: 'Azores' }]));
act(() => result.current.handleSelectBucketPoi({ name: 'Azores', lat: 38.7, lng: -27.2, address: 'Portugal' }));
expect(result.current.bucketForm).toEqual({
name: 'Azores',
notes: 'go in May',
lat: '38.7',
lng: '-27.2',
target_date: '',
address: 'Portugal',
});
expect(result.current.bucketSearchResults).toEqual([]);
expect(result.current.bucketSearch).toBe('');
});
it('FE-ATLAS2-DATA-185: a hit without a name takes the search text, and missing fields stay empty', () => {
const { result } = setup();
act(() => result.current.setBucketSearch('somewhere'));
act(() => result.current.handleSelectBucketPoi({ address: null }));
expect(result.current.bucketForm).toEqual({
name: 'somewhere',
notes: '',
lat: '',
lng: '',
target_date: '',
address: undefined,
});
});
it('FE-ATLAS2-DATA-186: resetting the add form empties it and closes it', () => {
const { result } = setup();
act(() => result.current.setShowBucketAdd(true));
fill(result, { name: 'X', notes: 'y' });
act(() => result.current.setBucketSearch('x'));
act(() => result.current.setBucketSearchResults([{ name: 'X' }]));
act(() => result.current.setBucketPoiMonth(2));
act(() => result.current.setBucketPoiYear(2030));
act(() => result.current.resetBucketAdd());
expect(result.current).toMatchObject({
showBucketAdd: false,
bucketForm: { name: '', notes: '', lat: '', lng: '', target_date: '' },
bucketSearch: '',
bucketSearchResults: [],
bucketPoiMonth: 0,
bucketPoiYear: 0,
});
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,164 @@
// FE-ATLAS2-HOOK-101 to FE-ATLAS2-HOOK-110: the debounced place search of the globe and locatePlace.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atlasBucketRepo, type BucketPlaceHit } from '../../repo/atlasBucketRepo';
import { locatePlace, useGlobePlaceSearch } from './useGlobePlaceSearch';
vi.mock('../../repo/atlasBucketRepo', () => ({
atlasBucketRepo: { searchPlaces: vi.fn(), locate: vi.fn() },
}));
function deferred<T>() {
let resolve: (value: T) => void = () => undefined;
const promise = new Promise<T>((res) => {
resolve = res;
});
return { promise, resolve };
}
function mount(query: string, lang = 'en') {
return renderHook(({ q, l }) => useGlobePlaceSearch(q, l), { initialProps: { q: query, l: lang } });
}
async function tick(ms: number) {
await act(async () => {
await vi.advanceTimersByTimeAsync(ms);
});
}
beforeEach(() => {
vi.useFakeTimers();
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue([]);
});
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});
describe('useGlobePlaceSearch', () => {
it('FE-ATLAS2-HOOK-101: under three characters nothing is asked and nothing loads', async () => {
const { result } = mount(' pa ');
expect(result.current).toEqual({ placeHits: [], placesLoading: false });
await tick(1000);
expect(atlasBucketRepo.searchPlaces).not.toHaveBeenCalled();
});
it('FE-ATLAS2-HOOK-102: from three characters it loads, asks after 350 ms with the trimmed query and the language', async () => {
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue([
{ name: 'Paris', address: 'France', lat: 48.8, lng: 2.3 },
]);
const { result } = mount(' par ', 'de');
expect(result.current.placesLoading).toBe(true);
await tick(349);
expect(atlasBucketRepo.searchPlaces).not.toHaveBeenCalled();
await tick(1);
expect(atlasBucketRepo.searchPlaces).toHaveBeenCalledWith('par', 'de');
expect(result.current).toEqual({
placeHits: [{ name: 'Paris', address: 'France', lat: 48.8, lng: 2.3 }],
placesLoading: false,
});
});
it('FE-ATLAS2-HOOK-103: places without coordinates are dropped, names and addresses fall back, at most five', async () => {
const places: BucketPlaceHit[] = [
{ name: 'No coords' },
{ lat: 1, lng: 1 },
{ name: 'B', address: '', lat: 2, lng: 2 },
{ name: 'C', lat: 3, lng: 3 },
{ name: 'D', lat: 4, lng: 4 },
{ name: 'E', lat: 5, lng: 5 },
{ name: 'F', lat: 6, lng: 6 },
];
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue(places);
const { result } = mount('rome');
await tick(350);
expect(result.current.placeHits).toEqual([
{ name: 'rome', address: null, lat: 1, lng: 1 },
{ name: 'B', address: null, lat: 2, lng: 2 },
{ name: 'C', address: null, lat: 3, lng: 3 },
{ name: 'D', address: null, lat: 4, lng: 4 },
{ name: 'E', address: null, lat: 5, lng: 5 },
]);
});
it('FE-ATLAS2-HOOK-104: typing on within the pause asks only once, for the last query', async () => {
const { rerender } = mount('par');
await tick(200);
rerender({ q: 'pari', l: 'en' });
await tick(200);
rerender({ q: 'paris', l: 'en' });
await tick(350);
expect(atlasBucketRepo.searchPlaces).toHaveBeenCalledTimes(1);
expect(atlasBucketRepo.searchPlaces).toHaveBeenCalledWith('paris', 'en');
});
it('FE-ATLAS2-HOOK-105: a slow answer for an older query never shows for the newer one', async () => {
const slow = deferred<BucketPlaceHit[]>();
const fast = deferred<BucketPlaceHit[]>();
vi.mocked(atlasBucketRepo.searchPlaces).mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);
const { result, rerender } = mount('lis');
await tick(350);
rerender({ q: 'lisb', l: 'en' });
await tick(350);
await act(async () => {
slow.resolve([{ name: 'Lisieux', lat: 49, lng: 0.2 }]);
await slow.promise;
});
expect(result.current).toEqual({ placeHits: [], placesLoading: true });
await act(async () => {
fast.resolve([{ name: 'Lisbon', lat: 38.7, lng: -9.1 }]);
await fast.promise;
});
expect(result.current.placeHits.map((h) => h.name)).toEqual(['Lisbon']);
expect(result.current.placesLoading).toBe(false);
});
it('FE-ATLAS2-HOOK-106: a failed lookup answers with no places and stops loading', async () => {
vi.mocked(atlasBucketRepo.searchPlaces).mockRejectedValue(new Error('geocoder down'));
const { result } = mount('oslo');
await tick(350);
expect(result.current).toEqual({ placeHits: [], placesLoading: false });
});
it('FE-ATLAS2-HOOK-107: a failure for an older query does not answer the newer one', async () => {
const old = deferred<BucketPlaceHit[]>();
vi.mocked(atlasBucketRepo.searchPlaces)
.mockReturnValueOnce(old.promise.then(() => Promise.reject(new Error('late'))))
.mockReturnValueOnce(new Promise(() => undefined));
const { result, rerender } = mount('ber');
await tick(350);
rerender({ q: 'bern', l: 'en' });
await tick(350);
await act(async () => {
old.resolve([]);
await old.promise;
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.placesLoading).toBe(true);
});
it('FE-ATLAS2-HOOK-108: clearing the query drops the shown places', async () => {
vi.mocked(atlasBucketRepo.searchPlaces).mockResolvedValue([{ name: 'Rome', lat: 41.9, lng: 12.5 }]);
const { result, rerender } = mount('rom');
await tick(350);
expect(result.current.placeHits).toHaveLength(1);
rerender({ q: '', l: 'en' });
expect(result.current).toEqual({ placeHits: [], placesLoading: false });
});
});
describe('locatePlace', () => {
it('FE-ATLAS2-HOOK-109: answers where the picked place lies', async () => {
const where = { country_code: 'FR', region_code: 'FR-IDF', region_name: 'Île-de-France' };
vi.mocked(atlasBucketRepo.locate).mockResolvedValue(where);
await expect(locatePlace({ name: 'Paris', address: null, lat: 48.8, lng: 2.3 })).resolves.toEqual(where);
expect(atlasBucketRepo.locate).toHaveBeenCalledWith(48.8, 2.3);
});
it('FE-ATLAS2-HOOK-110: a failed lookup answers null', async () => {
vi.mocked(atlasBucketRepo.locate).mockRejectedValue(new Error('offline'));
await expect(locatePlace({ name: 'Paris', address: null, lat: 48.8, lng: 2.3 })).resolves.toBeNull();
});
});
@@ -0,0 +1,162 @@
// FE-ATLAS2-REST-060 to 065: the map tabs kept alive once opened, and the other tabs' code loaded ahead.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { buildTrip, buildUser } from '../../../tests/helpers/factories';
import { makeActions } from '../../../tests/helpers/plannerActions';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { airtrailApi, authApi, healthApi, tripsApi } from '../../api/client';
import { warmPackingBags } from '../../components/Packing/usePackingBags';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAddonStore } from '../../store/addonStore';
import { useAuthStore } from '../../store/authStore';
import { useBackgroundTasksStore } from '../../store/backgroundTasksStore';
import { usePluginStore } from '../../store/pluginStore';
import { type TripStoreState, useTripStore } from '../../store/tripStore';
import { TAB_PANEL_LOADS } from './tabPanelPreload';
import { useTripPlanner } from './useTripPlanner';
const searchParams = new URLSearchParams();
vi.mock('react-router', () => ({
useParams: () => ({ id: '42' }),
useNavigate: () => vi.fn(),
useSearchParams: () => [searchParams, vi.fn()],
}));
vi.mock('./tabPanelPreload', () => ({
TAB_PANEL_LOADS: [vi.fn(async () => ({})), vi.fn(async () => Promise.reject(new Error('chunk gone')))],
}));
vi.mock('../../components/Packing/usePackingBags', async (importOriginal) => {
const real = await importOriginal<typeof import('../../components/Packing/usePackingBags')>();
return { ...real, warmPackingBags: vi.fn(async () => {}) };
});
vi.mock('../../hooks/useTripWebSocket', () => ({ useTripWebSocket: vi.fn() }));
vi.mock('../../hooks/useRouteCalculation', () => ({
useRouteCalculation: () => ({
route: null,
routeSegments: [],
routeVias: [],
routeInfo: null,
setRoute: vi.fn(),
setRouteInfo: vi.fn(),
updateRouteForDay: vi.fn(async () => {}),
}),
}));
vi.mock('../../hooks/useAirtrailConnection', () => ({
useAirtrailConnection: () => ({ airtrailEnabled: false, connected: false, available: false, loading: false }),
}));
vi.mock('../../repo/accommodationRepo', async (importOriginal) => {
const real = await importOriginal<typeof import('../../repo/accommodationRepo')>();
return { accommodationRepo: { ...real.accommodationRepo, list: vi.fn(async () => ({ accommodations: [] })) } };
});
vi.mock('../../services/photoService', () => ({
getCached: vi.fn(() => undefined),
fetchPhoto: vi.fn(),
}));
function wrapper({ children }: { children: ReactNode }) {
return <TranslationProvider>{children}</TranslationProvider>;
}
const loads = () => TAB_PANEL_LOADS as unknown as Array<ReturnType<typeof vi.fn>>;
async function mounted() {
const view = renderHook(() => useTripPlanner(), { wrapper });
await act(async () => {
await Promise.resolve();
});
return view;
}
beforeEach(() => {
vi.clearAllMocks();
resetAllStores();
usePluginStore.setState({ plugins: [], loaded: true });
useBackgroundTasksStore.setState({ tasks: [] });
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true, placesPhotosEnabled: false });
useTripStore.setState({
trip: buildTrip({ id: 42, title: 'Kyoto' }),
isLoading: false,
days: [],
places: [],
assignments: {},
reservations: [],
...(makeActions() as unknown as Partial<TripStoreState>),
} as Partial<TripStoreState>);
seedInstanceAddons(['collab']);
vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({});
vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false });
vi.spyOn(tripsApi, 'getMembers').mockResolvedValue({ owner: null, members: [] });
vi.spyOn(airtrailApi, 'sync').mockResolvedValue({ changed: 0 });
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useTripPlanner: map tabs kept once opened', () => {
it('FE-ATLAS2-REST-060: a trip opening on the plan keeps the plan map from the start', async () => {
const { result } = await mounted();
expect(result.current.planMapKept).toBe(true);
expect(result.current.tourMapKept).toBe(false);
expect(result.current.tourStageClass).toBe('invisible absolute inset-0');
});
it('FE-ATLAS2-REST-061: opening the tour planner keeps its map too; another tab keeps both and shows neither stage', async () => {
const { result } = await mounted();
act(() => result.current.handleTabChange('tour-planner'));
expect(result.current.tourMapKept).toBe(true);
expect(result.current.tourStageClass).toBe('absolute inset-0');
act(() => result.current.handleTabChange('collab'));
expect(result.current.planMapKept).toBe(true);
expect(result.current.tourMapKept).toBe(true);
expect(result.current.tourStageClass).toBe('invisible absolute inset-0');
});
it('FE-ATLAS2-REST-062: going back to a kept map tab keeps it kept', async () => {
const { result } = await mounted();
act(() => result.current.handleTabChange('plan'));
expect(result.current.planMapKept).toBe(true);
});
it('FE-ATLAS2-REST-063: a trip reopened on a list tab keeps no map until a map tab is opened', async () => {
sessionStorage.setItem('trip-tab-42', 'collab');
const { result } = await mounted();
expect(result.current.planMapKept).toBe(false);
expect(result.current.tourMapKept).toBe(false);
act(() => result.current.handleTabChange('plan'));
expect(result.current.planMapKept).toBe(true);
});
});
describe('useTripPlanner: the other tabs loaded ahead', () => {
it('FE-ATLAS2-REST-064: after the trip sits open every tab panel loads, a failed load is no error, and the bags are read ahead', async () => {
useAddonStore.setState({ bagTracking: true });
await mounted();
expect(loads()[0]).not.toHaveBeenCalled();
await waitFor(() => expect(loads()[0]).toHaveBeenCalledTimes(1), { timeout: 4000 });
expect(loads()[1]).toHaveBeenCalledTimes(1);
expect(warmPackingBags).toHaveBeenCalledWith(42);
});
it('FE-ATLAS2-REST-065: without bag tracking no bags are read ahead, and leaving the trip early cancels the loads', async () => {
const first = await mounted();
await waitFor(() => expect(loads()[0]).toHaveBeenCalledTimes(1), { timeout: 4000 });
expect(warmPackingBags).not.toHaveBeenCalled();
first.unmount();
// Left before the trip sat open long enough: the loads never start.
const second = await mounted();
second.unmount();
await new Promise((r) => setTimeout(r, 2300));
expect(loads()[0]).toHaveBeenCalledTimes(1);
});
});
+57
View File
@@ -0,0 +1,57 @@
// FE-ATLAS2-DATA-110 to FE-ATLAS2-DATA-114: the online lookups of the Atlas.
import { http, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { mapsApi } from '../api/client';
import { dawarichApi } from '../api/dawarich';
import { atlasBucketRepo } from './atlasBucketRepo';
type SearchResult = Awaited<ReturnType<typeof mapsApi.search>>;
afterEach(() => {
vi.restoreAllMocks();
});
describe('atlasBucketRepo', () => {
it('FE-ATLAS2-DATA-110: a place search hands back the places of the maps search, in the given language', async () => {
const search = vi
.spyOn(mapsApi, 'search')
.mockResolvedValue({ places: [{ name: 'Azores', lat: 38.7, lng: -27.2 }] } as unknown as SearchResult);
expect(await atlasBucketRepo.searchPlaces('azores', 'pt')).toEqual([{ name: 'Azores', lat: 38.7, lng: -27.2 }]);
expect(search).toHaveBeenCalledWith('azores', 'pt');
});
it('FE-ATLAS2-DATA-111: a search answer without places reads as none', async () => {
vi.spyOn(mapsApi, 'search').mockResolvedValue({} as unknown as SearchResult);
expect(await atlasBucketRepo.searchPlaces('nowhere', 'en')).toEqual([]);
});
it('FE-ATLAS2-DATA-112: locate asks the server where a point lies', async () => {
let asked: string | null = null;
server.use(
http.get('/api/addons/atlas/locate', ({ request }) => {
asked = new URL(request.url).search;
return HttpResponse.json({ country_code: 'PT', region_code: 'PT-11', region_name: 'Lisboa' });
})
);
expect(await atlasBucketRepo.locate(38.72, -9.14)).toEqual({
country_code: 'PT',
region_code: 'PT-11',
region_name: 'Lisboa',
});
expect(asked).toBe('?lat=38.72&lng=-9.14');
});
it('FE-ATLAS2-DATA-113: clearing a visit takes back the Dawarich tick of that wish', async () => {
const clear = vi.spyOn(dawarichApi, 'clearBucketVisit').mockResolvedValue({ success: true });
await atlasBucketRepo.clearVisit(12);
expect(clear).toHaveBeenCalledWith(12);
});
it('FE-ATLAS2-DATA-114: a failed clear reaches the caller', async () => {
vi.spyOn(dawarichApi, 'clearBucketVisit').mockRejectedValue(new Error('down'));
await expect(atlasBucketRepo.clearVisit(12)).rejects.toThrow('down');
});
});
@@ -0,0 +1,24 @@
// FE-ATLAS2-DATA-120 to FE-ATLAS2-DATA-122: the plugin tints of the Atlas, fail-safe.
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { atlasPluginLayersRepo } from './atlasPluginLayersRepo';
describe('atlasPluginLayersRepo', () => {
it('FE-ATLAS2-DATA-120: the layers the plugins answer are handed back', async () => {
const layers = [{ pluginId: 'p', id: 'l', name: 'Layer', countries: [{ code: 'DE', tone: 'success' }] }];
server.use(http.get('/api/atlas-layers', () => HttpResponse.json({ layers })));
expect(await atlasPluginLayersRepo.layers()).toEqual(layers);
});
it('FE-ATLAS2-DATA-121: an answer without layers reads as none', async () => {
server.use(http.get('/api/atlas-layers', () => HttpResponse.json({})));
expect(await atlasPluginLayersRepo.layers()).toEqual([]);
});
it('FE-ATLAS2-DATA-122: a failing read shows no layers instead of throwing', async () => {
server.use(http.get('/api/atlas-layers', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
expect(await atlasPluginLayersRepo.layers()).toEqual([]);
});
});
+205
View File
@@ -0,0 +1,205 @@
// FE-ATLAS2-DATA-090 to FE-ATLAS2-DATA-101: the online-only Atlas reads, adding a
// wish, and the online writes the offline suite does not reach.
import 'fake-indexeddb/auto';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { clearAll, offlineDb } from '../db/offlineDb';
import { keepAtlasPart, keptAtlasPart } from '../sync/atlasSnapshot';
import { setAuthed } from '../sync/authGate';
import { mutationQueue } from '../sync/mutationQueue';
import { atlasRepo } from './atlasRepo';
function setOnline(value: boolean): void {
Object.defineProperty(navigator, 'onLine', { value, writable: true, configurable: true });
}
beforeEach(async () => {
await clearAll();
mutationQueue._resetFlushing();
setAuthed(true);
setOnline(true);
});
afterEach(() => {
vi.restoreAllMocks();
setAuthed(false);
setOnline(true);
});
describe('people', () => {
it('FE-ATLAS2-DATA-090: the directory and the counts are joined by id, an unknown id reads as ?', async () => {
let askedIds: string | null = null;
server.use(
http.get('/api/auth/users', () =>
HttpResponse.json({
users: [
{ id: 1, username: 'ana', avatar_url: '/a.png' },
{ id: 2, username: 'ben' },
],
})
),
http.get('/api/addons/atlas/people', ({ request }) => {
askedIds = new URL(request.url).searchParams.get('ids');
return HttpResponse.json({
people: [
{ id: 1, countries: 3, continents: 1, regions: 2, flightKm: 10, codes: ['PT'], badges: [] },
{ id: 2, countries: 0, continents: 0, regions: 0, flightKm: 0, codes: [], badges: [] },
{ id: 9, countries: 1, continents: 1, regions: 0, flightKm: 0, codes: ['DE'], badges: [] },
],
});
})
);
const people = await atlasRepo.people();
expect(askedIds).toBe('1,2');
expect(people.map((p) => [p.id, p.username, p.avatar_url, p.countries])).toEqual([
[1, 'ana', '/a.png', 3],
[2, 'ben', null, 0],
[9, '?', null, 1],
]);
});
it('FE-ATLAS2-DATA-091: an empty directory asks for no counts', async () => {
let countsAsked = 0;
server.use(
http.get('/api/auth/users', () => HttpResponse.json({})),
http.get('/api/addons/atlas/people', () => {
countsAsked += 1;
return HttpResponse.json({ people: [] });
})
);
expect(await atlasRepo.people()).toEqual([]);
expect(countsAsked).toBe(0);
});
it('FE-ATLAS2-DATA-092: a counts answer without a people list reads as nobody', async () => {
server.use(
http.get('/api/auth/users', () => HttpResponse.json({ users: [{ id: 1, username: 'ana' }] })),
http.get('/api/addons/atlas/people', () => HttpResponse.json({}))
);
expect(await atlasRepo.people()).toEqual([]);
});
});
describe('online-only reads', () => {
it('FE-ATLAS2-DATA-093: mesh reads a file below the mesh path and hands its body back', async () => {
server.use(
http.get('/api/addons/atlas/mesh/manifest.json', () => HttpResponse.json({ files: ['countries.abc.json'] }))
);
expect(await atlasRepo.mesh('manifest.json')).toEqual({ files: ['countries.abc.json'] });
});
it('FE-ATLAS2-DATA-094: a country detail is read from the server, never kept', async () => {
server.use(http.get('/api/addons/atlas/country/PT', () => HttpResponse.json({ places: [], status: 'visited' })));
expect(await atlasRepo.countryDetail('PT')).toEqual({ places: [], status: 'visited' });
expect(await offlineDb.atlasSnapshot.count()).toBe(0);
});
it('FE-ATLAS2-DATA-095: a regions or bucket answer without its list reads as empty', async () => {
server.use(
http.get('/api/addons/atlas/regions', () => HttpResponse.json({})),
http.get('/api/addons/atlas/bucket-list', () => HttpResponse.json({}))
);
expect(await atlasRepo.regions()).toEqual({});
expect(await atlasRepo.bucketList()).toEqual([]);
});
});
describe('adding a wish', () => {
it('FE-ATLAS2-DATA-096: the new wish leads the kept bucket list', async () => {
await keepAtlasPart('bucketList', [{ id: 1, name: 'Old' }]);
let posted: unknown = null;
server.use(
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
posted = await request.json();
return HttpResponse.json({ item: { id: 2, name: 'Azores' } });
})
);
const item = await atlasRepo.addBucketItem({ name: 'Azores' });
expect(posted).toEqual({ name: 'Azores' });
expect(item).toEqual({ id: 2, name: 'Azores' });
expect((await keptAtlasPart('bucketList'))?.data).toEqual([
{ id: 2, name: 'Azores' },
{ id: 1, name: 'Old' },
]);
});
it('FE-ATLAS2-DATA-097: with no kept list, or no item in the answer, nothing is kept', async () => {
server.use(http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ item: { id: 3 } })));
await atlasRepo.addBucketItem({ name: 'A' });
expect(await keptAtlasPart('bucketList')).toBeUndefined();
await keepAtlasPart('bucketList', [{ id: 1 }]);
server.use(http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({})));
expect(await atlasRepo.addBucketItem({ name: 'B' })).toBeUndefined();
expect((await keptAtlasPart('bucketList'))?.data).toEqual([{ id: 1 }]);
});
it('FE-ATLAS2-DATA-098: a duplicate (409) is not swallowed and never queued', async () => {
server.use(
http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ error: 'exists' }, { status: 409 }))
);
await expect(atlasRepo.addBucketItem({ name: 'A' })).rejects.toMatchObject({ response: { status: 409 } });
expect(await offlineDb.userMutationQueue.count()).toBe(0);
});
});
describe('online writes', () => {
it('FE-ATLAS2-DATA-099: a region mark goes out with its name and country and lands in the kept regions', async () => {
await keepAtlasPart('regions', { ES: [] });
let body: unknown = null;
server.use(
http.post('/api/addons/atlas/region/ES-CT/mark', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ success: true });
})
);
await atlasRepo.markRegion('ES-CT', 'Catalunya', 'ES');
expect(body).toEqual({ name: 'Catalunya', country_code: 'ES' });
expect((await keptAtlasPart('regions'))?.data).toEqual({
ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }],
});
});
it('FE-ATLAS2-DATA-100: a region unmark and a country unmark online reach the server and the kept reads', async () => {
await keepAtlasPart('regions', { ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, manuallyMarked: true }] });
await keepAtlasPart('stats', { countries: [{ code: 'IS', status: 'visited' }], stats: { totalCountries: 1 } });
const hits: string[] = [];
server.use(
http.delete('/api/addons/atlas/region/ES-CT/mark', () => {
hits.push('region');
return HttpResponse.json({ success: true });
}),
http.delete('/api/addons/atlas/country/IS/mark', () => {
hits.push('country');
return HttpResponse.json({ success: true });
})
);
await atlasRepo.unmarkRegion('ES-CT');
await atlasRepo.unmarkCountry('IS');
expect(hits).toEqual(['region', 'country']);
expect((await keptAtlasPart('regions'))?.data).toEqual({ ES: [] });
expect((await keptAtlasPart('stats'))?.data).toMatchObject({ countries: [], stats: { totalCountries: 0 } });
expect(await offlineDb.userMutationQueue.count()).toBe(0);
});
it('FE-ATLAS2-DATA-101: a write the server refuses is thrown to the caller and not queued', async () => {
await keepAtlasPart('stats', { countries: [] });
server.use(
http.post('/api/addons/atlas/country/DE/mark', () => HttpResponse.json({ error: 'nope' }, { status: 403 }))
);
await expect(atlasRepo.markCountry('DE')).rejects.toMatchObject({ response: { status: 403 } });
expect(await offlineDb.userMutationQueue.count()).toBe(0);
expect((await keptAtlasPart('stats'))?.data).toEqual({ countries: [] });
});
});
@@ -0,0 +1,39 @@
// FE-ATLAS2-DATA-130 to FE-ATLAS2-DATA-132: the two Atlas writes of the Dawarich seam.
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { dawarichRepo } from './dawarichRepo';
const BASE = '/api/integrations/dawarich';
describe('dawarichRepo Atlas writes', () => {
it('FE-ATLAS2-DATA-130: confirming wishes sends the ids and the day they were reached', async () => {
let body: unknown = null;
server.use(
http.post(`${BASE}/bucket-list/confirm`, async ({ request }) => {
body = await request.json();
return HttpResponse.json({ updated: 2 });
})
);
expect(await dawarichRepo.confirmBucketVisits([3, 4], '2026-04-02T08:00:00Z')).toEqual({ updated: 2 });
expect(body).toEqual({ itemIds: [3, 4], visitedAt: '2026-04-02T08:00:00Z' });
});
it('FE-ATLAS2-DATA-131: accepting countries sends their codes and answers how many were marked', async () => {
let body: unknown = null;
server.use(
http.post(`${BASE}/atlas/accept`, async ({ request }) => {
body = await request.json();
return HttpResponse.json({ marked: 1 });
})
);
expect(await dawarichRepo.acceptAtlasCountries(['DE'])).toEqual({ marked: 1 });
expect(body).toEqual({ countryCodes: ['DE'] });
});
it('FE-ATLAS2-DATA-132: a refused confirmation reaches the caller', async () => {
server.use(http.post(`${BASE}/bucket-list/confirm`, () => HttpResponse.json({ error: 'no' }, { status: 400 })));
await expect(dawarichRepo.confirmBucketVisits([1])).rejects.toMatchObject({ response: { status: 400 } });
});
});
+356
View File
@@ -0,0 +1,356 @@
// FE-ATLAS2-DATA-001 to FE-ATLAS2-DATA-030: the Atlas reads with the queued
// writes laid over them, and a write that went through laid into the kept reads.
import { continentForCountry } from '@trek/shared';
import 'fake-indexeddb/auto';
import { beforeEach, describe, expect, it } from 'vitest';
import { clearAll, offlineDb, type MutationStatus, type UserQueuedMutation } from '../db/offlineDb';
import { ATLAS_RESOURCE, keepAtlasPart, keptAtlasPart, reconcileAtlasWrite, withWaitingWrites } from './atlasSnapshot';
let seq = 0;
/** A row in the account queue, the way userMutationQueue stores it. */
async function queued(
over: Partial<UserQueuedMutation> & Pick<UserQueuedMutation, 'resource' | 'entity' | 'method'>
): Promise<UserQueuedMutation> {
seq += 1;
const row: UserQueuedMutation = {
id: `row-${seq}`,
url: '/addons/atlas/x',
ids: {},
body: null,
createdAt: 1000 + seq,
status: 'pending' as MutationStatus,
attempts: 0,
lastError: null,
schemaVersion: 1,
buildVersion: '',
...over,
};
await offlineDb.userMutationQueue.put(row);
return row;
}
const country = (code: string, method: 'POST' | 'DELETE' = 'POST') => ({
resource: ATLAS_RESOURCE.country,
entity: `${ATLAS_RESOURCE.country}:${code}`,
method,
});
const region = (code: string, method: 'POST' | 'DELETE', body: unknown = null) => ({
resource: ATLAS_RESOURCE.region,
entity: `${ATLAS_RESOURCE.region}:${code}`,
method,
body,
});
interface Stats {
countries: Array<{ code: string; status?: string; placeCount?: number; tripCount?: number }>;
stats?: Record<string, number | undefined>;
continents?: Record<string, number>;
continentsPlanned?: Record<string, number>;
}
function baseStats(): Stats {
return {
countries: [
{ code: 'PT', status: 'visited', placeCount: 3, tripCount: 1 },
{ code: 'ES', status: 'planned', placeCount: 0, tripCount: 0 },
],
stats: { totalCountries: 1, totalCountriesPlanned: 1 },
continents: { Europe: 1 },
continentsPlanned: { Europe: 1 },
};
}
beforeEach(async () => {
await clearAll();
seq = 0;
});
describe('keeping a read', () => {
it('FE-ATLAS2-DATA-001: a kept part reads back as stored, a part never kept is undefined', async () => {
expect(await keptAtlasPart('stats')).toBeUndefined();
await keepAtlasPart('stats', { countries: [] });
expect((await keptAtlasPart('stats'))?.data).toEqual({ countries: [] });
await keepAtlasPart('stats', { countries: [{ code: 'DE' }] });
expect((await keptAtlasPart('stats'))?.data).toEqual({ countries: [{ code: 'DE' }] });
});
});
describe('countries over the stats read', () => {
it('FE-ATLAS2-DATA-002: no waiting writes leave the read as it is', async () => {
const data = baseStats();
expect(await withWaitingWrites('stats', data)).toBe(data);
});
it('FE-ATLAS2-DATA-003: marking a new country adds it visited and counts its continent', async () => {
await queued(country('JP'));
const out = (await withWaitingWrites('stats', baseStats())) as Stats;
const jp = out.countries.find((c) => c.code === 'JP');
expect(jp).toMatchObject({ code: 'JP', status: 'visited', placeCount: 0, tripCount: 0 });
expect(out.stats?.totalCountries).toBe(2);
expect(out.stats?.totalCountriesPlanned).toBe(1);
expect(out.continents?.[continentForCountry('JP')]).toBe(1);
});
it('FE-ATLAS2-DATA-004: marking a planned country moves it from the planned tally to the visited one', async () => {
await queued(country('ES'));
const out = (await withWaitingWrites('stats', baseStats())) as Stats;
expect(out.countries.find((c) => c.code === 'ES')?.status).toBe('visited');
expect(out.countries).toHaveLength(2);
expect(out.stats).toMatchObject({ totalCountries: 2, totalCountriesPlanned: 0 });
expect(out.continents?.Europe).toBe(2);
expect(out.continentsPlanned?.Europe).toBe(0);
});
it('FE-ATLAS2-DATA-005: marking a country already visited changes nothing, also one without a status', async () => {
await queued(country('PT'));
const data = baseStats();
expect(await withWaitingWrites('stats', data)).toBe(data);
await clearAll();
const noStatus: Stats = { countries: [{ code: 'FR' }], stats: { totalCountries: 1 } };
await queued(country('FR'));
expect(await withWaitingWrites('stats', noStatus)).toEqual(noStatus);
});
it('FE-ATLAS2-DATA-006: a read without a countries list is not touched', async () => {
await queued(country('JP'));
await queued(country('PT', 'DELETE'));
expect(await withWaitingWrites('stats', null)).toBeNull();
expect(await withWaitingWrites('stats', { other: true })).toEqual({ other: true });
expect(await withWaitingWrites('stats', [1, 2])).toEqual([1, 2]);
});
it('FE-ATLAS2-DATA-007: marking into a read without totals starts the counts at zero', async () => {
await queued(country('ES'));
const out = (await withWaitingWrites('stats', {
countries: [{ code: 'ES', status: 'planned' }],
})) as Stats;
expect(out.stats).toEqual({ totalCountries: 1, totalCountriesPlanned: 0 });
expect(out.continents).toEqual({ Europe: 1 });
expect(out.continentsPlanned).toEqual({ Europe: 0 });
});
it('FE-ATLAS2-DATA-008: unmarking a country with no trip and no place drops it and its counts', async () => {
const data: Stats = {
countries: [
{ code: 'PT', status: 'visited', placeCount: 3, tripCount: 1 },
{ code: 'IS', status: 'visited', placeCount: 0, tripCount: 0 },
],
stats: { totalCountries: 2 },
continents: { Europe: 2 },
};
await queued(country('IS', 'DELETE'));
const out = (await withWaitingWrites('stats', data)) as Stats;
expect(out.countries.map((c) => c.code)).toEqual(['PT']);
expect(out.stats?.totalCountries).toBe(1);
expect(out.continents?.Europe).toBe(1);
});
it('FE-ATLAS2-DATA-009: unmarking keeps a country that has places or trips, is unknown, or is only planned', async () => {
const data = baseStats();
await queued(country('PT', 'DELETE'));
await queued(country('XX', 'DELETE'));
await queued(country('ES', 'DELETE'));
expect(await withWaitingWrites('stats', data)).toBe(data);
const tripsOnly: Stats = { countries: [{ code: 'IT', status: 'visited', tripCount: 2 }] };
await queued(country('IT', 'DELETE'));
expect(await withWaitingWrites('stats', tripsOnly)).toBe(tripsOnly);
});
it('FE-ATLAS2-DATA-010: unmarking a country with no status counts it as visited and drops it, never below zero', async () => {
await queued(country('IS', 'DELETE'));
const out = (await withWaitingWrites('stats', { countries: [{ code: 'IS' }] })) as Stats;
expect(out.countries).toEqual([]);
expect(out.stats?.totalCountries).toBe(0);
expect(out.continents?.Europe).toBe(0);
});
it('FE-ATLAS2-DATA-011: a mark and its unmark laid over in order cancel out', async () => {
await queued(country('JP'));
await queued(country('JP', 'DELETE'));
const out = (await withWaitingWrites('stats', baseStats())) as Stats;
expect(out.countries.map((c) => c.code)).toEqual(['PT', 'ES']);
expect(out.stats?.totalCountries).toBe(1);
});
it('FE-ATLAS2-DATA-012: a country write with another method, or another resource, leaves the stats alone', async () => {
await queued({ ...country('JP'), method: 'PUT' });
await queued({ resource: ATLAS_RESOURCE.bucket, entity: `${ATLAS_RESOURCE.bucket}:3`, method: 'DELETE' });
const data = baseStats();
expect(await withWaitingWrites('stats', data)).toBe(data);
});
});
describe('which queued rows are laid over', () => {
it('FE-ATLAS2-DATA-013: a parked row, and a write of another feature, are not laid over', async () => {
await queued({ ...country('JP'), status: 'failed' });
await queued({ resource: 'journey', entity: 'journey:JP', method: 'POST' });
const data = baseStats();
expect(await withWaitingWrites('stats', data)).toBe(data);
});
it('FE-ATLAS2-DATA-014: a row that is syncing is still laid over', async () => {
await queued({ ...country('JP'), status: 'syncing' });
const out = (await withWaitingWrites('stats', baseStats())) as Stats;
expect(out.countries.some((c) => c.code === 'JP')).toBe(true);
});
it('FE-ATLAS2-DATA-015: writes are laid over oldest first, whatever order they were stored in', async () => {
await queued({ ...country('JP', 'DELETE'), createdAt: 50 });
await queued({ ...country('JP'), createdAt: 10 });
const out = (await withWaitingWrites('stats', baseStats())) as Stats;
// Mark at 10, unmark at 50: JP ends up gone.
expect(out.countries.some((c) => c.code === 'JP')).toBe(false);
});
});
describe('regions', () => {
const regions = () => ({
PT: [
{ code: 'PT-11', name: 'Lisboa', placeCount: 4, status: 'visited' },
{ code: 'PT-13', name: 'Porto', placeCount: 0, status: 'visited', manuallyMarked: true },
],
});
it('FE-ATLAS2-DATA-016: marking a new region adds it under its country, named from the body', async () => {
await queued(region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }));
const out = (await withWaitingWrites('regions', regions())) as Record<string, unknown[]>;
expect(out.ES).toEqual([
{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true },
]);
expect(out.PT).toHaveLength(2);
});
it('FE-ATLAS2-DATA-017: a region mark without a name in the body is named by its code', async () => {
await queued(region('ES-MD', 'POST', { country_code: 'ES' }));
const out = (await withWaitingWrites('regions', {})) as Record<string, Array<{ name: string }>>;
expect(out.ES[0].name).toBe('ES-MD');
});
it('FE-ATLAS2-DATA-018: marking a known region by hand keeps its places and sets the manual flag', async () => {
await queued(region('PT-11', 'POST', { name: 'Lisboa', country_code: 'PT' }));
const out = (await withWaitingWrites('regions', regions())) as ReturnType<typeof regions>;
expect(out.PT[0]).toEqual({
code: 'PT-11',
name: 'Lisboa',
placeCount: 4,
status: 'visited',
manuallyMarked: true,
});
expect(out.PT).toHaveLength(2);
});
it('FE-ATLAS2-DATA-019: marking a region already marked by hand changes nothing', async () => {
await queued(region('PT-13', 'POST', { name: 'Porto', country_code: 'PT' }));
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
});
it('FE-ATLAS2-DATA-020: a region mark without a country code, or over a read that is no map, is ignored', async () => {
await queued(region('ES-CT', 'POST', { name: 'Catalunya' }));
await queued(region('ES-AN', 'POST', 'not an object'));
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
await clearAll();
await queued(region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }));
expect(await withWaitingWrites('regions', [1])).toEqual([1]);
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-021: unmarking a region with places keeps it, only the manual flag goes', async () => {
await queued(region('PT-11', 'DELETE'));
const out = (await withWaitingWrites('regions', regions())) as ReturnType<typeof regions>;
expect(out.PT[0]).toMatchObject({ code: 'PT-11', manuallyMarked: false, placeCount: 4 });
});
it('FE-ATLAS2-DATA-022: unmarking a region without places drops it', async () => {
await queued(region('PT-13', 'DELETE'));
const out = (await withWaitingWrites('regions', regions())) as ReturnType<typeof regions>;
expect(out.PT.map((r) => r.code)).toEqual(['PT-11']);
});
it('FE-ATLAS2-DATA-023: unmarking an unknown region, or over a read that is no map, changes nothing', async () => {
await queued(region('DE-BY', 'DELETE'));
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
expect(await withWaitingWrites('regions', null)).toBeNull();
});
it('FE-ATLAS2-DATA-024: a country write or a PUT on a region leaves the regions read alone', async () => {
await queued(country('PT', 'DELETE'));
await queued({ ...region('PT-11', 'POST', { country_code: 'PT' }), method: 'PUT' });
const data = regions();
expect(await withWaitingWrites('regions', data)).toBe(data);
});
});
describe('the bucket list and the other reads', () => {
const bucket = { resource: ATLAS_RESOURCE.bucket, entity: `${ATLAS_RESOURCE.bucket}:7`, method: 'DELETE' as const };
it('FE-ATLAS2-DATA-025: a queued wish delete hides the wish', async () => {
await queued(bucket);
const out = await withWaitingWrites('bucketList', [{ id: 7 }, { id: 8 }, 'junk']);
expect(out).toEqual([{ id: 8 }, 'junk']);
});
it('FE-ATLAS2-DATA-026: a bucket POST, a country write, or a read that is no list leave the bucket list alone', async () => {
await queued({ ...bucket, method: 'POST' });
await queued(country('PT'));
const list = [{ id: 7 }];
expect(await withWaitingWrites('bucketList', list)).toBe(list);
await queued(bucket);
expect(await withWaitingWrites('bucketList', { id: 7 })).toEqual({ id: 7 });
});
it('FE-ATLAS2-DATA-027: the flights read is never changed by a write', async () => {
await queued(country('PT'));
await queued(bucket);
const flights = { routes: [] };
expect(await withWaitingWrites('flights', flights)).toBe(flights);
});
});
describe('a write that went through', () => {
it('FE-ATLAS2-DATA-028: it is laid into every kept read it changes, and the others stay as they were', async () => {
await keepAtlasPart('stats', baseStats());
await keepAtlasPart('flights', { routes: [] });
await keepAtlasPart('bucketList', [{ id: 7 }, { id: 9 }]);
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
await reconcileAtlasWrite({
resource: ATLAS_RESOURCE.bucket,
entity: `${ATLAS_RESOURCE.bucket}:9`,
method: 'DELETE',
ids: {},
body: null,
createdAt: 2,
answer: { success: true },
});
const stats = (await keptAtlasPart('stats'))?.data as Stats;
expect(stats.countries.map((c) => c.code)).toEqual(['PT', 'ES', 'JP']);
expect((await keptAtlasPart('flights'))?.data).toEqual({ routes: [] });
expect((await keptAtlasPart('bucketList'))?.data).toEqual([{ id: 7 }]);
});
it('FE-ATLAS2-DATA-029: laying the same write in twice changes nothing more', async () => {
await keepAtlasPart('regions', {});
const w = { ...region('ES-CT', 'POST', { name: 'Catalunya', country_code: 'ES' }), ids: {}, createdAt: 1 };
await reconcileAtlasWrite(w);
const once = (await keptAtlasPart('regions'))?.data;
await reconcileAtlasWrite(w);
expect((await keptAtlasPart('regions'))?.data).toEqual(once);
expect(once).toEqual({
ES: [{ code: 'ES-CT', name: 'Catalunya', placeCount: 0, status: 'visited', manuallyMarked: true }],
});
});
it('FE-ATLAS2-DATA-030: with nothing kept there is nothing to change', async () => {
await reconcileAtlasWrite({ ...country('JP'), ids: {}, body: null, createdAt: 1 });
expect(await offlineDb.atlasSnapshot.count()).toBe(0);
});
});
+30
View File
@@ -0,0 +1,30 @@
// FE-ATLAS2-DATA-080 to FE-ATLAS2-DATA-082: the replay rules both write queues share.
import { describe, expect, it } from 'vitest';
import {
BUILD_VERSION,
isRetryableStatus,
MAX_SERVER_ERROR_ATTEMPTS,
SERVER_ERROR_BACKOFF_MS,
STUCK_SYNCING_MS,
} from './queuePolicy';
describe('queuePolicy', () => {
it('FE-ATLAS2-DATA-080: only an expired login, a timeout, too-early and rate limiting are worth waiting out', () => {
for (const status of [401, 408, 425, 429]) expect(isRetryableStatus(status)).toBe(true);
for (const status of [undefined, 200, 400, 403, 404, 409, 422, 500, 503])
expect(isRetryableStatus(status)).toBe(false);
});
it('FE-ATLAS2-DATA-081: the gap doubles from 30 s up to 32 minutes before the last server-error try', () => {
expect(MAX_SERVER_ERROR_ATTEMPTS).toBe(8);
expect(SERVER_ERROR_BACKOFF_MS).toBe(30_000);
const lastGap = SERVER_ERROR_BACKOFF_MS * 2 ** (MAX_SERVER_ERROR_ATTEMPTS - 2);
expect(lastGap).toBe(32 * 60_000);
expect(STUCK_SYNCING_MS).toBe(60_000);
});
it('FE-ATLAS2-DATA-082: the build stamp is a string, empty where the bundler defined none', () => {
expect(typeof BUILD_VERSION).toBe('string');
});
});
+572
View File
@@ -0,0 +1,572 @@
// FE-ATLAS2-DATA-040 to FE-ATLAS2-DATA-075: the account's own write queue (the
// Atlas) - what has to wait, how a pass replays, and how it settles each answer.
import 'fake-indexeddb/auto';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { clearAll, MUTATION_SCHEMA_VERSION, offlineDb, type UserQueuedMutation } from '../db/offlineDb';
import { keepAtlasPart, keptAtlasPart } from './atlasSnapshot';
import { setAuthed } from './authGate';
import { mutationQueue } from './mutationQueue';
import { _resetNetworkMode, setForcedOffline } from './networkMode';
import { MAX_SERVER_ERROR_ATTEMPTS, SERVER_ERROR_BACKOFF_MS, STUCK_SYNCING_MS } from './queuePolicy';
import { userMutationQueue } from './userMutationQueue';
function setOnline(value: boolean): void {
Object.defineProperty(navigator, 'onLine', { value, writable: true, configurable: true });
}
let seq = 0;
/** A row as the queue stores it, written straight into Dexie. */
async function row(over: Partial<UserQueuedMutation> = {}): Promise<UserQueuedMutation> {
seq += 1;
const r: UserQueuedMutation = {
id: `id-${seq}`,
method: 'POST',
url: `/addons/atlas/country/C${seq}/mark`,
ids: {},
body: null,
resource: 'atlasCountry',
entity: `atlasCountry:C${seq}`,
createdAt: 100 + seq,
status: 'pending',
attempts: 0,
lastError: null,
schemaVersion: MUTATION_SCHEMA_VERSION,
buildVersion: '',
...over,
};
await offlineDb.userMutationQueue.put(r);
return r;
}
interface Sent {
method: string;
path: string;
key: string | null;
body: unknown;
}
let sent: Sent[];
/** Answer every request below /api/addons/atlas with `answer(path)`, recording what came in. */
function serve(answer: (path: string, method: string) => Response | Promise<Response>): void {
server.use(
http.all('/api/addons/atlas/*', async ({ request }) => {
const path = new URL(request.url).pathname;
const text = await request.text();
sent.push({
method: request.method,
path,
key: request.headers.get('X-Idempotency-Key'),
body: text ? (JSON.parse(text) as unknown) : null,
});
return answer(path, request.method);
})
);
}
const get = (id: string) => offlineDb.userMutationQueue.get(id);
beforeEach(async () => {
await clearAll();
mutationQueue._resetFlushing();
_resetNetworkMode();
setAuthed(true);
setOnline(true);
seq = 0;
sent = [];
});
afterEach(() => {
vi.restoreAllMocks();
setAuthed(false);
setOnline(true);
_resetNetworkMode();
});
describe('enqueue', () => {
it('FE-ATLAS2-DATA-040: a queued write is stamped pending, with the format and a FIFO time', async () => {
vi.spyOn(Date, 'now').mockReturnValue(5000);
const id = await userMutationQueue.enqueue({
id: 'a',
method: 'POST',
url: '/addons/atlas/country/DE/mark',
ids: {},
body: null,
resource: 'atlasCountry',
entity: 'atlasCountry:DE',
});
await userMutationQueue.enqueue({
id: 'b',
method: 'DELETE',
url: '/addons/atlas/country/DE/mark',
ids: {},
body: null,
resource: 'atlasCountry',
entity: 'atlasCountry:DE',
});
expect(id).toBe('a');
const a = await get('a');
expect(a).toMatchObject({
status: 'pending',
attempts: 0,
lastError: null,
schemaVersion: MUTATION_SCHEMA_VERSION,
createdAt: 5000,
});
expect(typeof a?.buildVersion).toBe('string');
// Same millisecond: the second one still sorts after the first.
expect((await get('b'))?.createdAt).toBe(5001);
});
it('FE-ATLAS2-DATA-041: the time counter starts over after a reset', async () => {
vi.spyOn(Date, 'now').mockReturnValue(10);
const input = {
method: 'POST' as const,
url: '/x',
ids: {},
body: null,
resource: 'atlasCountry',
entity: 'atlasCountry:X',
};
await userMutationQueue.enqueue({ ...input, id: 'one' });
await userMutationQueue.enqueue({ ...input, id: 'two' });
userMutationQueue._reset();
await userMutationQueue.enqueue({ ...input, id: 'three' });
expect((await get('two'))?.createdAt).toBe(11);
expect((await get('three'))?.createdAt).toBe(10);
});
});
describe('mustQueue', () => {
it('FE-ATLAS2-DATA-042: online with an empty queue a write goes straight out', async () => {
expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(false);
});
it('FE-ATLAS2-DATA-043: offline, by the device or by the switch, every write waits', async () => {
setOnline(false);
expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(true);
setOnline(true);
setForcedOffline(true);
expect(await userMutationQueue.mustQueue(null, [])).toBe(true);
});
it('FE-ATLAS2-DATA-044: a write naming a create still waiting here (negative id) waits', async () => {
expect(await userMutationQueue.mustQueue('atlasBucket:-3', [5, -3])).toBe(true);
});
it('FE-ATLAS2-DATA-045: any pending or syncing row puts a write in line, whatever its entity', async () => {
await row({ entity: 'atlasCountry:FR', status: 'syncing' });
expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(true);
});
it('FE-ATLAS2-DATA-046: a parked row holds back only its own entity', async () => {
await row({ entity: 'atlasCountry:FR', status: 'failed' });
expect(await userMutationQueue.mustQueue('atlasCountry:DE', [])).toBe(false);
expect(await userMutationQueue.mustQueue('atlasCountry:FR', [])).toBe(true);
expect(await userMutationQueue.mustQueue(null, [])).toBe(false);
});
});
describe('flushPass replays', () => {
it('FE-ATLAS2-DATA-047: a pending write is sent with its id as idempotency key, dropped and laid into the kept reads', async () => {
await keepAtlasPart('stats', { countries: [], stats: { totalCountries: 0 } });
serve(() => HttpResponse.json({ success: true }));
const r = await row({ url: '/addons/atlas/country/DE/mark', entity: 'atlasCountry:DE', body: { a: 1 } });
await userMutationQueue.flushPass();
expect(sent).toEqual([{ method: 'POST', path: '/api/addons/atlas/country/DE/mark', key: r.id, body: { a: 1 } }]);
expect(await get(r.id)).toBeUndefined();
const stats = (await keptAtlasPart('stats'))?.data as { countries: Array<{ code: string }> };
expect(stats.countries.map((c) => c.code)).toEqual(['DE']);
});
it('FE-ATLAS2-DATA-048: rows go out oldest first', async () => {
serve(() => HttpResponse.json({ success: true }));
await row({ url: '/addons/atlas/country/B/mark', createdAt: 20 });
await row({ url: '/addons/atlas/country/A/mark', createdAt: 10 });
await userMutationQueue.flushPass();
expect(sent.map((s) => s.path)).toEqual(['/api/addons/atlas/country/A/mark', '/api/addons/atlas/country/B/mark']);
expect(await offlineDb.userMutationQueue.count()).toBe(0);
});
it('FE-ATLAS2-DATA-049: a write that is no Atlas write is sent and dropped without touching the kept reads', async () => {
await keepAtlasPart('bucketList', [{ id: 1 }]);
serve(() => HttpResponse.json({ ok: true }));
const r = await row({ method: 'DELETE', url: '/addons/atlas/bucket-list/1', resource: 'other', entity: 'other:1' });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
expect(await get(r.id)).toBeUndefined();
expect((await keptAtlasPart('bucketList'))?.data).toEqual([{ id: 1 }]);
});
it('FE-ATLAS2-DATA-050: a create learns its real id, and the later writes naming it use it, in memory and on disk', async () => {
serve((path, method) => {
if (method === 'POST') return HttpResponse.json({ id: 42 });
if (path.endsWith('/42') && method === 'PUT') return HttpResponse.json({ ok: true });
return HttpResponse.json({ error: 'down' }, { status: 503 });
});
const create = await row({
url: '/addons/atlas/bucket-list',
resource: 'atlasBucket',
entity: 'atlasBucket:-5',
tempId: -5,
createdAt: 1,
});
const edit = await row({
method: 'PUT',
url: '/addons/atlas/bucket-list/{id}',
ids: { id: -5 },
resource: 'atlasBucket',
entity: 'atlasBucket:-5',
createdAt: 2,
});
const remove = await row({
method: 'DELETE',
url: '/addons/atlas/bucket-list/{id}/thing',
ids: { id: -5, other: 3 },
resource: 'atlasBucket',
entity: 'atlasBucket:-5',
createdAt: 3,
});
await userMutationQueue.flushPass();
expect(sent.map((s) => `${s.method} ${s.path}`)).toEqual([
'POST /api/addons/atlas/bucket-list',
'PUT /api/addons/atlas/bucket-list/42',
'DELETE /api/addons/atlas/bucket-list/42/thing',
]);
expect(await get(create.id)).toBeUndefined();
expect(await get(edit.id)).toBeUndefined();
// The delete met a 503 and waits, already naming the real id.
expect(await get(remove.id)).toMatchObject({
ids: { id: 42, other: 3 },
entity: 'atlasBucket:42',
status: 'pending',
});
});
it('FE-ATLAS2-DATA-051: a create answered without a numeric id teaches nothing; its dependent is parked', async () => {
serve(() => HttpResponse.json({ id: 'not-a-number' }));
await row({ url: '/addons/atlas/bucket-list', resource: 'atlasBucket', entity: 'atlasBucket:-1', tempId: -1 });
const dep = await row({
method: 'DELETE',
url: '/addons/atlas/bucket-list/{id}',
ids: { id: -1 },
resource: 'atlasBucket',
entity: 'atlasBucket:-1',
});
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
expect(await get(dep.id)).toMatchObject({
status: 'failed',
attempts: 1,
lastError: 'unresolved temp id (dependent create did not sync)',
});
});
it('FE-ATLAS2-DATA-052: a write naming a create that never synced is parked and holds back its entity, not the others', async () => {
serve(() => HttpResponse.json({ success: true }));
const orphan = await row({
method: 'DELETE',
url: '/addons/atlas/bucket-list/{id}',
ids: { id: -9 },
resource: 'atlasBucket',
entity: 'atlasBucket:-9',
createdAt: 1,
});
const behind = await row({ resource: 'atlasBucket', entity: 'atlasBucket:-9', url: '/x/behind', createdAt: 2 });
const other = await row({ url: '/addons/atlas/country/PT/mark', entity: 'atlasCountry:PT', createdAt: 3 });
await userMutationQueue.flushPass();
expect((await get(orphan.id))?.status).toBe('failed');
expect((await get(behind.id))?.status).toBe('pending');
expect(await get(other.id)).toBeUndefined();
expect(sent.map((s) => s.path)).toEqual(['/api/addons/atlas/country/PT/mark']);
});
});
describe('flushPass settles a failed replay', () => {
it('FE-ATLAS2-DATA-053: a delete answered 404 did its job and is dropped; the pass goes on', async () => {
serve((path) =>
path.includes('bucket-list')
? HttpResponse.json({ error: 'gone' }, { status: 404 })
: HttpResponse.json({ success: true })
);
const del = await row({ method: 'DELETE', url: '/addons/atlas/bucket-list/7', entity: 'atlasBucket:7' });
const next = await row();
await userMutationQueue.flushPass();
expect(await get(del.id)).toBeUndefined();
expect(await get(next.id)).toBeUndefined();
expect(sent).toHaveLength(2);
});
it('FE-ATLAS2-DATA-054: a refusal (4xx) is parked and holds back the later writes to that entity only', async () => {
serve((path) =>
path.includes('/DE/') ? HttpResponse.json({ error: 'no' }, { status: 409 }) : HttpResponse.json({ success: true })
);
const refused = await row({ url: '/addons/atlas/country/DE/mark', entity: 'atlasCountry:DE', createdAt: 1 });
const sameEntity = await row({
method: 'DELETE',
url: '/addons/atlas/country/DE/mark',
entity: 'atlasCountry:DE',
createdAt: 2,
});
const otherEntity = await row({ url: '/addons/atlas/country/FR/mark', entity: 'atlasCountry:FR', createdAt: 3 });
await userMutationQueue.flushPass();
const parked = await get(refused.id);
expect(parked).toMatchObject({ status: 'failed', attempts: 1 });
expect(parked?.lastError).toContain('409');
expect(parked?.retryAfter).toBeUndefined();
expect((await get(sameEntity.id))?.status).toBe('pending');
expect(await get(otherEntity.id)).toBeUndefined();
});
it('FE-ATLAS2-DATA-055: a 404 on a POST is a refusal, not a success', async () => {
serve(() => HttpResponse.json({ error: 'missing' }, { status: 404 }));
const r = await row();
await userMutationQueue.flushPass();
expect((await get(r.id))?.status).toBe('failed');
});
it('FE-ATLAS2-DATA-056: a retryable status puts the row back in line and stops the pass', async () => {
serve(() => HttpResponse.json({ error: 'slow' }, { status: 408 }));
const first = await row({ attempts: 2, createdAt: 1 });
const second = await row({ createdAt: 2 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
const back = await get(first.id);
expect(back).toMatchObject({ status: 'pending', attempts: 3 });
expect(back?.lastError).toContain('408');
expect(back?.retryAfter).toBeUndefined();
expect((await get(second.id))?.status).toBe('pending');
});
it('FE-ATLAS2-DATA-057: a request that never reaches the server goes back in line and stops the pass', async () => {
serve(() => HttpResponse.error());
const first = await row({ createdAt: 1 });
await row({ createdAt: 2 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
expect(await get(first.id)).toMatchObject({ status: 'pending', attempts: 1 });
});
it('FE-ATLAS2-DATA-058: a server error is retried later with a growing gap and stops the pass', async () => {
serve(() => HttpResponse.json({ error: 'boom' }, { status: 500 }));
const before = Date.now();
const first = await row({ attempts: 2, createdAt: 1 });
await row({ createdAt: 2 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
const back = await get(first.id);
expect(back).toMatchObject({ status: 'pending', attempts: 3 });
// Third try: 30 s doubled twice.
expect(back?.retryAfter ?? 0).toBeGreaterThanOrEqual(before + SERVER_ERROR_BACKOFF_MS * 4);
expect(back?.retryAfter ?? 0).toBeLessThan(Date.now() + SERVER_ERROR_BACKOFF_MS * 4 + 1);
});
it('FE-ATLAS2-DATA-059: a server error on the last allowed try parks the write', async () => {
serve(() => HttpResponse.json({ error: 'boom' }, { status: 502 }));
const r = await row({ attempts: MAX_SERVER_ERROR_ATTEMPTS - 1 });
await userMutationQueue.flushPass();
expect(await get(r.id)).toMatchObject({ status: 'failed', attempts: MAX_SERVER_ERROR_ATTEMPTS });
});
});
describe('flushPass skips and stops', () => {
it('FE-ATLAS2-DATA-060: a row whose retry time has not come stops the pass before sending', async () => {
serve(() => HttpResponse.json({ success: true }));
const waiting = await row({ retryAfter: Date.now() + 60_000, createdAt: 1 });
await row({ createdAt: 2 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(0);
expect((await get(waiting.id))?.status).toBe('pending');
});
it('FE-ATLAS2-DATA-061: a row whose retry time has passed is sent', async () => {
serve(() => HttpResponse.json({ success: true }));
const r = await row({ retryAfter: Date.now() - 1 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
expect(await get(r.id)).toBeUndefined();
});
it('FE-ATLAS2-DATA-062: a row from a newer format is left alone and holds back its entity', async () => {
serve(() => HttpResponse.json({ success: true }));
const newer = await row({ schemaVersion: MUTATION_SCHEMA_VERSION + 1, entity: 'atlasCountry:DE', createdAt: 1 });
const behind = await row({ entity: 'atlasCountry:DE', createdAt: 2 });
const other = await row({ entity: 'atlasCountry:FR', url: '/addons/atlas/country/FR/mark', createdAt: 3 });
await userMutationQueue.flushPass();
expect(await get(newer.id)).toMatchObject({ status: 'pending', attempts: 0 });
expect((await get(behind.id))?.status).toBe('pending');
expect(await get(other.id)).toBeUndefined();
expect(sent.map((s) => s.path)).toEqual(['/api/addons/atlas/country/FR/mark']);
});
it('FE-ATLAS2-DATA-063: a row parked earlier holds back the later writes to its entity, an older one still goes', async () => {
serve(() => HttpResponse.json({ success: true }));
await row({ status: 'failed', entity: 'atlasCountry:DE', createdAt: 10 });
await row({ status: 'failed', entity: 'atlasCountry:DE', createdAt: 5 });
const older = await row({ entity: 'atlasCountry:DE', url: '/addons/atlas/country/DE/older', createdAt: 1 });
const later = await row({ entity: 'atlasCountry:DE', createdAt: 20 });
await userMutationQueue.flushPass();
expect(await get(older.id)).toBeUndefined();
expect((await get(later.id))?.status).toBe('pending');
expect(sent.map((s) => s.path)).toEqual(['/api/addons/atlas/country/DE/older']);
});
it('FE-ATLAS2-DATA-064: a row stuck on syncing past the limit is replayed, a fresh one is not', async () => {
serve(() => HttpResponse.json({ success: true }));
const stuck = await row({ status: 'syncing', syncingSince: Date.now() - STUCK_SYNCING_MS - 1000 });
const stuckUnstamped = await row({ status: 'syncing' });
const fresh = await row({ status: 'syncing', syncingSince: Date.now() + 60_000 });
await userMutationQueue.flushPass();
expect(await get(stuck.id)).toBeUndefined();
expect(await get(stuckUnstamped.id)).toBeUndefined();
expect((await get(fresh.id))?.status).toBe('syncing');
expect(sent).toHaveLength(2);
});
it('FE-ATLAS2-DATA-065: logged out or offline, a pass sends nothing', async () => {
serve(() => HttpResponse.json({ success: true }));
const r = await row();
setAuthed(false);
await userMutationQueue.flushPass();
setAuthed(true);
setForcedOffline(true);
await userMutationQueue.flushPass();
expect(sent).toHaveLength(0);
expect((await get(r.id))?.status).toBe('pending');
});
it('FE-ATLAS2-DATA-066: a logout during the pass stops it before the next row', async () => {
serve(() => {
setAuthed(false);
return HttpResponse.json({ success: true });
});
await row({ createdAt: 1 });
const second = await row({ createdAt: 2 });
await userMutationQueue.flushPass();
expect(sent).toHaveLength(1);
expect((await get(second.id))?.status).toBe('pending');
});
});
describe('count, retry, discard', () => {
it('FE-ATLAS2-DATA-067: count reads the rows in the given states', async () => {
await row({ status: 'pending' });
await row({ status: 'syncing' });
await row({ status: 'failed' });
expect(await userMutationQueue.count(['pending', 'syncing'])).toBe(2);
expect(await userMutationQueue.count(['failed'])).toBe(1);
});
it('FE-ATLAS2-DATA-068: retryFailed puts every parked row back in line from a fresh start', async () => {
const parked = await row({ status: 'failed', attempts: 8, lastError: 'x', retryAfter: 99 });
const pending = await row({ attempts: 2 });
await userMutationQueue.retryFailed();
expect(await get(parked.id)).toMatchObject({ status: 'pending', attempts: 0, lastError: null });
expect((await get(parked.id))?.retryAfter).toBeUndefined();
expect((await get(pending.id))?.attempts).toBe(2);
});
it('FE-ATLAS2-DATA-069: discardFailed drops the parked rows only', async () => {
const parked = await row({ status: 'failed' });
const pending = await row();
await userMutationQueue.discardFailed();
expect(await get(parked.id)).toBeUndefined();
expect(await get(pending.id)).toBeDefined();
});
});
describe('through the trip queue', () => {
it('FE-ATLAS2-DATA-070: the badge counts the account rows beside the trip rows', async () => {
await row({ status: 'pending' });
await row({ status: 'syncing' });
await row({ status: 'failed' });
expect(await mutationQueue.pendingCount()).toBe(2);
expect(await mutationQueue.failedCount()).toBe(1);
});
it('FE-ATLAS2-DATA-071: flush replays the account queue too', async () => {
serve(() => HttpResponse.json({ success: true }));
const r = await row();
await mutationQueue.flush();
expect(await get(r.id)).toBeUndefined();
expect(sent).toHaveLength(1);
});
it('FE-ATLAS2-DATA-072: retryFailed puts a parked account row back and sends it', async () => {
serve(() => HttpResponse.json({ success: true }));
const r = await row({ status: 'failed', attempts: 3 });
await mutationQueue.retryFailed();
expect(await get(r.id)).toBeUndefined();
expect(sent).toHaveLength(1);
});
it('FE-ATLAS2-DATA-073: discardFailed drops a parked account row and lets the one behind it go out', async () => {
serve(() => HttpResponse.json({ success: true }));
const parked = await row({ status: 'failed', entity: 'atlasCountry:DE', createdAt: 1 });
const behind = await row({ entity: 'atlasCountry:DE', createdAt: 2 });
await mutationQueue.discardFailed();
expect(await get(parked.id)).toBeUndefined();
expect(await get(behind.id)).toBeUndefined();
expect(sent).toHaveLength(1);
});
it('FE-ATLAS2-DATA-074: logged out, flush leaves the account queue alone', async () => {
serve(() => HttpResponse.json({ success: true }));
const r = await row();
setAuthed(false);
await mutationQueue.flush();
expect((await get(r.id))?.status).toBe('pending');
expect(sent).toHaveLength(0);
});
it('FE-ATLAS2-DATA-075: the trip queue reset also resets the account time counter', async () => {
vi.spyOn(Date, 'now').mockReturnValue(7);
const input = { method: 'POST' as const, url: '/x', ids: {}, body: null, resource: 'atlasCountry', entity: 'e' };
await userMutationQueue.enqueue({ ...input, id: 'p' });
await userMutationQueue.enqueue({ ...input, id: 'q' });
mutationQueue._resetFlushing();
await userMutationQueue.enqueue({ ...input, id: 'r' });
expect((await get('q'))?.createdAt).toBe(8);
expect((await get('r'))?.createdAt).toBe(7);
});
});
+191
View File
@@ -0,0 +1,191 @@
// FE-ATLAS2-REST-001 to 010: the View Transitions groundwork (canAnimate, settled, transitionTo).
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { canAnimate, settled, transitionTo } from './viewTransition';
interface FakeTransition {
ready: Promise<void>;
finished: Promise<void>;
updateCallbackDone: Promise<void>;
skipTransition: () => void;
}
/** A hand-made deferred, so a test decides when a transition finishes or is skipped. */
function deferred() {
let resolve: () => void = () => {};
let reject: (e: unknown) => void = () => {};
const promise = new Promise<void>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
interface Started {
update: () => Promise<void>;
done: Promise<void>;
finished: ReturnType<typeof deferred>;
ready: ReturnType<typeof deferred>;
}
let started: Started[] = [];
function installStart() {
const start = vi.fn((update: () => Promise<void>): FakeTransition => {
const finished = deferred();
const ready = deferred();
const done = update();
started.push({ update, done, finished, ready });
return { ready: ready.promise, finished: finished.promise, updateCallbackDone: done, skipTransition: vi.fn() };
});
Object.defineProperty(document, 'startViewTransition', { value: start, configurable: true, writable: true });
return start;
}
function stubReducedMotion(reduce: boolean) {
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => ({ matches: reduce && query.includes('reduce'), media: query }))
);
}
const flush = () => new Promise<void>((r) => setTimeout(r, 0));
beforeEach(() => {
started = [];
});
afterEach(() => {
delete (document as { startViewTransition?: unknown }).startViewTransition;
delete document.documentElement.dataset.routeTransition;
document.querySelectorAll('[data-route-fallback]').forEach((n) => n.remove());
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('canAnimate', () => {
it('FE-ATLAS2-REST-001: is false where the browser has no View Transitions', () => {
expect(canAnimate()).toBe(false);
});
it('FE-ATLAS2-REST-002: is true with View Transitions and motion allowed, false when reduced motion is asked', () => {
installStart();
stubReducedMotion(false);
expect(canAnimate()).toBe(true);
stubReducedMotion(true);
expect(canAnimate()).toBe(false);
});
});
describe('settled', () => {
it('FE-ATLAS2-REST-003: resolves at once while no loading placeholder is on screen', async () => {
let done = false;
void settled().then(() => {
done = true;
});
await Promise.resolve();
expect(done).toBe(true);
});
it('FE-ATLAS2-REST-004: waits while a route fallback shows and resolves once it is gone', async () => {
const fallback = document.createElement('div');
fallback.setAttribute('data-route-fallback', '');
document.body.appendChild(fallback);
let done = false;
const wait = settled().then(() => {
done = true;
});
await new Promise((r) => setTimeout(r, 40));
expect(done).toBe(false);
fallback.remove();
await wait;
expect(done).toBe(true);
});
it('FE-ATLAS2-REST-005: gives up waiting after the settle time even while the fallback stays', async () => {
const fallback = document.createElement('div');
fallback.setAttribute('data-route-fallback', '');
document.body.appendChild(fallback);
const clock = [0, 100, 1000];
vi.spyOn(performance, 'now').mockImplementation(() => clock.shift() ?? 1000);
let done = false;
const wait = settled().then(() => {
done = true;
});
await Promise.resolve();
expect(done).toBe(false);
await wait;
expect(done).toBe(true);
expect(document.querySelector('[data-route-fallback]')).not.toBeNull();
});
});
describe('transitionTo', () => {
it('FE-ATLAS2-REST-006: just runs the update without View Transitions and marks nothing', () => {
const update = vi.fn();
transitionTo('tab', update);
expect(update).toHaveBeenCalledTimes(1);
expect(document.documentElement.dataset.routeTransition).toBeUndefined();
});
it('FE-ATLAS2-REST-007: just runs the update when reduced motion is asked', () => {
const start = installStart();
stubReducedMotion(true);
const update = vi.fn();
transitionTo('tab', update);
expect(update).toHaveBeenCalledTimes(1);
expect(start).not.toHaveBeenCalled();
});
it('FE-ATLAS2-REST-008: runs the update inside a transition marked with its kind and clears the mark when it finishes', async () => {
const start = installStart();
stubReducedMotion(false);
const update = vi.fn();
transitionTo('fade', update);
expect(start).toHaveBeenCalledTimes(1);
expect(update).toHaveBeenCalledTimes(1);
expect(document.documentElement.dataset.routeTransition).toBe('fade');
await started[0].done;
started[0].ready.resolve();
started[0].finished.resolve();
await flush();
expect(document.documentElement.dataset.routeTransition).toBeUndefined();
});
it('FE-ATLAS2-REST-009: a skipped transition does not take the mark away from the newer one', async () => {
installStart();
stubReducedMotion(false);
transitionTo('forward', vi.fn());
transitionTo('back', vi.fn());
expect(document.documentElement.dataset.routeTransition).toBe('back');
// The first one was skipped by the second: its promises reject, which is no error.
started[0].ready.reject(new DOMException('skipped', 'AbortError'));
started[0].finished.reject(new DOMException('skipped', 'AbortError'));
await flush();
expect(document.documentElement.dataset.routeTransition).toBe('back');
started[1].finished.resolve();
await flush();
expect(document.documentElement.dataset.routeTransition).toBeUndefined();
});
it('FE-ATLAS2-REST-010: the update callback waits for the loading placeholder to go', async () => {
installStart();
stubReducedMotion(false);
const fallback = document.createElement('div');
fallback.setAttribute('data-route-fallback', '');
document.body.appendChild(fallback);
let updated = false;
transitionTo('tab', () => {
updated = true;
});
let callbackDone = false;
void started[0].done.then(() => {
callbackDone = true;
});
await new Promise((r) => setTimeout(r, 40));
expect(updated).toBe(true);
expect(callbackDone).toBe(false);
fallback.remove();
await started[0].done;
expect(callbackDone).toBe(true);
});
});
+114
View File
@@ -0,0 +1,114 @@
import { vi } from 'vitest';
import type { AtlasGlobeState } from '../../src/pages/atlas/useAtlasGlobe';
import { buildAtlasData } from './atlas';
/**
* A stand-in for what useAtlasGlobe hands the phone Atlas: every field the
* mobile globe, its sheets and the hub tabs read, with spies for the actions.
* `t` echoes the key, followed by the parameter values, so a test names the
* contract rather than a locale string.
*/
export const echoT = (key: string, params?: Record<string, unknown>): string =>
params ? `${key}:${Object.values(params).join(',')}` : key;
/** A country's name as the fake resolves it: Iceland by its name, the rest as name-XX. */
export const fakeResolveName = (a2: string): string => (a2 === 'IS' ? 'Iceland' : `name-${a2}`);
export function buildBucketState(over: Record<string, unknown> = {}): Record<string, unknown> {
return {
bucketList: [],
setBucketList: vi.fn(),
showBucketAdd: false,
setShowBucketAdd: vi.fn(),
bucketForm: { name: '', notes: '', lat: '', lng: '', target_date: '' },
setBucketForm: vi.fn(),
bucketPoiYear: 0,
setBucketPoiYear: vi.fn(),
bucketPoiMonth: 0,
setBucketPoiMonth: vi.fn(),
resetBucketAdd: vi.fn(),
handleSelectBucketPoi: vi.fn(),
handleAddBucketItem: vi.fn(async () => undefined),
handleDeleteBucketItem: vi.fn(async () => undefined),
handleClearBucketVisit: vi.fn(async () => undefined),
...over,
};
}
export function buildGlobeState(over: Record<string, unknown> = {}): AtlasGlobeState {
const base: Record<string, unknown> = {
t: echoT,
language: 'en',
placeLang: 'en',
data: buildAtlasData(),
setData: vi.fn(),
totals: { countries: 1, continents: 1, regions: 0 },
badges: [],
resolveName: fakeResolveName,
// the hub
passportOpen: false,
setPassportOpen: vi.fn(),
passportTab: 'overview',
setPassportTab: vi.fn(),
openPassport: vi.fn(),
// dawarich
dawarichEnabled: false,
dawarichSub: 'wishes',
openDawarich: vi.fn(),
reload: vi.fn(async () => undefined),
// travellers
compareEnabled: false,
loadPeople: vi.fn(),
people: null,
ranking: null,
me: null,
hidden: false,
setHidden: vi.fn(),
profile: null,
setProfileId: vi.fn(),
startCompare: vi.fn(),
compareWith: null,
gaps: false,
setGaps: vi.fn(),
stopCompare: vi.fn(),
// the wishlist
bucketState: buildBucketState(),
bucket: [],
setBucket: vi.fn(),
handleDeleteBucketItem: vi.fn(async () => undefined),
flyToPoint: vi.fn(),
// country dialogs
confirmAction: null,
setConfirmAction: vi.fn(),
executeConfirmAction: vi.fn(async () => undefined),
closeDialogs: vi.fn(),
regions: {},
setRegions: vi.fn(),
detail: null,
progress: null,
askUnmarkDetail: vi.fn(),
// layers
showPlanned: false,
setShowPlanned: vi.fn(),
flights: null,
showFlights: false,
setShowFlights: vi.fn(),
pluginLayers: [],
hiddenPluginLayers: new Set<string>(),
togglePluginLayer: vi.fn(),
colorMode: 'country',
setColorMode: vi.fn(),
// the globe itself
fetchJson: vi.fn(),
labelFor: vi.fn(),
labelRegionsOf: vi.fn(),
paint: vi.fn(),
paintKey: 'k',
onSelect: vi.fn(),
onReady: vi.fn(),
setError: vi.fn(),
pins: [],
};
return { ...base, ...over } as unknown as AtlasGlobeState;
}
+122
View File
@@ -0,0 +1,122 @@
import type { Badge } from '@trek/shared';
import { vi } from 'vitest';
import type { AtlasGlobeState } from '../../src/pages/atlas/useAtlasGlobe';
/**
* Fakes for the hub tabs, dialogs and overlays of the globe Atlas. Each view
* reads a few fields of the one state object useAtlasGlobe returns, so a test
* builds it here with neutral values and fresh spies, and overrides only the
* fields it is about.
*/
/** t() that shows its params, so a test can see which key was asked with what. */
export function viewT(key: string, params?: Record<string, unknown>): string {
if (!params) return key;
return `${key}[${Object.entries(params)
.map(([k, v]) => `${k}=${String(v)}`)
.join(',')}]`;
}
export interface ViewBucketForm {
name: string;
notes: string;
lat: string;
lng: string;
target_date: string;
address?: string;
}
export function viewBadge(over: Partial<Badge> = {}): Badge {
return {
id: 'countries-5',
category: 'countries',
motif: 'countries',
tier: 'bronze',
titleKey: 'atlas.badge.countries.title',
descKey: 'atlas.badge.countries.desc',
earned: false,
current: 2,
target: 5,
...over,
};
}
export function viewBucket(over: Record<string, unknown> = {}): Record<string, unknown> {
return {
bucketForm: { name: '', notes: '', lat: '', lng: '', target_date: '' } as ViewBucketForm,
setBucketForm: vi.fn(),
bucketPoiYear: 0,
setBucketPoiYear: vi.fn(),
bucketPoiMonth: 0,
setBucketPoiMonth: vi.fn(),
handleSelectBucketPoi: vi.fn(),
handleAddBucketItem: vi.fn(async () => undefined),
resetBucketAdd: vi.fn(),
...over,
};
}
export function viewState(over: Record<string, unknown> = {}): AtlasGlobeState {
const base: Record<string, unknown> = {
t: viewT,
language: 'en',
placeLang: 'en',
data: null,
manifest: null,
error: null,
retryLoad: vi.fn(),
totals: { countries: 0, continents: 0, regions: 0, trips: 0, firstYear: null, perYear: new Map<number, number>() },
year: null,
setYear: vi.fn(),
timelineOpen: false,
setTimelineOpen: vi.fn(),
bucketState: viewBucket(),
bucket: [],
setBucket: vi.fn(),
regions: {},
setRegions: vi.fn(),
setData: vi.fn(),
confirmAction: null,
setConfirmAction: vi.fn(),
executeConfirmAction: vi.fn(async () => undefined),
bucketMonth: 0,
setBucketMonth: vi.fn(),
bucketYear: 0,
setBucketYear: vi.fn(),
handleDeleteBucketItem: vi.fn(async () => undefined),
askUnmarkDetail: vi.fn(),
detail: null,
progress: null,
closeDialogs: vi.fn(),
resolveName: (code: string) => `name-${code}`,
showPlanned: false,
setShowPlanned: vi.fn(),
flights: null,
showFlights: false,
setShowFlights: vi.fn(),
colorMode: 'country',
setColorMode: vi.fn(),
pluginLayers: [],
hiddenPluginLayers: new Set<string>(),
togglePluginLayer: vi.fn(),
badges: [] as Badge[],
passportOpen: false,
setPassportOpen: vi.fn(),
passportTab: 'overview',
setPassportTab: vi.fn(),
openPassport: vi.fn(),
profile: null,
profileId: null,
setProfileId: vi.fn(),
startCompare: vi.fn(),
dawarichEnabled: false,
compareEnabled: false,
openDawarich: vi.fn(),
loadPeople: vi.fn(),
ranking: null,
me: null,
hidden: false,
setHidden: vi.fn(),
};
return { ...base, ...over } as unknown as AtlasGlobeState;
}
+93
View File
@@ -0,0 +1,93 @@
import type { Badge } from '@trek/shared';
import { vi } from 'vitest';
import type { AtlasGlobeState } from '../../src/pages/atlas/useAtlasGlobe';
import { buildAtlasData } from './atlas';
/**
* Fakes for the desktop globe Atlas surfaces (view, search, badges, wishlist,
* Dawarich tab, badge unlock). They all read one big state object from
* useAtlasGlobe; a test builds only the slice its surface reads, with fresh
* spies every call (the suite keeps mock history between tests).
*/
/** A translator that shows the key and its named params, so a test can read both. */
export function viewT(key: string, params?: Record<string, unknown>): string {
const parts = Object.entries(params ?? {}).map(([k, v]) => `${k}=${String(v)}`);
if (!parts.length) return key;
return `${key}(${parts.join(',')})`;
}
const NAMES: Record<string, string> = { FR: 'France', JP: 'Japan', DE: 'Germany', IT: 'Italy', US: 'United States' };
export function buildViewBadge(over: Partial<Badge> = {}): Badge {
return {
id: 'countries-5',
category: 'countries',
motif: 'countries',
tier: 'bronze',
titleKey: 'atlas.badge.countries.title',
descKey: 'atlas.badge.countries.desc',
earned: false,
current: 2,
target: 5,
...over,
};
}
/** The globe state with harmless defaults; `over` replaces any field. */
export function buildViewState(over: Record<string, unknown> = {}): AtlasGlobeState {
const base: Record<string, unknown> = {
t: vi.fn(viewT),
language: 'en',
data: buildAtlasData(),
manifest: { countries: [], attribution: [] },
regions: {},
badges: [] as Badge[],
me: { id: 7 },
people: null,
compareEnabled: false,
loadPeople: vi.fn(),
resolveName: vi.fn((a2: string) => NAMES[a2] ?? ''),
// search
query: '',
setQuery: vi.fn(),
results: [],
pickResult: vi.fn(),
placeHits: [],
placesLoading: false,
pickPlace: vi.fn(async () => undefined),
loadRegionSearch: vi.fn(),
// wishlist / dawarich
bucketState: {
bucketList: [],
showBucketAdd: false,
setShowBucketAdd: vi.fn(),
handleClearBucketVisit: vi.fn(async () => undefined),
handleDeleteBucketItem: vi.fn(async () => undefined),
},
dawarichEnabled: false,
dawarichSub: 'wishes',
openDawarich: vi.fn(),
reload: vi.fn(async () => undefined),
flyToPoint: vi.fn(),
// globe view
pins: [],
hover: null,
compareWith: null,
gaps: false,
setGaps: vi.fn(),
stopCompare: vi.fn(),
setError: vi.fn(),
zoomIn: vi.fn(),
zoomOut: vi.fn(),
fetchJson: vi.fn(),
labelFor: vi.fn(),
labelRegionsOf: vi.fn(),
paint: vi.fn(),
paintKey: 'k',
onHover: vi.fn(),
onSelect: vi.fn(),
onReady: vi.fn(),
};
return { ...base, ...over } as unknown as AtlasGlobeState;
}
+340
View File
@@ -0,0 +1,340 @@
import { vi } from 'vitest';
/**
* A hand-written stand-in for WebGL2RenderingContext, for the Atlas globe
* renderer. jsdom has no WebGL, so this fake keeps just enough state to tell
* what the renderer asked for: which program and vertex array a draw ran with,
* the uniform values each program held at that moment, which buffers were
* created, filled and deleted, and what went into the status textures.
*
* Uniforms and attributes are read from the GLSL sources the renderer links,
* so a uniform the renderer sets but no shader declares shows up as a call
* with an undefined location.
*/
export interface FakeShader {
kind: 'shader';
type: number;
src: string;
}
export type UniformValue = number | number[];
export interface FakeProgram {
kind: 'program';
id: number;
srcs: string[];
uniforms: string[];
attribs: string[];
attribLoc: Map<string, number>;
values: Record<string, UniformValue>;
}
export interface FakeUniformLoc {
kind: 'uniform';
name: string;
program: FakeProgram;
}
export interface FakeObject {
kind: 'buffer' | 'vao' | 'texture' | 'framebuffer';
id: number;
data?: ArrayBufferView | null;
}
export interface FakeDraw {
call: 'drawElements' | 'drawArrays' | 'drawArraysInstanced';
program: FakeProgram | null;
vao: FakeObject | null;
framebuffer: FakeObject | null;
mode: number;
count: number;
instances: number;
values: Record<string, UniformValue>;
}
export interface FakeGlOptions {
/** Whether a shader with this source compiles. Default: all do. */
compileOk?: (src: string) => boolean;
shaderLog?: string | null;
linkOk?: boolean;
programLog?: string | null;
/**
* Location of an attribute of the program with this fragment shader; null
* leaves it out of the active list (as a compiler drops an unused one).
*/
attribLocation?: (fs: string, name: string, index: number) => number | null;
/** RGBA the pick pass reads back. */
pixel?: [number, number, number, number];
}
export const GL = {
COMPILE_STATUS: 0x8b81,
LINK_STATUS: 0x8b82,
ACTIVE_UNIFORMS: 0x8b86,
ACTIVE_ATTRIBUTES: 0x8b89,
VERTEX_SHADER: 0x8b31,
FRAGMENT_SHADER: 0x8b30,
ARRAY_BUFFER: 0x8892,
ELEMENT_ARRAY_BUFFER: 0x8893,
STATIC_DRAW: 0x88e4,
TEXTURE_2D: 0x0de1,
RGBA8: 0x8058,
RGBA: 0x1908,
UNSIGNED_BYTE: 0x1401,
TEXTURE_MIN_FILTER: 0x2801,
TEXTURE_MAG_FILTER: 0x2800,
NEAREST: 0x2600,
FLOAT: 0x1406,
DEPTH_TEST: 0x0b71,
BLEND: 0x0be2,
SRC_ALPHA: 0x0302,
ONE_MINUS_SRC_ALPHA: 0x0303,
ONE: 1,
TRIANGLES: 4,
TRIANGLE_STRIP: 5,
TEXTURE0: 0x84c0,
TEXTURE1: 0x84c1,
UNSIGNED_INT: 0x1405,
FRAMEBUFFER: 0x8d40,
COLOR_ATTACHMENT0: 0x8ce0,
COLOR_BUFFER_BIT: 0x4000,
} as const;
const UNIFORM_RE = /^\s*uniform\s+\w+\s+(\w+)\s*;/gm;
const ATTRIB_RE = /^in\s+\w+\s+(a_\w+)\s*;/gm;
function namesOf(re: RegExp, src: string): string[] {
const out: string[] = [];
for (const m of src.matchAll(re)) if (!out.includes(m[1])) out.push(m[1]);
return out;
}
export function createFakeGl(opts: FakeGlOptions = {}) {
let nextId = 1;
const make = (kind: FakeObject['kind']): FakeObject => ({ kind, id: nextId++ });
const programs: FakeProgram[] = [];
const draws: FakeDraw[] = [];
const buffers: FakeObject[] = [];
const textures: FakeObject[] = [];
const framebuffers: FakeObject[] = [];
const bound = new Map<number, FakeObject | null>();
const statusUploads: Uint8Array[] = [];
const enabled = new Set<number>();
let program: FakeProgram | null = null;
let vao: FakeObject | null = null;
let fbo: FakeObject | null = null;
const store = (loc: FakeUniformLoc | null | undefined, v: UniformValue): void => {
if (loc) loc.program.values[loc.name] = v;
};
const record = (call: FakeDraw['call'], mode: number, count: number, instances: number): void => {
draws.push({
call,
program,
vao,
framebuffer: fbo,
mode,
count,
instances,
values: program ? { ...program.values } : {},
});
};
const gl = {
...GL,
createShader: vi.fn((type: number): FakeShader => ({ kind: 'shader', type, src: '' })),
shaderSource: vi.fn((s: FakeShader, src: string) => {
s.src = src;
}),
compileShader: vi.fn((_s: FakeShader) => undefined),
getShaderParameter: vi.fn((s: FakeShader, pname: number) =>
pname === GL.COMPILE_STATUS ? (opts.compileOk ? opts.compileOk(s.src) : true) : null
),
getShaderInfoLog: vi.fn(() => (opts.shaderLog === undefined ? 'shader log' : opts.shaderLog)),
deleteShader: vi.fn((_s: FakeShader) => undefined),
createProgram: vi.fn((): FakeProgram => {
const p: FakeProgram = {
kind: 'program',
id: nextId++,
srcs: [],
uniforms: [],
attribs: [],
attribLoc: new Map(),
values: {},
};
programs.push(p);
return p;
}),
attachShader: vi.fn((p: FakeProgram, s: FakeShader) => {
p.srcs.push(s.src);
}),
linkProgram: vi.fn((p: FakeProgram) => {
const [vs = '', fs = ''] = p.srcs;
p.uniforms = namesOf(UNIFORM_RE, `${vs}\n${fs}`);
namesOf(ATTRIB_RE, vs).forEach((name, i) => {
const loc = opts.attribLocation ? opts.attribLocation(fs, name, i) : i;
if (loc === null) return;
p.attribs.push(name);
p.attribLoc.set(name, loc);
});
}),
getProgramParameter: vi.fn((p: FakeProgram, pname: number) => {
if (pname === GL.LINK_STATUS) return opts.linkOk ?? true;
// One more than there are, so the renderer meets a null info as well.
if (pname === GL.ACTIVE_UNIFORMS) return p.uniforms.length + 1;
if (pname === GL.ACTIVE_ATTRIBUTES) return p.attribs.length + 1;
return null;
}),
getProgramInfoLog: vi.fn(() => (opts.programLog === undefined ? 'program log' : opts.programLog)),
getActiveUniform: vi.fn((p: FakeProgram, i: number) =>
i < p.uniforms.length ? { name: p.uniforms[i], size: 1, type: 0 } : null
),
getUniformLocation: vi.fn((p: FakeProgram, name: string): FakeUniformLoc => ({
kind: 'uniform',
name,
program: p,
})),
getActiveAttrib: vi.fn((p: FakeProgram, i: number) =>
i < p.attribs.length ? { name: p.attribs[i], size: 1, type: 0 } : null
),
getAttribLocation: vi.fn((p: FakeProgram, name: string) => p.attribLoc.get(name) ?? -1),
createBuffer: vi.fn(() => {
const b = make('buffer');
buffers.push(b);
return b;
}),
bindBuffer: vi.fn((target: number, b: FakeObject | null) => {
bound.set(target, b);
}),
bufferData: vi.fn((target: number, data: ArrayBufferView) => {
const b = bound.get(target);
if (b) b.data = data;
}),
deleteBuffer: vi.fn((_b: FakeObject | null) => undefined),
createVertexArray: vi.fn(() => make('vao')),
bindVertexArray: vi.fn((v: FakeObject | null) => {
vao = v;
}),
deleteVertexArray: vi.fn((_v: FakeObject | null) => undefined),
enableVertexAttribArray: vi.fn((_loc: number) => undefined),
vertexAttribPointer: vi.fn(
(_loc: number, _size: number, _type: number, _normalized: boolean, _stride: number, _offset: number) => undefined
),
vertexAttribDivisor: vi.fn((_loc: number, _divisor: number) => undefined),
vertexAttrib2f: vi.fn((_loc: number | undefined, _x: number, _y: number) => undefined),
createTexture: vi.fn(() => {
const t = make('texture');
textures.push(t);
return t;
}),
bindTexture: vi.fn((target: number, t: FakeObject | null) => {
bound.set(target, t);
}),
texImage2D: vi.fn(
(
_target: number,
_level: number,
_internal: number,
_w: number,
_h: number,
_border: number,
_format: number,
_type: number,
_data: ArrayBufferView | null
) => undefined
),
texParameteri: vi.fn((_target: number, _pname: number, _value: number) => undefined),
texSubImage2D: vi.fn(
(
_target: number,
_level: number,
_x: number,
_y: number,
_w: number,
_h: number,
_format: number,
_type: number,
data: Uint8Array
) => {
statusUploads.push(data.slice());
}
),
activeTexture: vi.fn((_unit: number) => undefined),
deleteTexture: vi.fn((_t: FakeObject | null) => undefined),
createFramebuffer: vi.fn(() => {
const f = make('framebuffer');
framebuffers.push(f);
return f;
}),
bindFramebuffer: vi.fn((_target: number, f: FakeObject | null) => {
fbo = f;
}),
framebufferTexture2D: vi.fn(
(_target: number, _attachment: number, _texTarget: number, _t: FakeObject | null, _level: number) => undefined
),
deleteFramebuffer: vi.fn((_f: FakeObject | null) => undefined),
useProgram: vi.fn((p: FakeProgram | null) => {
program = p;
}),
uniform1f: vi.fn((loc: FakeUniformLoc | null | undefined, v: number) => store(loc, v)),
uniform1i: vi.fn((loc: FakeUniformLoc | null | undefined, v: number) => store(loc, v)),
uniform2f: vi.fn((loc: FakeUniformLoc | null | undefined, a: number, b: number) => store(loc, [a, b])),
uniform4f: vi.fn((loc: FakeUniformLoc | null | undefined, a: number, b: number, c: number, d: number) =>
store(loc, [a, b, c, d])
),
uniform3fv: vi.fn((loc: FakeUniformLoc | null | undefined, v: ArrayLike<number>) => store(loc, Array.from(v))),
uniform4fv: vi.fn((loc: FakeUniformLoc | null | undefined, v: ArrayLike<number>) => store(loc, Array.from(v))),
viewport: vi.fn((_x: number, _y: number, _w: number, _h: number) => undefined),
enable: vi.fn((cap: number) => {
enabled.add(cap);
}),
disable: vi.fn((cap: number) => {
enabled.delete(cap);
}),
blendFuncSeparate: vi.fn((_a: number, _b: number, _c: number, _d: number) => undefined),
clearColor: vi.fn((_r: number, _g: number, _b: number, _a: number) => undefined),
clear: vi.fn((_mask: number) => undefined),
drawArrays: vi.fn((mode: number, _first: number, count: number) => record('drawArrays', mode, count, 1)),
drawElements: vi.fn((mode: number, count: number) => record('drawElements', mode, count, 1)),
drawArraysInstanced: vi.fn((mode: number, _first: number, count: number, instances: number) =>
record('drawArraysInstanced', mode, count, instances)
),
readPixels: vi.fn(
(_x: number, _y: number, _w: number, _h: number, _format: number, _type: number, px: Uint8Array) => {
if (opts.pixel) px.set(opts.pixel);
}
),
};
return {
gl,
programs,
draws,
buffers,
textures,
framebuffers,
statusUploads,
enabled,
/** The program linked with this fragment shader. */
programWith(fs: string): FakeProgram {
const p = programs.find((x) => x.srcs[1] === fs);
if (!p) throw new Error('no program with that fragment shader');
return p;
},
/** Draws run with the program of this fragment shader. */
drawsWith(fs: string): FakeDraw[] {
return draws.filter((d) => d.program?.srcs[1] === fs);
},
/** The buffer that was filled with exactly this array. */
bufferOf(data: ArrayBufferView): FakeObject | undefined {
return buffers.find((b) => b.data === data);
},
canvas(): HTMLCanvasElement {
return { getContext: vi.fn(() => gl) } as unknown as HTMLCanvasElement;
},
};
}
export type FakeGl = ReturnType<typeof createFakeGl>;
@@ -0,0 +1,63 @@
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import MAdminAddonManager from '../../../../src/mobile/screens/admin/MAdminAddonManager';
import { useAddonStore } from '../../../../src/store/addonStore';
import { useAuthStore } from '../../../../src/store/authStore';
import { useSettingsStore } from '../../../../src/store/settingsStore';
import { buildSettings } from '../../../helpers/factories';
import { server } from '../../../helpers/msw/server';
import { render, screen, waitFor } from '../../../helpers/render';
import { resetAllStores, seedStore } from '../../../helpers/store';
// FE-ATLAS2-REST-050 to 052: the Atlas ranking row under the Atlas addon on the phone admin screen.
const RANKING = 'Ranking and profiles';
function atlasAddon(enabled: boolean) {
return { id: 'atlas', name: 'Atlas', description: 'World map', icon: 'Globe', type: 'trip', enabled };
}
beforeEach(() => {
resetAllStores();
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }) });
useAuthStore.setState({ atlasCompareEnabled: false });
vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('MAdminAddonManager: Atlas ranking', () => {
it('FE-ATLAS2-REST-050: an enabled Atlas shows the ranking switch, off as the app config says', async () => {
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })));
render(<MAdminAddonManager />);
const toggle = await screen.findByRole('switch', { name: RANKING });
expect(toggle).toHaveAttribute('aria-checked', 'false');
});
it('FE-ATLAS2-REST-051: the switch stays away while Atlas itself is off', async () => {
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(false)] })));
render(<MAdminAddonManager />);
await waitFor(() => expect(screen.getAllByRole('switch').length).toBeGreaterThan(0));
expect(screen.queryByRole('switch', { name: RANKING })).not.toBeInTheDocument();
});
it('FE-ATLAS2-REST-052: flipping it saves atlas_compare_enabled and shows it on', 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(<MAdminAddonManager />);
await user.click(await screen.findByRole('switch', { name: RANKING }));
await waitFor(() => expect(bodies).toEqual([{ atlas_compare_enabled: true }]));
await waitFor(() => expect(screen.getByRole('switch', { name: RANKING })).toHaveAttribute('aria-checked', 'true'));
expect(useAuthStore.getState().atlasCompareEnabled).toBe(true);
});
});
@@ -0,0 +1,141 @@
/**
* AtlasFlightsService: the Atlas flight map read through the user's own flight
* endpoints, and the folding rules of aggregateFlights the older
* atlas-flights.test.ts leaves open (airports without a code, endpoints without
* coordinates, dates on either end of a leg, the order of routes and airports).
*/
import { ReservationEndpoints } from '../../../src/db/entities/ReservationEndpoints.entity';
import { AtlasFlightsService, aggregateFlights, greatCircleKm } from '../../../src/nest/atlas/atlas-flights.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { getRepositoryToken } from '@mikro-orm/nestjs';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
type Row = Parameters<typeof aggregateFlights>[0][number];
const FRA = { code: 'FRA', name: 'Frankfurt', lat: 50.033, lng: 8.57 };
const JFK = { code: 'JFK', name: 'New York JFK', lat: 40.641, lng: -73.778 };
const LHR = { code: 'LHR', name: 'London Heathrow', lat: 51.47, lng: -0.4543 };
const row = (
reservation_id: number,
at: Omit<Row, 'reservation_id' | 'local_date'>,
local_date: string | null = null,
) => ({
reservation_id,
...at,
local_date,
});
const db = createSnapshotTestDb();
let t: TestModule;
let service: AtlasFlightsService;
const endpoints = {
listOwnedFlightRoutesForUser: vi.fn(async () => [
{ ...row(1, FRA, '2024-05-01'), sequence: 0 },
{ ...row(1, JFK), sequence: 1 },
]),
};
beforeAll(async () => {
t = await createTestModule({
db,
imports: [],
providers: [AtlasFlightsService, { provide: getRepositoryToken(ReservationEndpoints), useValue: endpoints }],
});
service = t.get(AtlasFlightsService);
});
afterAll(async () => {
await t.close();
db.close();
});
describe('AtlasFlightsService', () => {
it("ATLAS2-REST-020: reads the user's own flight endpoints and folds them into the map", async () => {
const map = await service.flights(9);
expect(endpoints.listOwnedFlightRoutesForUser).toHaveBeenCalledWith(9);
expect(map.routes).toHaveLength(1);
expect(map.routes[0]).toMatchObject({
a: { code: 'FRA' },
b: { code: 'JFK' },
count: 1,
firstDate: '2024-05-01',
lastDate: '2024-05-01',
km: Math.round(greatCircleKm(FRA, JFK)),
});
expect(map.totals).toEqual({
flights: 1,
km: Math.round(greatCircleKm(FRA, JFK)),
airports: 2,
longestKm: Math.round(greatCircleKm(FRA, JFK)),
});
});
});
describe('aggregateFlights', () => {
it('ATLAS2-REST-021: nothing to fold is an empty map', () => {
expect(aggregateFlights([])).toEqual({
routes: [],
airports: [],
totals: { flights: 0, km: 0, airports: 0, longestKm: 0 },
});
});
it('ATLAS2-REST-022: an airport without a code is known by its rounded position, the same spot twice is one airport', () => {
const field = { code: null, name: 'Airstrip', lat: 47.123, lng: 11.456 };
const sameField = { code: null, name: 'Airstrip (again)', lat: 47.1249, lng: 11.4551 };
const r = aggregateFlights([row(1, FRA), row(1, field), row(2, sameField), row(2, FRA)]);
expect(r.routes).toHaveLength(1);
expect(r.routes[0].count).toBe(2);
expect(r.airports).toHaveLength(2);
expect(r.airports.find((a) => a.code === null)).toMatchObject({ name: 'Airstrip', count: 2 });
// A lowercase code is the same airport as its uppercase spelling.
const lower = aggregateFlights([row(3, { ...FRA, code: 'fra' }), row(3, JFK), row(4, JFK), row(4, FRA)]);
expect(lower.routes).toHaveLength(1);
expect(lower.airports).toHaveLength(2);
});
it('ATLAS2-REST-023: skips a leg with an endpoint that has no coordinates', () => {
const nowhere = { code: 'XXX', name: 'Unknown', lat: Number.NaN, lng: Number.NaN };
expect(aggregateFlights([row(1, FRA), row(1, nowhere)]).totals.flights).toBe(0);
expect(aggregateFlights([row(1, nowhere), row(1, FRA)]).totals.flights).toBe(0);
});
it('ATLAS2-REST-024: a leg dated only on its arrival takes that date, an undated leg leaves the dates as they are', () => {
const r = aggregateFlights([
row(1, FRA, null),
row(1, LHR, '2021-07-04'),
row(2, LHR, null),
row(2, FRA, null),
row(3, FRA, '2020-01-01'),
row(3, LHR, null),
]);
expect(r.routes).toHaveLength(1);
expect(r.routes[0]).toMatchObject({ count: 3, firstDate: '2020-01-01', lastDate: '2021-07-04' });
});
it('ATLAS2-REST-025: an undated first leg takes the first date a later leg brings', () => {
const r = aggregateFlights([row(1, FRA), row(1, LHR), row(2, LHR, '2022-02-02'), row(2, FRA)]);
expect(r.routes[0]).toMatchObject({ firstDate: '2022-02-02', lastDate: '2022-02-02', count: 2 });
});
it('ATLAS2-REST-026: routes and airports come busiest first, the totals sum every leg', () => {
const r = aggregateFlights([
row(1, FRA),
row(1, LHR),
row(2, FRA),
row(2, JFK),
row(3, JFK),
row(3, FRA),
row(4, FRA),
row(4, JFK),
]);
expect(r.routes.map((x) => `${x.a.code}-${x.b.code}:${x.count}`)).toEqual(['FRA-JFK:3', 'FRA-LHR:1']);
expect(r.airports.map((a) => `${a.code}:${a.count}`)).toEqual(['FRA:4', 'JFK:3', 'LHR:1']);
expect(r.totals.flights).toBe(4);
expect(r.totals.airports).toBe(3);
expect(r.totals.km).toBe(Math.round(3 * greatCircleKm(FRA, JFK) + greatCircleKm(FRA, LHR)));
});
});
@@ -0,0 +1,125 @@
/**
* AtlasMeshController, the cases atlas-mesh.controller.test.ts leaves open: a
* read that breaks after the first bytes went out, the world files sent from
* the mesh root, and the manifest sent without ranges.
*/
import { AtlasMeshController } from '../../../src/nest/atlas/atlas-mesh.controller';
import type { Response } from 'express';
import fs from 'node:fs';
import { PassThrough, Readable } from 'node:stream';
import zlib from 'node:zlib';
import { afterEach, describe, expect, it, vi } from 'vitest';
/** A writable stand-in for express's Response that records what the controller does with it. */
class FakeResponse extends PassThrough {
headers: Record<string, string> = {};
sent: { name: string; options: Record<string, unknown> } | null = null;
statusCode = 200;
headersSent = false;
body = '';
destroyedWith: Error | null = null;
constructor() {
super();
this.on('data', (chunk: Buffer) => {
this.headersSent = true;
this.body += chunk.toString('utf8');
});
}
setHeader(name: string, value: string): this {
this.headers[name] = value;
return this;
}
sendFile(name: string, options: Record<string, unknown>): void {
this.sent = { name, options };
}
status(code: number): this {
this.statusCode = code;
return this;
}
override destroy(error?: Error): this {
this.destroyedWith = error ?? null;
return super.destroy(error);
}
}
const FILE = 'world-50m.0123456789ab.json';
const asRes = (r: FakeResponse) => r as unknown as Response;
afterEach(() => vi.restoreAllMocks());
describe('AtlasMeshController streaming', () => {
const controller = new AtlasMeshController();
it('ATLAS2-REST-030: a read that breaks after bytes went out ends the connection instead of a 500', async () => {
const json = JSON.stringify({ type: 'Topology', objects: { land: { type: 'GeometryCollection' } } });
const packed = zlib.brotliCompressSync(Buffer.from(json));
async function* brokenAfterFirstChunk() {
yield packed;
await new Promise((r) => setTimeout(r, 30));
throw new Error('disk went away');
}
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
vi.spyOn(fs, 'createReadStream').mockReturnValue(
Readable.from(brokenAfterFirstChunk()) as unknown as fs.ReadStream,
);
const res = new FakeResponse();
// The fake swallows the error it is destroyed with, as a socket's close would.
res.on('error', () => undefined);
const closed = new Promise<void>((resolve) => res.on('close', resolve));
controller.world(FILE, 'gzip, deflate', asRes(res));
await closed;
expect(res.body).toBe(json);
expect(res.statusCode).toBe(200);
expect(res.destroyedWith?.message).toBe('disk went away');
});
it('ATLAS2-REST-031: a world file goes out of the mesh root itself, without ranges or last-modified', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
const res = new FakeResponse();
controller.world(FILE, 'br', asRes(res));
expect(res.headers['Content-Encoding']).toBe('br');
expect(res.headers['Content-Type']).toBe('application/json; charset=utf-8');
expect(res.sent?.name).toBe(`${FILE}.br`);
expect(String(res.sent?.options.root)).toMatch(/atlas-mesh$/);
expect(res.sent?.options).toMatchObject({ acceptRanges: false, lastModified: false });
});
it('ATLAS2-REST-032: the manifest is sent from the mesh root without ranges', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
const res = new FakeResponse();
controller.manifest(asRes(res));
expect(String(res.sent?.options.root)).toMatch(/atlas-mesh$/);
expect(res.sent?.options).toMatchObject({ acceptRanges: false });
});
it('ATLAS2-REST-033: "br" must stand as a word in Accept-Encoding, not inside another token', async () => {
const json = '{"ok":true}';
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
vi.spyOn(fs, 'createReadStream').mockReturnValue(
Readable.from([zlib.brotliCompressSync(Buffer.from(json))]) as unknown as fs.ReadStream,
);
const res = new FakeResponse();
const done = new Promise<void>((resolve) => {
res.on('finish', resolve);
res.on('close', resolve);
});
controller.regions('FR.0123456789ab.json', 'xbrx', asRes(res));
await done;
expect(res.headers['Content-Encoding']).toBeUndefined();
expect(res.body).toBe(json);
});
});
@@ -0,0 +1,199 @@
/**
* AtlasPeopleService over a built globe manifest: the region totals of the
* "x of n" badges come from the manifest's `counted` per country, read once and
* kept. The rest covers the shapes the Atlas reads answer with: a status left
* out counts as visited, a country without a first visit has no year, a flight
* route over the antimeridian earns the date line, and the opt-out setting is
* read in every spelling the settings store hands back.
*
* The manifest is read once per process, so this file is the one that sees it
* built; atlas-people.no-manifest.test.ts sees it missing.
*/
import { AtlasFlightsService } from '../../../src/nest/atlas/atlas-flights.service';
import { AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service';
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import fs from 'node:fs';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let people: AtlasPeopleService;
const MANIFEST = JSON.stringify({ regions: { FR: { counted: 6 }, DE: { counted: 16 } } });
const realRead = fs.readFileSync.bind(fs);
const manifestReads = vi.fn();
vi.spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, options?: unknown) => {
if (String(file).replace(/\\/g, '/').endsWith('assets/atlas-mesh/manifest.json')) {
manifestReads();
return MANIFEST;
}
return realRead(file, options as BufferEncoding);
}) as unknown as typeof fs.readFileSync);
let userSettings: Record<string, unknown> = {};
const settings = {
getUserSettings: vi.fn(async () => userSettings),
getAppSetting: vi.fn(async (): Promise<string | null> => null),
};
let statsAnswer: { countries: Array<Record<string, unknown>>; streak?: number } = { countries: [] };
let regionsAnswer: { regions?: Record<string, Array<{ code: string; status?: string }>> } = {};
let bucketAnswer: Array<{ visited_at?: string | null }> = [];
let flightsAnswer = {
routes: [] as Array<{ a: { lng: number }; b: { lng: number } }>,
airports: [],
totals: { flights: 0, km: 0, airports: 0, longestKm: 0 },
};
const atlas = {
stats: vi.fn(async () => statsAnswer),
visitedRegions: vi.fn(async () => regionsAnswer),
bucketList: vi.fn(async () => bucketAnswer),
};
const flights = { flights: vi.fn(async () => flightsAnswer) };
beforeAll(async () => {
t = await createTestModule({
db,
imports: [],
providers: [
AtlasPeopleService,
{ provide: SettingsService, useValue: settings },
{ provide: AtlasService, useValue: atlas },
{ provide: AtlasFlightsService, useValue: flights },
],
});
people = t.get(AtlasPeopleService);
});
beforeEach(() => {
userSettings = {};
statsAnswer = { countries: [] };
regionsAnswer = {};
bucketAnswer = [];
flightsAnswer = { routes: [], airports: [], totals: { flights: 0, km: 0, airports: 0, longestKm: 0 } };
});
afterAll(async () => {
await t.close();
db.close();
vi.restoreAllMocks();
});
const regionRows = (country: string, n: number, status?: string) =>
Array.from({ length: n }, (_, i) => ({ code: `${country}-${i}`, ...(status ? { status } : {}) }));
describe('AtlasPeopleService over a built manifest', () => {
it("ATLAS2-REST-001: measures a country's regions against the manifest's counted total, read once", async () => {
// Three of FR's six counted regions: half of them. Without the manifest the
// three rows alone would be all there is, and under five no badge counts.
regionsAnswer = { regions: { FR: regionRows('FR', 3, 'visited') } };
const badges = await people.badges(1);
expect(badges.find((b) => b.id === 'regions-half-FR')).toMatchObject({ earned: true, current: 3, target: 3 });
expect(badges.find((b) => b.id === 'regions-next-FR')).toMatchObject({ earned: false, current: 3, target: 6 });
await people.badges(2);
expect(manifestReads).toHaveBeenCalledTimes(1);
});
it('ATLAS2-REST-002: a country the manifest does not list counts its own rows, and only visited rows count', async () => {
regionsAnswer = {
regions: {
IT: [...regionRows('IT', 5), { code: 'IT-X', status: 'planned' }],
},
};
const [person] = await people.people([3]);
expect(person.regions).toBe(5);
const badges = await people.badges(3);
// 5 visited of the 6 rows IT answered with, the planned one counting toward the total only.
expect(badges.find((b) => b.id === 'regions-half-IT')).toMatchObject({ earned: true, target: 3 });
});
it('ATLAS2-REST-003: a country without a status is visited, a planned one is not, and no first visit means no year', async () => {
statsAnswer = {
countries: [
{ code: 'DE' },
{ code: 'JP', status: 'planned' },
{ code: 'FR', status: 'visited', firstVisit: null },
],
};
const [person] = await people.people([4]);
expect(person).toMatchObject({ id: 4, countries: 2, continents: 1, codes: ['DE', 'FR'] });
const first = person.badges.find((b) => b.id === 'countries-1');
expect(first).toMatchObject({ year: null, tier: 'bronze', titleKey: 'atlas.badge.first' });
expect(Object.keys(first ?? {}).sort()).toEqual(['id', 'motif', 'params', 'target', 'tier', 'titleKey', 'year']);
});
it('ATLAS2-REST-004: answers with no regions at all, no streak and no reached wishes', async () => {
bucketAnswer = [{ visited_at: null }, {}];
const [person] = await people.people([5]);
expect(person).toMatchObject({ regions: 0, countries: 0, continents: 0, flightKm: 0, codes: [] });
expect(person.badges).toEqual([]);
const badges = await people.badges(5);
expect(badges.find((b) => b.id === 'wishes-1')).toMatchObject({ earned: false, current: 0 });
expect(badges.find((b) => b.id === 'streak-3')).toMatchObject({ earned: false, current: 0 });
});
it('ATLAS2-REST-005: a flight route over the antimeridian earns the date line, the streak and the wishes count', async () => {
flightsAnswer = {
routes: [{ a: { lng: 151.2 }, b: { lng: -118.4 } }],
airports: [],
totals: { flights: 1, km: 12000, airports: 2, longestKm: 12000 },
};
statsAnswer = { countries: [{ code: 'AU', status: 'visited', firstVisit: '2019-01-05' }], streak: 3 };
bucketAnswer = [{ visited_at: '2019-01-05' }];
const [person] = await people.people([6]);
const ids = person.badges.map((b) => b.id);
expect(ids).toEqual(
expect.arrayContaining(['flights-dateline', 'flights-1', 'flights-longhaul', 'streak-3', 'wishes-1', 'equator']),
);
expect(ids).not.toContain('flights-ultra');
expect(person.flightKm).toBe(12000);
expect(person.badges.find((b) => b.id === 'countries-1')?.year).toBe(2019);
});
it('ATLAS2-REST-006: a route that stays on one side of the antimeridian earns no date line', async () => {
flightsAnswer = {
routes: [{ a: { lng: 8.5 }, b: { lng: -73.7 } }],
airports: [],
totals: { flights: 1, km: 6200, airports: 2, longestKm: 6200 },
};
const badges = await people.badges(7);
expect(badges.find((b) => b.id === 'flights-dateline')).toMatchObject({ earned: false, current: 0 });
});
it('ATLAS2-REST-007: the opt-out reads as hidden in every spelling the settings store hands back, and nothing else does', async () => {
for (const v of [true, 'true', 1, '1']) {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(true);
}
for (const v of [false, 'false', 0, '0', null, undefined, 'yes']) {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(false);
}
expect(settings.getUserSettings).toHaveBeenCalledWith(8);
});
it('ATLAS2-REST-008: the comparison is on while the admin stored nothing or anything but false', async () => {
settings.getAppSetting.mockResolvedValueOnce(null);
expect(await people.compareEnabled()).toBe(true);
settings.getAppSetting.mockResolvedValueOnce('true');
expect(await people.compareEnabled()).toBe(true);
settings.getAppSetting.mockResolvedValueOnce('false');
expect(await people.compareEnabled()).toBe(false);
});
it('ATLAS2-REST-009: asks for at most 200 travellers, each once, in the order asked', async () => {
const ids = Array.from({ length: 250 }, (_, i) => 1000 + i);
atlas.stats.mockClear();
const answer = await people.people([...ids, 1000, 1001]);
expect(answer).toHaveLength(200);
expect(answer[0].id).toBe(1000);
expect(answer[199].id).toBe(1199);
expect(atlas.stats).toHaveBeenCalledTimes(200);
});
});
@@ -0,0 +1,85 @@
/**
* AtlasPeopleService while the globe manifest cannot be read (not built, or
* broken): the region totals fall back to the rows each country answers with,
* and the manifest is not tried again for every traveller. The manifest is read
* once per process, so this file is the one that sees it missing;
* atlas-people.manifest.test.ts sees it built.
*/
import { AtlasFlightsService } from '../../../src/nest/atlas/atlas-flights.service';
import { AtlasPeopleService } from '../../../src/nest/atlas/atlas-people.service';
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import fs from 'node:fs';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let people: AtlasPeopleService;
const realRead = fs.readFileSync.bind(fs);
const manifestReads = vi.fn();
vi.spyOn(fs, 'readFileSync').mockImplementation(((file: fs.PathOrFileDescriptor, options?: unknown) => {
if (String(file).replace(/\\/g, '/').endsWith('assets/atlas-mesh/manifest.json')) {
manifestReads();
return '{ not json';
}
return realRead(file, options as BufferEncoding);
}) as unknown as typeof fs.readFileSync);
const settings = {
getUserSettings: vi.fn(async () => ({})),
getAppSetting: vi.fn(async (): Promise<string | null> => null),
};
const atlas = {
stats: vi.fn(async () => ({ countries: [{ code: 'FR', status: 'visited', firstVisit: '2020-03-01' }] })),
visitedRegions: vi.fn(async () => ({
regions: { FR: Array.from({ length: 6 }, (_, i) => ({ code: `FR-${i}`, status: 'visited' })) },
})),
bucketList: vi.fn(async () => []),
};
const flights = {
flights: vi.fn(async () => ({
routes: [],
airports: [],
totals: { flights: 0, km: 0, airports: 0, longestKm: 0 },
})),
};
beforeAll(async () => {
t = await createTestModule({
db,
imports: [],
providers: [
AtlasPeopleService,
{ provide: SettingsService, useValue: settings },
{ provide: AtlasService, useValue: atlas },
{ provide: AtlasFlightsService, useValue: flights },
],
});
people = t.get(AtlasPeopleService);
});
afterAll(async () => {
await t.close();
db.close();
vi.restoreAllMocks();
});
describe('AtlasPeopleService without a readable manifest', () => {
it("ATLAS2-REST-010: counts a country's own rows as its total, so all six visited earn the country", async () => {
const badges = await people.badges(1);
expect(badges.find((b) => b.id === 'regions-all-FR')).toMatchObject({ earned: true, current: 6, target: 6 });
expect(badges.find((b) => b.id === 'regions-next-FR')).toBeUndefined();
expect(badges.find((b) => b.id === 'countries-1')).toMatchObject({ year: 2020, country: 'FR' });
});
it('ATLAS2-REST-011: does not try the broken manifest again for the next traveller', async () => {
const [person] = await people.people([2]);
expect(person.regions).toBe(6);
expect(person.badges.map((b) => b.id)).toContain('regions-all-FR');
expect(manifestReads).toHaveBeenCalledTimes(1);
});
});
+141
View File
@@ -0,0 +1,141 @@
import { BADGE_CATEGORIES, computeBadges, crossesDateline, type BadgeInput } from './atlas-badges';
import { describe, expect, it } from 'vitest';
// ATLAS2-REST-040 to 052: the badge rules atlas-badges.spec.ts leaves open.
const base: BadgeInput = {
countries: [],
continents: [],
regions: [],
flights: { count: 0, km: 0, longestKm: 0, crossesDateline: false },
streak: 0,
wishesReached: 0,
};
const byId = (input: Partial<BadgeInput>) => new Map(computeBadges({ ...base, ...input }).map((b) => [b.id, b]));
const codes = (...list: string[]) => list.map((code) => ({ code }));
describe('atlas badge rules', () => {
it('ATLAS2-REST-040: the country steps run bronze, silver, gold, gold... and end on aurora', () => {
const b = byId({});
expect(
['countries-5', 'countries-10', 'countries-25', 'countries-50', 'countries-150'].map((id) => b.get(id)?.tier),
).toEqual(['bronze', 'silver', 'gold', 'gold', 'aurora']);
// Three steps or fewer never reach aurora: their last step is gold.
expect(b.get('regions-100')?.tier).toBe('gold');
expect(b.get('flights-100')?.tier).toBe('aurora');
expect(b.get('streak-10')?.tier).toBe('gold');
expect(b.get('islands-10')?.tier).toBe('silver');
});
it('ATLAS2-REST-041: a step not reached has no year or country, and its progress stops at the target', () => {
const countries = Array.from({ length: 7 }, (_, i) => ({ code: `C${i}`, year: 2000 + i }));
const b = byId({ countries });
expect(b.get('countries-10')).toMatchObject({ earned: false, current: 7, year: null, country: null });
expect(b.get('countries-5')).toMatchObject({ earned: true, current: 5, target: 5, year: 2004, country: 'C4' });
expect(b.get('countries-1')).toMatchObject({ current: 1, target: 1 });
});
it('ATLAS2-REST-042: countries without a year count after the dated ones, in code order', () => {
const b = byId({ countries: [{ code: 'ZA' }, { code: 'BE', year: null }, { code: 'NO', year: 2015 }] });
expect(b.get('countries-1')).toMatchObject({ year: 2015, country: 'NO' });
const undated = byId({ countries: [{ code: 'ZA' }, { code: 'BE' }] });
expect(undated.get('countries-1')).toMatchObject({ year: null, country: 'BE' });
});
it('ATLAS2-REST-043: no country at all leaves the first badge without a year or a country', () => {
expect(byId({}).get('countries-1')).toMatchObject({ earned: false, current: 0, year: null, country: null });
});
it('ATLAS2-REST-044: Antarctica counts for all seven but not as an inhabited continent', () => {
const b = byId({ continents: ['Europe', 'Antarctica', 'Europe'] });
expect(b.get('continents-2')).toMatchObject({ earned: false, current: 1 });
expect(b.get('continents-7')).toMatchObject({ current: 2 });
const two = byId({ continents: ['Europe', 'Asia'] });
expect(two.get('continents-2')?.earned).toBe(true);
expect(two.get('continents-3')?.earned).toBe(false);
});
it("ATLAS2-REST-045: under half of a country's regions earns nothing yet, the closest country is the next goal", () => {
const b = byId({
regions: [
{ country: 'DE', visited: 2, total: 16 },
{ country: 'FR', visited: 6, total: 13 },
{ country: 'IT', visited: 20, total: 20 },
],
});
expect(b.get('regions-half-DE')).toBeUndefined();
expect(b.get('regions-all-DE')).toBeUndefined();
// FR is closer to all its regions than DE, and IT is done already.
expect(b.get('regions-next-FR')).toMatchObject({ earned: false, current: 6, target: 13, tier: 'aurora' });
expect(b.get('regions-next-DE')).toBeUndefined();
expect(b.get('regions-next-IT')).toBeUndefined();
expect(b.get('regions-all-IT')).toMatchObject({ earned: true, country: 'IT', params: { country: 'IT' } });
// The totals count every visited region.
expect(b.get('regions-10')).toMatchObject({ earned: true, current: 10 });
expect(b.get('regions-50')).toMatchObject({ earned: false, current: 28 });
});
it('ATLAS2-REST-046: with every country done there is no next region goal', () => {
const b = byId({ regions: [{ country: 'AT', visited: 9, total: 9 }] });
expect([...b.keys()].some((id) => id.startsWith('regions-next-'))).toBe(false);
});
it('ATLAS2-REST-047: the long-haul, ultra and airport badges read their own numbers', () => {
const b = byId({ flights: { count: 3, km: 41000.4, longestKm: 13000.2, crossesDateline: false, airports: 12 } });
expect(b.get('flights-ultra')?.earned).toBe(true);
expect(b.get('flights-earth')).toMatchObject({ earned: true, current: 40075 });
expect(b.get('flights-earth-5')).toMatchObject({ earned: false, current: 41000 });
expect(b.get('airports-10')?.earned).toBe(true);
expect(b.get('airports-25')).toMatchObject({ earned: false, current: 12 });
expect(b.get('flights-dateline')?.earned).toBe(false);
// No airport count given is none.
expect(byId({}).get('airports-10')).toMatchObject({ current: 0 });
});
it('ATLAS2-REST-048: both hemispheres need a country west of Greenwich and one east of it', () => {
expect(byId({ countries: codes('US') }).get('hemispheres')?.earned).toBe(false);
expect(byId({ countries: codes('DE') }).get('hemispheres')?.earned).toBe(false);
expect(byId({ countries: codes('US', 'DE') }).get('hemispheres')?.earned).toBe(true);
});
it('ATLAS2-REST-049: the tropics, the polar north and the islands count their countries', () => {
const b = byId({ countries: codes('TH', 'IS', 'JP', 'MT', 'CY', 'GB', 'IE') });
expect(b.get('tropics')?.earned).toBe(true);
expect(b.get('polar')?.earned).toBe(true);
expect(b.get('islands-5')).toMatchObject({ earned: true, current: 5 });
expect(b.get('islands-10')).toMatchObject({ earned: false, current: 6 });
const none = byId({ countries: codes('DE') });
expect(none.get('tropics')?.earned).toBe(false);
expect(none.get('polar')?.earned).toBe(false);
expect(none.get('equator')?.earned).toBe(false);
});
it('ATLAS2-REST-050: the busiest year wins the burst, the earlier one on a tie, and undated countries never count', () => {
const tie = [2018, 2018, 2018, 2016, 2016, 2016].map((year, i) => ({ code: `T${i}`, year }));
const b = byId({ countries: [...tie, { code: 'U1' }, { code: 'U2', year: null }] });
expect(b.get('burst-3')).toMatchObject({ earned: true, current: 3, year: 2016 });
expect(b.get('burst-5')).toMatchObject({ earned: false, current: 3, year: null });
const undated = byId({ countries: codes('A1', 'A2', 'A3') });
expect(undated.get('burst-3')).toMatchObject({ earned: false, current: 0, year: null });
});
it('ATLAS2-REST-051: streaks and wishes climb their steps', () => {
const b = byId({ streak: 5, wishesReached: 10 });
expect(b.get('streak-3')?.earned).toBe(true);
expect(b.get('streak-5')?.earned).toBe(true);
expect(b.get('streak-10')).toMatchObject({ earned: false, current: 5 });
expect(['wishes-1', 'wishes-5', 'wishes-10'].every((id) => b.get(id)?.earned)).toBe(true);
expect(b.get('wishes-10')?.category).toBe('collector');
});
it('ATLAS2-REST-052: every badge sits in one of the listed categories, ids are unique, and the date line needs more than 180 degrees', () => {
const all = computeBadges({ ...base, regions: [{ country: 'US', visited: 30, total: 50 }] });
expect(new Set(all.map((b) => b.id)).size).toBe(all.length);
expect(all.every((b) => BADGE_CATEGORIES.includes(b.category))).toBe(true);
expect(new Set(all.map((b) => b.category))).toEqual(new Set(BADGE_CATEGORIES));
expect(crossesDateline(0, 180)).toBe(false);
expect(crossesDateline(-179, 179)).toBe(true);
});
});