feat(client): let the atlas hide countries you have not reached yet

Planned countries are off the map by default and come back through a switch
above the globe, drawn dashed so they never read as somewhere you have been.
The switch only appears once there is something planned to show, and it
remembers its state.

Three things that needed care:

The colour palette is built from the visited countries alone. It assigns
colours by index, so letting planned ones join would reshuffle the whole map
every time the switch is flipped.

countryMap decides both the tooltip and what a click does, so it is built
from the visible countries — a hidden country has to fall through to the
mark-as-visited branch or it becomes unclickable.

The region layer read `data` without listing it as a dependency, which meant
region colours already went stale on their own; adding the switch would have
made that visible.

Five copies of the optimistic mark-as-visited update have moved into
withCountryMarkedVisited, which also promotes a planned country instead of
adding it twice. Antarctica joins the continent row when someone has been.
This commit is contained in:
Maurice
2026-08-03 19:40:04 +02:00
committed by Maurice
parent 97f6a43333
commit 558f348881
9 changed files with 561 additions and 62 deletions
+32 -18
View File
@@ -6,10 +6,11 @@ import CustomSelect from '../components/shared/CustomSelect'
import EmptyState from '../components/shared/EmptyState'
import { Globe, MapPin, Briefcase, Calendar, Flag, PanelLeftOpen, PanelLeftClose, X, Star, Plus, Trash2, Search } from 'lucide-react'
import type { TranslationFn } from '../types'
import { A2_TO_A3, countryCodeToFlag, type AtlasCountry, type AtlasStats, type AtlasData, type CountryDetail } from './atlas/atlasModel'
import { A2_TO_A3, countryCodeToFlag, withCountryMarkedVisited, type AtlasCountry, type AtlasStats, type AtlasData, type CountryDetail } from './atlas/atlasModel'
import { continentForCountry } from '@trek/shared'
import { useAtlas } from './atlas/useAtlas'
import AtlasCountrySearch from './atlas/AtlasCountrySearch'
import AtlasLayerToggle from './atlas/AtlasLayerToggle'
import { useToast } from '../components/shared/Toast'
import { getApiErrorMessage } from '../types'
import { useIsPhone } from '../mobile/useIsPhone'
@@ -29,6 +30,7 @@ function AtlasPageDesktop(): React.ReactElement {
mapRef, regionTooltipRef, panelRef, glareRef, borderGlareRef,
handlePanelMouseMove, handlePanelMouseLeave,
data, setData, stats, countries, selectedCountry, countryDetail,
showPlanned, togglePlanned,
loadCountryDetail, handleUnmarkCountry, select_country_from_search,
visitedRegions, setVisitedRegions,
atlas_country_search, set_atlas_country_search,
@@ -89,6 +91,12 @@ function AtlasPageDesktop(): React.ReactElement {
options={atlas_country_options}
onSelect={select_country_from_search}
/>
<AtlasLayerToggle
t={t}
showPlanned={showPlanned}
onToggle={togglePlanned}
plannedCount={stats.totalCountriesPlanned || 0}
/>
{/* Mobile: Bottom bar */}
<div className="md:hidden absolute left-0 right-0 z-10 flex justify-center" style={{ bottom: 'calc(84px + env(safe-area-inset-bottom, 0px) + 8px)', touchAction: 'manipulation' }}>
@@ -173,11 +181,7 @@ function AtlasPageDesktop(): React.ReactElement {
<button onClick={async () => {
try {
await apiClient.post(`/addons/atlas/country/${confirmAction.code}/mark`)
setData(prev => {
if (!prev || prev.countries.find(c => c.code === confirmAction.code)) return prev
const cont = continentForCountry(confirmAction.code)
return { ...prev, countries: [...prev.countries, { code: confirmAction.code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }], stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 }, continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 } }
})
setData(prev => (prev ? withCountryMarkedVisited(prev, confirmAction.code) : prev))
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
}
@@ -222,11 +226,7 @@ function AtlasPageDesktop(): React.ReactElement {
if (existing.find(r => r.code === rCode)) return prev
return { ...prev, [countryCode]: [...existing, { code: rCode, name: rName, placeCount: 0, manuallyMarked: true }] }
})
setData(prev => {
if (!prev || prev.countries.find(c => c.code === countryCode)) return prev
const cont = continentForCountry(countryCode)
return { ...prev, countries: [...prev.countries, { code: countryCode, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }], stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 }, continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 } }
})
setData(prev => (prev ? withCountryMarkedVisited(prev, countryCode) : prev))
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
}
@@ -463,7 +463,7 @@ function SidebarContent({ data, stats, countries, selectedCountry, countryDetail
const { mostVisited, continents, lastTrip, nextTrip, streak, firstYear, tripsThisYear } = data || {}
const contEntries = continents ? Object.entries(continents).sort((a, b) => b[1] - a[1]) : []
const maxCont = contEntries.length > 0 ? contEntries[0][1] : 1
const CL = { 'Europe': t('atlas.europe'), 'Asia': t('atlas.asia'), 'North America': t('atlas.northAmerica'), 'South America': t('atlas.southAmerica'), 'Africa': t('atlas.africa'), 'Oceania': t('atlas.oceania') }
const CL = { 'Europe': t('atlas.europe'), 'Asia': t('atlas.asia'), 'North America': t('atlas.northAmerica'), 'South America': t('atlas.southAmerica'), 'Africa': t('atlas.africa'), 'Oceania': t('atlas.oceania'), 'Antarctica': t('atlas.antarctica') }
const contColors = ['#818cf8', '#f472b6', '#34d399', '#fbbf24', '#fb923c', '#22d3ee']
// Tab switcher
@@ -620,9 +620,16 @@ function SidebarContent({ data, stats, countries, selectedCountry, countryDetail
{/* ═══ SECTION 1: Numbers ═══ */}
{/* Countries hero */}
<div className="flex items-baseline gap-1.5 px-5 py-4 mx-2 my-2 rounded-xl" style={{ background: bg(0.08) }}>
<span className="text-5xl font-black tabular-nums leading-none" style={{ color: tp }}>{stats.totalCountries}</span>
<span className="text-sm font-medium" style={{ color: tm }}>{t('atlas.countries')}</span>
<div className="flex flex-col justify-center px-5 py-4 mx-2 my-2 rounded-xl" style={{ background: bg(0.08) }}>
<div className="flex items-baseline gap-1.5">
<span className="text-5xl font-black tabular-nums leading-none" style={{ color: tp }}>{stats.totalCountries}</span>
<span className="text-sm font-medium" style={{ color: tm }}>{t('atlas.countries')}</span>
</div>
{(stats.totalCountriesPlanned || 0) > 0 && (
<span className="text-[9px] font-semibold mt-1.5 uppercase tracking-wide whitespace-nowrap" style={{ color: tf }}>
+{stats.totalCountriesPlanned} {t('atlas.planned')}
</span>
)}
</div>
{/* Other stats */}
{[[stats.totalTrips, t('atlas.trips')], [stats.totalPlaces, t('atlas.places')], [stats.totalCities || 0, t('atlas.cities')], [stats.totalDays, t('atlas.days')]].map(([v, l], i) => (
@@ -637,7 +644,9 @@ function SidebarContent({ data, stats, countries, selectedCountry, countryDetail
{/* ═══ SECTION 2: Continents ═══ */}
<div className="flex items-center gap-4 px-3 py-4 shrink-0">
{['Europe', 'Asia', 'North America', 'South America', 'Africa', 'Oceania'].map((cont) => {
{/* Antarctica only joins the row once someone has actually been — CONTINENT_MAP has
always known AQ, but a permanent zero column would be dead space for everyone else. */}
{['Europe', 'Asia', 'North America', 'South America', 'Africa', 'Oceania', ...((continents?.['Antarctica'] || 0) > 0 ? ['Antarctica'] : [])].map((cont) => {
const count = continents?.[cont] || 0
const active = count > 0
return (
@@ -693,8 +702,13 @@ function SidebarContent({ data, stats, countries, selectedCountry, countryDetail
<div className="flex items-center gap-3 px-6 py-4">
<span className="text-3xl">{countryCodeToFlag(selectedCountry)}</span>
<div>
<p className="text-sm font-bold" style={{ color: tp }}>{resolveName(selectedCountry)}</p>
<p className="text-[10px] mb-1" style={{ color: tf }}>{countryDetail.places.length} {t('atlas.places')} · {countryDetail.trips.length} Trips</p>
<p className="text-sm font-bold" style={{ color: tp }}>
{resolveName(selectedCountry)}
{countryDetail.status && countryDetail.status !== 'visited' && (
<span className="ml-2 text-[9px] font-semibold uppercase tracking-wide" style={{ color: tf }}>{t('atlas.planned')}</span>
)}
</p>
<p className="text-[10px] mb-1" style={{ color: tf }}>{countryDetail.places.length} {t('atlas.places')} · {countryDetail.trips.length} {t('atlas.tripPlural')}</p>
<div className="flex flex-wrap gap-1">
{countryDetail.trips.slice(0, 3).map(trip => (
<button key={trip.id} onClick={() => onTripClick(trip.id)}
+49 -2
View File
@@ -8,7 +8,7 @@ import type { AtlasController } from '../mobile/screens/atlas/atlasController';
import type { AtlasData, CountryDetail } from './atlas/atlasModel';
import AtlasPage from './AtlasPage';
// FE-PAGE-ATLASW-001 to FE-PAGE-ATLASW-026
// FE-PAGE-ATLASW-001 to FE-PAGE-ATLASW-034
//
// AtlasPage is a wiring container around useAtlas: the hook is mocked here so the
// confirm popup and the sidebar can be driven into every state directly, which the
@@ -450,7 +450,7 @@ describe('AtlasPage wiring', () => {
render(<AtlasPage />);
expect(screen.getByText('France')).toBeInTheDocument();
expect(screen.getByText('3 atlas.places · 4 Trips')).toBeInTheDocument();
expect(screen.getByText('3 atlas.places · 4 atlas.tripPlural')).toBeInTheDocument();
// Only the first three trips are shown.
expect(screen.queryByText('Brest')).not.toBeInTheDocument();
@@ -662,4 +662,51 @@ describe('AtlasPage wiring', () => {
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ type: 'choose', code: 'DE', name: 'Germany' });
});
});
describe('planned countries (#1048)', () => {
const withPlanned = (totalCountriesPlanned: number) =>
buildAtlasData({
stats: { totalTrips: 6, totalPlaces: 40, totalCountries: 9, totalDays: 55, totalCities: 12, totalCountriesPlanned },
});
it('FE-PAGE-ATLASW-032: the panel only mentions planned countries once there are some', () => {
setAtlas({ data: withPlanned(0) });
const { unmount } = render(<AtlasPage />);
expect(screen.queryByText(/atlas\.planned/)).not.toBeInTheDocument();
unmount();
setAtlas({ data: withPlanned(3) });
render(<AtlasPage />);
expect(screen.getByText('+3 atlas.planned')).toBeInTheDocument();
});
it('FE-PAGE-ATLASW-033: the layer toggle rides on the same count and flips the planned layer', () => {
setAtlas({ data: withPlanned(0) });
const { unmount } = render(<AtlasPage />);
expect(screen.queryByRole('button', { name: 'atlas.showPlanned' })).not.toBeInTheDocument();
unmount();
const atlas = setAtlas({ data: withPlanned(3) });
render(<AtlasPage />);
fireEvent.click(screen.getByRole('button', { name: 'atlas.showPlanned' }));
expect(atlas.togglePlanned).toHaveBeenCalled();
});
it('FE-PAGE-ATLASW-034: the country detail badges a country you have not reached yet', () => {
setAtlas({ selectedCountry: 'FR', countryDetail: buildCountryDetail({ status: 'planned' }) });
const { unmount } = render(<AtlasPage />);
expect(screen.getByText('atlas.planned')).toBeInTheDocument();
unmount();
setAtlas({ selectedCountry: 'FR', countryDetail: buildCountryDetail({ status: 'visited' }) });
render(<AtlasPage />);
expect(screen.queryByText('atlas.planned')).not.toBeInTheDocument();
});
});
});
@@ -0,0 +1,39 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '../../../tests/helpers/render';
import type { TranslationFn } from '../../types';
import AtlasLayerToggle from './AtlasLayerToggle';
// FE-ATLAS-TOGGLE-001 to FE-ATLAS-TOGGLE-003
const t = ((key: string) => key) as TranslationFn;
describe('AtlasLayerToggle', () => {
it('FE-ATLAS-TOGGLE-001: stays out of the way while nothing is planned', () => {
const { container } = render(
<AtlasLayerToggle t={t} showPlanned={false} onToggle={vi.fn()} plannedCount={0} />,
);
expect(container).toBeEmptyDOMElement();
});
it('FE-ATLAS-TOGGLE-002: shows the label and how many countries the layer would add', () => {
render(<AtlasLayerToggle t={t} showPlanned={false} onToggle={vi.fn()} plannedCount={4} />);
expect(screen.getByText('atlas.showPlanned')).toBeInTheDocument();
expect(screen.getByText('4')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'atlas.showPlanned' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-ATLAS-TOGGLE-003: reports the flip and reflects the current state', () => {
const onToggle = vi.fn();
const { rerender } = render(
<AtlasLayerToggle t={t} showPlanned={false} onToggle={onToggle} plannedCount={4} />,
);
fireEvent.click(screen.getByRole('button', { name: 'atlas.showPlanned' }));
expect(onToggle).toHaveBeenCalledTimes(1);
rerender(<AtlasLayerToggle t={t} showPlanned onToggle={onToggle} plannedCount={4} />);
expect(screen.getByRole('button', { name: 'atlas.showPlanned' })).toHaveAttribute('aria-pressed', 'true');
});
});
@@ -0,0 +1,42 @@
import React from 'react'
import ToggleSwitch from '../../components/Settings/ToggleSwitch'
import type { TranslationFn } from '../../types'
interface AtlasLayerToggleProps {
t: TranslationFn
showPlanned: boolean
onToggle: () => void
plannedCount: number
}
// Floating switch that reveals the countries you only plan to visit (#1048). Hidden
// entirely when there is nothing planned — an always-present control for an empty set
// is just clutter over the globe. Sits on the desktop map only; the mobile atlas has
// its own compact toggle in MAtlas.
export default function AtlasLayerToggle({ t, showPlanned, onToggle, plannedCount }: AtlasLayerToggleProps): React.ReactElement | null {
if (plannedCount <= 0) return null
return (
<div
className="absolute z-20 hidden md:flex"
style={{ top: 'calc(env(safe-area-inset-top, 0px) + 14px)', right: 18 }}
>
<div
className="flex items-center gap-3 rounded-full border border-edge"
style={{
padding: '8px 14px',
background: 'var(--bg-elevated)',
boxShadow: 'var(--shadow-popover)',
backdropFilter: 'blur(18px) saturate(180%)',
WebkitBackdropFilter: 'blur(18px) saturate(180%)',
}}
>
<span className="text-caption font-semibold text-content whitespace-nowrap">
{t('atlas.showPlanned')}
</span>
<span className="text-caption font-bold tabular-nums text-content-muted">{plannedCount}</span>
<ToggleSwitch on={showPlanned} onToggle={onToggle} label={t('atlas.showPlanned')} />
</div>
</div>
)
}
+119 -1
View File
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest';
import { A2_TO_A3, normalizeRegionName } from './atlasModel';
import {
A2_TO_A3,
countryStatus,
isCountryVisible,
normalizeRegionName,
withCountryMarkedVisited,
type AtlasData,
} from './atlasModel';
describe('normalizeRegionName', () => {
it('matches names that only differ by diacritics (Ile-de-France vs Île-de-France)', () => {
@@ -37,3 +44,114 @@ describe('A2_TO_A3 hardcoded entries (#1609)', () => {
expect(countryCode).toBe('XK');
});
});
// Trip-date driven visit status (#1048). The three helpers below are the only place
// the client decides what "been there" means, so every mark flow shares one answer.
describe('countryStatus', () => {
it('treats a country without a status as visited (older server, no #1048 field)', () => {
expect(countryStatus({})).toBe('visited');
});
it('passes an explicit status through', () => {
expect(countryStatus({ status: 'visited' })).toBe('visited');
expect(countryStatus({ status: 'planned' })).toBe('planned');
expect(countryStatus({ status: 'idea' })).toBe('idea');
});
});
describe('isCountryVisible', () => {
it('always shows visited countries', () => {
expect(isCountryVisible({ status: 'visited' }, false)).toBe(true);
expect(isCountryVisible({ status: 'visited' }, true)).toBe(true);
});
it('hides planned and dateless countries until the layer is switched on', () => {
expect(isCountryVisible({ status: 'planned' }, false)).toBe(false);
expect(isCountryVisible({ status: 'idea' }, false)).toBe(false);
expect(isCountryVisible({ status: 'planned' }, true)).toBe(true);
expect(isCountryVisible({ status: 'idea' }, true)).toBe(true);
});
it('keeps a status-less country on the map with the toggle off', () => {
expect(isCountryVisible({}, false)).toBe(true);
});
});
describe('withCountryMarkedVisited', () => {
const base = (over: Partial<AtlasData> = {}): AtlasData => ({
countries: [{ code: 'FR', tripCount: 2, placeCount: 5, status: 'visited' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCountriesPlanned: 0 },
continents: { Europe: 1 },
continentsPlanned: {},
...over,
});
it('appends an unknown country as visited and counts it once', () => {
const next = withCountryMarkedVisited(base(), 'JP');
expect(next.countries).toHaveLength(2);
expect(next.countries[1]).toEqual({
code: 'JP', placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null, status: 'visited',
});
expect(next.stats.totalCountries).toBe(2);
expect(next.continents).toEqual({ Europe: 1, Asia: 1 });
// Nothing was planned, so the planned tallies stay untouched.
expect(next.stats.totalCountriesPlanned).toBe(0);
expect(next.continentsPlanned).toEqual({});
});
it('returns the very same object when the country is already visited', () => {
const prev = base();
expect(withCountryMarkedVisited(prev, 'FR')).toBe(prev);
});
it('promotes a planned country instead of adding a second entry', () => {
const prev = base({
countries: [
{ code: 'FR', tripCount: 2, placeCount: 5, status: 'visited' },
{ code: 'JP', tripCount: 1, placeCount: 0, status: 'planned' },
],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCountriesPlanned: 1 },
continents: { Europe: 1 },
continentsPlanned: { Asia: 1 },
});
const next = withCountryMarkedVisited(prev, 'JP');
expect(next.countries).toHaveLength(2);
expect(next.countries.find((c) => c.code === 'JP')?.status).toBe('visited');
expect(next.stats.totalCountries).toBe(2);
expect(next.stats.totalCountriesPlanned).toBe(0);
expect(next.continents).toEqual({ Europe: 1, Asia: 1 });
expect(next.continentsPlanned).toEqual({ Asia: 0 });
});
it('promotes a dateless country the same way', () => {
const prev = base({
countries: [{ code: 'JP', tripCount: 1, placeCount: 0, status: 'idea' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 0, totalDays: 14, totalCountriesPlanned: 1 },
continents: {},
continentsPlanned: { Asia: 1 },
});
const next = withCountryMarkedVisited(prev, 'JP');
expect(next.countries).toHaveLength(1);
expect(next.countries[0].status).toBe('visited');
expect(next.stats.totalCountries).toBe(1);
expect(next.stats.totalCountriesPlanned).toBe(0);
});
it('never lets the planned tallies fall below zero', () => {
const prev = base({
countries: [{ code: 'JP', tripCount: 1, placeCount: 0, status: 'planned' }],
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 },
continents: {},
});
const next = withCountryMarkedVisited(prev, 'JP');
expect(next.stats.totalCountriesPlanned).toBe(0);
expect(next.continentsPlanned).toEqual({ Asia: 0 });
});
});
+49
View File
@@ -1,3 +1,5 @@
import { continentForCountry, type VisitStatus } from '@trek/shared'
/**
* Shared types + pure helpers for the Atlas page. No React, no side effects.
* A2_TO_A3 is deliberately a mutable module-level object: the geoData load
@@ -12,6 +14,8 @@ export interface AtlasCountry {
placeCount: number
firstVisit?: string | null
lastVisit?: string | null
/** Optional so a client talking to an older server keeps painting everything as visited. */
status?: VisitStatus
}
export interface AtlasStats {
@@ -20,6 +24,8 @@ export interface AtlasStats {
totalCountries: number
totalDays: number
totalCities?: number
totalCountriesPlanned?: number
totalCountriesIdea?: number
}
export interface AtlasData {
@@ -27,6 +33,7 @@ export interface AtlasData {
stats: AtlasStats
mostVisited?: AtlasCountry | null
continents?: Record<string, number>
continentsPlanned?: Record<string, number>
lastTrip?: { id: number; title: string; countryCode?: string } | null
nextTrip?: { id: number; title: string; countryCode?: string } | null
streak?: number
@@ -38,6 +45,48 @@ export interface CountryDetail {
places: import('../../types').AtlasPlace[]
trips: { id: number; title: string }[]
manually_marked?: boolean
status?: VisitStatus
}
/** A country from a server that predates #1048 has no status — treat it as visited. */
export function countryStatus(c: Pick<AtlasCountry, 'status'>): VisitStatus {
return c.status ?? 'visited'
}
/**
* Which countries belong on the map. Planned and dateless countries share one switch —
* splitting them into two would clutter the map for a distinction few users make.
*/
export function isCountryVisible(c: Pick<AtlasCountry, 'status'>, showPlanned: boolean): boolean {
return countryStatus(c) === 'visited' || showPlanned
}
/**
* Fold a manual "I have been here" mark into the loaded data without refetching — the
* map redraws from `data`, so a reload would flash the whole globe. A country that was
* merely planned moves over to the visited tally instead of being added twice.
* Shared by every mark flow (map click, search, mobile popup) so none of them can drift.
*/
export function withCountryMarkedVisited(prev: AtlasData, code: string): AtlasData {
const existing = prev.countries.find(c => c.code === code)
if (existing && countryStatus(existing) === 'visited') return prev
const cont = continentForCountry(code)
const wasPlanned = !!existing
return {
...prev,
countries: existing
? prev.countries.map(c => (c.code === code ? { ...c, status: 'visited' as const } : c))
: [...prev.countries, { code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null, status: 'visited' as const }],
stats: {
...prev.stats,
totalCountries: prev.stats.totalCountries + 1,
...(wasPlanned ? { totalCountriesPlanned: Math.max(0, (prev.stats.totalCountriesPlanned || 0) - 1) } : {}),
},
continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 },
...(wasPlanned
? { continentsPlanned: { ...prev.continentsPlanned, [cont]: Math.max(0, (prev.continentsPlanned?.[cont] || 0) - 1) } }
: {}),
}
}
export interface BucketItem {
+115 -1
View File
@@ -9,7 +9,7 @@ import { useSettingsStore } from '../../store/settingsStore';
import { A2_TO_A3 } from './atlasModel';
import { useAtlas } from './useAtlas';
// FE-HOOK-ATLAS-001 to FE-HOOK-ATLAS-030
// FE-HOOK-ATLAS-001 to FE-HOOK-ATLAS-035
interface MockGeoJson {
data: { features?: Record<string, unknown>[] };
@@ -133,6 +133,20 @@ const statsResponse = {
tripsThisYear: 1,
};
// FR has already happened, DE is a trip that starts next month, JP has no dates at all.
// totalCountries counts the visited ones only — that split is the whole point of #1048.
const plannedStatsResponse = {
...statsResponse,
countries: [
{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01', status: 'visited' },
{ code: 'DE', tripCount: 1, placeCount: 0, firstVisit: '2099-05-01', lastVisit: '2099-05-08', status: 'planned' },
{ code: 'JP', tripCount: 1, placeCount: 0, firstVisit: null, lastVisit: null, status: 'idea' },
],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCities: 3, totalCountriesPlanned: 1, totalCountriesIdea: 1 },
continents: { Europe: 1 },
continentsPlanned: { Europe: 1, Asia: 1 },
};
const feature = (props: Record<string, unknown>) => ({ type: 'Feature', properties: props, geometry: null });
const geoCountries = {
@@ -173,6 +187,11 @@ function useAtlasHandlers(over: Partial<Record<string, unknown>> = {}) {
);
}
/** The country layer is the only GeoJSON drawn without a dedicated pane. */
function countryLayers(): MockGeoJson[] {
return (lf.geoJson as MockGeoJson[]).filter((g) => g.options.pane === undefined);
}
async function mountAtlas(over: Partial<Record<string, unknown>> = {}, props: { withPanel?: boolean } = {}) {
useAtlasHandlers(over);
const view = render(<Harness {...props} />);
@@ -727,4 +746,99 @@ describe('useAtlas', () => {
expect((lf.geoJson as MockGeoJson[]).some((g) => g.options.pane === 'regionPane')).toBe(false);
});
});
describe('planned countries (#1048)', () => {
it('FE-HOOK-ATLAS-031: the planned layer starts off and only lists the visited countries', async () => {
await mountAtlas({ stats: plannedStatsResponse });
expect(atlas.showPlanned).toBe(false);
expect(atlas.visitedCountries.map((c) => c.code)).toEqual(['FR']);
expect(atlas.visibleCountries.map((c) => c.code)).toEqual(['FR']);
// countries stays the raw server list — the map picks from visibleCountries.
expect(atlas.countries.map((c) => c.code)).toEqual(['FR', 'DE', 'JP']);
});
it('FE-HOOK-ATLAS-032: a stored preference brings the planned countries back on mount', async () => {
localStorage.setItem('trek_atlas_show_planned', '1');
await mountAtlas({ stats: plannedStatsResponse });
expect(atlas.showPlanned).toBe(true);
expect(atlas.visibleCountries.map((c) => c.code)).toEqual(['FR', 'DE', 'JP']);
expect(atlas.visitedCountries.map((c) => c.code)).toEqual(['FR']);
});
it('FE-HOOK-ATLAS-032b: any other stored value keeps the layer off', async () => {
localStorage.setItem('trek_atlas_show_planned', '0');
await mountAtlas({ stats: plannedStatsResponse });
expect(atlas.showPlanned).toBe(false);
});
it('FE-HOOK-ATLAS-033: toggling reveals the planned countries and remembers the choice', async () => {
await mountAtlas({ stats: plannedStatsResponse });
act(() => atlas.togglePlanned());
expect(atlas.showPlanned).toBe(true);
expect(atlas.visibleCountries.map((c) => c.code)).toEqual(['FR', 'DE', 'JP']);
expect(localStorage.getItem('trek_atlas_show_planned')).toBe('1');
act(() => atlas.togglePlanned());
expect(atlas.showPlanned).toBe(false);
expect(atlas.visibleCountries.map((c) => c.code)).toEqual(['FR']);
expect(localStorage.getItem('trek_atlas_show_planned')).toBe('0');
});
it('FE-HOOK-ATLAS-034: a storage that refuses reads and writes still leaves a working toggle', async () => {
// Safari private mode: localStorage exists but throws. The toggle must not take
// the atlas down with it — it just forgets the choice between reloads.
const realGet = Storage.prototype.getItem;
const realSet = Storage.prototype.setItem;
const getSpy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(function (this: Storage, key: string) {
if (key === 'trek_atlas_show_planned') throw new DOMException('denied', 'SecurityError');
return realGet.call(this, key);
});
const setSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (this: Storage, key: string, value: string) {
if (key === 'trek_atlas_show_planned') throw new DOMException('denied', 'SecurityError');
realSet.call(this, key, value);
});
try {
await mountAtlas({ stats: plannedStatsResponse });
expect(atlas.showPlanned).toBe(false);
act(() => atlas.togglePlanned());
expect(atlas.showPlanned).toBe(true);
expect(atlas.visibleCountries.map((c) => c.code)).toEqual(['FR', 'DE', 'JP']);
} finally {
getSpy.mockRestore();
setSpy.mockRestore();
}
});
it('FE-HOOK-ATLAS-035: planned countries are painted dashed and never eat a visited colour', async () => {
await mountAtlas({ stats: plannedStatsResponse, geo: geoCountries });
await waitFor(() => expect(countryLayers().length).toBeGreaterThan(0));
const before = countryLayers().length;
act(() => atlas.togglePlanned());
await waitFor(() => expect(countryLayers().length).toBeGreaterThan(before));
const layers = countryLayers();
const layer = layers[layers.length - 1];
const styleFor = (a2: string) => {
const i = (layer.data.features ?? []).findIndex(
(f) => (f.properties as Record<string, string>).ISO_A2 === a2,
);
return layer.styles[i] as { fillOpacity: number; dashArray?: string; fillColor: string };
};
expect(styleFor('FR').dashArray).toBeUndefined();
expect(styleFor('DE').dashArray).toBe('6 4');
// The palette is built from the visited list only, so France keeps the first colour
// whether or not the planned layer is on.
expect(styleFor('FR').fillColor).toBe('#6366f1');
expect(styleFor('DE').fillColor).not.toBe('#6366f1');
});
});
});
+96 -37
View File
@@ -5,8 +5,10 @@ import { useSettingsStore } from '../../store/settingsStore'
import apiClient, { mapsApi, pluginsApi, type PluginAtlasLayer } from '../../api/client'
import L from 'leaflet'
import type { GeoJsonFeatureCollection } from '../../types'
import { A2_TO_A3, normalizeRegionName, type AtlasData, type CountryDetail, type BucketItem } from './atlasModel'
import { continentForCountry } from '@trek/shared'
import { A2_TO_A3, countryStatus, isCountryVisible, normalizeRegionName, withCountryMarkedVisited, type AtlasData, type CountryDetail, type BucketItem } from './atlasModel'
import { continentForCountry, type VisitStatus } from '@trek/shared'
const PLANNED_KEY = 'trek_atlas_show_planned'
function useCountryNames(language: string): (code: string) => string {
const [resolver, setResolver] = useState<(code: string) => string>(() => (code: string) => code)
@@ -67,12 +69,22 @@ export function useAtlas() {
const [selectedCountry, setSelectedCountry] = useState<string | null>(null)
const [countryDetail, setCountryDetail] = useState<CountryDetail | null>(null)
const [geoData, setGeoData] = useState<GeoJsonFeatureCollection | null>(null)
const [visitedRegions, setVisitedRegions] = useState<Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean }[]>>({})
const [visitedRegions, setVisitedRegions] = useState<Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean; status?: VisitStatus }[]>>({})
const [pluginLayers, setPluginLayers] = useState<PluginAtlasLayer[]>([])
const pluginLayerRef = useRef<L.GeoJSON | null>(null)
const regionLayerRef = useRef<L.GeoJSON | null>(null)
const regionGeoCache = useRef<Record<string, GeoJsonFeatureCollection>>({})
const [showRegions, setShowRegions] = useState(false)
// Countries you only plan to visit stay off the map until asked for — the atlas is a
// record of where you have been, not of where you booked a flight to (#1048).
const [showPlanned, setShowPlanned] = useState<boolean>(() => {
try { return localStorage.getItem(PLANNED_KEY) === '1' } catch { return false }
})
const togglePlanned = () => setShowPlanned(v => {
const next = !v
try { localStorage.setItem(PLANNED_KEY, next ? '1' : '0') } catch { /* private mode — keep the toggle working anyway */ }
return next
})
const [regionGeoLoaded, setRegionGeoLoaded] = useState(0)
const regionTooltipRef = useRef<HTMLDivElement>(null)
const loadCountryDetailRef = useRef<(code: string) => void>(() => {})
@@ -98,6 +110,11 @@ export function useAtlas() {
const [atlas_country_results, set_atlas_country_results] = useState<{ code: string; label: string }[]>([])
const [atlas_country_open, set_atlas_country_open] = useState(false)
// visitedCountries drives the colour palette and every "how many" number;
// visibleCountries drives what the map paints and what stays clickable.
const visitedCountries = useMemo(() => (data?.countries ?? []).filter(c => countryStatus(c) === 'visited'), [data])
const visibleCountries = useMemo(() => (data?.countries ?? []).filter(c => isCountryVisible(c, showPlanned)), [data, showPlanned])
const atlas_country_options = useMemo(() => {
if (!geoData) return []
// Precompute A3 → A2 reverse lookup once per geoData change instead of
@@ -291,9 +308,10 @@ export function useAtlas() {
useEffect(() => {
if (!mapInstance.current || !geoData || !data) return
const visitedA3 = new Set(data.countries.map(c => A2_TO_A3[c.code]).filter(Boolean))
const visitedA3 = new Set(visibleCountries.map(c => A2_TO_A3[c.code]).filter(Boolean))
const plannedA3 = new Set(visibleCountries.filter(c => countryStatus(c) !== 'visited').map(c => A2_TO_A3[c.code]).filter(Boolean))
const countryMap = {}
data.countries.forEach(c => { if (A2_TO_A3[c.code]) countryMap[A2_TO_A3[c.code]] = c })
visibleCountries.forEach(c => { if (A2_TO_A3[c.code]) countryMap[A2_TO_A3[c.code]] = c })
// Preserve current map view
const currentCenter = mapInstance.current.getCenter()
@@ -305,8 +323,10 @@ export function useAtlas() {
// Generate deterministic color per country code
const VISITED_COLORS = ['#6366f1','#ec4899','#14b8a6','#f97316','#8b5cf6','#ef4444','#3b82f6','#22c55e','#06b6d4','#f43f5e','#a855f7','#10b981','#0ea5e9','#e11d48','#0d9488','#7c3aed','#2563eb','#dc2626','#059669','#d946ef']
// Assign colors in order of visit (by index in countries array) so no two neighbors share a color easily
const visitedA3List = [...visitedA3]
// Assign colors in order of visit (by index in countries array) so no two neighbors share a color easily.
// Built from the visited countries only — if planned ones took part, flipping the toggle
// would shift every index and reshuffle the colours of the whole map.
const visitedA3List = [...new Set(visitedCountries.map(c => A2_TO_A3[c.code]).filter(Boolean))]
const colorMap = {}
visitedA3List.forEach((a3, i) => { colorMap[a3] = VISITED_COLORS[i % VISITED_COLORS.length] })
const colorForCode = (a3) => colorMap[a3] || VISITED_COLORS[0]
@@ -319,6 +339,17 @@ export function useAtlas() {
bubblingMouseEvents: false,
style: (feature) => {
const a3 = feature.properties?.ADM0_A3 || feature.properties?.ISO_A3 || feature.properties?.['ISO3166-1-Alpha-3'] || feature.id
// Planned countries read as an outline rather than a fill: dashed border, muted
// wash. Deliberately not one of the VISITED_COLORS, so "been there" stays distinct.
if (plannedA3.has(a3)) {
return {
fillColor: dark ? '#818cf8' : '#4f46e5',
fillOpacity: 0.38,
color: dark ? '#818cf8' : '#4f46e5',
weight: 1,
dashArray: '6 4',
}
}
const visited = visitedA3.has(a3)
return {
fillColor: visited ? colorForCode(a3) : (dark ? '#1e1e2e' : '#e2e8f0'),
@@ -334,22 +365,31 @@ export function useAtlas() {
country_layer_by_a2_ref.current[c.code] = layer
const name = resolveName(c.code)
const formatDate = (d) => { if (!d) return '—'; const dt = new Date(d); return dt.toLocaleDateString(getLocaleForLanguage(language), { month: 'short', year: 'numeric' }) }
const tooltipHtml = `
<div style="display:flex;flex-direction:column;gap:8px;min-width:160px">
<div style="font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:0.1em;padding-bottom:6px;border-bottom:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'}">${name}</div>
<div style="display:flex;gap:14px">
<div><span style="font-size:16px;font-weight:800">${c.tripCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.tripCount === 1 ? t('atlas.tripSingular') : t('atlas.tripPlural')}</span></div>
<div><span style="font-size:16px;font-weight:800">${c.placeCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.placeCount === 1 ? t('atlas.placeVisited') : t('atlas.placesVisited')}</span></div>
</div>
<div style="display:flex;gap:2px;border-top:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'};padding-top:8px">
<div style="flex:1;display:flex;flex-direction:column;gap:2px">
// "First trip / Last trip" is simply wrong for a country you haven't reached yet —
// a planned one gets a single departure date instead.
const planned = countryStatus(c) !== 'visited'
const datesHtml = planned
? `<div style="flex:1;display:flex;flex-direction:column;gap:2px">
<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.4">${t('atlas.plannedFor')}</span>
<span style="font-size:12px;font-weight:700">${formatDate(c.firstVisit)}</span>
</div>`
: `<div style="flex:1;display:flex;flex-direction:column;gap:2px">
<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.4">${t('atlas.firstVisit')}</span>
<span style="font-size:12px;font-weight:700">${formatDate(c.firstVisit)}</span>
</div>
<div style="flex:1;display:flex;flex-direction:column;gap:2px">
<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.4">${t('atlas.lastVisitLabel')}</span>
<span style="font-size:12px;font-weight:700">${formatDate(c.lastVisit)}</span>
</div>
</div>`
const tooltipHtml = `
<div style="display:flex;flex-direction:column;gap:8px;min-width:160px">
<div style="font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:0.1em;padding-bottom:6px;border-bottom:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'}">${name}${planned ? ` <span style="font-size:9px;font-weight:700;opacity:0.55;letter-spacing:0.06em">· ${t('atlas.planned')}</span>` : ''}</div>
<div style="display:flex;gap:14px">
<div><span style="font-size:16px;font-weight:800">${c.tripCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.tripCount === 1 ? t('atlas.tripSingular') : t('atlas.tripPlural')}</span></div>
<div><span style="font-size:16px;font-weight:800">${c.placeCount}</span> <span style="font-size:10px;opacity:0.5;text-transform:uppercase;letter-spacing:0.05em">${c.placeCount === 1 ? t('atlas.placeVisited') : t('atlas.placesVisited')}</span></div>
</div>
<div style="display:flex;gap:2px;border-top:1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'};padding-top:8px">
${datesHtml}
</div>
</div>`
layer.bindTooltip(tooltipHtml, {
@@ -395,7 +435,7 @@ export function useAtlas() {
// Restore map view after re-render
mapInstance.current.setView(currentCenter, currentZoom, { animate: false })
}, [geoData, data, dark])
}, [geoData, data, dark, visibleCountries, visitedCountries])
// Render plugin tint layers (atlasLayerProvider hook) — a dashed wash over the
// countries a plugin flagged, in its own non-interactive pane above the country
@@ -452,29 +492,41 @@ export function useAtlas() {
if (Object.keys(regionGeoCache.current).length === 0) return
// Build set of visited region codes and per-country name sets
// Build set of visited region codes and per-country name sets. Regions follow their
// country's status, so zooming into a planned country can't reveal "visited" regions.
const visitedRegionCodes = new Set<string>()
const plannedRegionCodes = new Set<string>()
const visitedRegionNamesByCountry = new Map<string, Set<string>>()
const plannedRegionNamesByCountry = new Map<string, Set<string>>()
const regionPlaceCounts: Record<string, number> = {}
for (const [countryCode, regions] of Object.entries(visitedRegions)) {
const names = new Set<string>()
const plannedNames = new Set<string>()
for (const r of regions) {
visitedRegionCodes.add(r.code)
names.add(normalizeRegionName(r.name))
const planned = (r.status ?? 'visited') !== 'visited'
if (planned && !showPlanned) continue
if (planned) {
plannedRegionCodes.add(r.code)
plannedNames.add(normalizeRegionName(r.name))
} else {
visitedRegionCodes.add(r.code)
names.add(normalizeRegionName(r.name))
}
regionPlaceCounts[r.code] = r.placeCount
regionPlaceCounts[`${countryCode}:${normalizeRegionName(r.name)}`] = r.placeCount
}
visitedRegionNamesByCountry.set(countryCode, names)
plannedRegionNamesByCountry.set(countryCode, plannedNames)
}
// Match feature by ISO code OR region name scoped to the feature's country. Names are
// normalized (diacritics/dash variants folded) since the geocoder's cached region_name
// and the bundled boundaries' name don't always agree on accenting (e.g. a cached
// "Ile-de-France" must still match the bundle's "Île-de-France") (#atlas-region-match).
const isVisitedFeature = (f: any) => {
if (visitedRegionCodes.has(f.properties?.iso_3166_2)) return true
const matchesRegions = (f: any, codes: Set<string>, namesByCountry: Map<string, Set<string>>) => {
if (codes.has(f.properties?.iso_3166_2)) return true
const countryA2 = (f.properties?.iso_a2 || '').toUpperCase()
const countryNames = visitedRegionNamesByCountry.get(countryA2)
const countryNames = namesByCountry.get(countryA2)
if (!countryNames) return false
const name = normalizeRegionName(f.properties?.name || '')
if (countryNames.has(name)) return true
@@ -482,6 +534,8 @@ export function useAtlas() {
if (nameEn && countryNames.has(nameEn)) return true
return false
}
const isVisitedFeature = (f: any) => matchesRegions(f, visitedRegionCodes, visitedRegionNamesByCountry)
const isPlannedFeature = (f: any) => matchesRegions(f, plannedRegionCodes, plannedRegionNamesByCountry)
// Include ALL region features — visited ones get colored fill, unvisited get outline only
const allFeatures: any[] = []
@@ -494,12 +548,14 @@ export function useAtlas() {
// Use same colors as country layer
const VISITED_COLORS = ['#6366f1','#ec4899','#14b8a6','#f97316','#8b5cf6','#ef4444','#3b82f6','#22c55e','#06b6d4','#f43f5e','#a855f7','#10b981','#0ea5e9','#e11d48','#0d9488','#7c3aed','#2563eb','#dc2626','#059669','#d946ef']
const countryA3Set = data ? data.countries.map(c => A2_TO_A3[c.code]).filter(Boolean) : []
// Same source as the country layer's palette (visited only), or the two layers would
// hand the same country different colours.
const countryA3Set = [...new Set(visitedCountries.map(c => A2_TO_A3[c.code]).filter(Boolean))]
const countryColorMap: Record<string, string> = {}
countryA3Set.forEach((a3, i) => { countryColorMap[a3] = VISITED_COLORS[i % VISITED_COLORS.length] })
// Map country A2 code to country color
const a2ColorMap: Record<string, string> = {}
if (data) data.countries.forEach(c => { if (A2_TO_A3[c.code] && countryColorMap[A2_TO_A3[c.code]]) a2ColorMap[c.code] = countryColorMap[A2_TO_A3[c.code]] })
visitedCountries.forEach(c => { if (A2_TO_A3[c.code] && countryColorMap[A2_TO_A3[c.code]]) a2ColorMap[c.code] = countryColorMap[A2_TO_A3[c.code]] })
const mergedGeo = { type: 'FeatureCollection', features: allFeatures }
@@ -511,6 +567,15 @@ export function useAtlas() {
pane: 'regionPane',
style: (feature) => {
const countryA2 = (feature?.properties?.iso_a2 || '').toUpperCase()
if (isPlannedFeature(feature)) {
return {
fillColor: dark ? '#818cf8' : '#4f46e5',
fillOpacity: 0.4,
color: dark ? '#818cf8' : '#4f46e5',
weight: 1,
dashArray: '6 4',
}
}
const visited = isVisitedFeature(feature)
return visited ? {
fillColor: a2ColorMap[countryA2] || '#6366f1',
@@ -586,7 +651,9 @@ export function useAtlas() {
if (mapInstance.current.getZoom() >= 6) {
regionLayerRef.current.addTo(mapInstance.current)
}
}, [regionGeoLoaded, visitedRegions, dark, t])
// visitedCountries belongs here: the region colours are derived from it, and without
// the dep this effect kept painting regions from a stale country list.
}, [regionGeoLoaded, visitedRegions, dark, t, visitedCountries, showPlanned])
const handleMarkCountry = (code: string, name: string): void => {
setConfirmAction({ type: 'choose', code, name })
@@ -637,16 +704,7 @@ export function useAtlas() {
// Update local state immediately (no API reload = no map re-render flash)
if (type === 'mark') {
apiClient.post(`/addons/atlas/country/${code}/mark`).catch(() => {})
setData(prev => {
if (!prev || prev.countries.find(c => c.code === code)) return prev
const cont = continentForCountry(code)
return {
...prev,
countries: [...prev.countries, { code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }],
stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 },
continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 },
}
})
setData(prev => (prev ? withCountryMarkedVisited(prev, code) : prev))
} else {
apiClient.delete(`/addons/atlas/country/${code}/mark`).catch(() => {})
setSelectedCountry(null)
@@ -756,6 +814,7 @@ export function useAtlas() {
mapRef, regionTooltipRef, panelRef, glareRef, borderGlareRef,
handlePanelMouseMove, handlePanelMouseLeave,
data, setData, stats, countries, selectedCountry, countryDetail,
visitedCountries, visibleCountries, showPlanned, togglePlanned,
loadCountryDetail, handleUnmarkCountry, select_country_from_search,
visitedRegions, setVisitedRegions,
atlas_country_search, set_atlas_country_search,
+20 -3
View File
@@ -1,5 +1,6 @@
import { vi } from 'vitest';
import type { AtlasController } from '../../src/mobile/screens/atlas/atlasController';
import type { VisitStatus } from '@trek/shared';
import type { AtlasData, BucketItem, CountryDetail } from '../../src/pages/atlas/atlasModel';
/**
@@ -12,17 +13,21 @@ import type { AtlasData, BucketItem, CountryDetail } from '../../src/pages/atlas
* setter was called" and "this is the state it produced".
*/
export type VisitedRegions = Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean }[]>;
export type VisitedRegions = Record<
string,
{ code: string; name: string; placeCount: number; manuallyMarked?: boolean; status?: VisitStatus }[]
>;
const echoT = (key: string, params?: Record<string, string | number>): string =>
params ? `${key}:${Object.values(params).join(',')}` : key;
export function buildAtlasData(over: Partial<AtlasData> = {}): AtlasData {
return {
countries: [{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCities: 3 },
countries: [{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01', status: 'visited' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCities: 3, totalCountriesPlanned: 0, totalCountriesIdea: 0 },
mostVisited: null,
continents: { Europe: 1 },
continentsPlanned: {},
lastTrip: { id: 7, title: 'Paris Trip', countryCode: 'FR' },
nextTrip: null,
streak: 2,
@@ -50,6 +55,7 @@ export function buildCountryDetail(over: Partial<CountryDetail> = {}): CountryDe
places: [],
trips: [],
manually_marked: false,
status: 'visited',
...over,
};
}
@@ -99,6 +105,10 @@ export function buildAtlasController(over: Record<string, unknown> = {}): AtlasC
data: buildAtlasData(),
stats: buildAtlasData().stats,
countries: buildAtlasData().countries,
visitedCountries: buildAtlasData().countries,
visibleCountries: buildAtlasData().countries,
showPlanned: false,
togglePlanned: vi.fn(() => undefined),
selectedCountry: null,
countryDetail: null,
loadCountryDetail: vi.fn(async () => undefined),
@@ -144,6 +154,13 @@ export function buildAtlasController(over: Record<string, unknown> = {}): AtlasC
const data = ctrl.data as AtlasData | null;
if (!('stats' in over)) ctrl.stats = data?.stats ?? { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 };
if (!('countries' in over)) ctrl.countries = data?.countries ?? [];
// The hook derives these from data + showPlanned; mirror that so a test that only
// sets `data` still gets a consistent controller.
const all = (ctrl.countries ?? []) as AtlasData['countries'];
if (!('visitedCountries' in over)) ctrl.visitedCountries = all.filter(c => (c.status ?? 'visited') === 'visited');
if (!('visibleCountries' in over)) {
ctrl.visibleCountries = ctrl.showPlanned ? all : all.filter(c => (c.status ?? 'visited') === 'visited');
}
return ctrl as unknown as AtlasController;
}