refactor(atlas): share the country popup actions between desktop and phone

useAtlasCountryActions marks a country or a region, unmarks a region, adds the
country or region to the bucket list and takes the country off it again for
both the desktop dialog and the phone sheet. The desktop dialog moves into its
own component in AtlasPage so the page body keeps calling useAtlas only. The
phone sheet keeps storing a marked region as visited and its own month input;
the desktop keeps its month and year picker in useAtlas.
This commit is contained in:
Maurice
2026-10-09 10:43:12 +02:00
parent df6a8ba003
commit e40bc98a33
5 changed files with 649 additions and 348 deletions
@@ -1,13 +1,8 @@
import { useEffect, useState } from 'react'
import { ChevronRight, MapPin, Star, Trash2 } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import apiClient from '../../../api/client'
import { continentForCountry } from '@trek/shared'
import { findBucketDuplicate, isBucketDuplicateError, withCountryMarkedVisited } from '../../../pages/atlas/atlasModel'
import { getApiErrorMessage } from '../../../types'
import { useToast } from '../../../components/shared/Toast'
import MSheet from '../../components/MSheet'
import type { AtlasController } from './atlasController'
import { useAtlasCountryActions } from '../../../pages/atlas/useAtlasCountryActions'
const markTint = 'bg-[rgba(47,163,122,.16)] text-[color:var(--m-st-confirmed)]' // theme-lint-disable — fixed tint from the design's option rows
const bucketTint = 'bg-[rgba(232,161,58,.16)] text-[color:var(--m-st-pending)]' // theme-lint-disable — fixed tint from the design's option rows
@@ -58,131 +53,11 @@ interface MAtlasCountryPopupProps {
* rendered as the mobile card sheet.
*/
export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
const {
t,
confirmAction,
setConfirmAction,
executeConfirmAction,
setData,
setVisitedRegions,
setBucketList,
visitedRegions,
bucketList,
handleDeleteBucketItem,
} = atlas
const toast = useToast()
const [bucketDate, setBucketDate] = useState('')
useEffect(() => {
if (!confirmAction) setBucketDate('')
}, [confirmAction])
const markCountry = async (): Promise<void> => {
if (!confirmAction) return
const { code } = confirmAction
try {
await apiClient.post(`/addons/atlas/country/${code}/mark`)
setData((prev) => (prev ? withCountryMarkedVisited(prev, code) : prev))
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
}
setConfirmAction(null)
}
const markRegion = async (): Promise<void> => {
if (!confirmAction) return
const { code: countryCode, name: regionName, regionCode } = confirmAction
if (!regionCode) return
try {
await apiClient.post(`/addons/atlas/region/${regionCode}/mark`, { name: regionName, country_code: countryCode })
setVisitedRegions((prev) => {
const existing = prev[countryCode] || []
if (existing.find((r) => r.code === regionCode)) return prev
return { ...prev, [countryCode]: [...existing, { code: regionCode, name: regionName, placeCount: 0, status: 'visited' as const, manuallyMarked: true }] }
})
setData((prev) => (prev ? withCountryMarkedVisited(prev, countryCode) : prev))
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
}
setConfirmAction(null)
}
const unmarkRegion = async (): Promise<void> => {
if (!confirmAction) return
const { code: countryCode, regionCode } = confirmAction
if (!regionCode) return
try {
await apiClient.delete(`/addons/atlas/region/${regionCode}/mark`)
setVisitedRegions((prev) => {
const remaining = (prev[countryCode] || []).filter((r) => r.code !== regionCode)
const next = { ...prev, [countryCode]: remaining }
if (remaining.length === 0) delete next[countryCode]
return next
})
// Drop the country too once no visible region is left — how a region was
// derived does not matter, the server hides it either way. Countries with
// real place/trip data are never hidden server-side (#1490), so removing
// them here would only flash and reappear on the next load.
setData((prev) => {
if (!prev) return prev
const c = prev.countries.find((c) => c.code === countryCode)
if (!c || c.placeCount > 0 || c.tripCount > 0) return prev
const remainingRegions = (visitedRegions[countryCode] || []).filter((r) => r.code !== regionCode)
if (remainingRegions.length > 0) return prev
const cont = continentForCountry(countryCode)
return {
...prev,
countries: prev.countries.filter((c) => c.code !== countryCode),
stats: { ...prev.stats, totalCountries: Math.max(0, prev.stats.totalCountries - 1) },
continents: { ...prev.continents, [cont]: Math.max(0, (prev.continents?.[cont] || 0) - 1) },
}
})
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
}
setConfirmAction(null)
}
const addBucket = async (): Promise<void> => {
if (!confirmAction) return
const targetDate = bucketDate || null
// #1898: one entry per target date. The sheet stays open on a duplicate so
// another month can be picked right away.
if (findBucketDuplicate(bucketList, { name: confirmAction.name, country_code: confirmAction.code, target_date: targetDate, lat: null, lng: null })) {
toast.error(t('atlas.bucketDuplicate'))
return
}
try {
const r = await apiClient.post('/addons/atlas/bucket-list', {
name: confirmAction.name,
country_code: confirmAction.code,
target_date: targetDate,
// A region wish hatches that region on the map, not the whole country (#1901).
region_code: confirmAction.regionCode ?? null,
})
setBucketList((prev) => [r.data.item, ...prev])
} catch (err) {
if (isBucketDuplicateError(err)) {
toast.error(t('atlas.bucketDuplicate'))
return
}
toast.error(getApiErrorMessage(err, t('common.error')))
}
setConfirmAction(null)
}
// A country can sit on the bucket list more than once (one entry per place and
// target date), so taking it off the wishlist means dropping every entry for
// that code.
const removeBucket = async (): Promise<void> => {
if (!confirmAction) return
const wishlistItems = bucketList.filter((b) => b.country_code === confirmAction.code)
await Promise.all(wishlistItems.map((item) => handleDeleteBucketItem(item.id)))
setConfirmAction(null)
}
const { t, confirmAction, setConfirmAction, executeConfirmAction } = atlas
const { bucketDate, setBucketDate, onWishlist, markCountry, markRegion, unmarkRegion, addBucketForDate, removeBucket } =
useAtlasCountryActions(atlas)
const a = confirmAction
const onWishlist = !!a && bucketList.some((b) => b.country_code === a.code)
return (
<MSheet open={!!a} onClose={() => setConfirmAction(null)} variant="card" ariaLabel={a?.name}>
@@ -231,7 +106,7 @@ export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
{a.type === 'choose-region' && (
<>
<OptionRow icon={MapPin} tint={markTint} title={t('atlas.markVisited')} hint={t('atlas.markRegionVisitedHint')} onClick={markRegion} />
<OptionRow icon={MapPin} tint={markTint} title={t('atlas.markVisited')} hint={t('atlas.markRegionVisitedHint')} onClick={() => markRegion(true)} />
<OptionRow
icon={Star}
tint={bucketTint}
@@ -298,7 +173,7 @@ export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
>
{t('common.back')}
</button>
<button type="button" onClick={addBucket} className={actBtn}>
<button type="button" onClick={addBucketForDate} className={actBtn}>
{t('atlas.addToBucket')}
</button>
</div>