mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(atlas): the globe Atlas with its hub, on desktop and phone
The Atlas page is now the globe. Everything the classic map offered carries over: visited countries and regions, planned countries, the wishlist with places and target dates, Dawarich, tours, plugin layers and the place search. New: - regions on the globe, with how much of a country has been seen (#2675, #316, #487) - flight arcs (#1369, #2642) - a hub with statistics, badges, wishlist, Dawarich, tours and travellers - an instance ranking, traveller profiles and a compare overlay - a timeline that plays back how the map grew - phone layouts of their own: sheets, chips and swipe actions The classic Leaflet Atlas and its phone screen are removed.
This commit is contained in:
+3
-2
@@ -320,7 +320,7 @@ function RouteFallback() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadUser, isAuthenticated, demoMode, setManaged, setDemoMode, setDevMode, setIsPrerelease, setAppVersion, setHasMapsKey, setHasAmapKey, setPlacesProvider, setServerTimezone, setAppRequireMfa, setTripRemindersEnabled, setAtlasCompareEnabled, setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled, setPlacesEnrichEnabled, setPlaceShadowEnabled } = useAuthStore()
|
||||
const { loadSettings } = useSettingsStore()
|
||||
const { loadAddons } = useAddonStore()
|
||||
const { loadPlugins } = usePluginStore()
|
||||
@@ -351,7 +351,7 @@ export default function App() {
|
||||
}, Math.min(30_000, 1_000 * 2 ** attempt))
|
||||
})
|
||||
})
|
||||
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
|
||||
fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; atlas_compare_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
|
||||
setManaged(!!config?.managed)
|
||||
setDemoMode(!!config?.demo_mode)
|
||||
if (config?.dev_mode) setDevMode(true)
|
||||
@@ -363,6 +363,7 @@ export default function App() {
|
||||
if (config?.timezone) setServerTimezone(config.timezone)
|
||||
if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa)
|
||||
if (config?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(config.trip_reminders_enabled)
|
||||
if (config?.atlas_compare_enabled !== undefined) setAtlasCompareEnabled(config.atlas_compare_enabled)
|
||||
if (config?.places_photos_enabled !== undefined) setPlacesPhotosEnabled(config.places_photos_enabled)
|
||||
if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled)
|
||||
if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
|
||||
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar, Trophy } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import AirTrailIcon from '../shared/AirTrailIcon'
|
||||
@@ -94,6 +94,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
wandererOffered,
|
||||
toggleToursWanderer,
|
||||
mapSwitches,
|
||||
atlasCompare,
|
||||
toggleAtlasCompare,
|
||||
} = useAddonManager()
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -109,6 +111,17 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
|
||||
* parent as shelf rows, and each shelf only shows while its parent is on —
|
||||
* a provider toggled under a disabled Journey would hit the server's 409. */
|
||||
const shelfFor = (addon: Addon) => {
|
||||
if (addon.id === 'atlas' && addon.enabled) {
|
||||
return (
|
||||
<AddonSubRow
|
||||
icon={<Trophy size={14} />}
|
||||
title={t('admin.atlasCompare.title')}
|
||||
description={t('admin.atlasCompare.subtitle')}
|
||||
enabled={atlasCompare}
|
||||
onToggle={() => void toggleAtlasCompare()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (addon.id === 'packing' && addon.enabled && onToggleBagTracking) {
|
||||
return (
|
||||
<AddonSubRow
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { AdminFeatureToggleResponse } from '@trek/shared';
|
||||
import { Bike, Footprints, MountainSnow } from 'lucide-react';
|
||||
import { useEffect, useEffectEvent, useState } from 'react';
|
||||
|
||||
import { adminApi } from '../../../api/client';
|
||||
import { adminApi, authApi } from '../../../api/client';
|
||||
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
|
||||
import { wandererAdminApi } from '../../../api/wanderer';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
@@ -43,6 +43,9 @@ export function useAddonManager() {
|
||||
const [toursHikingMap, setToursHikingMap] = useState(false);
|
||||
const [toursCycleMap, setToursCycleMap] = useState(false);
|
||||
const [toursSkiRouting, setToursSkiRouting] = useState(false);
|
||||
// The Atlas ranking switch is an app setting the app config already carries.
|
||||
const atlasCompare = useAuthStore((s) => s.atlasCompareEnabled);
|
||||
const setAtlasCompare = useAuthStore((s) => s.setAtlasCompareEnabled);
|
||||
|
||||
const loadAddons = async () => {
|
||||
try {
|
||||
@@ -105,6 +108,11 @@ export function useAddonManager() {
|
||||
void refreshGlobalAddons();
|
||||
toast.success(t('admin.addons.toast.updated'));
|
||||
};
|
||||
/** Whether travellers on this instance see the Atlas ranking and each other's profiles. */
|
||||
const toggleAtlasCompare = () =>
|
||||
flipToursSwitch(atlasCompare, setAtlasCompare, (enabled) =>
|
||||
authApi.updateAppSettings({ atlas_compare_enabled: enabled })
|
||||
);
|
||||
const toggleToursWanderer = () => flipToursSwitch(toursWanderer, setToursWanderer, wandererAdminApi.update);
|
||||
/** The maps and the piste router Tours offers on their operators' terms, one switch each (MAP-01, BIK-06, SKI-02). */
|
||||
const mapSwitches = [
|
||||
@@ -167,5 +175,7 @@ export function useAddonManager() {
|
||||
wandererOffered,
|
||||
toggleToursWanderer,
|
||||
mapSwitches,
|
||||
atlasCompare,
|
||||
toggleAtlasCompare,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
// FE-STA2-PANE-001 to FE-STA2-PANE-006
|
||||
// STA-02: the Atlas tab of the user's own tour activities: the distance large
|
||||
// with how many tours at its corner, the climb, the types, what the numbers
|
||||
// rest on, and the full list in a dialog.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { summarizeTourActivities, type TourActivityStatsEntry, type TourActivityStatsResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildSettings } from '../../../../tests/helpers/factories';
|
||||
import { render, screen } from '../../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { AtlasTourActivityPane } from './AtlasTourActivityPane';
|
||||
import type { TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
const hook = vi.hoisted(() => ({ current: null as unknown, active: [] as boolean[] }));
|
||||
vi.mock('./useTourActivityStats', () => ({
|
||||
useTourActivityStats: (active: boolean) => {
|
||||
hook.active.push(active);
|
||||
return hook.current;
|
||||
},
|
||||
}));
|
||||
|
||||
const TODAY = '2026-10-20';
|
||||
|
||||
function entry(overrides: Partial<TourActivityStatsEntry> = {}): TourActivityStatsEntry {
|
||||
return {
|
||||
place_id: 1,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
trip: { id: 5, title: 'Alps' },
|
||||
derived_from_place_id: null,
|
||||
date: '2026-07-02',
|
||||
basis: 'plan',
|
||||
track: null,
|
||||
day_count: 1,
|
||||
distance_km: 12,
|
||||
ascent_m: 800,
|
||||
descent_m: 790,
|
||||
excluded: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function statsOf(data: TourActivityStatsResponse | null, overrides: Partial<TourActivityStats> = {}) {
|
||||
const stats: TourActivityStats = {
|
||||
status: data ? 'ready' : 'loading',
|
||||
data,
|
||||
summary: data ? summarizeTourActivities(data.entries, { today: TODAY }) : null,
|
||||
period: 'all',
|
||||
setPeriod: vi.fn(),
|
||||
periods: ['all', 'thisYear', 'last12'],
|
||||
type: 'all',
|
||||
setType: vi.fn(),
|
||||
types: ['all', 'hike', 'kayak'],
|
||||
pending: new Set(),
|
||||
setExcluded: vi.fn().mockResolvedValue(undefined),
|
||||
retry: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
hook.current = stats;
|
||||
return stats;
|
||||
}
|
||||
|
||||
const data: TourActivityStatsResponse = {
|
||||
entries: [
|
||||
entry(),
|
||||
entry({ place_id: 2, name: 'Summit', date: '2026-08-01', distance_km: 20.5, ascent_m: 1200, descent_m: 1200 }),
|
||||
entry({
|
||||
place_id: 3,
|
||||
name: 'Lake',
|
||||
tour_type: 'kayak',
|
||||
basis: 'track',
|
||||
track: { place_id: 9, name: 'Watch' },
|
||||
distance_km: 8,
|
||||
ascent_m: null,
|
||||
descent_m: null,
|
||||
}),
|
||||
],
|
||||
uncounted: { unassigned: 0, undated: 1 },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
hook.active = [];
|
||||
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
|
||||
});
|
||||
|
||||
describe('AtlasTourActivityPane', () => {
|
||||
it('FE-STA2-PANE-001: follows whether the tab is shown, silent before, loading until the read is there', () => {
|
||||
statsOf(null, { status: 'idle' });
|
||||
const { rerender } = render(<AtlasTourActivityPane active={false} />);
|
||||
expect(hook.active).toEqual([false]);
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument();
|
||||
statsOf(null);
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(hook.active).toEqual([false, true]);
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Loading');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-002: shows the distance large with the tour count at its corner, and the climb', () => {
|
||||
statsOf(data);
|
||||
render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByTestId('atlas-tour-activity-distance')).toHaveTextContent('40.5km');
|
||||
expect(screen.getByTestId('atlas-tour-activity-count')).toHaveTextContent('3');
|
||||
expect(screen.getByTestId('atlas-tour-activity-ascent')).toHaveTextContent('2000m');
|
||||
expect(screen.getByTestId('atlas-tour-activity-type-hike')).toHaveTextContent('2');
|
||||
expect(screen.getByTestId('atlas-tour-activity-type-kayak')).toHaveTextContent('8 km');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-003: says what the numbers rest on and what does not count', () => {
|
||||
statsOf(data);
|
||||
render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByTestId('tour-activity-basis-plan')).toHaveTextContent('Planned2');
|
||||
expect(screen.getByTestId('tour-activity-basis-track')).toHaveTextContent('Recorded1');
|
||||
expect(screen.getByTestId('tour-activity-undated')).toHaveTextContent('1');
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-004: one type chosen leaves the type columns out; nothing done says so', () => {
|
||||
statsOf(data, { type: 'hike', summary: summarizeTourActivities(data.entries, { today: TODAY, type: 'hike' }) });
|
||||
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||
expect(screen.queryByTestId('atlas-tour-activity-type-hike')).not.toBeInTheDocument();
|
||||
|
||||
statsOf(data, { summary: summarizeTourActivities(data.entries, { today: TODAY, from: '2027-01-01' }) });
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByText('No completed tours in this period')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Show tours' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-005: the full list opens in the dialog', async () => {
|
||||
statsOf(data);
|
||||
const user = userEvent.setup();
|
||||
render(<AtlasTourActivityPane active />);
|
||||
await user.click(screen.getByRole('button', { name: 'Show tours' }));
|
||||
expect(screen.getByRole('heading', { name: 'My tour activities' })).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tour-activity-list')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-STA2-PANE-006: offline and failed reads say so, a failed one with a retry', async () => {
|
||||
statsOf(null, { status: 'offline' });
|
||||
const { rerender } = render(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByText(/needs a connection/i)).toBeInTheDocument();
|
||||
|
||||
const failed = statsOf(null, { status: 'error' });
|
||||
rerender(<AtlasTourActivityPane active />);
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Tour activities could not be loaded');
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: 'Try again' }));
|
||||
expect(failed.retry).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,223 +0,0 @@
|
||||
import type { TourActivitySummary } from '@trek/shared';
|
||||
import { Footprints, ListOrdered } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { CardAction, InfoDot } from '../../Tours/tourParts';
|
||||
import { ActivityFilters, ActivityStatusLine, BasisBadges, UncountedBadges } from './tourActivityParts';
|
||||
import { distanceReading, heightReading, typeIcon, typeLabel, useDistanceUnit } from './tourActivityReading';
|
||||
import { TourActivityStatsDialog } from './TourActivityStatsDialog';
|
||||
import { splitMeasure } from './tourActivityStatsModel';
|
||||
import { useTourActivityStats, type TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
/** The wash the hero tile sits on, as the Atlas numbers do: the text colour, faintly, over the glass. */
|
||||
const HERO_TINT = 'color-mix(in srgb, var(--text-primary) 7%, transparent)';
|
||||
/** How many types the strip names before the dialog takes over. */
|
||||
const STRIP_TYPES = 3;
|
||||
const EYEBROW = 'mt-1.5 whitespace-nowrap font-semibold uppercase tracking-wide text-content-faint';
|
||||
|
||||
function Divider() {
|
||||
return <span aria-hidden="true" className="mx-3 my-3 w-0.5 flex-none rounded-full bg-edge-faint" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The distance of the period, large, with how many tours at its corner; the
|
||||
* tour count stands in when no tour knows its distance.
|
||||
*/
|
||||
function Hero({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
const reading = distanceReading(summary.totals, unit);
|
||||
const shown = reading ? splitMeasure(reading.text) : { value: String(summary.totals.count), unit: '' };
|
||||
const countLabel = `${t('tours.mode.tours')}: ${summary.totals.count}`;
|
||||
return (
|
||||
<div
|
||||
className="relative mx-2 my-2 flex flex-col justify-center rounded-xl px-5 py-4"
|
||||
style={{ background: HERO_TINT }}
|
||||
>
|
||||
<div className="flex items-baseline gap-1.5" data-testid="atlas-tour-activity-distance">
|
||||
<span className="font-black tabular-nums leading-none text-content" style={fs(40, 'title')}>
|
||||
{shown.value}
|
||||
</span>
|
||||
{shown.unit && (
|
||||
<span className="font-medium text-content-muted" style={fs(14, 'body')}>
|
||||
{shown.unit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className={EYEBROW} style={fs(9)}>
|
||||
{reading ? t('tours.detail.distance') : t('tours.mode.tours')}
|
||||
</span>
|
||||
{reading && (
|
||||
<Tooltip label={countLabel}>
|
||||
<span
|
||||
aria-label={countLabel}
|
||||
data-testid="atlas-tour-activity-count"
|
||||
className="absolute -end-2 -top-2 inline-flex h-[22px] items-center gap-1 rounded-full bg-surface-card px-2 font-geist font-semibold tabular-nums text-content shadow-sm ring-1 ring-inset ring-edge-faint"
|
||||
style={fs(11)}
|
||||
>
|
||||
<Footprints size={11} strokeWidth={2.2} className="flex-none text-content-muted" />
|
||||
{summary.totals.count}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A height sum as the Atlas numbers stand: the value, its unit, and what it is below. */
|
||||
function Figure({ label, text, testId }: { label: string; text: string; testId: string }) {
|
||||
const { value, unit } = splitMeasure(text);
|
||||
return (
|
||||
<div className="flex flex-none flex-col items-center justify-center px-3 py-4" data-testid={testId}>
|
||||
<span className="flex items-baseline gap-1">
|
||||
<span className="font-black tabular-nums leading-none text-content" style={fs(24, 'subtitle')}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="font-medium text-content-muted" style={fs(11, 'body')}>
|
||||
{unit}
|
||||
</span>
|
||||
</span>
|
||||
<span className={EYEBROW} style={fs(9)}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The types of the period, the most tours first: each an icon with its count at the corner, its distance below. */
|
||||
function TypeColumns({ summary, unit }: { summary: TourActivitySummary; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-none items-center gap-4 px-2 py-3">
|
||||
{summary.types.slice(0, STRIP_TYPES).map((scope) => {
|
||||
const Icon = typeIcon(scope.type);
|
||||
const distance = distanceReading(scope, unit);
|
||||
const label = `${typeLabel(scope.type, t)}: ${scope.count}${distance ? `, ${distance.text}` : ''}`;
|
||||
return (
|
||||
<Tooltip key={scope.type} label={label}>
|
||||
<span
|
||||
aria-label={label}
|
||||
className="flex flex-col items-center gap-1.5"
|
||||
data-testid={`atlas-tour-activity-type-${scope.type}`}
|
||||
>
|
||||
<span className="relative">
|
||||
<span className="grid h-8 w-8 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-inset ring-edge-faint">
|
||||
<Icon size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span
|
||||
className="absolute -end-1.5 -top-1.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 font-geist font-semibold tabular-nums text-accent-text ring-2 ring-surface-card"
|
||||
style={fs(9)}
|
||||
>
|
||||
{scope.count}
|
||||
</span>
|
||||
</span>
|
||||
{distance && (
|
||||
<span
|
||||
className="whitespace-nowrap font-semibold tabular-nums text-content-secondary"
|
||||
style={fs(11, 'body')}
|
||||
>
|
||||
{distance.text}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the sums rest on, what does not count, and the way into the full list. */
|
||||
interface StripProps {
|
||||
stats: TourActivityStats;
|
||||
summary: TourActivitySummary;
|
||||
onOpen: () => void;
|
||||
}
|
||||
|
||||
function SideColumn({ stats, summary, onOpen }: StripProps) {
|
||||
const { t } = useTranslation();
|
||||
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
|
||||
return (
|
||||
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<BasisBadges byBasis={summary.totals.byBasis} />
|
||||
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
|
||||
</div>
|
||||
{summary.done.length > 0 && (
|
||||
<CardAction icon={<ListOrdered size={13} strokeWidth={2.2} />} onClick={onOpen}>
|
||||
{t('tours.stats.showTours')}
|
||||
</CardAction>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The numbers of the period, or why there are none, with the filters before them. */
|
||||
function Strip({ stats, summary, onOpen }: StripProps) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useDistanceUnit();
|
||||
const ascent = heightReading(summary.totals.ascentM, unit);
|
||||
const descent = heightReading(summary.totals.descentM, unit);
|
||||
const counted = summary.totals.count > 0;
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-none flex-col items-start justify-center gap-1.5 px-3 py-3">
|
||||
<ActivityFilters stats={stats} quiet />
|
||||
</div>
|
||||
{counted ? (
|
||||
<>
|
||||
<Hero summary={summary} unit={unit} />
|
||||
{ascent && <Figure label={t('tours.detail.ascent')} text={ascent.text} testId="atlas-tour-activity-ascent" />}
|
||||
{descent && (
|
||||
<Figure label={t('tours.detail.descent')} text={descent.text} testId="atlas-tour-activity-descent" />
|
||||
)}
|
||||
{stats.type === 'all' && summary.types.length > 1 && (
|
||||
<>
|
||||
<Divider />
|
||||
<TypeColumns summary={summary} unit={unit} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="m-0 flex max-w-[260px] items-center px-4 py-5 text-content-muted" style={fs(12, 'body')}>
|
||||
{t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')}
|
||||
</p>
|
||||
)}
|
||||
<Divider />
|
||||
<SideColumn stats={stats} summary={summary} onOpen={onOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* STA-02: the Atlas tab of the user's own tour activities: the period and type,
|
||||
* the distance done with how many tours at its corner, the climb, the types,
|
||||
* and what the numbers rest on (the trip planning, or recorded tracks where
|
||||
* linked). The full list, where a tour can be left out, opens in a dialog. The
|
||||
* read waits until the tab is first shown.
|
||||
*/
|
||||
export function AtlasTourActivityPane({ active, maxWidth }: { active: boolean; maxWidth?: number }) {
|
||||
const stats = useTourActivityStats(active);
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div
|
||||
className="flex w-full items-stretch justify-center overflow-x-auto px-2"
|
||||
style={{ maxWidth }}
|
||||
data-testid="atlas-tour-activity"
|
||||
>
|
||||
{stats.summary ? (
|
||||
<Strip stats={stats} summary={stats.summary} onOpen={() => setOpen(true)} />
|
||||
) : (
|
||||
<div className="flex items-center px-6 py-5">
|
||||
<ActivityStatusLine stats={stats} />
|
||||
</div>
|
||||
)}
|
||||
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { periodYear, type ActivityPeriod, type ActivityType } from './tourActivi
|
||||
import type { TourActivityStats } from './useTourActivityStats';
|
||||
|
||||
/** What a period is called in the filter. */
|
||||
function periodLabel(period: ActivityPeriod, t: Translate): string {
|
||||
export function periodLabel(period: ActivityPeriod, t: Translate): string {
|
||||
if (period === 'all') return t('tours.stats.period.all');
|
||||
if (period === 'thisYear') return t('tours.stats.period.thisYear');
|
||||
if (period === 'last12') return t('tours.stats.period.last12');
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { useRef, type RefObject } from 'react'
|
||||
|
||||
export interface GlassGlare {
|
||||
/** Goes on the panel itself — the glare is measured against its box. */
|
||||
panelRef: RefObject<HTMLDivElement | null>
|
||||
/** The soft light under the cursor. */
|
||||
glareRef: RefObject<HTMLDivElement | null>
|
||||
/** The lit stretch of border around it. */
|
||||
borderGlareRef: RefObject<HTMLDivElement | null>
|
||||
onMouseMove: (e: { clientX: number; clientY: number }) => void
|
||||
onMouseLeave: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The Atlas panels' liquid-glass hover: a pool of light under the cursor and the
|
||||
* piece of border nearest to it lighting up.
|
||||
*
|
||||
* Extracted so a second panel beside the first one behaves identically. Two
|
||||
* hand-copied versions of a gradient are two versions that drift, and the whole
|
||||
* point of the effect is that the panels look like one material.
|
||||
*
|
||||
* Written straight to the DOM rather than through state: this runs on every
|
||||
* mousemove, and a re-render per frame would cost more than the effect is worth.
|
||||
*/
|
||||
export function useGlassGlare(dark: boolean): GlassGlare {
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const glareRef = useRef<HTMLDivElement>(null)
|
||||
const borderGlareRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const onMouseMove = (e: { clientX: number; clientY: number }): void => {
|
||||
if (!panelRef.current || !glareRef.current || !borderGlareRef.current) return
|
||||
const rect = panelRef.current.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
const y = e.clientY - rect.top
|
||||
glareRef.current.style.background = `radial-gradient(circle 300px at ${x}px ${y}px, ${dark ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.25)'} 0%, transparent 70%)`
|
||||
glareRef.current.style.opacity = '1'
|
||||
borderGlareRef.current.style.opacity = '1'
|
||||
borderGlareRef.current.style.maskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
borderGlareRef.current.style.webkitMaskImage = `radial-gradient(circle 150px at ${x}px ${y}px, black 0%, transparent 100%)`
|
||||
}
|
||||
|
||||
const onMouseLeave = (): void => {
|
||||
if (glareRef.current) glareRef.current.style.opacity = '0'
|
||||
if (borderGlareRef.current) borderGlareRef.current.style.opacity = '0'
|
||||
}
|
||||
|
||||
return { panelRef, glareRef, borderGlareRef, onMouseMove, onMouseLeave }
|
||||
}
|
||||
@@ -1,637 +0,0 @@
|
||||
// FE-DAWARICH-ATLASDLG-001 to FE-DAWARICH-ATLASDLG-029
|
||||
/**
|
||||
* The room where Dawarich's two Atlas questions get answered.
|
||||
*
|
||||
* Nothing in here runs on its own, and that is the whole design: the Atlas is a
|
||||
* curated list that carries tombstones precisely so a country somebody removed
|
||||
* stays removed, so every read and every write starts with a person pressing a
|
||||
* button. What is worth pinning is therefore not "does it fetch" but everything
|
||||
* arranged around the fetch.
|
||||
*
|
||||
* - **What is written, and dated when.** A wish is ticked off on the day it was
|
||||
* reached, not on today, and wishes reached on the same day travel in one
|
||||
* request. A regression here either back-dates somebody's list wrongly or
|
||||
* turns one confirmation into twenty requests.
|
||||
* - **The five states each half can be in.** Unasked, in flight, answered,
|
||||
* answered with nothing, answered with caveats. The confirm button is
|
||||
* rendered or absent rather than merely greyed out, so each state has to
|
||||
* decide whether that control exists at all, and the caveats under the list
|
||||
* are only said when there is something to say.
|
||||
* - **Refusing to write blind.** Offline is not a server error: nothing was
|
||||
* sent, and "something went wrong talking to Dawarich" for a train tunnel
|
||||
* sends people hunting for a bug in their own instance.
|
||||
* - **Both shells.** The phone gets an MSheet with its own footer, the desktop
|
||||
* a Modal; the body between them is the same tree, so a regression that
|
||||
* dropped one shell would otherwise only surface on a device.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { act, fireEvent } from '@testing-library/react'
|
||||
import { setForcedOffline } from '../../sync/networkMode'
|
||||
import { DawarichOfflineError } from '../../repo/dawarichRepo'
|
||||
import DawarichAtlasDialog from './DawarichAtlasDialog'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
|
||||
|
||||
const repo = {
|
||||
bucketScan: vi.fn(),
|
||||
atlasSuggestions: vi.fn(),
|
||||
}
|
||||
vi.mock('../../repo/dawarichRepo', () => ({
|
||||
dawarichRepo: {
|
||||
bucketScan: (...args: unknown[]) => repo.bucketScan(...args),
|
||||
atlasSuggestions: (...args: unknown[]) => repo.atlasSuggestions(...args),
|
||||
},
|
||||
DawarichOfflineError: class extends Error {},
|
||||
}))
|
||||
|
||||
const api = {
|
||||
confirmBucketVisits: vi.fn(),
|
||||
acceptAtlasCountries: vi.fn(),
|
||||
}
|
||||
vi.mock('../../api/dawarich', () => ({
|
||||
dawarichApi: {
|
||||
confirmBucketVisits: (...args: unknown[]) => api.confirmBucketVisits(...args),
|
||||
acceptAtlasCountries: (...args: unknown[]) => api.acceptAtlasCountries(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
// The one thing the dialog reads about the device. A hoisted flag rather than a
|
||||
// resize: useIsPhone is matchMedia-driven and the global stub always answers false.
|
||||
const phone = vi.hoisted(() => ({ value: false }))
|
||||
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }))
|
||||
|
||||
const SCAN = {
|
||||
matches: [
|
||||
{
|
||||
itemId: 11,
|
||||
name: 'Museum Ludwig',
|
||||
match: { at: '2026-09-10T14:00:00Z', minutes: 145, distanceMeters: 49, points: 60 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 12,
|
||||
name: 'Kölner Dom',
|
||||
match: { at: '2026-09-09T14:00:00Z', minutes: 30, distanceMeters: 80, points: 12 },
|
||||
alreadyVisited: true,
|
||||
},
|
||||
{ itemId: 13, name: 'Rheinpark', match: null, alreadyVisited: false },
|
||||
],
|
||||
skippedWithoutCoordinates: 2,
|
||||
truncated: false,
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
const COUNTRIES = {
|
||||
countries: [
|
||||
{ countryCode: 'DE', sourceName: 'Germany', cities: [{ name: 'Cologne', minutes: 400, lastSeenAt: '2026-09-10T10:00:00Z' }], alreadyVisited: true },
|
||||
{ countryCode: 'NL', sourceName: 'Netherlands', cities: [{ name: 'Maastricht', minutes: 90, lastSeenAt: '2026-09-08T10:00:00Z' }], alreadyVisited: false },
|
||||
],
|
||||
unresolved: ['Freedonia'],
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* Three wishes reached on two days. The pair sharing a timestamp is the whole
|
||||
* point of the fixture: the dialog groups by the date it is about to write, and
|
||||
* a regression that lost the grouping would send one request per wish. The
|
||||
* third one sits far enough away to be reported in kilometres rather than
|
||||
* metres, which is the other half of the row's arithmetic.
|
||||
*/
|
||||
const SAME_DAY = {
|
||||
matches: [
|
||||
{
|
||||
itemId: 21,
|
||||
name: 'Van Gogh Museum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 95, distanceMeters: 30, points: 40 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 22,
|
||||
name: 'Rijksmuseum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 120, distanceMeters: 55, points: 51 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 23,
|
||||
name: 'Kinderdijk',
|
||||
match: { at: '2026-07-30T09:00:00Z', minutes: 70, distanceMeters: 1400, points: 22 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
],
|
||||
skippedWithoutCoordinates: 0,
|
||||
truncated: false,
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* A reading with nothing to apologise for: no unmatched names, one country with
|
||||
* more cities than fit beside a flag and one with none at all.
|
||||
*/
|
||||
const MORE_COUNTRIES = {
|
||||
countries: [
|
||||
{
|
||||
countryCode: 'FR',
|
||||
sourceName: 'France',
|
||||
cities: ['Paris', 'Lyon', 'Nice', 'Nantes'].map(name => ({
|
||||
name,
|
||||
minutes: 120,
|
||||
lastSeenAt: '2026-08-02T10:00:00Z',
|
||||
})),
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{ countryCode: 'BE', sourceName: 'Belgium', cities: [], alreadyVisited: false },
|
||||
],
|
||||
unresolved: [],
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/** A promise this test settles by hand, to pin down what is on screen mid-flight. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>(res => {
|
||||
resolve = res
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function open(props: Partial<React.ComponentProps<typeof DawarichAtlasDialog>> = {}) {
|
||||
return render(<DawarichAtlasDialog isOpen onClose={vi.fn()} {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
phone.value = false
|
||||
setForcedOffline(false)
|
||||
toast.success.mockReset()
|
||||
toast.error.mockReset()
|
||||
repo.bucketScan.mockReset().mockResolvedValue(SCAN)
|
||||
repo.atlasSuggestions.mockReset().mockResolvedValue(COUNTRIES)
|
||||
api.confirmBucketVisits.mockReset().mockResolvedValue({ updated: 1 })
|
||||
api.acceptAtlasCountries.mockReset().mockResolvedValue({ marked: 1 })
|
||||
})
|
||||
|
||||
// Force-offline is module state, not component state: left on, it would leak
|
||||
// into the next file's writes.
|
||||
afterEach(() => setForcedOffline(false))
|
||||
|
||||
describe('DawarichAtlasDialog', () => {
|
||||
it('FE-DAWARICH-ATLASDLG-001: asks nothing on its own — the scan runs when the reader says so', () => {
|
||||
open()
|
||||
expect(repo.bucketScan).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-002: offers no confirmation before there is anything to confirm', () => {
|
||||
open()
|
||||
// Hidden until a result is on screen rather than merely disabled: a greyed
|
||||
// out "Tick off 0" is a dead control asking to be understood, and `hidden`
|
||||
// keeps it out of the accessibility tree too.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-003: a scan lists what it found, with the distance, the time and the day', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
const row = screen.getByRole('checkbox', { name: 'Museum Ludwig' })
|
||||
expect(row.textContent).toContain('49 m away')
|
||||
expect(row.textContent).toContain('2 h 25 min')
|
||||
// A wish with no match at all is not a row — there is nothing to decide.
|
||||
expect(screen.queryByRole('checkbox', { name: 'Rheinpark' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-004: open wishes start selected, already ticked ones do not', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toHaveAttribute('aria-checked', 'false')
|
||||
expect(screen.getByRole('checkbox', { name: 'Kölner Dom' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-005: unticking a row takes it out of what gets written', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: /Tick off 0/ })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-006: confirming writes exactly the picked wishes and reports back', async () => {
|
||||
const onChanged = vi.fn()
|
||||
open({ onChanged })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
// With the date the stay was actually reached on — a wish from last year
|
||||
// ticked off with today's date is a wrong entry in a list people keep.
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
|
||||
expect(onChanged).toHaveBeenCalled()
|
||||
// Marked in place rather than rescanned — one upstream request per wish is
|
||||
// not worth spending to tell the reader what they just did.
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeDisabled())
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-007: the countries tab offers only what the Atlas does not already have', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
expect(screen.queryByRole('checkbox', { name: 'Germany' })).not.toBeInTheDocument()
|
||||
// A country Dawarich named but TREK could not code is said out loud, not dropped.
|
||||
expect(screen.getByText(/Freedonia/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-008: confirming countries sends their codes', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['NL']))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-009: a scan that fails says so and leaves the dialog usable', async () => {
|
||||
repo.bucketScan.mockRejectedValue({ response: { data: { error: 'Dawarich rejected the API key.' } } })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Dawarich rejected the API key.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-010: while the recordings are being read there are placeholders and nothing to press', async () => {
|
||||
const scan = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(scan.promise)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
expect(screen.getByText('Checking…')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
// Neither control exists yet: there is nothing to confirm, and "check again"
|
||||
// before the first answer is a second request for the same thing.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Check again' })).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
scan.resolve(SCAN)
|
||||
})
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-011: a scan that found nothing says so in a sentence and offers no confirmation', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, matches: [], skippedWithoutCoordinates: 0 })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Nothing on your wishlist turned up in your recordings.')).toBeInTheDocument(),
|
||||
)
|
||||
// Absent, not greyed out: a dead "Tick off 0" under an empty state only asks
|
||||
// to be understood.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
// The rule stays on screen, because it is the answer to "why did nothing
|
||||
// turn up": driving past a wish does not count as reaching it.
|
||||
expect(screen.getByText(/A wish counts as reached within 250 m and after 20 minutes/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-012: the caveats under a scan are only said when there are any', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, skippedWithoutCoordinates: 0, truncated: true })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Only the first entries were checked. Run it again for the rest.')).toBeInTheDocument(),
|
||||
)
|
||||
// Nothing was skipped this time, so nothing is said about skipping: a
|
||||
// "0 entries have no coordinates" line is noise dressed as information.
|
||||
expect(screen.queryByText(/have no coordinates/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-013: a country shows the first of its cities, one without any shows none', async () => {
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'France' })).toBeInTheDocument())
|
||||
const france = screen.getByRole('checkbox', { name: 'France' })
|
||||
// The badge counts all four; the line beside it names three, which is what
|
||||
// fits beside a flag at the width a phone gives this dialog.
|
||||
expect(france.textContent).toContain('4 cities')
|
||||
expect(france.textContent).toContain('Paris, Lyon, Nice')
|
||||
expect(france.textContent).not.toContain('Nantes')
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' }).textContent).not.toContain('cities')
|
||||
// Everything matched, so the dialog does not mention matching at all.
|
||||
expect(screen.queryByText(/could not match these to a country/)).toBeNull()
|
||||
expect(screen.getByText('The last 12 months were looked at.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-014: a reading with nothing new in it says so rather than showing an empty list', async () => {
|
||||
// Germany alone, and the Atlas already has it.
|
||||
repo.atlasSuggestions.mockResolvedValue({ ...COUNTRIES, countries: [COUNTRIES.countries[0]] })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-015: wishes reached on one day travel in one request, another day in its own', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Rijksmuseum' })).toBeInTheDocument())
|
||||
// Over a kilometre out is said in kilometres: "1400 m away" is a
|
||||
// measurement, "1.4 km away" is how far it was.
|
||||
expect(screen.getByRole('checkbox', { name: 'Kinderdijk' }).textContent).toContain('1.4 km away')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 3/ }))
|
||||
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(2))
|
||||
// Grouped by date, not ordered by it: the row order inside a day is the
|
||||
// sort's business and nothing here depends on it.
|
||||
const calls = api.confirmBucketVisits.mock.calls as Array<[number[], string]>
|
||||
const byDate = new Map(calls.map(([ids, at]) => [at, [...ids].sort((a, b) => a - b)]))
|
||||
expect(byDate.get('2026-08-02T11:00:00Z')).toEqual([21, 22])
|
||||
expect(byDate.get('2026-07-30T09:00:00Z')).toEqual([23])
|
||||
// Both answers counted, not just the last one to come back.
|
||||
expect(toast.success).toHaveBeenCalledWith('2 wishes ticked off')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-016: an unticked wish is left out of the write entirely', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Kinderdijk' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Kinderdijk' }))
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Rijksmuseum' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
// One request, for one day, carrying one id. The day whose other wish was
|
||||
// dropped does not travel half-empty, and the other day does not travel at all.
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(1))
|
||||
expect(api.confirmBucketVisits).toHaveBeenCalledWith([21], '2026-08-02T11:00:00Z')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-017: a row that was unticked can be put back', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-018: offline, a wish confirmation is refused before anything is sent', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
// Not attempted at all: a confirmation fired into a dead connection hangs to
|
||||
// a timeout and then reports a server error for something no server saw.
|
||||
expect(api.confirmBucketVisits).not.toHaveBeenCalled()
|
||||
// And the selection survives, so pressing it again once there is signal is enough.
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-019: offline, a country confirmation is refused before anything is sent', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
expect(api.acceptAtlasCountries).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-020: a write that failed leaves every row exactly as it was', async () => {
|
||||
// A rejection with no `{ error }` envelope at all: a socket that died
|
||||
// mid-request rather than a server that answered.
|
||||
api.confirmBucketVisits.mockRejectedValue(new Error('socket hang up'))
|
||||
const onChanged = vi.fn()
|
||||
open({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
// Nothing was marked off locally, so a second attempt still has something to
|
||||
// send, and the Atlas is not asked to re-read for a write that never landed.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeEnabled()
|
||||
expect(onChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-021: a refusal carrying no readable reason still gets a sentence', async () => {
|
||||
// An `{ error }` that is not a string is not a message: falling through to
|
||||
// the generic sentence beats printing "[object Object]" at somebody.
|
||||
api.acceptAtlasCountries.mockRejectedValue({ response: { data: { error: { code: 502 } } } })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toHaveAttribute('aria-checked', 'true')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-022: a read that never left the device reads as a connection, not a failure', async () => {
|
||||
// The repo refuses offline reads itself, and its refusal has to survive the
|
||||
// trip through failureText as the connection message rather than as
|
||||
// "something went wrong talking to Dawarich", which points at the instance.
|
||||
repo.atlasSuggestions.mockRejectedValue(new DawarichOfflineError())
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now')),
|
||||
)
|
||||
// Still unasked, so the button that asks is the one on screen.
|
||||
expect(screen.getByRole('button', { name: 'Look for countries' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-023: the other tab asks the other question, and each keeps its own answer', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Countries/ }))
|
||||
|
||||
// Switching tabs asks nothing on its own: a country reading costs an
|
||||
// upstream request, and nobody asked for it by moving their eyes.
|
||||
expect(repo.atlasSuggestions).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Wishlist/ }))
|
||||
|
||||
// The scan is still there, and was not repeated for the return trip.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument()
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-024: "Check again" re-runs the scan and is inert while it runs', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
const second = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(second.promise)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
// A second press while the first is in flight would run the whole scan twice:
|
||||
// one upstream request per wish, for the same answer.
|
||||
expect(screen.getByRole('button', { name: 'Check again' })).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
second.resolve(SCAN)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Check again' })).toBeEnabled())
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-025: "Check again" on the countries tab re-reads the countries, not the wishes', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
await waitFor(() => expect(repo.atlasSuggestions).toHaveBeenCalledTimes(2))
|
||||
expect(repo.bucketScan).not.toHaveBeenCalled()
|
||||
// A year back from the moment it was asked, both times: the window is the
|
||||
// same question asked again, not a widening one.
|
||||
const calls = repo.atlasSuggestions.mock.calls as Array<[string, string]>
|
||||
for (const [from, to] of calls) {
|
||||
expect(Date.parse(to) - Date.parse(from)).toBe(365 * 24 * 60 * 60 * 1000)
|
||||
}
|
||||
expect(Date.parse(calls[1][0])).toBeGreaterThanOrEqual(Date.parse(calls[0][0]))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-026: on a phone it is a sheet, and the count and the confirm live in its own footer', async () => {
|
||||
phone.value = true
|
||||
const onClose = vi.fn()
|
||||
open({ onClose })
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Dawarich' })).toBeInTheDocument()
|
||||
// The desktop modal puts the title in a heading: its absence is the tell
|
||||
// that the right shell rendered.
|
||||
expect(screen.queryByRole('heading', { name: /Dawarich/ })).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
expect(screen.getByText('1 selected')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-027: a country that was just added stops being offered, and the Atlas is told', async () => {
|
||||
const onChanged = vi.fn()
|
||||
open({ initialTab: 'countries', onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
|
||||
// Marked in place rather than re-read: the reading costs an upstream request
|
||||
// and the only thing that changed is what the reader just pressed. The row
|
||||
// leaving the list is what says the write landed.
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('checkbox', { name: 'Netherlands' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countr/ })).toBeNull()
|
||||
expect(repo.atlasSuggestions).toHaveBeenCalledTimes(1)
|
||||
// The Atlas keeps its own map and its own counts; without this the country
|
||||
// it was just told about only appears there after a reload.
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-028: a request that died without a reason at all still gets a sentence', async () => {
|
||||
// An aborted request rejects with nothing: not an Error, not a response.
|
||||
// Reaching into `.response.data` on that must not be the thing that takes
|
||||
// the dialog down, because a crash here loses the scan the reader is
|
||||
// looking at as well as the message they needed.
|
||||
repo.bucketScan.mockRejectedValue(undefined)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-029: a country can be unticked and put back, and only the ticked ones are written', async () => {
|
||||
// Both offers start ticked, which is the useful default but not the answer
|
||||
// every time: a border crossed on the way to somewhere else is a country
|
||||
// Dawarich saw and the reader does not want in their Atlas. Taking one out
|
||||
// has to actually take it out of the write, and changing one's mind has to
|
||||
// put it back, because the Atlas carries tombstones and an unwanted country
|
||||
// added here is removed by hand afterwards.
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Belgium' })).toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: /Add 2 countries/ })).toBeEnabled()
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Belgium' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
// Out and back in again: the tick is a toggle, not a one-way door.
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('button', { name: /Add 0 countries/ })).toBeDisabled()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'France' })).toHaveAttribute('aria-checked', 'true')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 country/ }))
|
||||
|
||||
// Belgium was never sent, so nothing has to be undone in the Atlas after.
|
||||
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['FR']))
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 country added'))
|
||||
// And it is still on offer, still unticked, for the trip it does belong to.
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
})
|
||||
})
|
||||
@@ -1,575 +0,0 @@
|
||||
import React, { useId, useState } from 'react'
|
||||
import { Building2, Check, CalendarDays, Globe2, Hourglass, Info, Loader2, MapPin, RefreshCw, Star } from 'lucide-react'
|
||||
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared'
|
||||
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { Skeleton } from '../shared/Skeleton'
|
||||
import { SlidingTabs } from '../shared/SlidingTabs'
|
||||
import { DialogFooter, DialogHeader, DialogShell, NEUTRAL_TINT } from '../shared/DialogShell'
|
||||
import MSheet from '../../mobile/components/MSheet'
|
||||
import { FormSheetHeader } from '../../mobile/screens/trip/sheets/PlSheetChrome'
|
||||
import { useIsPhone } from '../../mobile/useIsPhone'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import DawarichBadge from './DawarichBadge'
|
||||
import { dawarichApi } from '../../api/dawarich'
|
||||
import { dawarichRepo, DawarichOfflineError } from '../../repo/dawarichRepo'
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode'
|
||||
import { formatDuration } from './dawarichSuggestionModel'
|
||||
import { cityLine, countryLabel, countryWindow, formatDistance, newCountries, orderedMatches } from './dawarichAtlasModel'
|
||||
|
||||
type Tab = 'wishes' | 'countries'
|
||||
|
||||
/**
|
||||
* Everything Dawarich can answer about the Atlas, in a room of its own.
|
||||
*
|
||||
* It used to be a card wedged under the wishlist, which made two different
|
||||
* questions — "which wishes did I actually reach?" and "which countries was I
|
||||
* in?" — look like one paragraph of small print. Both are offers that need
|
||||
* reading before they are accepted, and reading needs space, so they get a
|
||||
* dialog with a tab each, one selection model and one confirm button.
|
||||
*
|
||||
* Nothing here runs on its own. The Atlas is curated — it carries tombstones
|
||||
* precisely so a country somebody removed stays removed — and a background job
|
||||
* that ticked countries off would be fighting its owner.
|
||||
*/
|
||||
export default function DawarichAtlasDialog({
|
||||
isOpen,
|
||||
initialTab = 'wishes',
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
isOpen: boolean
|
||||
/** Which question was asked to open it — the panel has a button per tab. */
|
||||
initialTab?: Tab
|
||||
onClose: () => void
|
||||
/** Called after something was written, so the Atlas can re-read itself. */
|
||||
onChanged?: () => void
|
||||
}): React.ReactElement {
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const phone = useIsPhone()
|
||||
const labelId = useId()
|
||||
const [tab, setTab] = useState<Tab>(initialTab)
|
||||
|
||||
const [scan, setScan] = useState<DawarichBucketScan | null>(null)
|
||||
const [scanning, setScanning] = useState(false)
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set())
|
||||
|
||||
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null)
|
||||
const [loadingCountries, setLoadingCountries] = useState(false)
|
||||
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set())
|
||||
// One write at a time: the button stays on screen while the request is in
|
||||
// flight, and a second press would send the same confirmation twice.
|
||||
const [writing, setWriting] = useState(false)
|
||||
|
||||
const matches = orderedMatches(scan?.matches ?? [])
|
||||
const openMatches = matches.filter(match => !match.alreadyVisited)
|
||||
const offered = newCountries(countries?.countries ?? [])
|
||||
|
||||
const runScan = async (): Promise<void> => {
|
||||
setScanning(true)
|
||||
try {
|
||||
const result = await dawarichRepo.bucketScan()
|
||||
setScan(result)
|
||||
// Everything with a match and not already ticked starts selected: the
|
||||
// common case is "yes, all of those", and unticking the odd one is less
|
||||
// work than ticking twenty.
|
||||
setPicked(new Set(result.matches.filter(m => m.match && !m.alreadyVisited).map(m => m.itemId)))
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setScanning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadCountries = async (): Promise<void> => {
|
||||
setLoadingCountries(true)
|
||||
try {
|
||||
const { from, to } = countryWindow(new Date())
|
||||
const result = await dawarichRepo.atlasSuggestions(from, to)
|
||||
setCountries(result)
|
||||
setPickedCountries(new Set(newCountries(result.countries).map(c => c.countryCode)))
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setLoadingCountries(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmWishes = async (): Promise<void> => {
|
||||
if (picked.size === 0 || writing) return
|
||||
// Writes are online-only: the reads are gated in the repo, and firing a
|
||||
// confirmation into a dead connection would hang to a timeout and then
|
||||
// report a server error for something the server never saw.
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'))
|
||||
return
|
||||
}
|
||||
setWriting(true)
|
||||
try {
|
||||
// Ticked off on the day each wish was reached, not on today. The dialog is
|
||||
// holding that date for every row it is about to write, so it says it;
|
||||
// grouping by date keeps that to one request per day rather than per wish.
|
||||
const byDate = new Map<string, number[]>()
|
||||
for (const m of matches) {
|
||||
if (!picked.has(m.itemId) || !m.match) continue
|
||||
const bucket = byDate.get(m.match.at)
|
||||
if (bucket) bucket.push(m.itemId)
|
||||
else byDate.set(m.match.at, [m.itemId])
|
||||
}
|
||||
const results = await Promise.all(
|
||||
[...byDate].map(([at, ids]) => dawarichApi.confirmBucketVisits(ids, at)),
|
||||
)
|
||||
const result = { updated: results.reduce((sum, r) => sum + r.updated, 0) }
|
||||
toast.success(t('dawarich.bucket.confirmed', { count: result.updated }))
|
||||
// Marked in place rather than rescanned: the scan costs one upstream
|
||||
// request per wish, and the reader already knows what they just ticked.
|
||||
setScan(prev =>
|
||||
prev === null
|
||||
? prev
|
||||
: { ...prev, matches: prev.matches.map(m => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) },
|
||||
)
|
||||
setPicked(new Set())
|
||||
onChanged?.()
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setWriting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmCountries = async (): Promise<void> => {
|
||||
if (pickedCountries.size === 0 || writing) return
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'))
|
||||
return
|
||||
}
|
||||
setWriting(true)
|
||||
try {
|
||||
const result = await dawarichApi.acceptAtlasCountries([...pickedCountries])
|
||||
toast.success(t('dawarich.atlas.accepted', { count: result.marked }))
|
||||
setCountries(prev =>
|
||||
prev === null
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
countries: prev.countries.map(c =>
|
||||
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c,
|
||||
),
|
||||
},
|
||||
)
|
||||
setPickedCountries(new Set())
|
||||
onChanged?.()
|
||||
} catch (err) {
|
||||
toast.error(failureText(err, t))
|
||||
} finally {
|
||||
setWriting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = <T,>(set: Set<T>, value: T): Set<T> => {
|
||||
const next = new Set(set)
|
||||
if (next.has(value)) next.delete(value)
|
||||
else next.add(value)
|
||||
return next
|
||||
}
|
||||
|
||||
const busy = tab === 'wishes' ? scanning : loadingCountries
|
||||
const loaded = tab === 'wishes' ? scan !== null : countries !== null
|
||||
const selected = tab === 'wishes' ? picked.size : pickedCountries.size
|
||||
// Nothing was found, so there is nothing to confirm — the empty state says so
|
||||
// in a sentence, and a greyed-out "Add 0 countries" underneath it only asks to
|
||||
// be understood.
|
||||
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0
|
||||
|
||||
// The same two questions in both shells — only the frame differs.
|
||||
const body = (
|
||||
<div className="space-y-4">
|
||||
<SlidingTabs<Tab>
|
||||
tabs={[
|
||||
{ id: 'wishes', label: t('dawarich.atlas.tab.wishes'), icon: Star, count: openMatches.length || undefined },
|
||||
{ id: 'countries', label: t('dawarich.atlas.tab.countries'), icon: Globe2, count: offered.length || undefined },
|
||||
]}
|
||||
activeTab={tab}
|
||||
onChange={setTab}
|
||||
size="sm"
|
||||
fullWidth
|
||||
/>
|
||||
|
||||
{tab === 'wishes' ? (
|
||||
<Section
|
||||
icon={Star}
|
||||
title={t('dawarich.bucket.title')}
|
||||
description={t('dawarich.bucket.description')}
|
||||
action={t('dawarich.bucket.scan')}
|
||||
busyLabel={t('dawarich.bucket.scanning')}
|
||||
busy={scanning}
|
||||
loaded={scan !== null}
|
||||
onRun={() => { void runScan() }}
|
||||
empty={matches.length === 0}
|
||||
emptyLabel={t('dawarich.bucket.noMatches')}
|
||||
notes={[
|
||||
scan && scan.skippedWithoutCoordinates > 0
|
||||
? t('dawarich.bucket.skipped', { count: scan.skippedWithoutCoordinates })
|
||||
: null,
|
||||
scan?.truncated ? t('dawarich.bucket.truncated') : null,
|
||||
t('dawarich.bucket.rule', {
|
||||
meters: DAWARICH_BUCKET_MATCH_RADIUS_M,
|
||||
count: DAWARICH_BUCKET_MATCH_MIN_MINUTES,
|
||||
}),
|
||||
]}
|
||||
>
|
||||
{matches.map(match => (
|
||||
<Row
|
||||
key={match.itemId}
|
||||
name={match.name}
|
||||
checked={picked.has(match.itemId)}
|
||||
disabled={match.alreadyVisited}
|
||||
onToggle={() => setPicked(prev => toggle(prev, match.itemId))}
|
||||
leading={
|
||||
<span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-surface-secondary">
|
||||
<Star className="w-4 h-4 text-accent-on" />
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{match.alreadyVisited ? (
|
||||
<DawarichBadge icon={Check} tone="success" size="sm">
|
||||
{t('dawarich.bucket.alreadyVisited')}
|
||||
</DawarichBadge>
|
||||
) : (
|
||||
<>
|
||||
<DawarichBadge icon={MapPin} size="sm">
|
||||
{formatDistance(match.match!.distanceMeters, t)}
|
||||
</DawarichBadge>
|
||||
<DawarichBadge icon={Hourglass} size="sm">
|
||||
{formatDuration(match.match!.minutes, t)}
|
||||
</DawarichBadge>
|
||||
<DawarichBadge icon={CalendarDays} size="sm">
|
||||
{new Date(match.match!.at).toLocaleDateString(locale, {
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</DawarichBadge>
|
||||
</>
|
||||
)}
|
||||
</Row>
|
||||
))}
|
||||
</Section>
|
||||
) : (
|
||||
<Section
|
||||
icon={Globe2}
|
||||
title={t('dawarich.atlas.title')}
|
||||
description={t('dawarich.atlas.description')}
|
||||
action={t('dawarich.atlas.load')}
|
||||
busyLabel={t('dawarich.atlas.loading')}
|
||||
busy={loadingCountries}
|
||||
loaded={countries !== null}
|
||||
onRun={() => { void loadCountries() }}
|
||||
empty={offered.length === 0}
|
||||
emptyLabel={t('dawarich.atlas.empty')}
|
||||
notes={[
|
||||
countries && countries.unresolved.length > 0
|
||||
? t('dawarich.atlas.unresolved', { names: countries.unresolved.join(', ') })
|
||||
: null,
|
||||
countries ? t('dawarich.atlas.window') : null,
|
||||
]}
|
||||
>
|
||||
{offered.map(country => (
|
||||
<Row
|
||||
key={country.countryCode}
|
||||
name={countryLabel(country.countryCode, country.sourceName, locale)}
|
||||
checked={pickedCountries.has(country.countryCode)}
|
||||
onToggle={() => setPickedCountries(prev => toggle(prev, country.countryCode))}
|
||||
leading={
|
||||
// The Atlas page draws its countries with the same flags, and a
|
||||
// list of country names without them looks like a spreadsheet.
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${country.countryCode.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-6 w-8 flex-shrink-0 rounded object-cover"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{country.cities.length > 0 && (
|
||||
<>
|
||||
<DawarichBadge icon={Building2} size="sm">
|
||||
{t('dawarich.atlas.cities', { count: country.cities.length })}
|
||||
</DawarichBadge>
|
||||
<span className="min-w-0 truncate text-caption text-content-muted">
|
||||
{cityLine(country.cities)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Row>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
// Rendered or not, rather than `hidden`: the attribute loses to the display
|
||||
// utility on the class list, so the button stayed on screen greyed out.
|
||||
const confirmButton = !loaded || !anything ? null : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void (tab === 'wishes' ? confirmWishes() : confirmCountries()) }}
|
||||
disabled={selected === 0 || writing}
|
||||
className={
|
||||
phone
|
||||
? 'inline-flex h-[38px] items-center gap-2 rounded-full bg-m-act px-4 text-[0.8125rem] font-bold text-m-actfg disabled:opacity-40'
|
||||
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-accent px-4 py-2 text-body font-medium text-accent-text hover:opacity-90 disabled:opacity-40'
|
||||
}
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
{tab === 'wishes'
|
||||
? t('dawarich.bucket.confirm', { count: selected })
|
||||
: t('dawarich.atlas.accept', { count: selected })}
|
||||
</button>
|
||||
)
|
||||
|
||||
const againButton = loaded ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void (tab === 'wishes' ? runScan() : loadCountries()) }}
|
||||
disabled={busy}
|
||||
className={
|
||||
phone
|
||||
? 'inline-flex h-[38px] items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-4 text-[0.8125rem] font-bold text-m-muted disabled:opacity-50'
|
||||
: 'inline-flex items-center gap-1.5 rounded-[10px] bg-surface-card px-3.5 py-2 text-body font-medium text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-secondary disabled:opacity-50'
|
||||
}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />}
|
||||
{t('dawarich.again')}
|
||||
</button>
|
||||
) : null
|
||||
|
||||
// The phone shell has its own sheet, its own rounding and its own pill
|
||||
// buttons, and every other panel on it uses them.
|
||||
if (phone) {
|
||||
return (
|
||||
<MSheet open={isOpen} onClose={onClose} variant="bottom" material="glass" ariaLabel={t('dawarich.title')}>
|
||||
<div className="flex max-h-[88dvh] min-h-0 flex-col">
|
||||
<FormSheetHeader
|
||||
leading={
|
||||
<span className="flex h-10 w-10 flex-none overflow-hidden rounded-[13px]">
|
||||
<DawarichIcon size={40} />
|
||||
</span>
|
||||
}
|
||||
title={t('dawarich.title')}
|
||||
subtitle={t('dawarich.atlas.dialogSubtitle')}
|
||||
onClose={onClose}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-3">{body}</div>
|
||||
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.71875rem] text-m-muted">
|
||||
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
|
||||
</span>
|
||||
{againButton}
|
||||
{confirmButton}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="editor"
|
||||
// The answer replaces the pitch below the tabs, so the upper edge stays put.
|
||||
align="top"
|
||||
header={(
|
||||
<DialogHeader
|
||||
// The mark fills its tile, rounded like the phone's: a small logo in a
|
||||
// grey square reads as a placeholder.
|
||||
tile={<span className="flex h-[46px] w-[46px] flex-none overflow-hidden rounded-[14px] shadow-sm"><DawarichIcon size={46} /></span>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
title={t('dawarich.title')}
|
||||
sub={t('dawarich.atlas.dialogSubtitle')}
|
||||
/>
|
||||
)}
|
||||
// Before the first answer the pitch carries its own button, so there is no bar to show.
|
||||
footer={againButton || confirmButton ? (
|
||||
<DialogFooter>
|
||||
<span className="min-w-0 flex-1 truncate text-caption text-content-muted">
|
||||
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''}
|
||||
</span>
|
||||
{againButton}
|
||||
{confirmButton}
|
||||
</DialogFooter>
|
||||
) : undefined}
|
||||
>
|
||||
{body}
|
||||
</DialogShell>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One half of the dialog: the pitch before anything has been asked, the wait
|
||||
* while it is being asked, and the answer.
|
||||
*
|
||||
* Both halves behave identically, which is the point — the two questions are
|
||||
* different, the shape of answering them is not.
|
||||
*/
|
||||
function Section({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
busyLabel,
|
||||
busy,
|
||||
loaded,
|
||||
onRun,
|
||||
empty,
|
||||
emptyLabel,
|
||||
notes,
|
||||
children,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
title: string
|
||||
description: string
|
||||
action: string
|
||||
busyLabel: string
|
||||
busy: boolean
|
||||
loaded: boolean
|
||||
onRun: () => void
|
||||
empty: boolean
|
||||
emptyLabel: string
|
||||
notes: (string | null)[]
|
||||
children: React.ReactNode
|
||||
}): React.ReactElement {
|
||||
if (busy) {
|
||||
return (
|
||||
<div className="space-y-2" aria-busy>
|
||||
<p className="text-caption text-content-muted">{busyLabel}</p>
|
||||
{[0, 1, 2].map(i => (
|
||||
<div key={i} className="flex items-center gap-3 rounded-xl border border-edge p-3">
|
||||
<Skeleton width={32} height={32} radius={8} />
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Skeleton width="45%" height={13} radius={4} />
|
||||
<Skeleton width="70%" height={11} radius={4} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<div className="flex flex-col items-center rounded-xl border border-dashed border-edge px-6 py-8 text-center">
|
||||
<span className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-surface-secondary">
|
||||
<Icon className="w-5 h-5 text-content-secondary" />
|
||||
</span>
|
||||
<p className="text-body font-semibold text-content">{title}</p>
|
||||
<p className="mt-1.5 max-w-md text-caption text-content-muted">{description}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRun}
|
||||
className="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-caption font-semibold text-accent-text hover:bg-accent-hover"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
{action}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{empty ? (
|
||||
<div className="rounded-xl border border-dashed border-edge px-6 py-8 text-center text-caption text-content-muted">
|
||||
{emptyLabel}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">{children}</div>
|
||||
)}
|
||||
{notes.filter(Boolean).length > 0 && (
|
||||
<div className="space-y-1 border-t border-edge-faint pt-2.5">
|
||||
{notes.filter(Boolean).map(note => (
|
||||
<p key={note} className="flex items-start gap-1.5 text-caption text-content-faint">
|
||||
<Info className="w-3 h-3 flex-shrink-0 mt-0.5" />
|
||||
{note}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A selectable answer: what it is on the left, why it is being offered
|
||||
* underneath, and a tick that says whether it will be applied.
|
||||
*
|
||||
* The whole row is the control — a 16px checkbox is a hard target on a phone,
|
||||
* and there is nothing else in the row to click.
|
||||
*/
|
||||
function Row({
|
||||
name,
|
||||
checked,
|
||||
disabled = false,
|
||||
onToggle,
|
||||
leading,
|
||||
children,
|
||||
}: {
|
||||
name: string
|
||||
checked: boolean
|
||||
disabled?: boolean
|
||||
onToggle: () => void
|
||||
leading: React.ReactNode
|
||||
children: React.ReactNode
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
aria-label={name}
|
||||
disabled={disabled}
|
||||
onClick={onToggle}
|
||||
className={`flex w-full items-center gap-3 rounded-xl border p-2.5 text-start transition-colors ${
|
||||
checked ? 'border-accent bg-accent-subtle' : 'border-edge hover:bg-surface-hover'
|
||||
} ${disabled ? 'opacity-60' : ''}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={`flex h-4 w-4 flex-shrink-0 items-center justify-center rounded ${
|
||||
checked ? 'bg-accent' : 'border-[1.5px] border-edge'
|
||||
}`}
|
||||
>
|
||||
{checked && <Check className="w-2.5 h-2.5 text-accent-text" strokeWidth={3} />}
|
||||
</span>
|
||||
{leading}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-medium text-content">{name}</span>
|
||||
<span className="mt-1 flex flex-wrap items-center gap-1">{children}</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What to tell the reader when a question could not be asked.
|
||||
*
|
||||
* Being offline is not an error the server reported — nothing was sent — and
|
||||
* "something went wrong" for a plane journey is the kind of message that sends
|
||||
* somebody looking for a bug in their Dawarich instance.
|
||||
*/
|
||||
function failureText(err: unknown, t: (key: string) => string): string {
|
||||
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline')
|
||||
return errorText(err) ?? t('dawarich.error.unknown')
|
||||
}
|
||||
|
||||
/** The server's `{ error }` envelope, when there is one. */
|
||||
function errorText(err: unknown): string | null {
|
||||
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data
|
||||
return typeof data?.error === 'string' ? data.error : null
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
// FE-DAWARICH-ATLASPANEL-001 to FE-DAWARICH-ATLASPANEL-007
|
||||
/**
|
||||
* Dawarich's own panel on the Atlas, beside the stats.
|
||||
*
|
||||
* The panel itself holds almost no logic, and the little it does hold is the
|
||||
* kind that is invisible until it is wrong:
|
||||
*
|
||||
* - **It has to disappear completely when the addon is off.** Not empty, not a
|
||||
* blank pane of glass in the row beside the stats: absent, so an Atlas
|
||||
* without Dawarich looks exactly as it did before the integration landed.
|
||||
* - **It has to ask the question that was pressed.** Two tiles, one dialog, one
|
||||
* `initialTab` between them. Wiring both tiles to the same tab is a bug that
|
||||
* looks like a working panel.
|
||||
* - **It mounts the dialog on open and throws it away on close**, deliberately,
|
||||
* so a second visit starts from a fresh question rather than from a scan
|
||||
* somebody ran an hour ago.
|
||||
* - **It is made of the same glass as the Atlas panel next to it.** The tint
|
||||
* and the cursor glare are hand-written rgba rather than tokens (a solid
|
||||
* surface token would punch an opaque hole in a panel floating over a blurred
|
||||
* map), so nothing but a test stops the two panels drifting apart in the
|
||||
* dark theme.
|
||||
*
|
||||
* The dialog is pinned by its own file and stands in for itself here, so the
|
||||
* panel's decisions are observable without a scan and without mocking Dawarich.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import DawarichAtlasSidePanel from './DawarichAtlasSidePanel'
|
||||
|
||||
vi.mock('./DawarichAtlasDialog', () => ({
|
||||
default: ({
|
||||
initialTab,
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
initialTab: string
|
||||
onClose: () => void
|
||||
onChanged?: () => void
|
||||
}) => (
|
||||
<div data-testid="atlas-dialog">
|
||||
<span>asked: {initialTab}</span>
|
||||
<button type="button" onClick={onClose}>
|
||||
dismiss
|
||||
</button>
|
||||
<button type="button" onClick={() => onChanged?.()}>
|
||||
wrote something
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const ADDON = { id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'route', enabled: true }
|
||||
|
||||
/** The glass the Atlas hands down, reduced to the one property jsdom can answer for. */
|
||||
const GLASS: React.CSSProperties = { borderRadius: 20 }
|
||||
|
||||
/** Inline rgba comes back from jsdom respaced; nothing here cares about the spaces. */
|
||||
const rgba = (el: HTMLElement): string => el.style.background.replace(/\s/g, '')
|
||||
|
||||
function mount(props: Partial<React.ComponentProps<typeof DawarichAtlasSidePanel>> = {}) {
|
||||
return render(<DawarichAtlasSidePanel style={GLASS} dark {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAddonStore.setState({ addons: [ADDON], loaded: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAddonStore.setState({ addons: [], loaded: false })
|
||||
})
|
||||
|
||||
describe('DawarichAtlasSidePanel', () => {
|
||||
it('FE-DAWARICH-ATLASPANEL-001: an Atlas without the addon gets no panel at all', () => {
|
||||
useAddonStore.setState({ addons: [{ ...ADDON, enabled: false }] })
|
||||
|
||||
const { container } = mount()
|
||||
|
||||
// Nothing rendered, rather than an empty pane of glass in the row: the
|
||||
// panel is stretched to the height of the stats beside it, so an empty one
|
||||
// would be a visible hole.
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
expect(screen.queryByRole('button', { name: 'Wishlist' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-002: with the addon on it offers two questions and asks neither', () => {
|
||||
const { container } = mount()
|
||||
|
||||
expect(screen.getByText('Dawarich')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Wishlist' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Countries' })).toBeInTheDocument()
|
||||
// A scan costs one upstream request per wish. Nothing is asked until asked.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
// And it wears the glass it was handed rather than one of its own.
|
||||
expect(container.firstElementChild).toHaveStyle({ borderRadius: '20px' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-003: the wishlist tile opens the dialog on the wishlist, and closing puts it away', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Wishlist' }))
|
||||
|
||||
expect(screen.getByText('asked: wishes')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'dismiss' }))
|
||||
|
||||
// Unmounted, not hidden: the next visit starts from a clean question rather
|
||||
// than from an answer that is an hour old.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-004: the countries tile opens the same dialog on the other question', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
|
||||
expect(screen.getByText('asked: countries')).toBeInTheDocument()
|
||||
expect(screen.queryByText('asked: wishes')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-005: what the dialog wrote is reported up to the Atlas', () => {
|
||||
// The Atlas keeps its own counts and its own map. Without this the confirmed
|
||||
// countries only appear after a reload.
|
||||
const onChanged = vi.fn()
|
||||
mount({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'wrote something' }))
|
||||
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-006: the tiles are a tint of the light the panel is made of, per theme', () => {
|
||||
const { rerender } = render(<DawarichAtlasSidePanel style={GLASS} dark={false} />)
|
||||
const wishes = screen.getByRole('button', { name: 'Wishlist' })
|
||||
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
fireEvent.mouseEnter(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.09)')
|
||||
fireEvent.mouseLeave(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
|
||||
rerender(<DawarichAtlasSidePanel style={GLASS} dark />)
|
||||
|
||||
// Inverted on the dark map, not merely darkened: the tile is light added to
|
||||
// the glass, and a black tint on a dark blurred map is an invisible button.
|
||||
expect(rgba(screen.getByRole('button', { name: 'Wishlist' }))).toBe('rgba(255,255,255,0.07)')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-007: the glass glare follows the cursor and goes out behind it', () => {
|
||||
const { container } = mount()
|
||||
const panel = container.firstElementChild as HTMLElement
|
||||
const [glare, borderGlare] = Array.from(panel.children) as HTMLElement[]
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
|
||||
fireEvent.mouseMove(panel, { clientX: 140, clientY: 60 })
|
||||
|
||||
// The pool of light has to sit under the pointer, not merely exist: the
|
||||
// panel's box measures as the origin here, so the cursor's own coordinates
|
||||
// are what should end up in the gradient. An effect that lit up in a fixed
|
||||
// spot would pass an opacity-only assertion and look broken on screen.
|
||||
expect(glare.style.background).toContain('at 140px 60px')
|
||||
expect(glare.style.opacity).toBe('1')
|
||||
expect(borderGlare.style.opacity).toBe('1')
|
||||
|
||||
fireEvent.mouseLeave(panel)
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
expect(borderGlare.style.opacity).toBe('0')
|
||||
})
|
||||
})
|
||||
@@ -1,133 +0,0 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Globe2, Star } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { useGlassGlare } from '../Atlas/useGlassGlare'
|
||||
import DawarichIcon from '../shared/DawarichIcon'
|
||||
import DawarichAtlasDialog from './DawarichAtlasDialog'
|
||||
|
||||
type Question = 'wishes' | 'countries'
|
||||
|
||||
/**
|
||||
* Dawarich's own panel on the Atlas, beside the stats.
|
||||
*
|
||||
* The Atlas is a map with a single glass panel floating over it, and everything
|
||||
* it offers lives in that panel. Dawarich answers two questions about the same
|
||||
* map — which wishes were actually reached, and which countries the recordings
|
||||
* say you were in — but they are *its* answers, not the Atlas's own numbers, and
|
||||
* squeezed under the wishlist they read as fine print nobody asked for.
|
||||
*
|
||||
* So it gets a panel of its own, in the same glass and stretched to the same
|
||||
* height, and the two questions are two tiles built like the stat blocks beside
|
||||
* them: a mark, then a small capitalised label. The lists they produce open in a
|
||||
* dialog — they are offers to read and confirm, and a bar over a world map is no
|
||||
* place to read anything.
|
||||
*
|
||||
* Renders nothing when the addon is off, so an Atlas without Dawarich looks
|
||||
* exactly as it did before.
|
||||
*/
|
||||
export default function DawarichAtlasSidePanel({
|
||||
style,
|
||||
dark,
|
||||
onChanged,
|
||||
}: {
|
||||
/** The glass the Atlas panels are made of, handed down so the two cannot drift. */
|
||||
style: React.CSSProperties
|
||||
dark: boolean
|
||||
/** Called after something was written, so the Atlas can re-read itself. */
|
||||
onChanged?: () => void
|
||||
}): React.ReactElement | null {
|
||||
const { t } = useTranslation()
|
||||
const addonEnabled = useAddonStore(state => state.isEnabled)
|
||||
const [asked, setAsked] = useState<Question | null>(null)
|
||||
const glare = useGlassGlare(dark)
|
||||
|
||||
if (!addonEnabled('dawarich')) return null
|
||||
|
||||
// theme-lint-disable — the panel floats on a blurred map: a solid surface
|
||||
// token would punch an opaque hole in the glass, so the tiles are a tint of
|
||||
// the same light the panel is made of.
|
||||
const tile = dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)'
|
||||
const tileHover = dark ? 'rgba(255,255,255,0.13)' : 'rgba(0,0,0,0.09)'
|
||||
|
||||
const question = (id: Question, Icon: React.ComponentType<{ size?: number; strokeWidth?: number }>, label: string) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAsked(id)}
|
||||
className="group flex flex-col items-center justify-center text-content-secondary hover:text-content"
|
||||
style={{
|
||||
background: tile,
|
||||
border: 'none',
|
||||
borderRadius: 14,
|
||||
cursor: 'pointer',
|
||||
fontFamily: 'inherit',
|
||||
gap: 6,
|
||||
minWidth: 74,
|
||||
padding: '10px 12px',
|
||||
transition: 'background 0.15s ease, color 0.15s ease',
|
||||
}}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = tileHover }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = tile }}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2} />
|
||||
<span
|
||||
className="font-bold uppercase tracking-wide whitespace-nowrap"
|
||||
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={glare.panelRef}
|
||||
onMouseMove={glare.onMouseMove}
|
||||
onMouseLeave={glare.onMouseLeave}
|
||||
className="relative hidden md:flex flex-col justify-center gap-3 overflow-hidden px-5 py-4"
|
||||
style={style}
|
||||
>
|
||||
{/* Liquid glass glare, and the border glow that follows the cursor —
|
||||
the same two layers the Atlas panel carries. */}
|
||||
<div ref={glare.glareRef} className="absolute inset-0 pointer-events-none" style={{ opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20 }} />
|
||||
<div ref={glare.borderGlareRef} className="absolute inset-0 pointer-events-none" style={{
|
||||
opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20,
|
||||
border: dark ? '1.5px solid rgba(255,255,255,0.5)' : '2px solid rgba(0,0,0,0.15)',
|
||||
}} />
|
||||
{/* The long explanation moved into the tooltip: on a panel this size it
|
||||
was three lines of grey that said what the two tiles already say. */}
|
||||
<Tooltip label={t('dawarich.atlas.trigger')} placement="top">
|
||||
<span className="relative flex items-center justify-center gap-2.5">
|
||||
<span className="flex-shrink-0 overflow-hidden rounded-[9px]">
|
||||
<DawarichIcon size={30} />
|
||||
</span>
|
||||
<span
|
||||
className="truncate font-black tracking-tight text-content"
|
||||
style={{ fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))' }}
|
||||
>
|
||||
{t('dawarich.title')}
|
||||
</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
|
||||
<div className="relative flex items-stretch gap-2">
|
||||
{question('wishes', Star, t('dawarich.atlas.tab.wishes'))}
|
||||
{question('countries', Globe2, t('dawarich.atlas.tab.countries'))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mounted on open so every visit starts from a clean question rather than
|
||||
from a scan somebody ran an hour ago. */}
|
||||
{asked !== null && (
|
||||
<DawarichAtlasDialog
|
||||
isOpen
|
||||
initialTab={asked}
|
||||
onClose={() => setAsked(null)}
|
||||
onChanged={onChanged}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { DawarichOfflineError, dawarichRepo } from '../../repo/dawarichRepo';
|
||||
import { isEffectivelyOffline } from '../../sync/networkMode';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { countryWindow, newCountries, orderedMatches } from './dawarichAtlasModel';
|
||||
|
||||
export type DawarichAtlasTab = 'wishes' | 'countries';
|
||||
|
||||
/**
|
||||
* What to tell the reader when a question could not be asked. Being offline is
|
||||
* not an error the server reported (nothing was sent), and "something went
|
||||
* wrong" for a plane journey sends somebody looking for a bug in Dawarich.
|
||||
*/
|
||||
export function dawarichFailureText(err: unknown, t: (key: string) => string): string {
|
||||
if (err instanceof DawarichOfflineError) return t('dawarich.error.offline');
|
||||
const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data;
|
||||
return typeof data?.error === 'string' ? data.error : t('dawarich.error.unknown');
|
||||
}
|
||||
|
||||
function toggled<T>(set: Set<T>, value: T): Set<T> {
|
||||
const next = new Set(set);
|
||||
if (next.has(value)) next.delete(value);
|
||||
else next.add(value);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The two questions Dawarich answers for the Atlas, "which wishes did I reach?"
|
||||
* and "which countries was I in?", with one selection model and one confirm:
|
||||
* the state behind the Atlas dialog and the Atlas hub's Dawarich tab alike.
|
||||
* Nothing runs on its own; the Atlas is curated, so every write is confirmed.
|
||||
*/
|
||||
export function useDawarichAtlas({
|
||||
initialTab = 'wishes',
|
||||
onChanged,
|
||||
}: { initialTab?: DawarichAtlasTab; onChanged?: () => void } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [tab, setTab] = useState<DawarichAtlasTab>(initialTab);
|
||||
const [scan, setScan] = useState<DawarichBucketScan | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set());
|
||||
const [countries, setCountries] = useState<DawarichAtlasSuggestions | null>(null);
|
||||
const [loadingCountries, setLoadingCountries] = useState(false);
|
||||
const [pickedCountries, setPickedCountries] = useState<Set<string>>(new Set());
|
||||
// One write at a time: a second press would send the same confirmation twice.
|
||||
const [writing, setWriting] = useState(false);
|
||||
|
||||
const matches = orderedMatches(scan?.matches ?? []);
|
||||
const openMatches = matches.filter((match) => !match.alreadyVisited);
|
||||
const offered = newCountries(countries?.countries ?? []);
|
||||
|
||||
const runScan = async (): Promise<void> => {
|
||||
setScanning(true);
|
||||
try {
|
||||
const result = await dawarichRepo.bucketScan();
|
||||
setScan(result);
|
||||
// Everything with a match starts selected: the common case is "yes, all of those".
|
||||
setPicked(new Set(result.matches.filter((m) => m.match && !m.alreadyVisited).map((m) => m.itemId)));
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadCountries = async (): Promise<void> => {
|
||||
setLoadingCountries(true);
|
||||
try {
|
||||
const { from, to } = countryWindow(new Date());
|
||||
const result = await dawarichRepo.atlasSuggestions(from, to);
|
||||
setCountries(result);
|
||||
setPickedCountries(new Set(newCountries(result.countries).map((c) => c.countryCode)));
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setLoadingCountries(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmWishes = async (): Promise<void> => {
|
||||
if (picked.size === 0 || writing) return;
|
||||
// Writes are online-only: firing one into a dead connection would hang to a
|
||||
// timeout and then report a server error for something the server never saw.
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'));
|
||||
return;
|
||||
}
|
||||
setWriting(true);
|
||||
try {
|
||||
// Ticked off on the day each wish was reached, one request per day.
|
||||
const byDate = new Map<string, number[]>();
|
||||
for (const m of matches) {
|
||||
if (!picked.has(m.itemId) || !m.match) continue;
|
||||
const ids = byDate.get(m.match.at);
|
||||
if (ids) ids.push(m.itemId);
|
||||
else byDate.set(m.match.at, [m.itemId]);
|
||||
}
|
||||
const results = await Promise.all([...byDate].map(([at, ids]) => dawarichRepo.confirmBucketVisits(ids, at)));
|
||||
toast.success(t('dawarich.bucket.confirmed', { count: results.reduce((sum, r) => sum + r.updated, 0) }));
|
||||
setScan((prev) =>
|
||||
prev === null
|
||||
? prev
|
||||
: { ...prev, matches: prev.matches.map((m) => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) }
|
||||
);
|
||||
setPicked(new Set());
|
||||
onChanged?.();
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setWriting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmCountries = async (): Promise<void> => {
|
||||
if (pickedCountries.size === 0 || writing) return;
|
||||
if (isEffectivelyOffline()) {
|
||||
toast.error(t('dawarich.error.offline'));
|
||||
return;
|
||||
}
|
||||
setWriting(true);
|
||||
try {
|
||||
const result = await dawarichRepo.acceptAtlasCountries([...pickedCountries]);
|
||||
toast.success(t('dawarich.atlas.accepted', { count: result.marked }));
|
||||
setCountries((prev) =>
|
||||
prev === null
|
||||
? prev
|
||||
: {
|
||||
...prev,
|
||||
countries: prev.countries.map((c) =>
|
||||
pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c
|
||||
),
|
||||
}
|
||||
);
|
||||
setPickedCountries(new Set());
|
||||
onChanged?.();
|
||||
} catch (err) {
|
||||
toast.error(dawarichFailureText(err, t));
|
||||
} finally {
|
||||
setWriting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const busy = tab === 'wishes' ? scanning : loadingCountries;
|
||||
const loaded = tab === 'wishes' ? scan !== null : countries !== null;
|
||||
const selected = tab === 'wishes' ? picked.size : pickedCountries.size;
|
||||
// Nothing found means nothing to confirm; the empty state says so in a sentence.
|
||||
const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0;
|
||||
|
||||
return {
|
||||
tab,
|
||||
setTab,
|
||||
scan,
|
||||
scanning,
|
||||
picked,
|
||||
togglePicked: (id: number) => setPicked((prev) => toggled(prev, id)),
|
||||
countries,
|
||||
loadingCountries,
|
||||
pickedCountries,
|
||||
togglePickedCountry: (code: string) => setPickedCountries((prev) => toggled(prev, code)),
|
||||
writing,
|
||||
matches,
|
||||
openMatches,
|
||||
offered,
|
||||
runScan,
|
||||
loadCountries,
|
||||
confirmWishes,
|
||||
confirmCountries,
|
||||
/** Ask the open tab's question (again). */
|
||||
run: () => void (tab === 'wishes' ? runScan() : loadCountries()),
|
||||
/** Confirm the open tab's selection. */
|
||||
confirm: () => void (tab === 'wishes' ? confirmWishes() : confirmCountries()),
|
||||
busy,
|
||||
loaded,
|
||||
selected,
|
||||
anything,
|
||||
};
|
||||
}
|
||||
|
||||
export type DawarichAtlasState = ReturnType<typeof useDawarichAtlas>;
|
||||
@@ -356,8 +356,10 @@ input, textarea, select {
|
||||
transform: translateX(-2px);
|
||||
}
|
||||
|
||||
/* Global focus-visible ring — konsistent überall */
|
||||
:focus-visible {
|
||||
/* Global focus-visible ring — konsistent überall. Containers that only take the
|
||||
focus from code (a dialog panel with tabindex="-1") never draw it: the ring and
|
||||
its 4px radius would sit on the whole panel and square off its corners. */
|
||||
:focus-visible:not([tabindex="-1"]) {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useTranslation } from '../../../i18n'
|
||||
import { useIsDark } from '../../../hooks/useIsDark'
|
||||
import {
|
||||
Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Radar,
|
||||
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Radar, Trophy,
|
||||
} from 'lucide-react'
|
||||
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
|
||||
@@ -80,6 +80,8 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
wandererOffered,
|
||||
toggleToursWanderer,
|
||||
mapSwitches,
|
||||
atlasCompare,
|
||||
toggleAtlasCompare,
|
||||
} = useAddonManager()
|
||||
|
||||
if (loading) {
|
||||
@@ -125,6 +127,15 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
|
||||
onToggle={onToggleBagTracking}
|
||||
/>
|
||||
)}
|
||||
{addon.id === 'atlas' && addon.enabled && (
|
||||
<MSubRow
|
||||
icon={Trophy}
|
||||
title={t('admin.atlasCompare.title')}
|
||||
subtitle={t('admin.atlasCompare.subtitle')}
|
||||
enabled={atlasCompare}
|
||||
onToggle={() => void toggleAtlasCompare()}
|
||||
/>
|
||||
)}
|
||||
{addon.id === 'documents' && addon.enabled && <MProviderShelf options={documentProviderOptions} />}
|
||||
{addon.id === 'tours' && addon.enabled && (
|
||||
<>
|
||||
|
||||
@@ -1,266 +1,6 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router'
|
||||
import { CalendarClock, X } from 'lucide-react'
|
||||
import { useAtlas } from '../../../pages/atlas/useAtlas'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MChip from '../../components/MChip'
|
||||
import MAtlasStatsCard from './MAtlasStatsCard'
|
||||
import MAtlasSearch from './MAtlasSearch'
|
||||
import MAtlasCountryPopup from './MAtlasCountryPopup'
|
||||
import MAtlasBucketSheet from './MAtlasBucketSheet'
|
||||
import DawarichIcon from '../../../components/shared/DawarichIcon'
|
||||
import DawarichAtlasDialog from '../../../components/Dawarich/DawarichAtlasDialog'
|
||||
import { useAddonStore } from '../../../store/addonStore'
|
||||
import { countryStatus } from '../../../pages/atlas/atlasModel'
|
||||
import AtlasCountryPlaces from '../../../components/Atlas/AtlasCountryPlaces'
|
||||
import MSkeleton from '../../components/MSkeleton'
|
||||
import MAtlasGlobe from './MAtlasGlobe'
|
||||
|
||||
/** The atlas header's buttons: one shape, equal widths, the phone shell's glass. */
|
||||
const HEADER_BUTTON = 'flex h-[38px] min-w-0 flex-1 items-center justify-center gap-2 rounded-full border px-3 text-[0.78125rem] font-bold transition-transform active:scale-[.97]'
|
||||
const HEADER_IDLE = 'border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)] backdrop-blur-[24px] backdrop-saturate-[1.7]'
|
||||
|
||||
const removeBtnCls = 'mt-4 w-full rounded-full bg-[rgba(214,39,59,.12)] py-[11px] text-center text-[0.8125rem] font-bold text-[color:var(--m-st-danger)]' // theme-lint-disable — fixed status-danger tint
|
||||
|
||||
/**
|
||||
* Mobile atlas screen: the interactive world map fills the viewport, the
|
||||
* five-column stats card floats above the bottom nav and the search overlay
|
||||
* flies the map to a country. All map/data logic comes from the shared
|
||||
* useAtlas hook — this file is presentation and wiring only.
|
||||
*/
|
||||
/** The phone Atlas: the globe, its hub sheet and its dialogs. */
|
||||
export default function MAtlas() {
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const headerRef = useRef<HTMLDivElement>(null)
|
||||
// The map runs under the rail (m-bleed) and the header: the camera keeps clear
|
||||
// of both. The rail's share is the root's own negative margin, resolved by the
|
||||
// browser; the header's is how far down it reaches.
|
||||
const atlas = useAtlas({
|
||||
chromeInsets: () => {
|
||||
const root = rootRef.current
|
||||
if (!root) return { top: 0, start: 0 }
|
||||
const start = Math.max(0, -parseFloat(getComputedStyle(root).marginInlineStart) || 0)
|
||||
const header = headerRef.current?.getBoundingClientRect()
|
||||
const top = header ? Math.max(0, header.bottom - root.getBoundingClientRect().top) : 0
|
||||
return { top, start }
|
||||
},
|
||||
})
|
||||
const {
|
||||
t,
|
||||
navigate,
|
||||
resolveName,
|
||||
loading,
|
||||
mapRef,
|
||||
regionTooltipRef,
|
||||
stats,
|
||||
countries,
|
||||
visitedCountries,
|
||||
showPlanned,
|
||||
togglePlanned,
|
||||
bucketList,
|
||||
selectedCountry,
|
||||
countryDetail,
|
||||
handleUnmarkCountry,
|
||||
select_country_from_search,
|
||||
atlas_country_options,
|
||||
} = atlas
|
||||
const plannedCount = stats.totalCountriesPlanned || 0
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [bucketOpen, setBucketOpen] = useState(false)
|
||||
const [dawarichOpen, setDawarichOpen] = useState(false)
|
||||
const dawarichEnabled = useAddonStore(state => state.isEnabled)('dawarich')
|
||||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
|
||||
// The dock FAB is the search button on this screen (demo Z. 1099) and hands
|
||||
// off via ?search=1, mirroring the ?create= contract of the other pages.
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
useEffect(() => {
|
||||
if (searchParams.get('search') == null) return
|
||||
const next = new URLSearchParams(searchParams)
|
||||
next.delete('search')
|
||||
setSearchParams(next, { replace: true })
|
||||
setSearchOpen(true)
|
||||
}, [searchParams, setSearchParams])
|
||||
|
||||
// A search fly-to on a visited country loads its detail — surface it as a sheet.
|
||||
useEffect(() => {
|
||||
if (selectedCountry && countryDetail) setDetailOpen(true)
|
||||
}, [selectedCountry, countryDetail])
|
||||
|
||||
// Suggestions for the empty search field: recently visited countries first,
|
||||
// then countries already on the bucket list.
|
||||
const suggestions = useMemo(() => {
|
||||
const seen = new Set<string>()
|
||||
const list: { code: string; label: string }[] = []
|
||||
// Visited first, planned after — this list answers "where have I been", so a country
|
||||
// you only booked a flight to shouldn't outrank one you actually saw.
|
||||
const visited = [...countries].sort((a, b) => {
|
||||
const rank = (c: typeof a) => (countryStatus(c) === 'visited' ? 0 : 1)
|
||||
return rank(a) - rank(b) || (b.lastVisit || '').localeCompare(a.lastVisit || '')
|
||||
})
|
||||
for (const c of visited) {
|
||||
if (seen.has(c.code)) continue
|
||||
seen.add(c.code)
|
||||
list.push({ code: c.code, label: resolveName(c.code) })
|
||||
}
|
||||
for (const item of bucketList) {
|
||||
const code = item.country_code
|
||||
if (!code || code.length !== 2 || seen.has(code)) continue
|
||||
seen.add(code)
|
||||
list.push({ code, label: resolveName(code) })
|
||||
}
|
||||
return list.slice(0, 5)
|
||||
}, [countries, bucketList, resolveName])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="relative h-dvh">
|
||||
<MSkeleton variant="map" className="absolute inset-0" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
|
||||
// and a map on a percentage of an auto-height parent collapses to zero.
|
||||
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden">
|
||||
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
|
||||
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
|
||||
<div
|
||||
ref={regionTooltipRef}
|
||||
style={{ display: 'none' }}
|
||||
className="pointer-events-none fixed z-[80] min-w-[120px] rounded-[10px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[10px] text-[0.75rem] text-m-ink shadow-[0_4px_16px_rgba(0,0,0,.18)]"
|
||||
/>
|
||||
|
||||
{/* Full-width bucket-list button. The bottom nav makes a back button
|
||||
redundant on this main-nav screen, so the header spans the width. */}
|
||||
<div ref={headerRef} className="m-bar-x absolute top-[var(--m-safe-top,12px)] z-[5] flex items-center gap-2 wide:mx-auto wide:max-w-[720px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBucketOpen(true)}
|
||||
className={`${HEADER_BUTTON} ${HEADER_IDLE}`}
|
||||
>
|
||||
{t('atlas.bucketTab')}
|
||||
</button>
|
||||
{/* Dawarich answers two questions about this map, so it opens from the
|
||||
map — not from inside the wishlist sheet, where it was one card deep
|
||||
and looked like part of the list it is only asking about. Renders
|
||||
nothing when the addon is off. */}
|
||||
{dawarichEnabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDawarichOpen(true)}
|
||||
aria-label={t('dawarich.title')}
|
||||
className={`${HEADER_BUTTON} ${HEADER_IDLE}`}
|
||||
>
|
||||
<span className="flex h-[22px] w-[22px] flex-none overflow-hidden rounded-full">
|
||||
<DawarichIcon size={22} />
|
||||
</span>
|
||||
<span className="truncate">{t('dawarich.title')}</span>
|
||||
</button>
|
||||
)}
|
||||
{/* Only worth the space once there is something planned to reveal. A
|
||||
button of the same shape as its neighbours, filled while the planned
|
||||
countries show, rather than a label with a switch in a pill of its own. */}
|
||||
{plannedCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => togglePlanned()}
|
||||
aria-pressed={showPlanned}
|
||||
aria-label={t('atlas.showPlanned')}
|
||||
className={`${HEADER_BUTTON} ${showPlanned ? 'border-transparent bg-m-act text-m-actfg' : HEADER_IDLE}`}
|
||||
>
|
||||
<CalendarClock size={15} strokeWidth={2.2} className="flex-none" aria-hidden="true" />
|
||||
<span className="truncate">{t('atlas.planned')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{dawarichOpen && (
|
||||
<DawarichAtlasDialog
|
||||
isOpen
|
||||
onClose={() => setDawarichOpen(false)}
|
||||
onChanged={atlas.reloadAfterDawarich}
|
||||
/>
|
||||
)}
|
||||
|
||||
<MAtlasStatsCard stats={stats} />
|
||||
|
||||
<MAtlasSearch
|
||||
open={searchOpen}
|
||||
onClose={() => setSearchOpen(false)}
|
||||
options={atlas_country_options}
|
||||
suggestions={suggestions}
|
||||
isVisited={(code) => visitedCountries.some((c) => c.code === code)}
|
||||
isPlanned={(code) => countries.some((c) => c.code === code && countryStatus(c) !== 'visited')}
|
||||
isOnBucketList={(code) => bucketList.some((b) => b.country_code === code)}
|
||||
onSelect={(code) => {
|
||||
setSearchOpen(false)
|
||||
select_country_from_search(code)
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Country detail sheet (visited country with trips/places). */}
|
||||
<MSheet
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
variant="card"
|
||||
ariaLabel={selectedCountry ? resolveName(selectedCountry) : undefined}
|
||||
>
|
||||
{selectedCountry && countryDetail && (
|
||||
<div className="p-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<img
|
||||
src={`https://flagcdn.com/w80/${selectedCountry.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-[30px] w-[42px] flex-none rounded-[6px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[1.0625rem] font-extrabold text-m-ink">{resolveName(selectedCountry)}</div>
|
||||
<div className="mt-[4px] flex flex-wrap gap-1">
|
||||
{[[countryDetail.places.length, t('atlas.places', { count: countryDetail.places.length })], [countryDetail.trips.length, t('atlas.trips', { count: countryDetail.trips.length })]].map(([n, label]) => (
|
||||
<span key={label} className="rounded-full bg-[color:var(--m-ic)] px-2 py-[1px] font-geist text-[0.625rem] font-bold tabular-nums text-m-muted">
|
||||
{n} {label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={() => setDetailOpen(false)} ariaLabel={t('common.close')}>
|
||||
<X size={16} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
{countryDetail.trips.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-[6px]">
|
||||
{countryDetail.trips.slice(0, 6).map((trip) => (
|
||||
<MChip key={trip.id} onClick={() => navigate(`/trips/${trip.id}`)}>
|
||||
{trip.title}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* Every place counted for the country, by trip (#2174). */}
|
||||
{countryDetail.places.length > 0 && (
|
||||
<div className="mt-4 max-h-[46vh] overflow-y-auto">
|
||||
<AtlasCountryPlaces variant="mobile" detail={countryDetail} onOpenTrip={id => navigate(`/trips/${id}`)} />
|
||||
</div>
|
||||
)}
|
||||
{countryDetail.manually_marked && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDetailOpen(false)
|
||||
handleUnmarkCountry(selectedCountry)
|
||||
}}
|
||||
className={removeBtnCls}
|
||||
>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</MSheet>
|
||||
|
||||
<MAtlasBucketSheet atlas={atlas} open={bucketOpen} onClose={() => setBucketOpen(false)} />
|
||||
<MAtlasCountryPopup atlas={atlas} />
|
||||
</div>
|
||||
)
|
||||
return <MAtlasGlobe />
|
||||
}
|
||||
|
||||
@@ -1,304 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Calendar, ChevronDown, ChevronLeft, ChevronRight, MapPin, Plus, Search, Star, Trash2, X } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import { A2_TO_A3 } from '../../../pages/atlas/atlasModel'
|
||||
import type { BucketItem } from '../../../pages/atlas/atlasModel'
|
||||
import type { AtlasController } from './atlasController'
|
||||
import { getIntlLanguage } from '@trek/shared'
|
||||
import { TileHeader } from '../trip/sheets/MTripSheetUi'
|
||||
|
||||
interface MAtlasBucketSheetProps {
|
||||
atlas: AtlasController
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
'w-full rounded-[14px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] px-[14px] py-[11px] text-[0.84375rem] font-medium text-m-ink outline-none placeholder:text-m-faint'
|
||||
|
||||
function itemCountryA2(item: BucketItem): string | null {
|
||||
const code = item.country_code
|
||||
if (!code) return null
|
||||
if (code.length === 2) return code
|
||||
return Object.entries(A2_TO_A3).find(([, v]) => v === code)?.[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucket-list sheet, entered via the chip on the stats card. Lists every
|
||||
* bucket item with country, target month, coordinates and notes, and carries
|
||||
* the full add flow (POI search or free name, notes, target month).
|
||||
*/
|
||||
export default function MAtlasBucketSheet({ atlas, open, onClose }: MAtlasBucketSheetProps) {
|
||||
const {
|
||||
t,
|
||||
language,
|
||||
resolveName,
|
||||
bucketList,
|
||||
showBucketAdd,
|
||||
setShowBucketAdd,
|
||||
bucketForm,
|
||||
setBucketForm,
|
||||
bucketSearch,
|
||||
setBucketSearch,
|
||||
bucketSearchResults,
|
||||
setBucketSearchResults,
|
||||
bucketSearching,
|
||||
handleBucketPoiSearch,
|
||||
handleAddBucketItem,
|
||||
handleDeleteBucketItem,
|
||||
} = atlas
|
||||
|
||||
const resetForm = (): void => {
|
||||
setShowBucketAdd(false)
|
||||
setBucketForm({ name: '', notes: '', lat: '', lng: '', target_date: '' })
|
||||
setBucketSearch('')
|
||||
setBucketSearchResults([])
|
||||
}
|
||||
|
||||
const close = (): void => {
|
||||
resetForm()
|
||||
onClose()
|
||||
}
|
||||
|
||||
// Own POI pick instead of the hook's handleSelectBucketPoi: keeps the notes
|
||||
// and target month the user may already have typed into the form.
|
||||
const pickPoi = (result: { name?: string; lat?: number; lng?: number }): void => {
|
||||
setBucketForm({ ...bucketForm, name: result.name || bucketSearch, lat: String(result.lat ?? ''), lng: String(result.lng ?? '') })
|
||||
setBucketSearchResults([])
|
||||
setBucketSearch('')
|
||||
}
|
||||
|
||||
const fmtTarget = (targetDate: string): string => {
|
||||
const [y, m] = targetDate.split('-')
|
||||
return m ? new Date(Number(y), Number(m) - 1).toLocaleDateString(getIntlLanguage(language), { month: 'short', year: 'numeric' }) : y
|
||||
}
|
||||
|
||||
const itemSub = (item: BucketItem): string => {
|
||||
const a2 = itemCountryA2(item)
|
||||
return [
|
||||
a2 ? resolveName(a2) : null,
|
||||
item.target_date ? fmtTarget(item.target_date) : null,
|
||||
item.lat != null && item.lng != null ? `${item.lat.toFixed(2)}, ${item.lng.toFixed(2)}` : null,
|
||||
item.notes || null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={close} variant="bottom" material="glass" ariaLabel={t('atlas.bucketTab')}>
|
||||
<div className="flex min-h-0 flex-col px-[18px] pb-4 pt-4">
|
||||
<div className="mb-3">
|
||||
<TileHeader
|
||||
icon={<Star size={19} strokeWidth={1.8} className="text-[color:var(--m-st-pending)]" />}
|
||||
title={t('atlas.bucketTab')}
|
||||
sub={bucketList.length > 0 ? String(bucketList.length) : undefined}
|
||||
onClose={close}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto">
|
||||
{bucketList.length === 0 && !showBucketAdd && (
|
||||
<div className="px-4 py-8 text-center">
|
||||
<div className="text-[0.84375rem] font-semibold text-m-muted">{t('atlas.bucketEmpty')}</div>
|
||||
<div className="mt-1 font-geist text-[0.6875rem] text-m-faint">{t('atlas.bucketEmptyHint')}</div>
|
||||
</div>
|
||||
)}
|
||||
{bucketList.map((item) => {
|
||||
const a2 = itemCountryA2(item)
|
||||
const sub = itemSub(item)
|
||||
return (
|
||||
<div key={item.id} className="flex items-center gap-3 rounded-[18px] bg-[color:var(--m-ic)] px-[14px] py-[11px]">
|
||||
{a2 ? (
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${a2.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-[17px] w-6 flex-none rounded-[3px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
) : (
|
||||
<Star size={16} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[0.84375rem] font-semibold text-m-ink">{item.name}</div>
|
||||
{sub && <div className="mt-[1px] truncate font-geist text-[0.6875rem] text-m-muted">{sub}</div>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteBucketItem(item.id)}
|
||||
aria-label={t('atlas.unmark')}
|
||||
className="flex h-[30px] w-[30px] flex-none items-center justify-center rounded-full text-m-faint active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<Trash2 size={15} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{showBucketAdd ? (
|
||||
<div className="space-y-2 pt-3">
|
||||
<div className="relative">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={bucketForm.name || bucketSearch}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
if (bucketForm.name) setBucketForm({ ...bucketForm, name: v })
|
||||
else setBucketSearch(v)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter') return
|
||||
if (bucketForm.name) void handleAddBucketItem()
|
||||
else void handleBucketPoiSearch()
|
||||
}}
|
||||
placeholder={t('atlas.bucketNamePlaceholder')}
|
||||
className={`${inputCls} min-w-0 flex-1`}
|
||||
/>
|
||||
{bucketForm.name ? (
|
||||
<MIconBtn
|
||||
variant="neutral"
|
||||
size={40}
|
||||
onClick={() => {
|
||||
setBucketForm({ ...bucketForm, name: '', lat: '', lng: '' })
|
||||
setBucketSearch('')
|
||||
}}
|
||||
ariaLabel={t('common.cancel')}
|
||||
>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleBucketPoiSearch}
|
||||
disabled={bucketSearching}
|
||||
aria-label={t('common.search')}
|
||||
className="flex h-10 w-10 flex-none items-center justify-center rounded-[14px] bg-m-act text-m-actfg disabled:opacity-50"
|
||||
>
|
||||
<Search size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{bucketSearchResults.length > 0 && (
|
||||
<div className="absolute bottom-full inset-x-0 z-10 mb-2 max-h-40 divide-y divide-[color:var(--m-rowbr)] overflow-y-auto rounded-[16px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
{bucketSearchResults.slice(0, 6).map((result, i) => (
|
||||
<button key={i} type="button" onClick={() => pickPoi(result)} className="flex w-full flex-col px-[14px] py-[9px] text-start active:bg-[color:var(--m-ic)]">
|
||||
<span className="text-[0.8125rem] font-semibold text-m-ink">{result.name}</span>
|
||||
{result.address && <span className="font-geist text-[0.625rem] text-m-faint">{result.address}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{bucketForm.lat && bucketForm.lng && (
|
||||
<div className="flex items-center gap-1 px-1 font-geist text-[0.625rem] text-m-faint">
|
||||
<MapPin size={10} strokeWidth={2.2} />
|
||||
{Number(bucketForm.lat).toFixed(4)}, {Number(bucketForm.lng).toFixed(4)}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
value={bucketForm.notes}
|
||||
onChange={(e) => setBucketForm({ ...bucketForm, notes: e.target.value })}
|
||||
placeholder={t('atlas.bucketNotesPlaceholder')}
|
||||
className={inputCls}
|
||||
/>
|
||||
<MMonthYearField
|
||||
value={bucketForm.target_date}
|
||||
onChange={(v) => setBucketForm({ ...bucketForm, target_date: v })}
|
||||
placeholder={t('atlas.bucketWhen')}
|
||||
language={language}
|
||||
t={t}
|
||||
/>
|
||||
<div className="flex gap-2 pt-1">
|
||||
<button type="button" onClick={resetForm} className="flex-1 rounded-full bg-[color:var(--m-ic)] py-[11px] text-[0.8125rem] font-bold text-m-ink">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddBucketItem}
|
||||
disabled={!bucketForm.name.trim()}
|
||||
className="flex-1 rounded-full bg-m-act py-[11px] text-[0.8125rem] font-bold text-m-actfg disabled:opacity-50"
|
||||
>
|
||||
{t('common.add')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowBucketAdd(true)}
|
||||
className="mt-3 flex w-full flex-none items-center justify-center gap-[6px] rounded-full border border-dashed border-[color:var(--m-rowbr)] py-[10px] font-geist text-[0.75rem] font-semibold text-m-muted"
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
{t('atlas.addPoi')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
/** Custom month/year picker replacing the native <input type="month">: a year
|
||||
* stepper over a 12-month grid, opening upward so it clears the docked sheet. */
|
||||
function MMonthYearField({ value, onChange, placeholder, language, t }: {
|
||||
value: string
|
||||
onChange: (v: string) => void
|
||||
placeholder: string
|
||||
language: string
|
||||
t: AtlasController['t']
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const selYear = value ? Number(value.split('-')[0]) : null
|
||||
const selMonth = value ? Number(value.split('-')[1]) : null
|
||||
const [year, setYear] = useState(selYear ?? new Date().getFullYear())
|
||||
|
||||
const display = selYear
|
||||
? new Date(selYear, (selMonth ?? 1) - 1).toLocaleDateString(getIntlLanguage(language), { month: 'long', year: 'numeric' })
|
||||
: ''
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} className={`${inputCls} flex items-center gap-2 text-start`}>
|
||||
<Calendar size={15} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<span className={`min-w-0 flex-1 truncate ${display ? '' : 'text-m-faint'}`}>{display || placeholder}</span>
|
||||
<ChevronDown size={15} strokeWidth={2} className={`flex-none text-m-faint transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute bottom-full inset-x-0 z-10 mb-2 rounded-[16px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] p-3 shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
<div className="mb-[10px] flex items-center justify-between">
|
||||
<button type="button" onClick={() => setYear(y => y - 1)} aria-label={t('mobileVacay.prevYear')} className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<ChevronLeft size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
<span className="text-[0.9375rem] font-extrabold tabular-nums text-m-ink">{year}</span>
|
||||
<button type="button" onClick={() => setYear(y => y + 1)} aria-label={t('mobileVacay.nextYear')} className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<ChevronRight size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 gap-[6px]">
|
||||
{Array.from({ length: 12 }, (_, m) => {
|
||||
const on = selYear === year && selMonth === m + 1
|
||||
return (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
onClick={() => { onChange(`${year}-${String(m + 1).padStart(2, '0')}`); setOpen(false) }}
|
||||
className={`rounded-[10px] py-2 text-[0.71875rem] font-bold capitalize ${on ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'}`}
|
||||
>
|
||||
{new Date(2000, m, 1).toLocaleDateString(getIntlLanguage(language), { month: 'short' })}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{value && (
|
||||
<button type="button" onClick={() => { onChange(''); setOpen(false) }} className="mt-[10px] w-full rounded-[10px] py-[7px] text-[0.6875rem] font-bold text-m-muted">
|
||||
{t('common.reset')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { http, HttpResponse } from 'msw'
|
||||
import { render, screen, fireEvent, waitFor } from '../../../../tests/helpers/render'
|
||||
import { server } from '../../../../tests/helpers/msw/server'
|
||||
import MAtlasCountryPopup from './MAtlasCountryPopup'
|
||||
import type { AtlasController } from './atlasController'
|
||||
|
||||
const bucketItem = (id: number, name: string, countryCode: string | null) => ({
|
||||
id, name, country_code: countryCode, lat: null, lng: null, notes: null, target_date: null,
|
||||
@@ -12,7 +11,7 @@ const bucketItem = (id: number, name: string, countryCode: string | null) => ({
|
||||
|
||||
// Only the slice of the atlas hook this sheet reads. `t` echoes the key back so
|
||||
// the assertions name the contract, not a locale string.
|
||||
function makeAtlas(overrides: Record<string, unknown> = {}): AtlasController {
|
||||
function makeAtlas(overrides: Record<string, unknown> = {}): React.ComponentProps<typeof MAtlasCountryPopup>['atlas'] {
|
||||
return {
|
||||
t: (key: string) => key,
|
||||
confirmAction: { code: 'FR', name: 'France', type: 'choose' },
|
||||
@@ -25,7 +24,7 @@ function makeAtlas(overrides: Record<string, unknown> = {}): AtlasController {
|
||||
bucketList: [],
|
||||
handleDeleteBucketItem: vi.fn().mockResolvedValue(undefined),
|
||||
...overrides,
|
||||
} as unknown as AtlasController
|
||||
} as unknown as React.ComponentProps<typeof MAtlasCountryPopup>['atlas']
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ChevronRight, MapPin, Star, Trash2 } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import type { AtlasController } from './atlasController'
|
||||
import { useAtlasCountryActions } from '../../../pages/atlas/useAtlasCountryActions'
|
||||
import { type AtlasCountryActionsOptions, 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
|
||||
@@ -44,7 +43,8 @@ function OptionRow({ icon: Icon, tint, title, hint, onClick }: OptionRowProps) {
|
||||
}
|
||||
|
||||
interface MAtlasCountryPopupProps {
|
||||
atlas: AtlasController
|
||||
/** The country actions' state and setters, and what confirming a mark or unmark runs. */
|
||||
atlas: AtlasCountryActionsOptions & { executeConfirmAction: () => void | Promise<void> }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Briefcase, CalendarClock, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import AtlasCountryPlaces from '../../../components/Atlas/AtlasCountryPlaces';
|
||||
import CountryFlag from '../../../components/shared/CountryFlag';
|
||||
import { countryStatus } from '../../../pages/atlas/atlasModel';
|
||||
import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe';
|
||||
import MIconBtn from '../../components/MIconBtn';
|
||||
import MProgress from '../../components/MProgress';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MAtlasCountryPopup from './MAtlasCountryPopup';
|
||||
import { M_CARD } from './hub/mHubKit';
|
||||
|
||||
/**
|
||||
* The globe's country and region sheets on the phone: the action card (mark,
|
||||
* wish, take off) and a country's own sheet with its trips and places.
|
||||
*/
|
||||
export default function MAtlasCountrySheets({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
return (
|
||||
<>
|
||||
<MAtlasCountryPopup
|
||||
atlas={{
|
||||
t: s.t,
|
||||
confirmAction: s.confirmAction,
|
||||
setConfirmAction: (v) => {
|
||||
s.setConfirmAction(v);
|
||||
if (typeof v !== 'function' && v === null) s.closeDialogs();
|
||||
},
|
||||
executeConfirmAction: s.executeConfirmAction,
|
||||
setData: s.setData,
|
||||
visitedRegions: s.regions,
|
||||
setVisitedRegions: s.setRegions,
|
||||
bucketList: s.bucket,
|
||||
setBucketList: s.setBucket,
|
||||
handleDeleteBucketItem: s.handleDeleteBucketItem,
|
||||
}}
|
||||
/>
|
||||
<MSheet
|
||||
open={!!s.detail}
|
||||
onClose={s.closeDialogs}
|
||||
variant="bottom"
|
||||
ariaLabel={s.detail ? s.resolveName(s.detail.a2) : ''}
|
||||
>
|
||||
{s.detail && <CountrySheet s={s} />}
|
||||
</MSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CountrySheet({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const navigate = useNavigate();
|
||||
const d = s.detail;
|
||||
if (!d) return null;
|
||||
const row = s.data?.countries.find((c) => c.code === d.a2);
|
||||
const progress = s.progress;
|
||||
const placedTrips = new Set((d.data?.places ?? []).map((p) => p.trip_id));
|
||||
const tripsWithoutPlaces = (d.data?.trips ?? []).filter((trip) => !placedTrips.has(trip.id));
|
||||
const openTrip = (id: number) => navigate(`/trips/${id}`);
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col overflow-y-auto px-5 pb-6 pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<CountryFlag code={d.a2} size={30} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-title font-bold text-m-ink">{s.resolveName(d.a2)}</div>
|
||||
{row && (
|
||||
<div className="text-caption text-m-muted">
|
||||
{row.tripCount} {s.t('atlas.trips', { count: row.tripCount })}, {row.placeCount}{' '}
|
||||
{s.t('atlas.places', { count: row.placeCount })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.close')} onClick={s.closeDialogs}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
|
||||
{row && countryStatus(row) !== 'visited' && (
|
||||
<span className="mt-3 inline-flex items-center gap-1.5 self-start rounded-full bg-[color:var(--m-ic)] px-2.5 py-1 text-caption font-semibold text-m-muted">
|
||||
<CalendarClock size={12} /> {s.t('atlas.planned')}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{progress && progress.total > 0 && (
|
||||
<div className={`${M_CARD} mt-4 px-4 py-3.5`}>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="text-caption text-m-muted">{s.t('atlas.regions')}</span>
|
||||
<span className="text-body font-bold tabular-nums text-m-ink">
|
||||
{progress.visited} / {progress.total}
|
||||
</span>
|
||||
</div>
|
||||
<MProgress value={(progress.visited / Math.max(1, progress.total)) * 100} height={6} className="mt-2" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tripsWithoutPlaces.length > 0 && (
|
||||
<div className="-mx-5 mt-4 flex gap-2 overflow-x-auto px-5">
|
||||
{tripsWithoutPlaces.map((trip) => (
|
||||
<button
|
||||
key={trip.id}
|
||||
type="button"
|
||||
onClick={() => openTrip(trip.id)}
|
||||
className="inline-flex flex-none items-center gap-1.5 rounded-full bg-[color:var(--m-ic)] px-3 py-2 text-caption font-semibold text-m-ink"
|
||||
>
|
||||
<Briefcase size={13} className="text-m-muted" /> {trip.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-4">
|
||||
{d.data ? (
|
||||
<AtlasCountryPlaces variant="mobile" detail={d.data} onOpenTrip={openTrip} />
|
||||
) : (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="size-6 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)]" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{d.data?.manually_marked && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={s.askUnmarkDetail}
|
||||
className="mt-5 w-full rounded-[16px] bg-[color:var(--m-ic)] py-3 text-body font-semibold"
|
||||
style={{ color: 'var(--m-st-danger)' }}
|
||||
>
|
||||
{s.t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { Globe2, Layers, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
import AtlasGlobe from '../../../components/AtlasGlobe/AtlasGlobe';
|
||||
import type { GlobeEngine } from '../../../components/AtlasGlobe/GlobeEngine';
|
||||
import GlobePins, { type GlobePinsHandle } from '../../../components/AtlasGlobe/GlobePins';
|
||||
import GlobeSky from '../../../components/AtlasGlobe/GlobeSky';
|
||||
import '../../../components/AtlasGlobe/atlasGlobe.css';
|
||||
import { segmentStyle } from '../../../components/Map/mapControlShadow';
|
||||
import AtlasBadgeUnlock from '../../../pages/atlas/AtlasBadgeUnlock';
|
||||
import AtlasGlobeSearch from '../../../pages/atlas/AtlasGlobeSearch';
|
||||
import AtlasGlobeStatus from '../../../pages/atlas/AtlasGlobeStatus';
|
||||
import AtlasGlobeTimeline from '../../../pages/atlas/AtlasGlobeTimeline';
|
||||
import { COMPARE_COLORS, compareCounts } from '../../../pages/atlas/atlasGlobePaint';
|
||||
import { countryStatus } from '../../../pages/atlas/atlasModel';
|
||||
import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe';
|
||||
import { useAtlasGlobe } from '../../../pages/atlas/useAtlasGlobe';
|
||||
import { useGlobeStats } from '../../../pages/atlas/useGlobeStats';
|
||||
import MAtlasCountrySheets from './MAtlasCountrySheets';
|
||||
import MAtlasLayersSheet from './MAtlasLayersSheet';
|
||||
import MAtlasStatsCard from './MAtlasStatsCard';
|
||||
import MAtlasHub from './hub/MAtlasHub';
|
||||
|
||||
/**
|
||||
* The globe Atlas on the phone: the globe fills the screen under the shell,
|
||||
* search on top, the numbers as a row of cards above the bottom nav, and the
|
||||
* same dialogs as the desktop. State and data come from useAtlasGlobe.
|
||||
*/
|
||||
export default function MAtlasGlobe(): React.ReactElement {
|
||||
const s = useAtlasGlobe();
|
||||
const stats = useGlobeStats(s);
|
||||
const navigate = useNavigate();
|
||||
const [layersOpen, setLayersOpen] = React.useState(false);
|
||||
const pinsRef = React.useRef<GlobePinsHandle>(null);
|
||||
// The dock's search button hands over with ?search=1, as on every screen: take
|
||||
// it off the address and put the cursor into the search.
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [focusSearch, setFocusSearch] = React.useState(0);
|
||||
React.useEffect(() => {
|
||||
if (searchParams.get('search') == null) return;
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.delete('search');
|
||||
setSearchParams(next, { replace: true });
|
||||
setFocusSearch((n) => n + 1);
|
||||
}, [searchParams, setSearchParams]);
|
||||
const onFrame = React.useCallback(
|
||||
(e: GlobeEngine) => {
|
||||
s.skyRef.current?.layout(e);
|
||||
pinsRef.current?.layout(e);
|
||||
},
|
||||
[s.skyRef]
|
||||
);
|
||||
|
||||
return (
|
||||
// h-dvh, as the classic phone Atlas: the shell gives no definite height (#1809).
|
||||
<div className="atlas-globe m-bleed relative h-dvh overflow-hidden">
|
||||
<AtlasGlobe
|
||||
ref={s.globeRef}
|
||||
fetchJson={s.fetchJson}
|
||||
dark
|
||||
labelFor={s.labelFor}
|
||||
labelRegionsOf={s.labelRegionsOf}
|
||||
paint={s.paint}
|
||||
paintKey={s.paintKey}
|
||||
onSelect={s.onSelect}
|
||||
onReady={s.onReady}
|
||||
onFrame={onFrame}
|
||||
onError={(err) => s.setError(err instanceof Error ? err.message : String(err))}
|
||||
insetBottom={170}
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-0">
|
||||
<GlobeSky ref={s.skyRef} dark />
|
||||
</div>
|
||||
<div className="pointer-events-none absolute inset-0 overflow-hidden">
|
||||
<GlobePins ref={pinsRef} pins={s.pins} />
|
||||
</div>
|
||||
|
||||
<AtlasGlobeStatus s={s} />
|
||||
<AtlasGlobeSearch
|
||||
s={s}
|
||||
focusSignal={focusSearch}
|
||||
className={`end-[102px] start-3 top-[var(--m-safe-top,12px)]`}
|
||||
/>
|
||||
<div
|
||||
className="ag-liquid pointer-events-auto absolute end-3 top-[var(--m-safe-top,12px)] flex h-11 items-center rounded-full p-1"
|
||||
style={{ gap: 2 }}
|
||||
>
|
||||
{/* The hub on the phone: one button for statistics, badges, wishes, tours
|
||||
and travellers; a new badge flies into it. */}
|
||||
<button
|
||||
type="button"
|
||||
className={s.passportOpen ? 'bg-accent text-accent-text' : 'text-content-secondary'}
|
||||
style={segmentStyle(s.passportOpen)}
|
||||
onClick={() => s.openPassport(s.passportTab)}
|
||||
aria-label={s.t('atlas.globe.hub')}
|
||||
data-atlas-badges-btn
|
||||
>
|
||||
<Globe2 size={16} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={layersOpen ? 'bg-accent text-accent-text' : 'text-content-secondary'}
|
||||
style={segmentStyle(layersOpen)}
|
||||
onClick={() => setLayersOpen(true)}
|
||||
aria-label={s.t('atlas.globe.layers')}
|
||||
>
|
||||
<Layers size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<MAtlasStatsCard stats={stats} />
|
||||
|
||||
<AtlasGlobeTimeline s={s} className="end-3 start-3 top-[calc(var(--m-safe-top,12px)+56px)]" />
|
||||
<AtlasBadgeUnlock s={s} />
|
||||
<MAtlasLayersSheet s={s} open={layersOpen} onClose={() => setLayersOpen(false)} />
|
||||
<MAtlasCountrySheets s={s} />
|
||||
<MAtlasHub s={s} />
|
||||
<MCompareBar s={s} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The overlay with another traveller on the phone: who, the three counts with
|
||||
* their colours, the gaps switch and the way out, as one card above the numbers.
|
||||
*/
|
||||
function MCompareBar({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const p = s.compareWith;
|
||||
if (!p) return null;
|
||||
const mine = (s.data?.countries ?? []).filter((c) => countryStatus(c) === 'visited').map((c) => c.code);
|
||||
const c = compareCounts(mine, p.codes);
|
||||
const keys: Array<[string, number, string]> = [
|
||||
[COMPARE_COLORS.both, c.both, s.t('atlas.globe.together')],
|
||||
[COMPARE_COLORS.theirs, c.theirsOnly, s.t('atlas.globe.onlyThem', { name: p.username })],
|
||||
[COMPARE_COLORS.mine, c.mineOnly, s.t('atlas.globe.onlyYou')],
|
||||
];
|
||||
return (
|
||||
<div className="ag-liquid pointer-events-auto absolute inset-x-3 bottom-[calc(var(--bottom-nav-h,84px)+92px)] z-30 flex flex-col gap-2 rounded-[20px] px-3.5 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-body font-semibold">
|
||||
{s.t('atlas.globe.compareWith', { name: p.username })}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => s.setGaps(!s.gaps)}
|
||||
aria-pressed={s.gaps}
|
||||
className={`rounded-full px-3 py-1.5 text-caption font-semibold ${s.gaps ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-secondary'}`}
|
||||
>
|
||||
{s.t('atlas.globe.gaps')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={s.stopCompare}
|
||||
aria-label={s.t('common.close')}
|
||||
className="grid size-8 place-items-center rounded-full text-content-muted"
|
||||
>
|
||||
<X size={15} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1">
|
||||
{keys.map(([color, n, label]) => (
|
||||
<span key={label} className="inline-flex items-center gap-1.5 text-caption">
|
||||
<i className="inline-block size-2.5 rounded-full" style={{ background: color }} />
|
||||
<b className="tabular-nums">{n}</b>
|
||||
<span className="text-content-muted">{label}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { CalendarClock, Plane, Puzzle, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { GlobeColorMode } from '../../../pages/atlas/atlasGlobePaint';
|
||||
import type { AtlasGlobeState } from '../../../pages/atlas/useAtlasGlobe';
|
||||
import MIconBtn from '../../components/MIconBtn';
|
||||
import MSegmented from '../../components/MSegmented';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import MToggle from '../../components/MToggle';
|
||||
import { M_CARD } from './hub/mHubKit';
|
||||
|
||||
/**
|
||||
* What the globe shows, on the phone: the switches as rows of one card and
|
||||
* the colouring as a segmented control, in a sheet from the bottom.
|
||||
*/
|
||||
export default function MAtlasLayersSheet({
|
||||
s,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}): React.ReactElement {
|
||||
const rows: Array<{
|
||||
key: string;
|
||||
Icon: React.ComponentType<{ size?: number }>;
|
||||
label: string;
|
||||
on: boolean;
|
||||
toggle: () => void;
|
||||
}> = [
|
||||
{
|
||||
key: 'planned',
|
||||
Icon: CalendarClock,
|
||||
label: s.t('atlas.showPlanned'),
|
||||
on: s.showPlanned,
|
||||
toggle: () => s.setShowPlanned(!s.showPlanned),
|
||||
},
|
||||
...(s.flights?.routes.length
|
||||
? [
|
||||
{
|
||||
key: 'flights',
|
||||
Icon: Plane,
|
||||
label: s.t('atlas.globe.flights'),
|
||||
on: s.showFlights,
|
||||
toggle: () => s.setShowFlights(!s.showFlights),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...s.pluginLayers.map((l) => {
|
||||
const key = `${l.pluginId}:${l.id}`;
|
||||
return {
|
||||
key,
|
||||
Icon: Puzzle,
|
||||
label: l.name || l.id,
|
||||
on: !s.hiddenPluginLayers.has(key),
|
||||
toggle: () => s.togglePluginLayer(key),
|
||||
};
|
||||
}),
|
||||
];
|
||||
const modes: Array<{ value: GlobeColorMode; label: string }> = [
|
||||
{ value: 'country', label: s.t('atlas.globe.colorCountry') },
|
||||
{ value: 'status', label: s.t('atlas.globe.colorStatus') },
|
||||
{ value: 'year', label: s.t('atlas.globe.colorYear') },
|
||||
];
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} variant="bottom" ariaLabel={s.t('atlas.globe.layers')}>
|
||||
<div className="flex min-h-0 flex-col gap-5 overflow-y-auto px-5 pb-6 pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="min-w-0 flex-1 text-title font-bold text-m-ink">{s.t('atlas.globe.layers')}</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.close')} onClick={onClose}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className={`${M_CARD} flex flex-col p-1.5`}>
|
||||
{rows.map(({ key, Icon, label, on, toggle }, i) => (
|
||||
<div
|
||||
key={key}
|
||||
className={`flex items-center gap-3 px-3 py-3 ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}
|
||||
>
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Icon size={16} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-body font-semibold text-m-ink">{label}</span>
|
||||
<MToggle checked={on} onChange={toggle} ariaLabel={label} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="px-1 text-caption font-bold uppercase tracking-wide text-m-muted">
|
||||
{s.t('atlas.globe.colorBy')}
|
||||
</div>
|
||||
<MSegmented value={s.colorMode} onChange={s.setColorMode} options={modes} />
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ChevronRight, Search } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
|
||||
interface CountryOption {
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
interface MAtlasSearchProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** All searchable countries (code + localized label). */
|
||||
options: CountryOption[]
|
||||
/** Shown while the query is empty: recently visited + bucket countries. */
|
||||
suggestions: CountryOption[]
|
||||
isVisited: (code: string) => boolean
|
||||
/** Countries that only appear via a trip which hasn't started yet (#1048). */
|
||||
isPlanned: (code: string) => boolean
|
||||
isOnBucketList: (code: string) => boolean
|
||||
onSelect: (code: string) => void
|
||||
}
|
||||
|
||||
const statusCls = 'flex-none font-geist text-[0.625rem] font-bold uppercase tracking-[.04em] text-m-faint'
|
||||
|
||||
/**
|
||||
* Full-screen country search on a blurred scrim. Typing filters the country
|
||||
* list; while empty the suggestion list (visited + bucket countries) fills
|
||||
* the result card. Selecting a row flies the map to the country.
|
||||
*/
|
||||
export default function MAtlasSearch({
|
||||
open,
|
||||
onClose,
|
||||
options,
|
||||
suggestions,
|
||||
isVisited,
|
||||
isPlanned,
|
||||
isOnBucketList,
|
||||
onSelect,
|
||||
}: MAtlasSearchProps) {
|
||||
const { t } = useTranslation()
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setQuery('')
|
||||
}, [open])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
|
||||
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
|
||||
|
||||
return (
|
||||
<div
|
||||
className={scrimCls}
|
||||
// presentation, not role="button": the scrim wraps the whole search
|
||||
// overlay, so making it a button puts a full-screen tab stop around its
|
||||
// own contents — and screen readers would read the entire panel as the
|
||||
// button's label. Clicking it is a mouse shortcut for the Cancel control
|
||||
// inside, which is already in the tab order. Same treatment as the other
|
||||
// backdrops in this sweep.
|
||||
role="presentation"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div className="flex items-center gap-[10px]" role="presentation" onClick={(e) => e.stopPropagation()}>
|
||||
<label className="flex min-w-0 flex-1 items-center gap-[10px] rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-sheetop)] px-4 py-[14px] shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
<Search size={18} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
if (e.key === 'Enter' && rows.length > 0) onSelect(rows[0].code)
|
||||
}}
|
||||
enterKeyHint="search" placeholder={t('atlas.searchCountry')}
|
||||
className="min-w-0 flex-1 bg-transparent font-geist text-[0.9375rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
|
||||
/>
|
||||
</label>
|
||||
<button type="button" onClick={onClose} className="flex-none px-1 font-geist text-[0.9375rem] font-semibold text-white">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{rows.length > 0 && (
|
||||
<div
|
||||
className="m-pop-in mt-[14px] divide-y divide-[color:var(--m-rowbr)] overflow-hidden rounded-[20px] border border-[color:var(--m-gbr)] bg-[color:var(--m-sheetop)] shadow-[0_20px_44px_-18px_rgba(0,0,0,.4)]"
|
||||
role="presentation"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{rows.map((r) => (
|
||||
<button
|
||||
key={r.code}
|
||||
type="button"
|
||||
onClick={() => onSelect(r.code)}
|
||||
className="flex w-full items-center gap-3 px-4 py-[14px] text-start active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${r.code.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-6 w-[34px] flex-none rounded-[5px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">{r.label}</span>
|
||||
{isVisited(r.code) ? (
|
||||
<span className={statusCls}>{t('mobileAtlas.visited')}</span>
|
||||
) : isPlanned(r.code) ? (
|
||||
<span className={statusCls}>{t('mobileAtlas.planned')}</span>
|
||||
) : isOnBucketList(r.code) ? (
|
||||
<span className={statusCls}>{t('atlas.bucketTab')}</span>
|
||||
) : null}
|
||||
<ChevronRight size={17} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,41 +1,24 @@
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import type { AtlasStats } from '../../../pages/atlas/atlasModel'
|
||||
import type { GlobeStat } from '../../../components/AtlasGlobe/GlobeStatsBar'
|
||||
|
||||
interface MAtlasStatsCardProps {
|
||||
stats: AtlasStats
|
||||
}
|
||||
/** The five figures the phone card has room for, in this order when they exist. */
|
||||
const PHONE_KEYS = ['countries', 'continents', 'regions', 'badges', 'wishlist']
|
||||
|
||||
/**
|
||||
* Floating stats card above the bottom nav: five stat columns straight from the
|
||||
* design. The bucket-list entry now lives in the full-width top header, so this
|
||||
* card is stats only.
|
||||
* Floating stats card above the bottom nav, in the same liquid glass as the
|
||||
* search on top: five columns, a large number over
|
||||
* a small caps label, as the phone Atlas has always shown them. Each column
|
||||
* opens what it counts (the hub's numbers, badges or wishlist).
|
||||
*/
|
||||
export default function MAtlasStatsCard({ stats }: MAtlasStatsCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const cols: [number, string][] = [
|
||||
[stats.totalCountries, t('atlas.countries', { count: stats.totalCountries })],
|
||||
[stats.totalTrips, t('atlas.trips', { count: stats.totalTrips })],
|
||||
[stats.totalPlaces, t('atlas.places', { count: stats.totalPlaces })],
|
||||
[stats.totalCities || 0, t('atlas.cities', { count: stats.totalCities || 0 })],
|
||||
[stats.totalDays, t('atlas.days', { count: stats.totalDays })],
|
||||
]
|
||||
// All five columns are spoken for, so the planned count rides along with the country
|
||||
// number as a superscript rather than claiming a sixth column.
|
||||
const planned = stats.totalCountriesPlanned || 0
|
||||
|
||||
export default function MAtlasStatsCard({ stats }: { stats: GlobeStat[] }) {
|
||||
const cols = PHONE_KEYS.map((k) => stats.find((st) => st.key === k)).filter((st): st is GlobeStat => !!st)
|
||||
return (
|
||||
<div className="m-bar-x absolute bottom-[calc(var(--bottom-nav-h,84px)+16px)] z-[5] wide:mx-auto wide:max-w-[720px]">
|
||||
<div className="flex w-full rounded-[22px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheet)] px-3 py-[14px] shadow-[0_18px_44px_-20px_rgba(0,0,0,.4)]">
|
||||
{cols.map(([n, l], i) => (
|
||||
<div key={l} className="flex-1 text-center">
|
||||
<div className="text-[1.375rem] font-extrabold leading-none tabular-nums text-m-ink">
|
||||
{n}
|
||||
{i === 0 && planned > 0 && (
|
||||
<span className="align-super text-[0.6875rem] font-bold text-m-faint">+{planned}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 font-geist text-[0.53125rem] font-bold uppercase tracking-[.06em] text-m-faint">{l}</div>
|
||||
</div>
|
||||
<div className="ag-liquid flex w-full rounded-[22px] px-2 py-[12px]">
|
||||
{cols.map((st) => (
|
||||
<button key={st.key} type="button" onClick={st.onClick} className="min-w-0 flex-1 rounded-[14px] px-0.5 py-0.5 text-center active:bg-surface-hover">
|
||||
<div className="text-[1.375rem] font-extrabold leading-none tabular-nums text-content">{st.value}</div>
|
||||
<div className="mt-1 truncate font-geist text-[0.53125rem] font-bold uppercase tracking-[.06em] text-content-muted">{st.label}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { useAtlas } from '../../../pages/atlas/useAtlas'
|
||||
|
||||
/**
|
||||
* Full surface of the shared atlas hook. The mobile screen calls useAtlas()
|
||||
* once and hands the controller down to its sheets, so map state, bucket list
|
||||
* and the mark/unmark flows stay in a single instance.
|
||||
*/
|
||||
export type AtlasController = ReturnType<typeof useAtlas>
|
||||
@@ -0,0 +1,80 @@
|
||||
import { X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useHubTabs } from '../../../../pages/atlas/AtlasHubRail';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MChip from '../../../components/MChip';
|
||||
import MChipStrip from '../../../components/MChipStrip';
|
||||
import MIconBtn from '../../../components/MIconBtn';
|
||||
import MSheet from '../../../components/MSheet';
|
||||
import MHubBadges from './MHubBadges';
|
||||
import MHubDawarich from './MHubDawarich';
|
||||
import MHubOverview from './MHubOverview';
|
||||
import MHubTours from './MHubTours';
|
||||
import MHubTravellers from './MHubTravellers';
|
||||
import MHubWishlist from './MHubWishlist';
|
||||
|
||||
/**
|
||||
* The Atlas hub on the phone: a sheet that rises over the globe, with the tabs
|
||||
* as a strip of chips under the title and each tab laid out for a narrow
|
||||
* screen. Badge details, a traveller's profile and a new wish open as sheets
|
||||
* of their own on top.
|
||||
*/
|
||||
export default function MAtlasHub({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const tabs = useHubTabs(s);
|
||||
const tab = s.passportTab;
|
||||
const close = () => s.setPassportOpen(false);
|
||||
const earned = s.badges.filter((b) => b.earned).length;
|
||||
return (
|
||||
<MSheet
|
||||
open={s.passportOpen}
|
||||
onClose={close}
|
||||
variant="bottom"
|
||||
ariaLabel={s.t('atlas.globe.hub')}
|
||||
className="h-full"
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex items-start gap-3 px-5 pb-3 pt-5">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-title font-bold leading-tight text-m-ink">{s.t('atlas.globe.hub')}</div>
|
||||
<div className="text-caption text-m-muted">
|
||||
{s.t('atlas.globe.collected', { earned, total: s.badges.length })}
|
||||
</div>
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.close')} onClick={close}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<MChipStrip label={s.t('atlas.globe.hub')} className="gap-2 px-5 pb-3">
|
||||
{tabs.map(({ tab: k, label, Icon }) => (
|
||||
<MChip
|
||||
key={k}
|
||||
pressable
|
||||
active={tab === k}
|
||||
onClick={() => {
|
||||
s.setPassportTab(k);
|
||||
s.setProfileId(null);
|
||||
}}
|
||||
>
|
||||
<Icon size={13} strokeWidth={2.2} /> {label}
|
||||
</MChip>
|
||||
))}
|
||||
</MChipStrip>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-8 pt-1">
|
||||
{tab === 'overview' ? (
|
||||
<MHubOverview s={s} />
|
||||
) : tab === 'badges' ? (
|
||||
<MHubBadges s={s} />
|
||||
) : tab === 'wishlist' ? (
|
||||
<MHubWishlist s={s} />
|
||||
) : tab === 'dawarich' ? (
|
||||
<MHubDawarich s={s} />
|
||||
) : tab === 'tours' ? (
|
||||
<MHubTours s={s} />
|
||||
) : (
|
||||
<MHubTravellers s={s} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { BADGE_CATEGORIES, type Badge } from '@trek/shared';
|
||||
import { CalendarCheck, CheckCircle2, Hourglass, Target, Users, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import BadgeMedal, { TIERS } from '../../../../components/AtlasGlobe/BadgeMedal';
|
||||
import CountryFlag from '../../../../components/shared/CountryFlag';
|
||||
import { medalLabel } from '../../../../pages/atlas/AtlasGlobeBadges';
|
||||
import { badgeHolders, badgeLadder, formatNum } from '../../../../pages/atlas/atlasHubModel';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MIconBtn from '../../../components/MIconBtn';
|
||||
import MProgress from '../../../components/MProgress';
|
||||
import MSheet from '../../../components/MSheet';
|
||||
import { M_CARD, M_INNER, MHubSection, MHubTiles, type MHubTileData } from './mHubKit';
|
||||
|
||||
function titleOf(s: AtlasGlobeState, b: Badge): string {
|
||||
const params: Record<string, string | number> = { ...(b.params ?? {}) };
|
||||
if (typeof params.country === 'string') params.country = s.resolveName(params.country) || params.country;
|
||||
return s.t(b.titleKey, params);
|
||||
}
|
||||
|
||||
/** Badges on the phone: every category as a three-column grid; a tap opens the badge's own sheet. */
|
||||
export default function MHubBadges({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const [openId, setOpenId] = React.useState<string | null>(null);
|
||||
const open = openId ? (s.badges.find((b) => b.id === openId) ?? null) : null;
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
{BADGE_CATEGORIES.map((cat) => {
|
||||
const list = s.badges.filter((b) => b.category === cat);
|
||||
if (!list.length) return null;
|
||||
return (
|
||||
<MHubSection
|
||||
key={cat}
|
||||
title={s.t(`atlas.badgeCat.${cat}`)}
|
||||
meta={`${list.filter((b) => b.earned).length} / ${list.length}`}
|
||||
>
|
||||
<div className={`${M_CARD} grid grid-cols-3 gap-1 p-2`}>
|
||||
{list.map((b) => (
|
||||
<button
|
||||
key={b.id}
|
||||
type="button"
|
||||
onClick={() => setOpenId(b.id)}
|
||||
className="flex flex-col items-center gap-1.5 rounded-[16px] px-1 pb-2.5 pt-2 text-center active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<BadgeMedal
|
||||
id={`m-${b.id}`}
|
||||
motif={b.motif}
|
||||
tier={b.tier}
|
||||
earned={b.earned}
|
||||
size={78}
|
||||
progress={b.target ? b.current / b.target : 0}
|
||||
label={medalLabel(b)}
|
||||
/>
|
||||
<span className="line-clamp-2 text-caption font-semibold leading-tight text-m-ink">
|
||||
{titleOf(s, b)}
|
||||
</span>
|
||||
<span className="text-[0.6875rem] tabular-nums text-m-muted">
|
||||
{b.earned ? (b.year ?? '') : `${formatNum(b.current)} / ${formatNum(b.target)}`}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</MHubSection>
|
||||
);
|
||||
})}
|
||||
<MSheet open={!!open} onClose={() => setOpenId(null)} variant="bottom" ariaLabel={open ? titleOf(s, open) : ''}>
|
||||
{open && <BadgeSheet s={s} b={open} onClose={() => setOpenId(null)} onOpen={setOpenId} />}
|
||||
</MSheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BadgeSheet({
|
||||
s,
|
||||
b,
|
||||
onClose,
|
||||
onOpen,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
b: Badge;
|
||||
onClose: () => void;
|
||||
onOpen: (id: string) => void;
|
||||
}): React.ReactElement {
|
||||
const share = b.target ? Math.min(1, b.current / b.target) : 0;
|
||||
const metal = TIERS[b.tier][0];
|
||||
const { loadPeople, compareEnabled } = s;
|
||||
React.useEffect(() => {
|
||||
if (compareEnabled) loadPeople();
|
||||
}, [compareEnabled, loadPeople]);
|
||||
const ladder = badgeLadder(s.badges, b);
|
||||
const holders = compareEnabled ? badgeHolders(s.people, b) : null;
|
||||
const tiles: MHubTileData[] = [
|
||||
{ Icon: Target, value: `${formatNum(b.current)} / ${formatNum(b.target)}`, label: s.t('atlas.globe.progress') },
|
||||
b.earned
|
||||
? { Icon: CalendarCheck, value: b.year ?? '✓', label: s.t('atlas.globe.reached') }
|
||||
: { Icon: Hourglass, value: formatNum(Math.max(0, b.target - b.current)), label: s.t('atlas.globe.toGo') },
|
||||
];
|
||||
if (holders)
|
||||
tiles.push({ Icon: Users, value: `${holders.holders} / ${holders.of}`, label: s.t('atlas.globe.holders') });
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col overflow-y-auto px-5 pb-8 pt-4">
|
||||
<div className="flex justify-end">
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.close')} onClick={onClose}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className="relative -mt-4 flex flex-col items-center gap-3 text-center">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute top-0 size-56 rounded-full opacity-60"
|
||||
style={{
|
||||
background: `radial-gradient(circle, color-mix(in srgb, ${metal} 30%, transparent), transparent 70%)`,
|
||||
}}
|
||||
/>
|
||||
<div className="relative">
|
||||
<BadgeMedal
|
||||
id={`ms-${b.id}`}
|
||||
motif={b.motif}
|
||||
tier={b.tier}
|
||||
earned={b.earned}
|
||||
size={150}
|
||||
progress={share}
|
||||
label={medalLabel(b)}
|
||||
/>
|
||||
</div>
|
||||
<div className="relative flex flex-wrap justify-center gap-1.5">
|
||||
<span className="rounded-full bg-[color:var(--m-ic)] px-2.5 py-1 text-caption font-semibold text-m-muted">
|
||||
{s.t(`atlas.badgeCat.${b.category}`)}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-[color:var(--m-ic)] px-2.5 py-1 text-caption font-semibold text-m-ink">
|
||||
<span className="size-2 rounded-full" style={{ background: metal }} /> {s.t(`atlas.badgeTier.${b.tier}`)}
|
||||
</span>
|
||||
{b.earned && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full bg-[color:var(--m-ic)] px-2.5 py-1 text-caption font-semibold"
|
||||
style={{ color: 'var(--m-st-confirmed)' }}
|
||||
>
|
||||
<CheckCircle2 size={12} /> {s.t('atlas.globe.reached')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative text-title font-bold leading-tight text-m-ink">{titleOf(s, b)}</div>
|
||||
</div>
|
||||
|
||||
<div className={`${M_CARD} mt-5 flex flex-col gap-2 px-4 py-4`}>
|
||||
<span className="self-start rounded-full bg-[color:var(--m-ic)] px-2.5 py-1 text-caption font-semibold text-m-muted">
|
||||
{s.t('atlas.globe.howTo')}
|
||||
</span>
|
||||
<p className="m-0 text-body text-m-ink">
|
||||
{s.t(b.descKey, {
|
||||
...(b.params ?? {}),
|
||||
country: b.country ? s.resolveName(b.country) || b.country : '',
|
||||
count: b.target,
|
||||
})}
|
||||
</p>
|
||||
{!b.earned && <MProgress value={share * 100} height={6} color={metal} className="mt-1" />}
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<MHubTiles tiles={tiles} cols={tiles.length === 3 ? 3 : 2} />
|
||||
</div>
|
||||
|
||||
{b.earned && b.country && (
|
||||
<div className={`${M_CARD} mt-3 flex items-center gap-3 px-4 py-3`}>
|
||||
<span className={`${M_INNER} grid size-10 flex-none place-items-center rounded-full`}>
|
||||
<CountryFlag code={b.country} size={20} />
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-caption text-m-muted">{s.t('atlas.globe.madeBy')}</span>
|
||||
<span className="block truncate text-body font-bold text-m-ink">
|
||||
{s.resolveName(b.country) || b.country}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ladder.length > 1 && (
|
||||
<div className="mt-5">
|
||||
<MHubSection
|
||||
title={s.t('atlas.globe.stages')}
|
||||
meta={`${ladder.filter((x) => x.earned).length} / ${ladder.length}`}
|
||||
>
|
||||
<div className="-mx-5 flex gap-2 overflow-x-auto px-5 pb-1">
|
||||
{ladder.map((x) => (
|
||||
<button
|
||||
key={x.id}
|
||||
type="button"
|
||||
onClick={() => onOpen(x.id)}
|
||||
aria-current={x.id === b.id}
|
||||
className={`flex w-[78px] flex-none flex-col items-center gap-1 rounded-[16px] px-1 py-2 ${x.id === b.id ? 'bg-[color:var(--m-ic)]' : ''}`}
|
||||
>
|
||||
<BadgeMedal
|
||||
id={`ml-${x.id}`}
|
||||
motif={x.motif}
|
||||
tier={x.tier}
|
||||
earned={x.earned}
|
||||
size={56}
|
||||
progress={x.target ? x.current / x.target : 0}
|
||||
label={medalLabel(x)}
|
||||
/>
|
||||
<span className="w-full truncate text-[0.6875rem] font-semibold text-m-muted">{titleOf(s, x)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</MHubSection>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Check, Globe2, Info, Loader2, RefreshCw, Star } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { cityLine, countryLabel, formatDistance } from '../../../../components/Dawarich/dawarichAtlasModel';
|
||||
import { formatDuration } from '../../../../components/Dawarich/dawarichSuggestionModel';
|
||||
import { useDawarichAtlas } from '../../../../components/Dawarich/useDawarichAtlas';
|
||||
import CountryFlag from '../../../../components/shared/CountryFlag';
|
||||
import { dawarichNotes } from '../../../../pages/atlas/AtlasGlobeDawarich';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MSegmented from '../../../components/MSegmented';
|
||||
import { M_CARD, M_INNER, MHubAction, MHubEmpty } from './mHubKit';
|
||||
|
||||
/**
|
||||
* Dawarich on the phone, inside the hub sheet: the two questions as a
|
||||
* segmented control, each offer as one tappable row with its facts on a single
|
||||
* line, and one full-width button that writes what is ticked.
|
||||
*/
|
||||
export default function MHubDawarich({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const d = useDawarichAtlas({ initialTab: s.dawarichSub, onChanged: () => void s.reload() });
|
||||
const { setTab } = d;
|
||||
React.useEffect(() => setTab(s.dawarichSub), [s.dawarichSub, setTab]);
|
||||
const t = s.t;
|
||||
const wishes = d.tab === 'wishes';
|
||||
const day = (iso: string) => new Date(iso).toLocaleDateString(s.language, { day: 'numeric', month: 'short' });
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<MSegmented
|
||||
value={d.tab}
|
||||
onChange={d.setTab}
|
||||
options={[
|
||||
{
|
||||
value: 'wishes',
|
||||
label: `${t('dawarich.atlas.tab.wishes')}${d.openMatches.length ? ` ${d.openMatches.length}` : ''}`,
|
||||
},
|
||||
{
|
||||
value: 'countries',
|
||||
label: `${t('dawarich.atlas.tab.countries')}${d.offered.length ? ` ${d.offered.length}` : ''}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{d.busy ? (
|
||||
<div className={`${M_CARD} flex items-center justify-center gap-2.5 px-4 py-8 text-body text-m-muted`}>
|
||||
<Loader2 size={17} className="animate-spin" />{' '}
|
||||
{t(wishes ? 'dawarich.bucket.scanning' : 'dawarich.atlas.loading')}
|
||||
</div>
|
||||
) : !d.loaded ? (
|
||||
<MHubEmpty
|
||||
Icon={wishes ? Star : Globe2}
|
||||
title={t(wishes ? 'dawarich.bucket.title' : 'dawarich.atlas.title')}
|
||||
hint={t(wishes ? 'dawarich.bucket.description' : 'dawarich.atlas.description')}
|
||||
action={
|
||||
<MHubAction Icon={RefreshCw} onClick={d.run}>
|
||||
{t(wishes ? 'dawarich.bucket.scan' : 'dawarich.atlas.load')}
|
||||
</MHubAction>
|
||||
}
|
||||
/>
|
||||
) : !d.anything ? (
|
||||
<MHubEmpty
|
||||
Icon={wishes ? Star : Globe2}
|
||||
title={t(wishes ? 'dawarich.bucket.noMatches' : 'dawarich.atlas.empty')}
|
||||
action={
|
||||
<MHubAction Icon={RefreshCw} onClick={d.run}>
|
||||
{t('dawarich.again')}
|
||||
</MHubAction>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className={`${M_CARD} flex flex-col gap-1 p-1.5`}>
|
||||
{wishes
|
||||
? d.matches.map((m) => (
|
||||
<Pick
|
||||
key={m.itemId}
|
||||
name={m.name}
|
||||
checked={d.picked.has(m.itemId)}
|
||||
disabled={m.alreadyVisited}
|
||||
onToggle={() => d.togglePicked(m.itemId)}
|
||||
leading={<Star size={15} style={{ color: 'var(--m-st-pending)' }} />}
|
||||
line={
|
||||
m.alreadyVisited
|
||||
? t('dawarich.bucket.alreadyVisited')
|
||||
: m.match
|
||||
? `${day(m.match.at)}, ${formatDuration(m.match.minutes, t)}, ${formatDistance(m.match.distanceMeters, t)}`
|
||||
: t('dawarich.bucket.noMatches')
|
||||
}
|
||||
/>
|
||||
))
|
||||
: d.offered.map((c) => (
|
||||
<Pick
|
||||
key={c.countryCode}
|
||||
name={countryLabel(c.countryCode, c.sourceName, s.language)}
|
||||
checked={d.pickedCountries.has(c.countryCode)}
|
||||
onToggle={() => d.togglePickedCountry(c.countryCode)}
|
||||
leading={<CountryFlag code={c.countryCode} size={18} />}
|
||||
line={c.cities.length ? cityLine(c.cities) : ''}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={d.run}
|
||||
aria-label={t('dawarich.again')}
|
||||
className="grid size-[50px] flex-none place-items-center rounded-[16px] bg-[color:var(--m-ic)] text-m-ink"
|
||||
>
|
||||
<RefreshCw size={18} />
|
||||
</button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MHubAction Icon={Check} disabled={d.selected === 0 || d.writing} onClick={d.confirm}>
|
||||
{wishes
|
||||
? t('dawarich.bucket.confirm', { count: d.selected })
|
||||
: t('dawarich.atlas.accept', { count: d.selected })}
|
||||
</MHubAction>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{d.loaded &&
|
||||
dawarichNotes(d, t).map((note) => (
|
||||
<p key={note} className="m-0 flex items-start gap-1.5 px-1 text-caption text-m-faint">
|
||||
<Info size={12} className="mt-0.5 flex-none" /> {note}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One offer: the whole row ticks it; the facts sit on one line under the name. */
|
||||
function Pick({
|
||||
name,
|
||||
line,
|
||||
checked,
|
||||
disabled = false,
|
||||
onToggle,
|
||||
leading,
|
||||
}: {
|
||||
name: string;
|
||||
line: string;
|
||||
checked: boolean;
|
||||
disabled?: boolean;
|
||||
onToggle: () => void;
|
||||
leading: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
aria-label={name}
|
||||
disabled={disabled}
|
||||
onClick={onToggle}
|
||||
className={`${M_INNER} flex w-full items-center gap-3 px-3 py-3 text-start ${disabled ? 'opacity-60' : ''}`}
|
||||
>
|
||||
<span className="grid size-10 flex-none place-items-center rounded-full bg-[color:var(--m-ic)]">{leading}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-m-ink">{name}</span>
|
||||
{line && <span className="block truncate text-caption text-m-muted">{line}</span>}
|
||||
</span>
|
||||
<span
|
||||
className={`grid size-6 flex-none place-items-center rounded-full border-2 ${checked || disabled ? 'border-[color:var(--m-act)] bg-m-act text-m-actfg' : 'border-[color:var(--m-checkbr)]'}`}
|
||||
>
|
||||
{(checked || disabled) && <Check size={13} strokeWidth={3} />}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Briefcase, Building2, CalendarDays, ChevronRight, Flame, Map as MapIcon, MapPin, Plane } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { continentCounts, WORLD_COUNTRIES } from '../../../../pages/atlas/atlasHubModel';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MProgress from '../../../components/MProgress';
|
||||
import { M_CARD, MHubDawarichEntry, MHubHero, MHubSection, MHubTiles } from './mHubKit';
|
||||
|
||||
/** The numbers on the phone: countries large, continents as rows of bars, the rest as tiles, the next trip at the foot. */
|
||||
export default function MHubOverview({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const d = s.data;
|
||||
const st = d?.stats;
|
||||
const countries = s.totals.countries;
|
||||
const share = Math.min(1, countries / WORLD_COUNTRIES);
|
||||
const planned = (st?.totalCountriesPlanned ?? 0) + (st?.totalCountriesIdea ?? 0);
|
||||
const continents = continentCounts(d);
|
||||
const maxC = Math.max(1, ...continents.map((c) => c.n));
|
||||
const next = d?.nextTrip as { id: number; title: string; daysUntil?: number } | null | undefined;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<MHubHero value={countries} unit={s.t('atlas.countries', { count: countries })}>
|
||||
<MProgress value={share * 100} height={6} />
|
||||
<div className="mt-2 flex items-center justify-between text-caption text-m-muted">
|
||||
<span>{s.t('atlas.globe.worldShare', { share: Math.round(share * 100) })}</span>
|
||||
{planned > 0 && (
|
||||
<span>
|
||||
+{planned} {s.t('atlas.planned')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</MHubHero>
|
||||
|
||||
{next && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(`/trips/${next.id}`)}
|
||||
className={`${M_CARD} flex items-center gap-3.5 px-4 py-3.5 text-start active:opacity-80`}
|
||||
>
|
||||
{typeof next.daysUntil === 'number' && (
|
||||
<span className="flex flex-none flex-col items-center rounded-[14px] bg-m-act px-3 py-1.5 text-m-actfg">
|
||||
<span className="text-subtitle font-bold tabular-nums leading-none">{next.daysUntil}</span>
|
||||
<span className="text-[0.625rem] font-semibold">{s.t('atlas.daysLeft')}</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-caption text-m-muted">{s.t('atlas.nextTrip')}</span>
|
||||
<span className="block truncate text-body font-bold text-m-ink">{next.title}</span>
|
||||
</span>
|
||||
<ChevronRight size={18} className="text-m-faint" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<MHubSection title={s.t('atlas.globe.continents')} meta={`${s.totals.continents} / ${continents.length}`}>
|
||||
<div className={`${M_CARD} flex flex-col gap-3 px-4 py-4`}>
|
||||
{continents.map((c) => (
|
||||
<div key={c.name} className="flex items-center gap-3">
|
||||
<span className="w-[38%] truncate text-caption font-semibold text-m-ink">{s.t(c.key)}</span>
|
||||
<div className="h-2 min-w-0 flex-1 overflow-hidden rounded-full bg-[color:var(--m-ic)]">
|
||||
<div
|
||||
className="h-full rounded-full bg-m-act transition-[width] duration-700"
|
||||
style={{ width: `${c.n ? Math.max(6, (c.n / maxC) * 100) : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="w-6 text-end text-caption font-bold tabular-nums text-m-ink">{c.n}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</MHubSection>
|
||||
|
||||
{s.dawarichEnabled && (
|
||||
<MHubDawarichEntry
|
||||
title={s.t('atlas.globe.dawarichCountries')}
|
||||
hint={s.t('atlas.globe.dawarichCountriesHint')}
|
||||
onClick={() => s.openDawarich('countries')}
|
||||
/>
|
||||
)}
|
||||
|
||||
<MHubTiles
|
||||
tiles={[
|
||||
{ Icon: MapIcon, value: s.totals.regions, label: s.t('atlas.regions', { count: s.totals.regions }) },
|
||||
{ Icon: Briefcase, value: st?.totalTrips ?? 0, label: s.t('atlas.trips', { count: st?.totalTrips ?? 0 }) },
|
||||
{ Icon: MapPin, value: st?.totalPlaces ?? 0, label: s.t('atlas.places', { count: st?.totalPlaces ?? 0 }) },
|
||||
{ Icon: Building2, value: st?.totalCities ?? 0, label: s.t('atlas.cities', { count: st?.totalCities ?? 0 }) },
|
||||
{ Icon: CalendarDays, value: st?.totalDays ?? 0, label: s.t('atlas.days', { count: st?.totalDays ?? 0 }) },
|
||||
{ Icon: Flame, value: d?.streak ?? 0, label: s.t('atlas.yearsInRow', { count: d?.streak ?? 0 }) },
|
||||
{
|
||||
Icon: Plane,
|
||||
value: d?.tripsThisYear ?? 0,
|
||||
label: `${s.t('atlas.tripsIn', { count: d?.tripsThisYear ?? 0 })} ${new Date().getFullYear()}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { ArrowDownRight, ArrowUpRight, Footprints, ListOrdered, Mountain } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import {
|
||||
ActivityStatusLine,
|
||||
BasisBadges,
|
||||
periodLabel,
|
||||
UncountedBadges,
|
||||
} from '../../../../components/Atlas/tourActivity/tourActivityParts';
|
||||
import {
|
||||
distanceReading,
|
||||
heightReading,
|
||||
typeIcon,
|
||||
typeLabel,
|
||||
useDistanceUnit,
|
||||
} from '../../../../components/Atlas/tourActivity/tourActivityReading';
|
||||
import { TourActivityStatsDialog } from '../../../../components/Atlas/tourActivity/TourActivityStatsDialog';
|
||||
import { splitMeasure } from '../../../../components/Atlas/tourActivity/tourActivityStatsModel';
|
||||
import { useTourActivityStats } from '../../../../components/Atlas/tourActivity/useTourActivityStats';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MChip from '../../../components/MChip';
|
||||
import MChipStrip from '../../../components/MChipStrip';
|
||||
import { M_CARD, M_INNER, MHubAction, MHubEmpty, MHubHero, MHubSection, MHubTiles } from './mHubKit';
|
||||
|
||||
/** Tours on the phone: the distance large, tours, climb and descent as three tiles, every type as a row with its bar. */
|
||||
export default function MHubTours({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const stats = useTourActivityStats(true);
|
||||
const unit = useDistanceUnit();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const summary = stats.summary;
|
||||
const t = s.t;
|
||||
// The period and the kind of tour as two rows of small chips: the desktop's
|
||||
// pickers would open a list over a phone sheet for a choice of a few words.
|
||||
const filters = (
|
||||
<div className="-mx-4 flex flex-col gap-2">
|
||||
<MChipStrip label={t('tours.stats.period')} className="gap-1.5 px-4">
|
||||
{stats.periods.map((p) => (
|
||||
<MChip key={p} pressable active={stats.period === p} onClick={() => stats.setPeriod(p)}>
|
||||
{periodLabel(p, t)}
|
||||
</MChip>
|
||||
))}
|
||||
</MChipStrip>
|
||||
{stats.types.length > 1 && (
|
||||
<MChipStrip label={t('tours.filter.type')} className="gap-1.5 px-4">
|
||||
{stats.types.map((type) => {
|
||||
const Icon = typeIcon(type);
|
||||
return (
|
||||
<MChip key={type} pressable active={stats.type === type} onClick={() => stats.setType(type)}>
|
||||
<Icon size={12} strokeWidth={2.2} /> {typeLabel(type, t)}
|
||||
</MChip>
|
||||
);
|
||||
})}
|
||||
</MChipStrip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!summary) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{filters}
|
||||
<div className={`${M_CARD} px-4 py-5`}>
|
||||
<ActivityStatusLine stats={stats} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const totals = summary.totals;
|
||||
if (totals.count === 0) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{filters}
|
||||
<MHubEmpty Icon={Mountain} title={t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const distance = distanceReading(totals, unit);
|
||||
const hero = distance ? splitMeasure(distance.text) : { value: String(totals.count), unit: '' };
|
||||
const ascent = heightReading(totals.ascentM, unit);
|
||||
const descent = heightReading(totals.descentM, unit);
|
||||
const types = summary.types;
|
||||
const maxKm = Math.max(1e-9, ...types.map((x) => x.distanceKm.value ?? 0));
|
||||
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{filters}
|
||||
<MHubHero value={hero.value} unit={hero.unit || undefined}>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<BasisBadges byBasis={totals.byBasis} />
|
||||
</div>
|
||||
</MHubHero>
|
||||
<MHubTiles
|
||||
cols={3}
|
||||
tiles={[
|
||||
{ Icon: Footprints, value: totals.count, label: t('tours.mode.tours') },
|
||||
{ Icon: ArrowUpRight, value: ascent?.text ?? '0', label: t('tours.detail.ascent') },
|
||||
{ Icon: ArrowDownRight, value: descent?.text ?? '0', label: t('tours.detail.descent') },
|
||||
]}
|
||||
/>
|
||||
{stats.type === 'all' && types.length > 0 && (
|
||||
<MHubSection title={t('atlas.globe.byType')} meta={types.length}>
|
||||
<div className={`${M_CARD} flex flex-col gap-1 p-1.5`}>
|
||||
{types.map((x) => {
|
||||
const Icon = typeIcon(x.type);
|
||||
const d = distanceReading(x, unit);
|
||||
return (
|
||||
<div key={x.type} className={`${M_INNER} flex flex-col gap-2 px-3 py-3`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Icon size={16} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-m-ink">{typeLabel(x.type, t)}</span>
|
||||
<span className="block text-caption tabular-nums text-m-muted">
|
||||
{t('atlas.globe.tourCount', { count: x.count })}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-body font-bold tabular-nums text-m-ink">{d?.text ?? ''}</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-[color:var(--m-ic)]">
|
||||
<div
|
||||
className="h-full rounded-full bg-m-act"
|
||||
style={{ width: `${Math.max(4, ((x.distanceKm.value ?? 0) / maxKm) * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</MHubSection>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
|
||||
</div>
|
||||
{summary.done.length > 0 && (
|
||||
<MHubAction Icon={ListOrdered} onClick={() => setOpen(true)}>
|
||||
{t('tours.stats.showTours')}
|
||||
</MHubAction>
|
||||
)}
|
||||
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { ChevronRight, Flag, Globe2, Layers, Map as MapIcon, Plane, Users, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import BadgeMedal from '../../../../components/AtlasGlobe/BadgeMedal';
|
||||
import { medalLabel } from '../../../../pages/atlas/AtlasGlobeBadges';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import MIconBtn from '../../../components/MIconBtn';
|
||||
import MSheet from '../../../components/MSheet';
|
||||
import MToggle from '../../../components/MToggle';
|
||||
import { M_CARD, M_INNER, MHubAction, MHubEmpty, MHubSection, MHubTiles } from './mHubKit';
|
||||
|
||||
/** Gold, silver and bronze for the first three places. */
|
||||
const PODIUM = ['#f5c542', '#c9d1db', '#d08a4f']; // theme-lint-disable: podium medal colours
|
||||
|
||||
function Avatar({
|
||||
name,
|
||||
url,
|
||||
size,
|
||||
}: {
|
||||
name: string;
|
||||
url: string | null | undefined;
|
||||
size: number;
|
||||
}): React.ReactElement {
|
||||
return url ? (
|
||||
<img src={url} alt="" className="flex-none rounded-full object-cover" style={{ width: size, height: size }} />
|
||||
) : (
|
||||
<span
|
||||
className="grid flex-none place-items-center rounded-full bg-m-act font-bold text-m-actfg"
|
||||
style={{ width: size, height: size }}
|
||||
>
|
||||
{name.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The travellers on the phone: being visible as a switch, the ranking as rows, a profile as its own sheet. */
|
||||
export default function MHubTravellers({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const { loadPeople } = s;
|
||||
React.useEffect(() => {
|
||||
loadPeople();
|
||||
}, [loadPeople]);
|
||||
const rows = s.ranking;
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className={`${M_CARD} flex items-center gap-3 px-4 py-3.5`}>
|
||||
<span className="min-w-0 flex-1 text-body font-semibold text-m-ink">{s.t('atlas.globe.visibleToOthers')}</span>
|
||||
<MToggle
|
||||
checked={!s.hidden}
|
||||
onChange={() => s.setHidden(!s.hidden)}
|
||||
ariaLabel={s.t('atlas.globe.visibleToOthers')}
|
||||
/>
|
||||
</div>
|
||||
{!rows ? null : rows.length <= 1 ? (
|
||||
<MHubEmpty Icon={Users} title={s.t('atlas.globe.noTravellers')} />
|
||||
) : (
|
||||
<MHubSection title={s.t('atlas.globe.ranking')} meta={rows.length}>
|
||||
<ol className={`${M_CARD} m-0 flex list-none flex-col gap-1 p-1.5`}>
|
||||
{rows.map((p, i) => {
|
||||
const isMe = p.id === s.me?.id;
|
||||
return (
|
||||
<li key={p.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={isMe}
|
||||
onClick={() => s.setProfileId(p.id)}
|
||||
className={`${M_INNER} flex w-full items-center gap-3 px-3 py-2.5 text-start ${isMe ? 'bg-[color:var(--m-ic)]' : 'active:opacity-80'}`}
|
||||
>
|
||||
<span
|
||||
className={`grid size-7 flex-none place-items-center rounded-full text-caption font-bold tabular-nums ${i < 3 ? 'text-m-ink' : 'text-m-faint'}`}
|
||||
style={
|
||||
i < 3
|
||||
? {
|
||||
background: `color-mix(in srgb, ${PODIUM[i]} 30%, transparent)`,
|
||||
boxShadow: `inset 0 0 0 1.5px ${PODIUM[i]}`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{i + 1}
|
||||
</span>
|
||||
<Avatar name={p.username} url={p.avatar_url} size={36} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="truncate text-body font-semibold text-m-ink">{p.username}</span>
|
||||
{isMe && (
|
||||
<span className="flex-none rounded-full bg-m-act px-1.5 py-px text-[0.625rem] font-bold text-m-actfg">
|
||||
{s.t('atlas.globe.you')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex items-center gap-2.5 text-caption tabular-nums text-m-muted">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Globe2 size={11} /> {p.continents}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<MapIcon size={11} /> {p.regions}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex w-12 flex-none flex-col items-end">
|
||||
<span className="text-subtitle font-bold tabular-nums leading-none text-m-ink">
|
||||
{p.countries}
|
||||
</span>
|
||||
<span className="mt-0.5 text-[0.625rem] text-m-muted">{s.t('atlas.countries')}</span>
|
||||
</span>
|
||||
<ChevronRight
|
||||
size={16}
|
||||
className={`flex-none text-m-faint ${isMe ? 'invisible' : ''}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</MHubSection>
|
||||
)}
|
||||
<MSheet
|
||||
open={!!s.profile}
|
||||
onClose={() => s.setProfileId(null)}
|
||||
variant="bottom"
|
||||
ariaLabel={s.profile?.username ?? ''}
|
||||
>
|
||||
{s.profile && <ProfileSheet s={s} />}
|
||||
</MSheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileSheet({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const p = s.profile;
|
||||
if (!p) return null;
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col overflow-y-auto px-5 pb-6 pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar name={p.username} url={p.avatar_url} size={52} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-title font-bold text-m-ink">{p.username}</div>
|
||||
<div className="text-caption text-m-muted">
|
||||
{s.t('atlas.globe.collected', { earned: p.badges.length, total: s.badges.length })}
|
||||
</div>
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.close')} onClick={() => s.setProfileId(null)}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<MHubTiles
|
||||
tiles={[
|
||||
{ Icon: Flag, value: p.countries, label: s.t('atlas.countries') },
|
||||
{ Icon: Globe2, value: p.continents, label: s.t('atlas.globe.continents') },
|
||||
{ Icon: MapIcon, value: p.regions, label: s.t('atlas.regions') },
|
||||
{ Icon: Plane, value: `${Math.round(p.flightKm / 1000)}k`, label: s.t('atlas.globe.flightKm') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
{p.badges.length ? (
|
||||
<MHubSection title={s.t('atlas.globe.badges')} meta={p.badges.length}>
|
||||
<div className={`${M_CARD} grid grid-cols-3 gap-1 p-2`}>
|
||||
{p.badges.map((b) => {
|
||||
const params: Record<string, string | number> = { ...(b.params ?? {}) };
|
||||
if (typeof params.country === 'string')
|
||||
params.country = s.resolveName(params.country) || params.country;
|
||||
return (
|
||||
<div key={b.id} className="flex flex-col items-center gap-1 px-1 py-2 text-center">
|
||||
<BadgeMedal
|
||||
id={`mp${p.id}-${b.id}`}
|
||||
motif={b.motif}
|
||||
tier={b.tier}
|
||||
earned
|
||||
size={68}
|
||||
label={medalLabel({ motif: b.motif, target: b.target, current: b.target })}
|
||||
/>
|
||||
<span className="line-clamp-2 text-caption font-semibold leading-tight text-m-ink">
|
||||
{s.t(b.titleKey, params)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</MHubSection>
|
||||
) : (
|
||||
<MHubEmpty Icon={Users} title={s.t('atlas.globe.noBadgesYet')} />
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<MHubAction
|
||||
Icon={Layers}
|
||||
onClick={() => {
|
||||
s.setProfileId(null);
|
||||
s.startCompare(p);
|
||||
}}
|
||||
>
|
||||
{s.t('atlas.globe.compareOnGlobe')}
|
||||
</MHubAction>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
import { getIntlLanguage } from '@trek/shared';
|
||||
import {
|
||||
CalendarCheck,
|
||||
CalendarClock,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Flag,
|
||||
Loader2,
|
||||
MapPin,
|
||||
Navigation,
|
||||
PenLine,
|
||||
Plus,
|
||||
Radar,
|
||||
Search,
|
||||
Star,
|
||||
Trash2,
|
||||
Undo2,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
import CountryFlag from '../../../../components/shared/CountryFlag';
|
||||
import { splitWishes, visitedOn, whenLabeller, wishCountry } from '../../../../pages/atlas/atlasHubModel';
|
||||
import type { BucketItem } from '../../../../pages/atlas/atlasModel';
|
||||
import type { AtlasGlobeState } from '../../../../pages/atlas/useAtlasGlobe';
|
||||
import { useGlobePlaceSearch } from '../../../../pages/atlas/useGlobePlaceSearch';
|
||||
import MIconBtn from '../../../components/MIconBtn';
|
||||
import MProgress from '../../../components/MProgress';
|
||||
import MSheet from '../../../components/MSheet';
|
||||
import MSwipeRow from '../../../components/MSwipeRow';
|
||||
import { M_CARD, M_FIELD, M_INNER, MHubAction, MHubDawarichEntry, MHubEmpty, MHubHero, MHubSection } from './mHubKit';
|
||||
|
||||
/** The wishlist on the phone: the headline, one button to add, then open and reached wishes as rows that swipe. */
|
||||
export default function MHubWishlist({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const when = whenLabeller(s.language);
|
||||
const items = b.bucketList;
|
||||
const { open, reached, countries, nextDated } = splitWishes(items);
|
||||
const add = () => b.setShowBucketAdd(true);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{items.length === 0 ? (
|
||||
<MHubEmpty
|
||||
Icon={Star}
|
||||
title={s.t('atlas.bucketEmpty')}
|
||||
hint={s.t('atlas.bucketEmptyHint')}
|
||||
action={
|
||||
<MHubAction Icon={Plus} onClick={add}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</MHubAction>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<MHubHero value={items.length} unit={s.t('atlas.globe.wishes', { count: items.length })}>
|
||||
<MProgress value={(reached.length / items.length) * 100} height={6} />
|
||||
<div className="mt-2 flex items-center justify-between gap-3 text-caption text-m-muted">
|
||||
<span>{s.t('atlas.globe.wishesReached', { done: reached.length, count: items.length })}</span>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Flag size={12} /> {countries}
|
||||
</span>
|
||||
</div>
|
||||
{nextDated && (
|
||||
<div className={`${M_INNER} mt-3 flex items-center gap-2.5 px-3 py-2.5`}>
|
||||
<CalendarClock size={15} className="text-m-muted" />
|
||||
<span className="min-w-0 flex-1 truncate text-caption font-semibold text-m-ink">{nextDated.name}</span>
|
||||
<span className="text-caption tabular-nums text-m-muted">{when(nextDated.target_date)}</span>
|
||||
</div>
|
||||
)}
|
||||
</MHubHero>
|
||||
<MHubAction Icon={Plus} onClick={add}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</MHubAction>
|
||||
{s.dawarichEnabled && (
|
||||
<MHubDawarichEntry
|
||||
title={s.t('atlas.globe.dawarichWishes')}
|
||||
hint={s.t('atlas.globe.dawarichWishesHint')}
|
||||
onClick={() => s.openDawarich('wishes')}
|
||||
/>
|
||||
)}
|
||||
{open.length > 0 && (
|
||||
<MHubSection title={s.t('atlas.globe.wishesOpen')} meta={open.length}>
|
||||
<div className={`${M_CARD} flex flex-col gap-1 p-1.5`}>
|
||||
{open.map((item) => (
|
||||
<WishRow key={item.id} s={s} item={item} when={when(item.target_date)} />
|
||||
))}
|
||||
</div>
|
||||
</MHubSection>
|
||||
)}
|
||||
{reached.length > 0 && (
|
||||
<MHubSection title={s.t('atlas.globe.wishesDone')} meta={reached.length}>
|
||||
<div className={`${M_CARD} flex flex-col gap-1 p-1.5`}>
|
||||
{reached.map((item) => (
|
||||
<WishRow key={item.id} s={s} item={item} when={when(item.target_date)} />
|
||||
))}
|
||||
</div>
|
||||
</MHubSection>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<MSheet
|
||||
open={b.showBucketAdd}
|
||||
onClose={b.resetBucketAdd}
|
||||
variant="bottom"
|
||||
ariaLabel={s.t('atlas.globe.newWish')}
|
||||
discardGuard={b.bucketForm}
|
||||
>
|
||||
{b.showBucketAdd && <AddWishSheet s={s} />}
|
||||
</MSheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WishRow({ s, item, when }: { s: AtlasGlobeState; item: BucketItem; when: string | null }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const done = !!item.visited_at;
|
||||
const a2 = wishCountry(item.country_code);
|
||||
const country = a2 ? s.resolveName(a2) : null;
|
||||
const byRecording = item.visited_source === 'dawarich';
|
||||
const hasPlace = !!(item.lat && item.lng);
|
||||
const sub = [country && country !== item.name ? country : null, item.notes].filter(Boolean).join(', ');
|
||||
return (
|
||||
<MSwipeRow
|
||||
surface="var(--m-inner)"
|
||||
inset={4}
|
||||
leading={
|
||||
hasPlace
|
||||
? {
|
||||
label: s.t('atlas.globe.showOnGlobe'),
|
||||
icon: Navigation,
|
||||
tone: 'accent',
|
||||
onAction: () => s.flyToPoint(Number(item.lng), Number(item.lat)),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
trailing={[
|
||||
{
|
||||
label: s.t('atlas.removeFromBucket'),
|
||||
icon: Trash2,
|
||||
tone: 'danger',
|
||||
onAction: () => void b.handleDeleteBucketItem(item.id),
|
||||
},
|
||||
...(done && byRecording
|
||||
? [
|
||||
{
|
||||
label: s.t('dawarich.bucket.clearVisit'),
|
||||
icon: Undo2,
|
||||
tone: 'neutral' as const,
|
||||
onAction: () => void b.handleClearBucketVisit(item.id),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => hasPlace && s.flyToPoint(Number(item.lng), Number(item.lat))}
|
||||
className={`${M_INNER} flex w-full items-center gap-3 px-3 py-3 text-start`}
|
||||
>
|
||||
<span className="grid size-10 flex-none place-items-center rounded-full bg-[color:var(--m-ic)]">
|
||||
{a2 ? <CountryFlag code={a2} size={20} /> : <Star size={16} style={{ color: 'var(--m-st-pending)' }} />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={`block truncate text-body font-semibold ${done ? 'text-m-muted line-through' : 'text-m-ink'}`}
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{sub && <span className="block truncate text-caption text-m-muted">{sub}</span>}
|
||||
</span>
|
||||
{done ? (
|
||||
<span
|
||||
className="inline-flex flex-none items-center gap-1 rounded-full bg-[color:var(--m-ic)] px-2 py-1 text-caption font-semibold tabular-nums"
|
||||
style={{ color: 'var(--m-st-confirmed)' }}
|
||||
>
|
||||
{byRecording ? <Radar size={11} /> : <CalendarCheck size={11} />} {visitedOn(item, s.language)}
|
||||
</span>
|
||||
) : (
|
||||
when && (
|
||||
<span className="inline-flex flex-none items-center gap-1 rounded-full bg-[color:var(--m-ic)] px-2 py-1 text-caption font-semibold tabular-nums text-m-muted">
|
||||
<CalendarClock size={11} /> {when}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</button>
|
||||
</MSwipeRow>
|
||||
);
|
||||
}
|
||||
|
||||
/** Adding a wish on the phone: where, when and a note, as one sheet with the save at its foot. */
|
||||
function AddWishSheet({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const lang = getIntlLanguage(s.language);
|
||||
const [query, setQuery] = React.useState('');
|
||||
const { placeHits, placesLoading } = useGlobePlaceSearch(query, s.placeLang);
|
||||
const picked = !!b.bucketForm.name;
|
||||
const thisYear = new Date().getFullYear();
|
||||
const year = b.bucketPoiYear;
|
||||
const month = b.bucketPoiMonth;
|
||||
const months = Array.from({ length: 12 }, (_, i) => new Date(2000, i).toLocaleString(lang, { month: 'short' }));
|
||||
const takeName = () => {
|
||||
const name = query.trim();
|
||||
if (!name) return;
|
||||
b.setBucketForm({ ...b.bucketForm, name, lat: '', lng: '', address: undefined });
|
||||
setQuery('');
|
||||
};
|
||||
const label = (text: string) => (
|
||||
<div className="px-1 text-caption font-bold uppercase tracking-wide text-m-muted">{text}</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col">
|
||||
<div className="flex items-center gap-3 px-5 pb-2 pt-5">
|
||||
<div className="min-w-0 flex-1 text-title font-bold text-m-ink">{s.t('atlas.globe.newWish')}</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={s.t('common.cancel')} onClick={b.resetBucketAdd}>
|
||||
<X size={17} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-5 pb-4 pt-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
{label(s.t('atlas.globe.wishWhere'))}
|
||||
{picked ? (
|
||||
<div className={`${M_INNER} flex items-center gap-3 px-3 py-3`}>
|
||||
<span
|
||||
className="grid size-10 flex-none place-items-center rounded-full bg-[color:var(--m-ic)]"
|
||||
style={{ color: 'var(--m-st-pending)' }}
|
||||
>
|
||||
{b.bucketForm.lat ? <MapPin size={17} /> : <Star size={16} />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<input
|
||||
value={b.bucketForm.name}
|
||||
onChange={(e) => b.setBucketForm({ ...b.bucketForm, name: e.target.value })}
|
||||
aria-label={s.t('atlas.bucketNamePlaceholder')}
|
||||
className="w-full bg-transparent text-body font-bold text-m-ink outline-none"
|
||||
/>
|
||||
<span className="block truncate text-caption text-m-muted">
|
||||
{b.bucketForm.address ||
|
||||
s.t(b.bucketForm.lat ? 'atlas.globe.showOnGlobe' : 'atlas.globe.wishNoPlace')}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => b.setBucketForm({ ...b.bucketForm, name: '', lat: '', lng: '', address: undefined })}
|
||||
className="rounded-full bg-[color:var(--m-ic)] px-3 py-1.5 text-caption font-semibold text-m-ink"
|
||||
>
|
||||
{s.t('atlas.globe.change')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="relative">
|
||||
<Search
|
||||
size={16}
|
||||
className="pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-m-muted"
|
||||
/>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={s.t('atlas.globe.wishSearch')}
|
||||
enterKeyHint="search"
|
||||
className={`${M_FIELD} ps-10`}
|
||||
/>
|
||||
{placesLoading && (
|
||||
<Loader2 size={16} className="absolute end-3.5 top-1/2 -translate-y-1/2 animate-spin text-m-muted" />
|
||||
)}
|
||||
</div>
|
||||
{(placeHits.length > 0 || query.trim()) && (
|
||||
<div className={`${M_CARD} flex flex-col p-1`}>
|
||||
{placeHits.map((p) => (
|
||||
<button
|
||||
key={`${p.lat},${p.lng}`}
|
||||
type="button"
|
||||
onClick={() => b.handleSelectBucketPoi(p)}
|
||||
className="flex items-center gap-3 rounded-[14px] px-3 py-3 text-start active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<MapPin size={16} className="flex-none text-m-muted" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-body font-semibold text-m-ink">{p.name}</span>
|
||||
{p.address && <span className="block truncate text-caption text-m-muted">{p.address}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{query.trim() && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={takeName}
|
||||
className="flex items-center gap-3 rounded-[14px] px-3 py-3 text-start text-m-muted active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<PenLine size={16} className="flex-none" />
|
||||
<span className="truncate text-body">
|
||||
{s.t('atlas.globe.wishJustName', { name: query.trim() })}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{label(s.t('atlas.globe.wishWhen'))}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
b.setBucketPoiYear(0);
|
||||
b.setBucketPoiMonth(0);
|
||||
}}
|
||||
aria-pressed={year === 0}
|
||||
className={`rounded-full px-4 py-2.5 text-body font-semibold ${year === 0 ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'}`}
|
||||
>
|
||||
{s.t('atlas.globe.someday')}
|
||||
</button>
|
||||
<div
|
||||
className={`flex flex-1 items-center justify-between rounded-full p-1 ${year ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={s.t('atlas.globe.yearEarlier')}
|
||||
onClick={() => b.setBucketPoiYear((year || thisYear) - 1)}
|
||||
className="grid size-9 place-items-center rounded-full"
|
||||
>
|
||||
<ChevronLeft size={17} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => b.setBucketPoiYear(year || thisYear)}
|
||||
className="text-body font-bold tabular-nums"
|
||||
>
|
||||
{year || thisYear}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={s.t('atlas.globe.yearLater')}
|
||||
onClick={() => b.setBucketPoiYear((year || thisYear) + 1)}
|
||||
className="grid size-9 place-items-center rounded-full"
|
||||
>
|
||||
<ChevronRight size={17} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`grid grid-cols-4 gap-1.5 ${year ? '' : 'pointer-events-none opacity-40'}`}
|
||||
aria-disabled={!year}
|
||||
>
|
||||
{months.map((m, i) => {
|
||||
const on = month === i + 1;
|
||||
return (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => b.setBucketPoiMonth(on ? 0 : i + 1)}
|
||||
className={`rounded-[12px] py-2.5 text-caption font-semibold ${on ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'}`}
|
||||
>
|
||||
{m}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{label(s.t('atlas.globe.wishNote'))}
|
||||
<textarea
|
||||
rows={3}
|
||||
value={b.bucketForm.notes}
|
||||
onChange={(e) => b.setBucketForm({ ...b.bucketForm, notes: e.target.value })}
|
||||
placeholder={s.t('atlas.bucketNotesPlaceholder')}
|
||||
className={`${M_FIELD} resize-none`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-[color:var(--m-rowbr)] px-5 pb-5 pt-3">
|
||||
<MHubAction Icon={Star} disabled={!b.bucketForm.name.trim()} onClick={() => void b.handleAddBucketItem()}>
|
||||
{s.t('atlas.globe.wishSave')}
|
||||
</MHubAction>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { ChevronRight, type LucideIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import DawarichIcon from '../../../../components/shared/DawarichIcon';
|
||||
|
||||
/**
|
||||
* The phone's own pieces for the Atlas hub, on the mobile tokens (--m-*): a
|
||||
* glass card, a large figure, tiles set into a card, a section head and an
|
||||
* empty state. Sized for a thumb and a narrow column, not shrunk desktop parts.
|
||||
*/
|
||||
|
||||
export const M_CARD = 'rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)]';
|
||||
export const M_INNER = 'rounded-[16px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)]';
|
||||
export const M_FIELD =
|
||||
'w-full rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-inner)] px-3.5 py-3 text-body text-m-ink outline-none placeholder:text-m-faint';
|
||||
|
||||
export function MHubHero({
|
||||
value,
|
||||
unit,
|
||||
children,
|
||||
}: {
|
||||
value: React.ReactNode;
|
||||
unit?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className={`${M_CARD} relative overflow-hidden px-5 pb-5 pt-4`}>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -end-12 -top-12 size-40 rounded-full opacity-70"
|
||||
style={{
|
||||
background: 'radial-gradient(circle, color-mix(in srgb, var(--m-act) 14%, transparent), transparent 70%)',
|
||||
}}
|
||||
/>
|
||||
<div className="relative flex items-end gap-2">
|
||||
<span className="text-[3.25rem] font-bold tabular-nums leading-none tracking-tight text-m-ink">{value}</span>
|
||||
{unit && <span className="mb-1 text-subtitle font-semibold text-m-muted">{unit}</span>}
|
||||
</div>
|
||||
{children && <div className="relative mt-3.5">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface MHubTileData {
|
||||
Icon: LucideIcon;
|
||||
value: React.ReactNode;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function MHubTiles({ tiles, cols = 2 }: { tiles: MHubTileData[]; cols?: 2 | 3 }): React.ReactElement {
|
||||
return (
|
||||
<div className={`${M_CARD} grid gap-1.5 p-1.5 ${cols === 3 ? 'grid-cols-3' : 'grid-cols-2'}`}>
|
||||
{tiles.map(({ Icon, value, label }, i) => {
|
||||
// An odd tile out takes the whole row instead of leaving a hole beside it.
|
||||
const wide = cols === 2 && tiles.length % 2 === 1 && i === tiles.length - 1;
|
||||
if (cols === 3) {
|
||||
// Three across leaves a third of a phone: no symbol, the value on one
|
||||
// line, the label allowed two lines instead of an ellipsis.
|
||||
return (
|
||||
<div key={label} className={`${M_INNER} flex min-w-0 flex-col gap-1 px-2.5 py-2.5`}>
|
||||
<span className="whitespace-nowrap text-body font-bold tabular-nums leading-tight text-m-ink">
|
||||
{value}
|
||||
</span>
|
||||
<span className="line-clamp-2 text-[0.6875rem] leading-tight text-m-muted">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={label}
|
||||
className={`${M_INNER} relative flex min-h-[78px] items-center gap-2 overflow-hidden px-3.5 py-3 ${wide ? 'col-span-2' : ''}`}
|
||||
>
|
||||
<span className="relative min-w-0 flex-1">
|
||||
<span className="block text-title font-bold tabular-nums leading-tight text-m-ink">{value}</span>
|
||||
<span className="block truncate text-caption text-m-muted">{label}</span>
|
||||
</span>
|
||||
<Icon
|
||||
size={cols === 3 ? 22 : 30}
|
||||
strokeWidth={1.6}
|
||||
className="flex-none text-m-faint opacity-70"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MHubSection({
|
||||
title,
|
||||
meta,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
meta?: React.ReactNode;
|
||||
action?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<section className="flex flex-col gap-2.5">
|
||||
<div className="flex items-center justify-between gap-3 px-1">
|
||||
<h3 className="m-0 text-body font-bold text-m-ink">{title}</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
{meta != null && <span className="text-caption font-semibold tabular-nums text-m-muted">{meta}</span>}
|
||||
{action}
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function MHubEmpty({
|
||||
Icon,
|
||||
title,
|
||||
hint,
|
||||
action,
|
||||
}: {
|
||||
Icon: LucideIcon;
|
||||
title: string;
|
||||
hint?: string;
|
||||
action?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className={`${M_CARD} flex flex-col items-center gap-2 px-6 py-9 text-center`}>
|
||||
<span className="grid size-12 place-items-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Icon size={21} strokeWidth={1.8} />
|
||||
</span>
|
||||
<div className="text-body font-bold text-m-ink">{title}</div>
|
||||
{hint && <div className="text-caption text-m-muted">{hint}</div>}
|
||||
{action && <div className="mt-2">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The way to Dawarich (addon) on the phone: logo, what it does here, chevron. */
|
||||
export function MHubDawarichEntry({
|
||||
title,
|
||||
hint,
|
||||
onClick,
|
||||
}: {
|
||||
title: string;
|
||||
hint: string;
|
||||
onClick: () => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`${M_CARD} flex items-center gap-3 px-4 py-3.5 text-start active:opacity-80`}
|
||||
>
|
||||
<span className="flex size-10 flex-none overflow-hidden rounded-full">
|
||||
<DawarichIcon size={40} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="line-clamp-2 block text-body font-semibold leading-tight text-m-ink">{title}</span>
|
||||
<span className="mt-0.5 line-clamp-2 block text-caption leading-snug text-m-muted">{hint}</span>
|
||||
</span>
|
||||
<ChevronRight size={17} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The one strong action of a tab, full width, in the phone's action colour. */
|
||||
export function MHubAction({
|
||||
onClick,
|
||||
Icon,
|
||||
children,
|
||||
disabled,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
Icon?: LucideIcon;
|
||||
children: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="flex w-full items-center justify-center gap-2 rounded-[16px] bg-m-act px-4 py-3.5 text-body font-semibold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{Icon && <Icon size={16} strokeWidth={2.2} />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
+12
-1836
File diff suppressed because it is too large
Load Diff
@@ -1,825 +1,18 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useTranslation } from '../i18n'
|
||||
import Navbar from '../components/Layout/Navbar'
|
||||
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, Check, ArrowLeft, ChevronRight, Footprints, type LucideIcon } from 'lucide-react'
|
||||
import type { TranslationFn } from '../types'
|
||||
import { Tooltip } from '../components/shared/Tooltip'
|
||||
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../components/shared/DialogShell'
|
||||
import { EditorField, GRID_2 } from '../components/shared/dialogParts'
|
||||
import DawarichAtlasSidePanel from '../components/Dawarich/DawarichAtlasSidePanel'
|
||||
import CountryFlag from '../components/shared/CountryFlag'
|
||||
import { A2_TO_A3, countryCodeToFlag, visitedRegionCount, type AtlasCountry, type AtlasStats, type AtlasData, type CountryDetail } from './atlas/atlasModel'
|
||||
import { useAtlas } from './atlas/useAtlas'
|
||||
import { bucketMonthTarget, useAtlasCountryActions, type AtlasCountryActionsOptions } from './atlas/useAtlasCountryActions'
|
||||
import AtlasCountrySearch from './atlas/AtlasCountrySearch'
|
||||
import AtlasLayerToggle from './atlas/AtlasLayerToggle'
|
||||
import React from 'react'
|
||||
import HelpAnchor from '../components/Help/HelpAnchor'
|
||||
import AtlasCountryPlaces from '../components/Atlas/AtlasCountryPlaces'
|
||||
import { AtlasTourActivityPane } from '../components/Atlas/tourActivity/AtlasTourActivityPane'
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import { useFormatDate } from '../hooks/useDateFormat'
|
||||
import { getIntlLanguage } from '@trek/shared'
|
||||
|
||||
// Fixed ids rather than useId: the page body stays free of hooks, and there is only one atlas.
|
||||
const COUNTRY_DIALOG_TITLE = 'atlas-country-dialog-title'
|
||||
const BUCKET_MONTH_ID = 'atlas-bucket-month'
|
||||
const BUCKET_YEAR_ID = 'atlas-bucket-year'
|
||||
/** The footer's destructive answer, filled like ConfirmDialog's. */
|
||||
const DANGER_BUTTON = 'inline-flex items-center gap-1.5 rounded-[10px] bg-danger px-4 py-2 font-medium text-white hover:opacity-90' // theme-lint-disable: white on the danger fill, as ConfirmDialog draws it
|
||||
import AtlasGlobeView from './atlas/AtlasGlobeView'
|
||||
|
||||
/**
|
||||
* The Atlas: the globe, with its hub and dialogs. A wiring container (see
|
||||
* pages/PATTERN.md); state and data come from useAtlasGlobe inside the view.
|
||||
* ViewportRoute in App.tsx picks this page or the phone screen, so the phone
|
||||
* screen is a chunk of its own.
|
||||
*/
|
||||
export default function AtlasPage(): React.ReactElement {
|
||||
// ViewportRoute in App.tsx picks the branch now, so the phone screen is a
|
||||
// chunk of its own instead of a dead limb in this one.
|
||||
return (
|
||||
<>
|
||||
<HelpAnchor id="atlas" />
|
||||
<AtlasPageDesktop />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function AtlasPageDesktop(): React.ReactElement {
|
||||
// Page = wiring container: the whole interactive globe (map lifecycle, atlas +
|
||||
// bucket data, mark/unmark flows, country search) lives in useAtlas. The page
|
||||
// only wires that state into JSX and its presentational SidebarContent helper.
|
||||
const {
|
||||
t, language, navigate, resolveName, dark, loading,
|
||||
mapRef, regionTooltipRef, panelRef, glareRef, borderGlareRef,
|
||||
handlePanelMouseMove, handlePanelMouseLeave,
|
||||
data, setData, stats, countries, selectedCountry, countryDetail,
|
||||
showPlanned, togglePlanned,
|
||||
loadCountryDetail, handleUnmarkCountry, select_country_from_search,
|
||||
visitedRegions, setVisitedRegions, regionsVisited, placesOpen, setPlacesOpen,
|
||||
atlas_country_search, set_atlas_country_search,
|
||||
atlas_country_results, set_atlas_country_results,
|
||||
atlas_country_open, set_atlas_country_open, atlas_country_options,
|
||||
atlas_place_results, atlas_places_loading, search_places, select_place_from_search,
|
||||
confirmAction, setConfirmAction, executeConfirmAction,
|
||||
bucketMonth, setBucketMonth, bucketYear, setBucketYear,
|
||||
bucketList, setBucketList, bucketTab, setBucketTab,
|
||||
showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm,
|
||||
handleAddBucketItem, handleDeleteBucketItem, handleClearBucketVisit, handleBucketPoiSearch, handleSelectBucketPoi,
|
||||
bucketSearchResults, setBucketSearchResults,
|
||||
bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear,
|
||||
bucketSearching, bucketSearch, setBucketSearch, reloadAfterDawarich,
|
||||
} = useAtlas()
|
||||
// Solid surfaces when the user disabled transparency (read at render — the
|
||||
// attribute is already set by applyAppearance before navigating here).
|
||||
const noTransparency = typeof document !== 'undefined' && document.documentElement.hasAttribute('data-no-transparency')
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-surface">
|
||||
<Navbar />
|
||||
<div className="flex items-center justify-center" style={{ paddingTop: 'var(--nav-h)', minHeight: 'calc(100vh - var(--nav-h))' }}>
|
||||
<div className="w-8 h-8 border-2 rounded-full animate-spin border-edge border-t-content" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// The glass both bottom panels are cut from. One object, because two panels
|
||||
// side by side that differ by a blur radius look like a mistake.
|
||||
const glassPanel: React.CSSProperties = {
|
||||
background: noTransparency ? (dark ? '#15151c' : '#ffffff') : (dark ? 'rgba(10,10,15,0.55)' : 'rgba(255,255,255,0.2)'),
|
||||
backdropFilter: 'blur(24px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
|
||||
border: '1px solid ' + (dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'),
|
||||
borderRadius: 20,
|
||||
boxShadow: dark ? '0 8px 32px rgba(0,0,0,0.3)' : '0 8px 32px rgba(0,0,0,0.08)',
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-screen overflow-hidden bg-surface">
|
||||
<Navbar />
|
||||
<div style={{ position: 'fixed', top: 'var(--nav-h)', insetInline: 0, bottom: 'env(safe-area-inset-bottom, 0px)' }}>
|
||||
{/* Map */}
|
||||
<div ref={mapRef} style={{ position: 'absolute', inset: 0, zIndex: 1, background: dark ? '#1a1a2e' : '#f0f0f0' }} />
|
||||
|
||||
{/* Region tooltip (custom, always on top, ref-controlled to avoid re-renders) */}
|
||||
<div ref={regionTooltipRef} style={{
|
||||
position: 'fixed', display: 'none',
|
||||
zIndex: 9999, pointerEvents: 'none',
|
||||
background: noTransparency ? (dark ? '#0f0f14' : '#ffffff') : (dark ? 'rgba(15,15,20,0.92)' : 'rgba(255,255,255,0.96)'),
|
||||
color: dark ? '#fff' : '#111',
|
||||
borderRadius: 10, padding: '10px 14px',
|
||||
boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
|
||||
border: `1px solid ${dark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)'}`,
|
||||
fontSize: 'calc(12px * var(--fs-scale-body, 1))', minWidth: 120,
|
||||
}} />
|
||||
<AtlasCountrySearch
|
||||
dark={dark}
|
||||
t={t}
|
||||
search={atlas_country_search}
|
||||
setSearch={set_atlas_country_search}
|
||||
results={atlas_country_results}
|
||||
setResults={set_atlas_country_results}
|
||||
open={atlas_country_open}
|
||||
setOpen={set_atlas_country_open}
|
||||
options={atlas_country_options}
|
||||
onSelect={select_country_from_search}
|
||||
placeResults={atlas_place_results}
|
||||
placesLoading={atlas_places_loading}
|
||||
onQueryChange={search_places}
|
||||
onSelectPlace={select_place_from_search}
|
||||
/>
|
||||
<AtlasLayerToggle
|
||||
t={t}
|
||||
showPlanned={showPlanned}
|
||||
onToggle={togglePlanned}
|
||||
plannedCount={stats.totalCountriesPlanned || 0}
|
||||
/>
|
||||
|
||||
{placesOpen && selectedCountry && countryDetail && (
|
||||
<DialogShell
|
||||
onClose={() => setPlacesOpen(false)}
|
||||
labelledBy="atlas-places-title"
|
||||
width="detail"
|
||||
header={(
|
||||
<DialogHeader
|
||||
tile={<DialogTile><CountryFlag code={selectedCountry} size={26} /></DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId="atlas-places-title"
|
||||
onClose={() => setPlacesOpen(false)}
|
||||
title={resolveName(selectedCountry)}
|
||||
sub={`${countryDetail.places.length} ${t('atlas.places', { count: countryDetail.places.length })}`}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<AtlasCountryPlaces detail={countryDetail} onOpenTrip={id => navigate(`/trips/${id}`)} />
|
||||
</DialogShell>
|
||||
)}
|
||||
|
||||
{/* Mobile: Bottom bar */}
|
||||
<div className="md:hidden absolute inset-x-0 z-10 flex justify-center" style={{ bottom: 'calc(84px + env(safe-area-inset-bottom, 0px) + 8px)', touchAction: 'manipulation' }}>
|
||||
<div className="flex items-center gap-4 px-5 py-4 rounded-2xl"
|
||||
style={{ background: dark ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.5)', backdropFilter: 'blur(16px)' }}>
|
||||
{/* Countries highlighted */}
|
||||
<div className="text-center px-3 py-1.5 rounded-xl" style={{ background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)' }}>
|
||||
<p className="text-3xl font-black tabular-nums leading-none text-content">{stats.totalCountries}</p>
|
||||
<p className="text-[9px] font-semibold uppercase tracking-wide mt-1 text-content-faint">{t('atlas.countries', { count: stats.totalCountries })}</p>
|
||||
</div>
|
||||
{[[regionsVisited, t('atlas.regions', { count: regionsVisited })], [stats.totalTrips, t('atlas.trips', { count: stats.totalTrips })], [stats.totalPlaces, t('atlas.places', { count: stats.totalPlaces })], [stats.totalCities || 0, t('atlas.cities', { count: stats.totalCities || 0 })], [stats.totalDays, t('atlas.days', { count: stats.totalDays })]].map(([v, l], i) => (
|
||||
<div key={i} className="text-center px-1">
|
||||
<p className="text-xl font-black tabular-nums leading-none text-content">{v}</p>
|
||||
<p className="text-[9px] font-semibold uppercase tracking-wide mt-1 text-content-faint">{l}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop Panels — bottom center, glass effect.
|
||||
Three columns so the Atlas panel stays exactly centred over the map
|
||||
however wide its neighbour is: Dawarich sits in the left column,
|
||||
right-aligned against the middle one, and stretches to its height. */}
|
||||
<div
|
||||
className="hidden md:grid absolute z-10 items-stretch"
|
||||
style={{
|
||||
bottom: 16,
|
||||
insetInline: 20,
|
||||
gridTemplateColumns: '1fr auto 1fr',
|
||||
alignItems: 'stretch',
|
||||
gap: 12,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-end" style={{ pointerEvents: 'auto', minWidth: 0 }}>
|
||||
<DawarichAtlasSidePanel style={glassPanel} dark={dark} onChanged={reloadAfterDawarich} />
|
||||
</div>
|
||||
<div
|
||||
ref={panelRef}
|
||||
onMouseMove={handlePanelMouseMove}
|
||||
onMouseLeave={handlePanelMouseLeave}
|
||||
className="hidden md:flex flex-col overflow-hidden transition-[width,height,transform,box-shadow] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]"
|
||||
style={{
|
||||
...glassPanel,
|
||||
width: 'fit-content',
|
||||
maxWidth: '100%',
|
||||
pointerEvents: 'auto',
|
||||
position: 'relative',
|
||||
}}
|
||||
>
|
||||
{/* Liquid glass glare effect */}
|
||||
<div ref={glareRef} className="absolute inset-0 pointer-events-none" style={{ opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20 }} />
|
||||
{/* Border glow that follows cursor */}
|
||||
<div ref={borderGlareRef} className="absolute inset-0 pointer-events-none" style={{
|
||||
opacity: 0, transition: 'opacity 0.3s ease', borderRadius: 20,
|
||||
border: dark ? '1.5px solid rgba(255,255,255,0.5)' : '2px solid rgba(0,0,0,0.15)',
|
||||
}} />
|
||||
<SidebarContent
|
||||
data={data} stats={stats} countries={countries} selectedCountry={selectedCountry}
|
||||
countryDetail={countryDetail} resolveName={resolveName}
|
||||
regionsVisited={regionsVisited}
|
||||
countryRegions={selectedCountry ? visitedRegionCount(visitedRegions, selectedCountry) : 0}
|
||||
onOpenPlaces={() => setPlacesOpen(true)}
|
||||
onCountryClick={loadCountryDetail} onTripClick={(id) => navigate(`/trips/${id}`)} onUnmarkCountry={handleUnmarkCountry}
|
||||
bucketList={bucketList} bucketTab={bucketTab} setBucketTab={setBucketTab}
|
||||
showBucketAdd={showBucketAdd} setShowBucketAdd={setShowBucketAdd}
|
||||
bucketForm={bucketForm} setBucketForm={setBucketForm}
|
||||
onAddBucket={handleAddBucketItem} onDeleteBucket={handleDeleteBucketItem}
|
||||
onClearBucketVisit={handleClearBucketVisit}
|
||||
onSearchBucket={handleBucketPoiSearch} onSelectBucketPoi={handleSelectBucketPoi}
|
||||
bucketSearchResults={bucketSearchResults} setBucketSearchResults={setBucketSearchResults} bucketPoiMonth={bucketPoiMonth} setBucketPoiMonth={setBucketPoiMonth}
|
||||
bucketPoiYear={bucketPoiYear} setBucketPoiYear={setBucketPoiYear} bucketSearching={bucketSearching}
|
||||
bucketSearch={bucketSearch} setBucketSearch={setBucketSearch}
|
||||
t={t} dark={dark}
|
||||
/>
|
||||
</div>
|
||||
<div aria-hidden />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{/* Country action popup: the flag and the name at the head, what can be
|
||||
done with the country below. A region names its country under its own name. */}
|
||||
<CountryActionDialog
|
||||
t={t} language={language} confirmAction={confirmAction} setConfirmAction={setConfirmAction}
|
||||
executeConfirmAction={executeConfirmAction} setData={setData} visitedRegions={visitedRegions}
|
||||
setVisitedRegions={setVisitedRegions} bucketList={bucketList} setBucketList={setBucketList}
|
||||
handleDeleteBucketItem={handleDeleteBucketItem}
|
||||
bucketMonth={bucketMonth} setBucketMonth={setBucketMonth} bucketYear={bucketYear} setBucketYear={setBucketYear}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type CountryActionDialogProps = AtlasCountryActionsOptions & Pick<ReturnType<typeof useAtlas>,
|
||||
'language' | 'executeConfirmAction' | 'bucketMonth' | 'setBucketMonth' | 'bucketYear' | 'setBucketYear'>
|
||||
|
||||
/** The country action popup over useAtlasCountryActions, the logic it shares with the phone sheet. */
|
||||
function CountryActionDialog(props: CountryActionDialogProps): React.ReactElement | null {
|
||||
const { t, language, confirmAction, setConfirmAction, executeConfirmAction, bucketMonth, setBucketMonth, bucketYear, setBucketYear } = props
|
||||
const { onWishlist, markCountry, markRegion, unmarkRegion, addBucket, removeBucket } = useAtlasCountryActions(props)
|
||||
const addBucketForMonth = () => addBucket(bucketMonthTarget(bucketMonth, bucketYear), () => { setBucketMonth(0); setBucketYear(0) })
|
||||
if (!confirmAction) return null
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={() => setConfirmAction(null)}
|
||||
labelledBy={COUNTRY_DIALOG_TITLE}
|
||||
width="narrow"
|
||||
header={(
|
||||
<DialogHeader
|
||||
tile={(
|
||||
<DialogTile>
|
||||
{confirmAction.code.length === 2 ? (
|
||||
<img src={`https://flagcdn.com/w80/${confirmAction.code.toLowerCase()}.png`} alt={confirmAction.code} className="h-6 w-[34px] rounded-[5px] object-cover ring-1 ring-edge-faint" />
|
||||
) : (
|
||||
<span className="leading-none" style={fs(26, 'subtitle')}>{countryCodeToFlag(confirmAction.code)}</span>
|
||||
)}
|
||||
</DialogTile>
|
||||
)}
|
||||
// The two removals take the danger wash ConfirmDialog asks its destructive questions in.
|
||||
tint={confirmAction.type === 'unmark' || confirmAction.type === 'unmark-region' ? 'var(--danger-soft)' : NEUTRAL_TINT}
|
||||
labelId={COUNTRY_DIALOG_TITLE}
|
||||
onClose={() => setConfirmAction(null)}
|
||||
title={confirmAction.name}
|
||||
sub={confirmAction.countryName || undefined}
|
||||
/>
|
||||
)}
|
||||
footer={(
|
||||
<DialogFooter>
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<DialogButton onClick={() => setConfirmAction({ ...confirmAction, type: confirmAction.regionCode ? 'choose-region' : 'choose' })} icon={<ArrowLeft size={14} strokeWidth={2.2} />}>
|
||||
{t('common.back')}
|
||||
</DialogButton>
|
||||
)}
|
||||
<FooterSpacer />
|
||||
{confirmAction.type !== 'bucket' && (
|
||||
<DialogButton onClick={() => setConfirmAction(null)}>{t('common.cancel')}</DialogButton>
|
||||
)}
|
||||
{confirmAction.type === 'mark' && (
|
||||
<DialogButton variant="primary" onClick={executeConfirmAction}>{t('atlas.markVisited')}</DialogButton>
|
||||
)}
|
||||
{confirmAction.type === 'unmark' && (
|
||||
<button type="button" onClick={executeConfirmAction} className={DANGER_BUTTON} style={fs(13, 'body')}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
{confirmAction.type === 'unmark-region' && (
|
||||
<button type="button" onClick={unmarkRegion} className={DANGER_BUTTON} style={fs(13, 'body')}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<DialogButton variant="primary" icon={<Star size={14} strokeWidth={2.2} />} onClick={addBucketForMonth}>
|
||||
{t('atlas.addToBucket')}
|
||||
</DialogButton>
|
||||
)}
|
||||
</DialogFooter>
|
||||
)}
|
||||
>
|
||||
{confirmAction.type === 'choose' && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<CountryChoice icon={MapPin} title={t('atlas.markVisited')} hint={t('atlas.markVisitedHint')} onClick={markCountry} />
|
||||
<CountryChoice icon={Star} tone="text-warning" title={t('atlas.addToBucket')} hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...confirmAction, type: 'bucket' })} />
|
||||
{onWishlist && (
|
||||
<CountryChoice icon={Trash2} tone="text-danger" title={t('atlas.removeFromBucket')} hint={t('atlas.removeFromBucketHint')} onClick={removeBucket} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'choose-region' && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<CountryChoice icon={MapPin} title={t('atlas.markVisited')} hint={t('atlas.markRegionVisitedHint')} onClick={() => markRegion()} />
|
||||
<CountryChoice icon={Star} tone="text-warning" title={t('atlas.addToBucket')} hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...confirmAction, type: 'bucket' })} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'unmark' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>{t('atlas.confirmUnmark')}</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'unmark-region' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>{t('atlas.confirmUnmarkRegion')}</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'mark' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>{t('atlas.confirmMark')}</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<>
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>{t('atlas.bucketWhen')}</p>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('atlas.month')} htmlFor={BUCKET_MONTH_ID}>
|
||||
<CustomSelect
|
||||
id={BUCKET_MONTH_ID}
|
||||
value={String(bucketMonth)}
|
||||
onChange={v => setBucketMonth(Number(v))}
|
||||
placeholder={t('atlas.month')}
|
||||
options={[
|
||||
{ value: '0', label: t('common.none') },
|
||||
...Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: new Date(2000, i).toLocaleString(getIntlLanguage(language), { month: 'long' }) })),
|
||||
]}
|
||||
size="sm"
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t('atlas.year')} htmlFor={BUCKET_YEAR_ID}>
|
||||
<CustomSelect
|
||||
id={BUCKET_YEAR_ID}
|
||||
value={String(bucketYear)}
|
||||
onChange={v => setBucketYear(Number(v))}
|
||||
placeholder={t('atlas.year')}
|
||||
options={[
|
||||
{ value: '0', label: t('common.none') },
|
||||
...Array.from({ length: 20 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) })),
|
||||
]}
|
||||
size="sm"
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogShell>
|
||||
)
|
||||
}
|
||||
|
||||
/** One answer of the country dialog, built like an export row: icon tile, what it does, and what that means. */
|
||||
function CountryChoice({ icon: Icon, tone = 'text-content-secondary', title, hint, onClick }: {
|
||||
icon: LucideIcon
|
||||
/** The icon's colour class. */
|
||||
tone?: string
|
||||
title: string
|
||||
hint: string
|
||||
onClick: () => void
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="group flex w-full items-center gap-3 rounded-[14px] border border-edge-faint bg-surface-card px-3 py-2.5 text-start transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
<span className={`grid h-9 w-9 flex-none place-items-center rounded-[10px] bg-surface-tertiary transition-colors group-hover:bg-surface-card ${tone}`}>
|
||||
<Icon size={16} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-semibold text-content" style={fs(13.5, 'body')}>{title}</span>
|
||||
<span className="block text-content-muted" style={fs(11.5)}>{hint}</span>
|
||||
</span>
|
||||
<ChevronRight size={15} strokeWidth={2} className="flex-none text-content-faint transition-transform group-hover:translate-x-0.5" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
interface SidebarContentProps {
|
||||
data: AtlasData | null
|
||||
stats: AtlasStats
|
||||
/** Regions visited over every country, and in the country picked (#1639). */
|
||||
regionsVisited: number
|
||||
countryRegions: number
|
||||
/** Opens the list of the picked country's places (#2174). */
|
||||
onOpenPlaces: () => void
|
||||
countries: AtlasCountry[]
|
||||
selectedCountry: string | null
|
||||
countryDetail: CountryDetail | null
|
||||
resolveName: (code: string) => string
|
||||
onCountryClick: (code: string) => void
|
||||
onTripClick: (id: number) => void
|
||||
onUnmarkCountry?: (code: string) => void
|
||||
bucketList: any[]
|
||||
/** The panel's tab: the travel numbers, the bucket list, or the user's own tours (STA-02, with the Tours addon). */
|
||||
bucketTab: 'stats' | 'bucket' | 'tours'
|
||||
setBucketTab: (tab: 'stats' | 'bucket' | 'tours') => void
|
||||
showBucketAdd: boolean
|
||||
setShowBucketAdd: (v: boolean) => void
|
||||
bucketForm: { name: string; notes: string; lat: string; lng: string; target_date: string }
|
||||
setBucketForm: (f: { name: string; notes: string; lat: string; lng: string; target_date: string }) => void
|
||||
onAddBucket: () => Promise<void>
|
||||
onDeleteBucket: (id: number) => Promise<void>
|
||||
onClearBucketVisit: (id: number) => void | Promise<void>
|
||||
onSearchBucket: () => Promise<void>
|
||||
onSelectBucketPoi: (result: any) => void
|
||||
bucketSearchResults: any[]
|
||||
setBucketSearchResults: (v: string[]) => void
|
||||
bucketPoiMonth: number
|
||||
setBucketPoiMonth: (v: number) => void
|
||||
bucketPoiYear: number
|
||||
setBucketPoiYear: (v: number) => void
|
||||
bucketSearching: boolean
|
||||
bucketSearch: string
|
||||
setBucketSearch: (v: string) => void
|
||||
t: TranslationFn
|
||||
dark: boolean
|
||||
}
|
||||
|
||||
function SidebarContent({ data, stats, regionsVisited, countryRegions, onOpenPlaces, countries, selectedCountry, countryDetail, resolveName, onTripClick, onUnmarkCountry, bucketList, bucketTab, setBucketTab, showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm, onAddBucket, onDeleteBucket, onClearBucketVisit, onSearchBucket, onSelectBucketPoi, bucketSearchResults, setBucketSearchResults, bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear, bucketSearching, bucketSearch, setBucketSearch, t, dark }: SidebarContentProps): React.ReactElement {
|
||||
const { language } = useTranslation()
|
||||
const { formatDate } = useFormatDate()
|
||||
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
|
||||
const statsContentRef = useRef<HTMLDivElement>(null)
|
||||
const bucketSearchRowRef = useRef<HTMLDivElement>(null)
|
||||
const [statsWidth, setStatsWidth] = useState<number | undefined>(undefined)
|
||||
useEffect(() => {
|
||||
const el = statsContentRef.current
|
||||
if (!el || typeof ResizeObserver === 'undefined') return
|
||||
const ro = new ResizeObserver(() => setStatsWidth(el.offsetWidth))
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
const bg = (o) => dark ? `rgba(255,255,255,${o})` : `rgba(0,0,0,${o})`
|
||||
const tp = dark ? '#f1f5f9' : '#0f172a'
|
||||
const tm = dark ? '#94a3b8' : '#64748b'
|
||||
const tf = dark ? '#475569' : '#94a3b8'
|
||||
const accent = '#818cf8'
|
||||
|
||||
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'), 'Antarctica': t('atlas.antarctica') }
|
||||
const contColors = ['#818cf8', '#f472b6', '#34d399', '#fbbf24', '#fb923c', '#22d3ee']
|
||||
|
||||
// Tab switcher
|
||||
const tabBar = (
|
||||
<div style={{ display: 'flex', gap: 4, padding: '12px 16px 0', marginBottom: 4 }}>
|
||||
{[
|
||||
{ id: 'stats', label: t('atlas.statsTab'), icon: Globe },
|
||||
{ id: 'bucket', label: t('atlas.bucketTab'), icon: Star },
|
||||
...(toursEnabled ? [{ id: 'tours', label: t('tours.mode.tours'), icon: Footprints }] : []),
|
||||
].map(tab => (
|
||||
<button type="button" key={tab.id} onClick={() => setBucketTab(tab.id as any)}
|
||||
style={{
|
||||
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
|
||||
padding: '7px 0', borderRadius: 10, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
|
||||
fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, transition: 'all 0.15s',
|
||||
background: bucketTab === tab.id ? bg(0.1) : 'transparent',
|
||||
color: bucketTab === tab.id ? tp : tf,
|
||||
}}>
|
||||
<tab.icon size={13} />
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
if (countries.length === 0 && !lastTrip && bucketTab === 'stats') {
|
||||
return (
|
||||
<>
|
||||
{tabBar}
|
||||
<EmptyState scene="atlas" title={t('atlas.noData')} layout="row" size={52} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const thisYear = new Date().getFullYear()
|
||||
const divider = `2px solid ${bg(0.08)}`
|
||||
|
||||
// Bucket list content
|
||||
const bucketContent = (
|
||||
<>
|
||||
<div className="flex items-stretch" style={{ overflowX: 'auto', padding: '0 8px', maxWidth: statsWidth, width: '100%' }}>
|
||||
{bucketList.map(item => (
|
||||
<div key={item.id} className="group flex flex-col items-center justify-center shrink-0" style={{ padding: '8px 14px', position: 'relative', minWidth: 80 }}>
|
||||
{(() => {
|
||||
const code = item.country_code?.length === 2 ? item.country_code : (Object.entries(A2_TO_A3).find(([, v]) => v === item.country_code)?.[0] || '')
|
||||
return code ? (
|
||||
<img src={`https://flagcdn.com/w40/${code.toLowerCase()}.png`} alt={code} style={{ width: 28, height: 20, borderRadius: 4, objectFit: 'cover', marginBottom: 4 }} />
|
||||
) : <Star size={16} className="text-[#fbbf24]" style={{ marginBottom: 4 }} fill="#fbbf24" />
|
||||
})()}
|
||||
<span className="text-xs font-semibold text-center leading-tight" style={{ color: tp, maxWidth: 90, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.name}</span>
|
||||
{item.target_date && (() => {
|
||||
const [y, m] = item.target_date.split('-')
|
||||
const label = m ? new Date(Number(y), Number(m) - 1).toLocaleString(getIntlLanguage(language), { month: 'short', year: 'numeric' }) : y
|
||||
return <span className="text-[9px] mt-0.5 text-center" style={{ color: tf }}>{label}</span>
|
||||
})()}
|
||||
{!item.target_date && item.notes && <span className="text-[9px] mt-0.5 text-center" style={{ color: tf, maxWidth: 90, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.notes}</span>}
|
||||
{/* Reached (#2279). A tick rather than removing the entry: a wish that
|
||||
came true is the part of the list worth keeping, and the source is
|
||||
named so a recording-derived tick is not mistaken for a manual one. */}
|
||||
{item.visited_at && (
|
||||
<Tooltip
|
||||
label={item.visited_source === 'dawarich'
|
||||
? `${t('dawarich.bucket.visitedFrom')}
|
||||
${t('dawarich.bucket.clearVisit')}`
|
||||
: ''}
|
||||
placement="top"
|
||||
>
|
||||
{/* A tick that came from a recording can be taken back here: the
|
||||
wishlist is curated by hand, and a suggestion nobody can undo
|
||||
is not a suggestion. A tick somebody set themselves is text. */}
|
||||
{item.visited_source === 'dawarich' ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void onClearBucketVisit(item.id) }}
|
||||
aria-label={t('dawarich.bucket.clearVisit')}
|
||||
className="text-success mt-0.5 flex items-center gap-1 hover:opacity-70"
|
||||
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit' }}
|
||||
>
|
||||
<Check size={9} />
|
||||
{formatDate(new Date(item.visited_at))}
|
||||
</button>
|
||||
) : (
|
||||
<span
|
||||
className="text-success mt-0.5 flex items-center gap-1"
|
||||
style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' }}
|
||||
>
|
||||
<Check size={9} />
|
||||
{formatDate(new Date(item.visited_at))}
|
||||
</span>
|
||||
)}
|
||||
</Tooltip>
|
||||
)}
|
||||
<button type="button" onClick={() => onDeleteBucket(item.id)}
|
||||
className="opacity-0 group-hover:opacity-100"
|
||||
style={{ position: 'absolute', top: 4, insetInlineEnd: 4, background: 'none', border: 'none', cursor: 'pointer', padding: 2, color: tf, display: 'flex', transition: 'opacity 0.15s' }}>
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{bucketList.length === 0 && !showBucketAdd && (
|
||||
<div className="flex items-center justify-center py-4 px-6" style={{ color: tf, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
{t('atlas.bucketEmptyHint')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{showBucketAdd ? (
|
||||
<div style={{ padding: '8px 16px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{/* Search or manual name */}
|
||||
<div>
|
||||
<div ref={bucketSearchRowRef} style={{ display: 'flex', gap: 4 }}>
|
||||
<input type="text" value={bucketForm.name || bucketSearch}
|
||||
onChange={e => { const v = e.target.value; if (bucketForm.name) setBucketForm({ ...bucketForm, name: v }); else setBucketSearch(v) }}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && !bucketForm.name) void onSearchBucket(); else if (e.key === 'Enter') void onAddBucket(); if (e.key === 'Escape') setShowBucketAdd(false) }}
|
||||
placeholder={t('atlas.bucketNamePlaceholder')}
|
||||
autoFocus
|
||||
className="border border-edge text-content bg-surface-input"
|
||||
style={{ flex: 1, padding: '6px 10px', borderRadius: 8, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }}
|
||||
/>
|
||||
{!bucketForm.name && (
|
||||
<button type="button" onClick={onSearchBucket} disabled={bucketSearching}
|
||||
className="bg-accent text-accent-text"
|
||||
style={{ padding: '6px 10px', borderRadius: 8, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
|
||||
<Search size={12} />
|
||||
</button>
|
||||
)}
|
||||
{bucketForm.name && (
|
||||
<button type="button" onClick={() => { setBucketForm({ ...bucketForm, name: '', lat: '', lng: '' }); setBucketSearch('') }}
|
||||
className="border border-edge text-content-faint"
|
||||
style={{ padding: '6px 8px', borderRadius: 8, background: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{/* Portalled to the body: the panel that hosts this form clips its
|
||||
overflow, which used to swallow the top of the list (#1899). */}
|
||||
{bucketSearchResults.length > 0 && createPortal(
|
||||
<div className="bg-surface-card border border-edge" style={{
|
||||
position: 'fixed',
|
||||
...(() => {
|
||||
const rect = bucketSearchRowRef.current?.getBoundingClientRect()
|
||||
if (!rect) return { left: 0, top: 0, width: 240, maxHeight: 160 }
|
||||
const above = rect.top - 12
|
||||
const below = window.innerHeight - rect.bottom - 12
|
||||
const openUp = above >= below
|
||||
return {
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
// Never taller than the room on that side, so the list scrolls
|
||||
// instead of running off the edge of the viewport.
|
||||
maxHeight: Math.min(160, openUp ? above : below),
|
||||
...(openUp ? { bottom: window.innerHeight - rect.top + 4 } : { top: rect.bottom + 4 }),
|
||||
}
|
||||
})(),
|
||||
zIndex: 99999, borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.12)', overflowY: 'auto',
|
||||
}}>
|
||||
{bucketSearchResults.slice(0, 6).map((r, i) => (
|
||||
<button type="button" key={i} onClick={() => onSelectBucketPoi(r)} className="border-b border-edge-faint" style={{ display: 'flex', flexDirection: 'column', gap: 1, width: '100%', padding: '6px 10px', borderTop: 'none', borderInline: 'none', background: 'none', cursor: 'pointer', textAlign: 'start', fontFamily: 'inherit' }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500 }}>{r.name}</span>
|
||||
{r.address && <span className="text-content-faint" style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}>{r.address}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
{/* Selected place indicator */}
|
||||
{bucketForm.lat && bucketForm.lng && (
|
||||
<div className="text-content-faint" style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<MapPin size={10} /> {Number(bucketForm.lat).toFixed(4)}, {Number(bucketForm.lng).toFixed(4)}
|
||||
</div>
|
||||
)}
|
||||
{/* Month / Year with CustomSelect */}
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<CustomSelect value={String(bucketPoiMonth)} onChange={v => setBucketPoiMonth(Number(v))} placeholder={t('atlas.month')} size="sm"
|
||||
options={[{ value: '0', label: '—' }, ...Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: new Date(2000, i).toLocaleString(getIntlLanguage(language), { month: 'short' }) }))]} />
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<CustomSelect value={String(bucketPoiYear)} onChange={v => setBucketPoiYear(Number(v))} placeholder={t('atlas.year')} size="sm"
|
||||
options={[{ value: '0', label: '—' }, ...Array.from({ length: 20 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))]} />
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
|
||||
<button type="button" onClick={() => { setShowBucketAdd(false); setBucketForm({ name: '', notes: '', lat: '', lng: '', target_date: '' }); setBucketSearch(''); setBucketSearchResults([]); setBucketPoiMonth(0); setBucketPoiYear(0) }}
|
||||
className="border border-edge text-content-muted"
|
||||
style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', padding: '4px 10px', borderRadius: 6, background: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="button" onClick={onAddBucket} disabled={!bucketForm.name.trim()}
|
||||
className="bg-[#fbbf24] text-[#1a1a1a]"
|
||||
style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', padding: '4px 12px', borderRadius: 6, border: 'none', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', opacity: bucketForm.name.trim() ? 1 : 0.5 }}>
|
||||
{t('common.add')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ padding: '4px 16px 8px' }}>
|
||||
<button type="button" onClick={() => setShowBucketAdd(true)}
|
||||
className="border border-dashed border-edge"
|
||||
style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4, width: '100%', padding: '5px 0', borderRadius: 8, background: 'none', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: tf, cursor: 'pointer', fontFamily: 'inherit' }}>
|
||||
<Plus size={11} /> {t('atlas.addPoi')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{tabBar}
|
||||
{/* Every tab always rendered so the widest one sets the panel width */}
|
||||
<div style={{ display: 'grid' }}>
|
||||
<div style={bucketTab !== 'stats' ? { visibility: 'hidden' as const, gridArea: '1/1' } : { gridArea: '1/1' }}>
|
||||
<div ref={statsContentRef} className="flex items-stretch justify-center">
|
||||
|
||||
{/* ═══ SECTION 1: Numbers ═══ */}
|
||||
{/* Countries hero */}
|
||||
<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', { count: stats.totalCountries })}</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 */}
|
||||
{[[regionsVisited, t('atlas.regions', { count: regionsVisited })], [stats.totalTrips, t('atlas.trips', { count: stats.totalTrips })], [stats.totalPlaces, t('atlas.places', { count: stats.totalPlaces })], [stats.totalCities || 0, t('atlas.cities', { count: stats.totalCities || 0 })], [stats.totalDays, t('atlas.days', { count: stats.totalDays })]].map(([v, l], i) => (
|
||||
<div key={i} className="flex flex-col items-center justify-center px-3 py-5 shrink-0">
|
||||
<span className="text-2xl font-black tabular-nums leading-none" style={{ color: tp }}>{v}</span>
|
||||
<span className="text-[9px] font-semibold mt-1.5 uppercase tracking-wide whitespace-nowrap" style={{ color: tf }}>{l}</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* ═══ DIVIDER ═══ */}
|
||||
<div style={{ width: 2, background: bg(0.08), margin: '12px 14px' }} />
|
||||
|
||||
{/* ═══ SECTION 2: Continents ═══ */}
|
||||
<div className="flex items-center gap-4 px-3 py-4 shrink-0">
|
||||
{/* 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 (
|
||||
<div key={cont} className="flex flex-col items-center shrink-0">
|
||||
<span className="text-2xl font-black tabular-nums leading-none" style={{ color: active ? tp : bg(0.15) }}>{count}</span>
|
||||
<span className="text-[9px] font-semibold mt-1.5 uppercase tracking-wide whitespace-nowrap" style={{ color: active ? tf : bg(0.1) }}>{CL[cont]}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* ═══ DIVIDER ═══ */}
|
||||
<div style={{ width: 2, background: bg(0.08), margin: '12px 14px' }} />
|
||||
|
||||
{/* ═══ SECTION 3: Highlights & Streaks ═══ */}
|
||||
<div className="flex items-center gap-5 px-3 py-4">
|
||||
{/* Streak */}
|
||||
{streak > 0 && (
|
||||
<div className="flex flex-col items-center justify-center px-3">
|
||||
<span className="text-2xl font-black tabular-nums leading-none" style={{ color: tp }}>{streak}</span>
|
||||
<span className="text-[9px] font-semibold mt-1.5 uppercase tracking-wide text-center leading-tight whitespace-nowrap" style={{ color: tf }}>
|
||||
{t('atlas.yearsInRow', { count: streak })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{/* This year */}
|
||||
{tripsThisYear > 0 && (
|
||||
<div className="flex flex-col items-center justify-center px-3">
|
||||
<span className="text-2xl font-black tabular-nums leading-none" style={{ color: tp }}>{tripsThisYear}</span>
|
||||
<span className="text-[9px] font-semibold mt-1.5 uppercase tracking-wide text-center leading-tight whitespace-nowrap" style={{ color: tf }}>
|
||||
{t('atlas.tripsIn', { count: tripsThisYear })} {thisYear}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ═══ Country detail overlay ═══ */}
|
||||
{selectedCountry && countryDetail && (
|
||||
<>
|
||||
<div style={{ width: 2, background: bg(0.08), margin: '12px 0' }} />
|
||||
<div className="flex items-center gap-3 px-6 py-4">
|
||||
{/* Twemoji where the platform has no flag glyphs: Windows draws the emoji as two letters. */}
|
||||
{/^[A-Za-z]{2}$/.test(selectedCountry)
|
||||
? <CountryFlag code={selectedCountry} size={30} />
|
||||
: <span className="text-3xl">{countryCodeToFlag(selectedCountry)}</span>}
|
||||
<div>
|
||||
<p className="text-sm font-bold" style={{ color: tp }}>
|
||||
{resolveName(selectedCountry)}
|
||||
{countryDetail.status && countryDetail.status !== 'visited' && (
|
||||
<span className="ms-2 text-[9px] font-semibold uppercase tracking-wide" style={{ color: tf }}>{t('atlas.planned')}</span>
|
||||
)}
|
||||
</p>
|
||||
{/* Counts as quiet badges, the regions among them once any is visited (#1639). */}
|
||||
<div className="mb-1.5 flex flex-wrap gap-1">
|
||||
{countryDetail.places.length > 0 && (
|
||||
<Tooltip label={t('atlas.placesShow')}>
|
||||
<button type="button" onClick={onOpenPlaces}
|
||||
className="inline-flex items-center gap-1 whitespace-nowrap rounded-full px-1.5 py-px text-[10px] font-semibold tabular-nums transition-opacity hover:opacity-75"
|
||||
style={{ background: bg(0.1), color: tp }}>
|
||||
<MapPin size={9} />{countryDetail.places.length} {t('atlas.places', { count: countryDetail.places.length })}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{[
|
||||
[countryDetail.trips.length, t('atlas.tripsLabel', { count: countryDetail.trips.length })],
|
||||
...(countryRegions > 0 ? [[countryRegions, t('atlas.regions', { count: countryRegions })] as const] : []),
|
||||
].map(([n, label]) => (
|
||||
<span key={label} className="whitespace-nowrap rounded-full px-1.5 py-px text-[10px] font-semibold tabular-nums" style={{ background: bg(0.06), color: tf }}>
|
||||
{n} {label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{countryDetail.trips.slice(0, 3).map(trip => (
|
||||
<button type="button" key={trip.id} onClick={() => onTripClick(trip.id)}
|
||||
className="flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold transition-opacity hover:opacity-75"
|
||||
style={{ background: bg(0.08), color: tp }}>
|
||||
<Briefcase size={9} style={{ color: tm }} />
|
||||
{trip.title}
|
||||
</button>
|
||||
))}
|
||||
{countryDetail.manually_marked && onUnmarkCountry && (
|
||||
<button type="button" onClick={() => onUnmarkCountry(selectedCountry!)}
|
||||
className="flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold transition-opacity hover:opacity-75 bg-[rgba(239,68,68,0.1)] text-[#ef4444]">
|
||||
<X size={9} />
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={bucketTab !== 'bucket' ? { visibility: 'hidden' as const, gridArea: '1/1' } : { gridArea: '1/1' }}>
|
||||
{bucketContent}
|
||||
</div>
|
||||
{/* STA-02: the user's own tours, read only once the tab is first shown. */}
|
||||
{toursEnabled && (
|
||||
<div className="flex justify-center" style={bucketTab !== 'tours' ? { visibility: 'hidden' as const, gridArea: '1/1' } : { gridArea: '1/1' }}>
|
||||
<AtlasTourActivityPane active={bucketTab === 'tours'} maxWidth={statsWidth} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<AtlasGlobeView />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,730 +0,0 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { render, screen, fireEvent, waitFor } from '../../tests/helpers/render';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { buildAtlasController, buildAtlasData, buildBucketItem, buildCountryDetail, type VisitedRegions } from '../../tests/helpers/atlas';
|
||||
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-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
|
||||
// map-click driven suite in AtlasPage.test.tsx cannot reach.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ atlas: {} as AtlasController }));
|
||||
|
||||
vi.mock('./atlas/useAtlas', () => ({ useAtlas: () => mocks.atlas }));
|
||||
vi.mock('../components/Layout/Navbar', () => ({
|
||||
default: () => React.createElement('nav', { 'data-testid': 'navbar' }),
|
||||
}));
|
||||
|
||||
const toast = vi.fn(() => 0);
|
||||
|
||||
function setAtlas(over: Record<string, unknown> = {}): AtlasController {
|
||||
mocks.atlas = buildAtlasController(over);
|
||||
return mocks.atlas;
|
||||
}
|
||||
|
||||
/**
|
||||
* The month and year triggers, both on their empty option: "None" in the country
|
||||
* dialog (the key, since t is mocked here), the older dash in the sidebar's form.
|
||||
*/
|
||||
function selectTriggers(): HTMLElement[] {
|
||||
return screen.getAllByRole('button').filter((b) => ['common.none', '—'].includes(b.textContent?.trim() ?? ''));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
toast.mockClear();
|
||||
window.__addToast = toast;
|
||||
setAtlas();
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
|
||||
http.post('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ success: true })),
|
||||
http.delete('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ success: true })),
|
||||
// After a region goes the atlas asks whether the country is still marked (#2597).
|
||||
http.get('/api/addons/atlas/country/:code', () => HttpResponse.json({ manually_marked: false })),
|
||||
http.post('/api/addons/atlas/bucket-list', () =>
|
||||
HttpResponse.json({ item: buildBucketItem({ id: 99, name: 'Germany', country_code: 'DE' }) }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('AtlasPage wiring', () => {
|
||||
it('FE-PAGE-ATLASW-002: shows navbar and spinner while the atlas is loading', () => {
|
||||
setAtlas({ loading: true });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByTestId('navbar')).toBeInTheDocument();
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('country popup', () => {
|
||||
it('FE-PAGE-ATLASW-003: the choose popup marks a country and updates the local atlas data', async () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'choose', code: 'DE', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
const flag = document.querySelector('img[alt="DE"]') as HTMLImageElement;
|
||||
expect(flag.src).toContain('flagcdn.com/w80/de.png');
|
||||
|
||||
const markBtn = screen.getByText('atlas.markVisited').closest('button') as HTMLButtonElement;
|
||||
// The option rows light up through their hover class now, not inline mouse handlers.
|
||||
expect(markBtn.className).toContain('hover:bg-surface-hover');
|
||||
|
||||
fireEvent.click(markBtn);
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
const data = atlas.data as AtlasData;
|
||||
expect(data.countries.map((c) => c.code)).toEqual(['FR', 'DE']);
|
||||
expect(data.stats.totalCountries).toBe(2);
|
||||
expect(data.continents?.Europe).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-004: a failing mark shows the server error as a toast', async () => {
|
||||
setAtlas({ confirmAction: { type: 'choose', code: 'DE', name: 'Germany' } });
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ error: 'Locked' }, { status: 400 })),
|
||||
);
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('Locked', 'error', undefined));
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-005: the bucket option and the backdrop drive the pending action', () => {
|
||||
const action = { type: 'choose', code: 'DE', name: 'Germany' } as AtlasController['confirmAction'];
|
||||
const atlas = setAtlas({ confirmAction: action });
|
||||
render(<AtlasPage />);
|
||||
|
||||
const bucketBtn = screen.getByText('atlas.addToBucket').closest('button') as HTMLButtonElement;
|
||||
fireEvent.mouseEnter(bucketBtn);
|
||||
fireEvent.mouseLeave(bucketBtn);
|
||||
fireEvent.click(bucketBtn);
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ ...action, type: 'bucket' });
|
||||
|
||||
// DialogShell closes only on a press that starts and ends on the backdrop.
|
||||
const backdrop = screen.getByRole('dialog').parentElement as HTMLElement;
|
||||
fireEvent.mouseDown(backdrop);
|
||||
fireEvent.click(backdrop);
|
||||
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-006: a three-letter code falls back to the flag glyph', () => {
|
||||
setAtlas({ confirmAction: { type: 'choose', code: 'DEU', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(document.querySelector('img[alt="DEU"]')).toBeNull();
|
||||
expect(screen.getByText('Germany')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-007: the region popup marks a region and adopts its country', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA', countryName: 'Spain' },
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('Spain')).toBeInTheDocument();
|
||||
const markBtn = screen.getByText('atlas.markVisited').closest('button') as HTMLButtonElement;
|
||||
fireEvent.mouseEnter(markBtn);
|
||||
fireEvent.mouseLeave(markBtn);
|
||||
fireEvent.click(markBtn);
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
expect((atlas.visitedRegions as VisitedRegions).ES).toEqual([
|
||||
{ code: 'ES-GA', name: 'Galicia', placeCount: 0, manuallyMarked: true },
|
||||
]);
|
||||
expect((atlas.data as AtlasData).countries.map((c) => c.code)).toContain('ES');
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-008: an already recorded region is not added twice and the country stays put', async () => {
|
||||
const regions: VisitedRegions = { FR: [{ code: 'FR-BRE', name: 'Bretagne', placeCount: 2 }] };
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'choose-region', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE', countryName: 'France' },
|
||||
visitedRegions: regions,
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
expect(atlas.visitedRegions).toBe(regions);
|
||||
expect((atlas.data as AtlasData).countries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-009: a failing region mark shows the error toast', async () => {
|
||||
setAtlas({ confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' } });
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ error: 'Nope' }, { status: 422 })),
|
||||
);
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('Nope', 'error', undefined));
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-010: a region popup without a region code cannot be confirmed', async () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
fireEvent.click(screen.getByText('atlas.addToBucket'));
|
||||
|
||||
expect(atlas.setVisitedRegions).not.toHaveBeenCalled();
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ type: 'bucket', code: 'ES', name: 'Galicia' });
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-010b: the region bucket option highlights on hover', () => {
|
||||
const action = { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' } as AtlasController['confirmAction'];
|
||||
const atlas = setAtlas({ confirmAction: action });
|
||||
render(<AtlasPage />);
|
||||
|
||||
const bucketBtn = screen.getByText('atlas.addToBucket').closest('button') as HTMLButtonElement;
|
||||
expect(bucketBtn.className).toContain('hover:bg-surface-hover');
|
||||
|
||||
fireEvent.click(bucketBtn);
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ ...action, type: 'bucket' });
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-010c: a region removal without a region code performs no request', async () => {
|
||||
const deleteSpy = vi.fn();
|
||||
server.use(
|
||||
http.delete('/api/addons/atlas/region/:code/mark', () => { deleteSpy(); return HttpResponse.json({}); }),
|
||||
);
|
||||
const atlas = setAtlas({ confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
await waitFor(() => expect(atlas.setVisitedRegions).not.toHaveBeenCalled());
|
||||
expect(deleteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-010d: marking a country that is already known leaves the totals alone', async () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'choose', code: 'FR', name: 'France' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
expect((atlas.data as AtlasData).stats.totalCountries).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-010e: region actions cope with atlas data that never loaded', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' },
|
||||
data: null,
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
expect(atlas.data).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-011: the unmark popup cancels or delegates to the shared executor', () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'unmark', code: 'FR', name: 'France' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('atlas.confirmUnmark')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('common.cancel'));
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
expect(atlas.executeConfirmAction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-012: the mark confirmation cancels or delegates to the shared executor', () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'mark', code: 'DE', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('atlas.confirmMark')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('common.cancel'));
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
expect(atlas.executeConfirmAction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-013: removing the last region of a data-free country drops the country as well', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62', countryName: 'Italy' },
|
||||
visitedRegions: { IT: [{ code: 'IT-62', name: 'Lazio', placeCount: 0 }] } as VisitedRegions,
|
||||
data: buildAtlasData({
|
||||
countries: [
|
||||
{ code: 'FR', tripCount: 2, placeCount: 5 },
|
||||
{ code: 'IT', tripCount: 0, placeCount: 0 },
|
||||
],
|
||||
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 2, totalDays: 14 },
|
||||
continents: { Europe: 2 },
|
||||
}),
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('Italy')).toBeInTheDocument();
|
||||
expect(screen.getByText('atlas.confirmUnmarkRegion')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('common.cancel'));
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
// The cancel above already closed with null, so wait for the unmark's own close:
|
||||
// it comes only after the region delete and the country check have both answered.
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledTimes(2));
|
||||
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
|
||||
expect(atlas.visitedRegions).toEqual({});
|
||||
const data = atlas.data as AtlasData;
|
||||
expect(data.countries.map((c) => c.code)).toEqual(['FR']);
|
||||
expect(data.stats.totalCountries).toBe(1);
|
||||
expect(data.continents?.Europe).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-014: a country with other regions left keeps its entry', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62' },
|
||||
visitedRegions: {
|
||||
IT: [
|
||||
{ code: 'IT-62', name: 'Lazio', placeCount: 0 },
|
||||
{ code: 'IT-25', name: 'Lombardia', placeCount: 0 },
|
||||
],
|
||||
} as VisitedRegions,
|
||||
data: buildAtlasData({
|
||||
countries: [{ code: 'IT', tripCount: 0, placeCount: 0 }],
|
||||
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 1, totalDays: 0 },
|
||||
}),
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
expect((atlas.visitedRegions as VisitedRegions).IT.map((r) => r.code)).toEqual(['IT-25']);
|
||||
expect((atlas.data as AtlasData).countries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-015: a failing region removal shows the error toast', async () => {
|
||||
setAtlas({ confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62' } });
|
||||
server.use(
|
||||
http.delete('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ error: 'Boom' }, { status: 500 })),
|
||||
);
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('Boom', 'error', undefined));
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-016: the bucket step offers a month and a year picker', () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('atlas.bucketWhen')).toBeInTheDocument();
|
||||
|
||||
const [monthTrigger, yearTrigger] = selectTriggers();
|
||||
fireEvent.click(monthTrigger);
|
||||
fireEvent.click(screen.getByText('March'));
|
||||
expect(atlas.setBucketMonth).toHaveBeenCalledWith(3);
|
||||
|
||||
const nextYear = String(new Date().getFullYear() + 1);
|
||||
fireEvent.click(yearTrigger);
|
||||
fireEvent.click(screen.getByText(nextYear));
|
||||
expect(atlas.setBucketYear).toHaveBeenCalledWith(Number(nextYear));
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-016b: a chosen month and year is posted as the target date and reset afterwards', async () => {
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ item: buildBucketItem({ id: 99, name: 'Germany', country_code: 'DE', target_date: '2027-05' }) });
|
||||
}),
|
||||
);
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' },
|
||||
bucketMonth: 5,
|
||||
bucketYear: 2027,
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.addToBucket'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
|
||||
expect(body).toMatchObject({ name: 'Germany', country_code: 'DE', target_date: '2027-05' });
|
||||
expect(atlas.bucketList as unknown[]).toHaveLength(1);
|
||||
expect(atlas.setBucketMonth).toHaveBeenLastCalledWith(0);
|
||||
expect(atlas.setBucketYear).toHaveBeenLastCalledWith(0);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-017: without a month and year the bucket item is posted open-ended', async () => {
|
||||
let body: unknown = null;
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ item: buildBucketItem({ id: 100, name: 'Bretagne' }) });
|
||||
}),
|
||||
);
|
||||
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('common.back'));
|
||||
expect(atlas.setConfirmAction).toHaveBeenCalledWith({
|
||||
type: 'choose-region', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE',
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.addToBucket'));
|
||||
|
||||
await waitFor(() => expect(body).toMatchObject({ name: 'Bretagne', country_code: 'FR', target_date: null }));
|
||||
// Let the post answer and the popup close here, not in the next test.
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-018b: a country already wishlisted for that date is not posted again (#1898)', async () => {
|
||||
const post = vi.fn();
|
||||
server.use(http.post('/api/addons/atlas/bucket-list', () => {
|
||||
post();
|
||||
return HttpResponse.json({ item: buildBucketItem({ id: 99, name: 'Germany', country_code: 'DE' }) });
|
||||
}));
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' },
|
||||
bucketList: [buildBucketItem({ id: 7, name: 'Germany', country_code: 'DE' })],
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.addToBucket'));
|
||||
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('atlas.bucketDuplicate', 'error', undefined));
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
// The popup stays open on the date step so another month can be picked.
|
||||
expect(atlas.setConfirmAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-018: a failing bucket post shows the error toast', async () => {
|
||||
server.use(
|
||||
http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ error: 'Full' }, { status: 400 })),
|
||||
);
|
||||
setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.addToBucket'));
|
||||
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('Full', 'error', undefined));
|
||||
});
|
||||
});
|
||||
|
||||
describe('sidebar', () => {
|
||||
it('FE-PAGE-ATLASW-019: the stats tab lists totals and continents ordered by size', () => {
|
||||
const atlas = setAtlas({
|
||||
data: buildAtlasData({
|
||||
continents: { Europe: 3, Asia: 5, Africa: 1 },
|
||||
stats: { totalTrips: 6, totalPlaces: 40, totalCountries: 9, totalDays: 55, totalCities: 12 },
|
||||
streak: 1,
|
||||
tripsThisYear: 1,
|
||||
}),
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
// Every total shows twice: once in the mobile bar, once in the desktop panel.
|
||||
expect(screen.getAllByText('9')).toHaveLength(2);
|
||||
expect(screen.getAllByText('40')).toHaveLength(2);
|
||||
expect(screen.getByText('atlas.europe')).toBeInTheDocument();
|
||||
// The labels get the counts, so the language's own rule picks the form.
|
||||
expect(screen.getByText('atlas.yearsInRow:1')).toBeInTheDocument();
|
||||
expect(screen.getByText(/atlas\.tripsIn:1/)).toBeInTheDocument();
|
||||
|
||||
// The last-trip tile used to sit in this row; the row is stats only now.
|
||||
expect(screen.queryByText('Paris Trip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-020: an empty atlas shows the mascot empty state instead of the stats', () => {
|
||||
setAtlas({ data: buildAtlasData({ countries: [], lastTrip: null, continents: {} }) });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('atlas.noData')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-021: the country detail overlay lists trips and offers the manual unmark', () => {
|
||||
const atlas = setAtlas({
|
||||
selectedCountry: 'FR',
|
||||
countryDetail: buildCountryDetail({
|
||||
places: [{ id: 1 }, { id: 2 }, { id: 3 }] as unknown as CountryDetail['places'],
|
||||
trips: [
|
||||
{ id: 11, title: 'Paris' },
|
||||
{ id: 12, title: 'Nice' },
|
||||
{ id: 13, title: 'Lyon' },
|
||||
{ id: 14, title: 'Brest' },
|
||||
],
|
||||
manually_marked: true,
|
||||
}),
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('France')).toBeInTheDocument();
|
||||
expect(screen.getAllByText((_, el) => el?.textContent?.trim() === '3 atlas.places:3').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText((_, el) => el?.textContent?.trim() === '4 atlas.tripsLabel:4').length).toBeGreaterThan(0);
|
||||
// Only the first three trips are shown.
|
||||
expect(screen.queryByText('Brest')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByText('Nice'));
|
||||
expect(atlas.navigate).toHaveBeenCalledWith('/trips/12');
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
expect(atlas.handleUnmarkCountry).toHaveBeenCalledWith('FR');
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-022: the stats panel measures itself through a ResizeObserver', () => {
|
||||
const observeSpy = vi.fn();
|
||||
const disconnectSpy = vi.fn();
|
||||
vi.stubGlobal(
|
||||
'ResizeObserver',
|
||||
class {
|
||||
observe = observeSpy;
|
||||
unobserve = vi.fn();
|
||||
disconnect = disconnectSpy;
|
||||
constructor(cb: ResizeObserverCallback) {
|
||||
cb([], this as unknown as ResizeObserver);
|
||||
}
|
||||
},
|
||||
);
|
||||
const { unmount } = render(<AtlasPage />);
|
||||
|
||||
expect(observeSpy).toHaveBeenCalled();
|
||||
unmount();
|
||||
expect(disconnectSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-023: the bucket tab renders items with target month, notes and a delete action', () => {
|
||||
const atlas = setAtlas({
|
||||
bucketTab: 'bucket',
|
||||
bucketList: [
|
||||
buildBucketItem({ id: 1, name: 'Kyoto', country_code: 'JPN', target_date: '2027-04' }),
|
||||
buildBucketItem({ id: 2, name: 'Patagonia', country_code: null, notes: 'road trip' }),
|
||||
buildBucketItem({ id: 3, name: 'Lisbon', country_code: 'PT', target_date: '2030' }),
|
||||
],
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('Kyoto')).toBeInTheDocument();
|
||||
expect(screen.getByText('Apr 2027')).toBeInTheDocument();
|
||||
expect(screen.getByText('road trip')).toBeInTheDocument();
|
||||
expect(screen.getByText('2030')).toBeInTheDocument();
|
||||
expect((document.querySelector('img[alt="JP"]') as HTMLImageElement).src).toContain('flagcdn.com/w40/jp.png');
|
||||
|
||||
const deleteBtn = screen.getByText('Patagonia').closest('div')?.querySelector('button') as HTMLButtonElement;
|
||||
fireEvent.click(deleteBtn);
|
||||
expect(atlas.handleDeleteBucketItem).toHaveBeenCalledWith(2);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.addPoi'));
|
||||
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-024: the bucket add form searches, picks a result and submits', () => {
|
||||
const atlas = setAtlas({
|
||||
bucketTab: 'bucket',
|
||||
showBucketAdd: true,
|
||||
bucketSearch: 'kyo',
|
||||
bucketSearchResults: [{ name: 'Kyoto', address: 'Japan' }],
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('atlas.bucketNamePlaceholder');
|
||||
expect(nameInput).toHaveValue('kyo');
|
||||
fireEvent.change(nameInput, { target: { value: 'kyot' } });
|
||||
expect(atlas.setBucketSearch).toHaveBeenCalledWith('kyot');
|
||||
|
||||
fireEvent.keyDown(nameInput, { key: 'Enter' });
|
||||
expect(atlas.handleBucketPoiSearch).toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(screen.getByText('Kyoto'));
|
||||
expect(atlas.handleSelectBucketPoi).toHaveBeenCalledWith({ name: 'Kyoto', address: 'Japan' });
|
||||
|
||||
const [monthTrigger, yearTrigger] = selectTriggers();
|
||||
fireEvent.click(monthTrigger);
|
||||
fireEvent.click(screen.getByText('Mar'));
|
||||
expect(atlas.setBucketPoiMonth).toHaveBeenCalledWith(3);
|
||||
|
||||
const nextYear = String(new Date().getFullYear() + 2);
|
||||
fireEvent.click(yearTrigger);
|
||||
fireEvent.click(screen.getByText(nextYear));
|
||||
expect(atlas.setBucketPoiYear).toHaveBeenCalledWith(Number(nextYear));
|
||||
|
||||
fireEvent.click(screen.getByText('common.cancel'));
|
||||
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(false);
|
||||
expect(atlas.setBucketForm).toHaveBeenCalledWith({ name: '', notes: '', lat: '', lng: '', target_date: '' });
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-025: a picked place shows its coordinates and can be cleared again', () => {
|
||||
const atlas = setAtlas({
|
||||
bucketTab: 'bucket',
|
||||
showBucketAdd: true,
|
||||
bucketForm: { name: 'Kyoto', notes: '', lat: '35.0116', lng: '135.7681', target_date: '' },
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText(/35\.0116, 135\.7681/)).toBeInTheDocument();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('atlas.bucketNamePlaceholder');
|
||||
fireEvent.change(nameInput, { target: { value: 'Kyoto old town' } });
|
||||
expect(atlas.setBucketForm).toHaveBeenCalledWith({
|
||||
name: 'Kyoto old town', notes: '', lat: '35.0116', lng: '135.7681', target_date: '',
|
||||
});
|
||||
|
||||
fireEvent.keyDown(nameInput, { key: 'Enter' });
|
||||
expect(atlas.handleAddBucketItem).toHaveBeenCalled();
|
||||
fireEvent.keyDown(nameInput, { key: 'Escape' });
|
||||
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(false);
|
||||
|
||||
const clearBtn = nameInput.parentElement?.querySelector('button') as HTMLButtonElement;
|
||||
fireEvent.click(clearBtn);
|
||||
expect(atlas.setBucketForm).toHaveBeenLastCalledWith({
|
||||
name: '', notes: '', lat: '', lng: '', target_date: '',
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('common.add'));
|
||||
expect(atlas.handleAddBucketItem).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-026: the tab bar switches between stats and bucket list', () => {
|
||||
const atlas = setAtlas({ bucketList: [] });
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect(screen.getByText('atlas.bucketEmptyHint')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('atlas.bucketTab'));
|
||||
expect(atlas.setBucketTab).toHaveBeenCalledWith('bucket');
|
||||
fireEvent.click(screen.getByText('atlas.statsTab'));
|
||||
expect(atlas.setBucketTab).toHaveBeenCalledWith('stats');
|
||||
});
|
||||
});
|
||||
|
||||
describe('appearance', () => {
|
||||
afterEach(() => {
|
||||
document.documentElement.removeAttribute('data-no-transparency');
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-027: the no-transparency setting paints the tooltip and the panel opaque', () => {
|
||||
document.documentElement.setAttribute('data-no-transparency', '');
|
||||
const atlas = setAtlas();
|
||||
const { unmount } = render(<AtlasPage />);
|
||||
|
||||
const tooltip = atlas.regionTooltipRef.current as HTMLElement;
|
||||
const panel = atlas.panelRef.current as HTMLElement;
|
||||
expect(tooltip.style.background).toBe('rgb(255, 255, 255)');
|
||||
expect(panel.style.background).toBe('rgb(255, 255, 255)');
|
||||
unmount();
|
||||
|
||||
const darkAtlas = setAtlas({ dark: true });
|
||||
render(<AtlasPage />);
|
||||
expect((darkAtlas.regionTooltipRef.current as HTMLElement).style.background).toBe('rgb(15, 15, 20)');
|
||||
expect((darkAtlas.panelRef.current as HTMLElement).style.background).toBe('rgb(21, 21, 28)');
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-028: without the setting both surfaces stay translucent', () => {
|
||||
const atlas = setAtlas();
|
||||
render(<AtlasPage />);
|
||||
|
||||
expect((atlas.regionTooltipRef.current as HTMLElement).style.background).toBe('rgba(255, 255, 255, 0.96)');
|
||||
expect((atlas.panelRef.current as HTMLElement).style.background).toBe('rgba(255, 255, 255, 0.2)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('continent bookkeeping', () => {
|
||||
it('FE-PAGE-ATLASW-029: marking a region on a new continent starts that continent at one', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'choose-region', code: 'JP', name: 'Kansai', regionCode: 'JP-27' },
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.markVisited'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
const data = atlas.data as AtlasData;
|
||||
// Europe was the only known continent; Asia is added from zero.
|
||||
expect(data.continents).toEqual({ Europe: 1, Asia: 1 });
|
||||
expect(data.stats.totalCountries).toBe(2);
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-030: removing a country that has no recorded regions clamps its continent at zero', async () => {
|
||||
const atlas = setAtlas({
|
||||
confirmAction: { type: 'unmark-region', code: 'JP', name: 'Kansai', regionCode: 'JP-27' },
|
||||
visitedRegions: {} as VisitedRegions,
|
||||
data: buildAtlasData({
|
||||
countries: [{ code: 'JP', tripCount: 0, placeCount: 0, firstVisit: null, lastVisit: null }],
|
||||
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 1, totalDays: 0 },
|
||||
continents: { Europe: 1 },
|
||||
}),
|
||||
});
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('atlas.unmark'));
|
||||
|
||||
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
|
||||
const data = atlas.data as AtlasData;
|
||||
expect(data.countries).toHaveLength(0);
|
||||
expect(data.stats.totalCountries).toBe(0);
|
||||
// Asia was never counted, so the decrement floors at 0 instead of going negative.
|
||||
expect(data.continents).toEqual({ Europe: 1, Asia: 0 });
|
||||
});
|
||||
|
||||
it('FE-PAGE-ATLASW-031: backing out of the bucket step returns to the country chooser', () => {
|
||||
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
|
||||
render(<AtlasPage />);
|
||||
|
||||
fireEvent.click(screen.getByText('common.back'));
|
||||
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,115 @@
|
||||
import type { Badge } from '@trek/shared';
|
||||
import React from 'react';
|
||||
import BadgeMedal from '../../components/AtlasGlobe/BadgeMedal';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { medalLabel } from './AtlasGlobeBadges';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
const KEY = (userId: number) => `trek_atlas_badges_seen_${userId}`;
|
||||
|
||||
function readSeen(userId: number): Set<string> | null {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(KEY(userId));
|
||||
return raw ? new Set(JSON.parse(raw) as string[]) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeSeen(userId: number, ids: Iterable<string>): void {
|
||||
try {
|
||||
window.localStorage.setItem(KEY(userId), JSON.stringify([...ids]));
|
||||
} catch {
|
||||
// Storage blocked: the celebration may repeat next time, nothing else breaks.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The one loud moment of the Atlas: a badge reached since the last visit rises
|
||||
* as a large medal with a ring of light, names itself, and flies into the
|
||||
* badges button. The first visit only remembers what is already earned.
|
||||
*/
|
||||
export default function AtlasBadgeUnlock({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const userId = s.me?.id ?? 0;
|
||||
const [queue, setQueue] = React.useState<Badge[]>([]);
|
||||
const medalRef = React.useRef<HTMLDivElement>(null);
|
||||
const ready = !!s.data && !!s.manifest;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!ready || !userId) return;
|
||||
const earned = s.badges.filter((b) => b.earned);
|
||||
const seen = readSeen(userId);
|
||||
if (!seen) {
|
||||
writeSeen(
|
||||
userId,
|
||||
earned.map((b) => b.id)
|
||||
);
|
||||
return;
|
||||
}
|
||||
const fresh = earned.filter((b) => !seen.has(b.id));
|
||||
if (fresh.length) setQueue((q) => [...q, ...fresh.filter((f) => !q.some((x) => x.id === f.id))]);
|
||||
}, [s.badges, ready, userId]);
|
||||
|
||||
const current = queue[0];
|
||||
|
||||
React.useEffect(() => {
|
||||
const el = medalRef.current;
|
||||
if (!current || !el) return;
|
||||
const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const target = document.querySelector<HTMLElement>('[data-atlas-badges-btn]')?.getBoundingClientRect();
|
||||
const from = el.getBoundingClientRect();
|
||||
const dx = target ? target.left + target.width / 2 - (from.left + from.width / 2) : 0;
|
||||
const dy = target ? target.top + target.height / 2 - (from.top + from.height / 2) : -200;
|
||||
const done = () => {
|
||||
const seen = readSeen(userId) ?? new Set<string>();
|
||||
seen.add(current.id);
|
||||
writeSeen(userId, seen);
|
||||
setQueue((q) => q.slice(1));
|
||||
};
|
||||
if (reduce) {
|
||||
const t = window.setTimeout(done, 2200);
|
||||
return () => window.clearTimeout(t);
|
||||
}
|
||||
const anim = el.animate(
|
||||
[
|
||||
{ transform: 'translate(0, 40px) scale(0.2) rotateY(-180deg)', opacity: 0 },
|
||||
{ transform: 'translate(0, 0) scale(1.08) rotateY(0deg)', opacity: 1, offset: 0.18 },
|
||||
{ transform: 'translate(0, 0) scale(1) rotateY(0deg)', opacity: 1, offset: 0.24 },
|
||||
{ transform: 'translate(0, 0) scale(1) rotateY(0deg)', opacity: 1, offset: 0.72 },
|
||||
{ transform: `translate(${dx}px, ${dy}px) scale(0.12) rotateY(360deg)`, opacity: 0.2 },
|
||||
],
|
||||
{ duration: 3400, easing: 'cubic-bezier(.3,.7,.2,1)' }
|
||||
);
|
||||
navigator.vibrate?.(18);
|
||||
anim.onfinish = done;
|
||||
return () => anim.cancel();
|
||||
}, [current, userId]);
|
||||
|
||||
if (!current) return null;
|
||||
const params = { ...(current.params ?? {}) };
|
||||
if (typeof params.country === 'string') params.country = s.resolveName(params.country) || params.country;
|
||||
const label = medalLabel(current);
|
||||
return (
|
||||
<div className="pointer-events-none fixed inset-0 z-[200] grid place-items-center" aria-live="polite">
|
||||
<div ref={medalRef} className="flex flex-col items-center gap-3" style={{ perspective: 800 }}>
|
||||
<span className="ag-unlock-ring" />
|
||||
<BadgeMedal
|
||||
id={`unlock-${current.id}`}
|
||||
motif={current.motif}
|
||||
tier={current.tier}
|
||||
earned
|
||||
label={label}
|
||||
size={150}
|
||||
/>
|
||||
<span className="ag-liquid rounded-full px-4 py-1.5 text-center">
|
||||
<span className="block text-content-muted" style={fs(11, 'caption')}>
|
||||
{s.t('atlas.globe.newBadge')}
|
||||
</span>
|
||||
<span className="block font-semibold text-content" style={fs(15, 'body')}>
|
||||
{s.t(current.titleKey, params)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { getIntlLanguage } from '@trek/shared';
|
||||
import { ArrowLeft, ChevronRight, MapPin, Star, Trash2, type LucideIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import CustomSelect from '../../components/shared/CustomSelect';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
fs,
|
||||
} from '../../components/shared/DialogShell';
|
||||
import { EditorField, GRID_2 } from '../../components/shared/dialogParts';
|
||||
import { countryCodeToFlag } from './atlasModel';
|
||||
import { bucketMonthTarget, useAtlasCountryActions, type AtlasCountryActionsOptions } from './useAtlasCountryActions';
|
||||
|
||||
// Fixed ids rather than useId: the page body stays free of hooks, and there is only one atlas.
|
||||
const COUNTRY_DIALOG_TITLE = 'atlas-country-dialog-title';
|
||||
const BUCKET_MONTH_ID = 'atlas-bucket-month';
|
||||
const BUCKET_YEAR_ID = 'atlas-bucket-year';
|
||||
/** The footer's destructive answer, filled like ConfirmDialog's. */
|
||||
const DANGER_BUTTON =
|
||||
'inline-flex items-center gap-1.5 rounded-[10px] bg-danger px-4 py-2 font-medium text-white hover:opacity-90'; // theme-lint-disable: white on the danger fill, as ConfirmDialog draws it
|
||||
|
||||
export type CountryActionDialogProps = AtlasCountryActionsOptions & {
|
||||
language: string;
|
||||
executeConfirmAction: () => void | Promise<void>;
|
||||
bucketMonth: number;
|
||||
setBucketMonth: (m: number) => void;
|
||||
bucketYear: number;
|
||||
setBucketYear: (y: number) => void;
|
||||
};
|
||||
|
||||
/** The country action popup over useAtlasCountryActions, the logic it shares with the phone sheet. */
|
||||
export default function CountryActionDialog(props: CountryActionDialogProps): React.ReactElement | null {
|
||||
const {
|
||||
t,
|
||||
language,
|
||||
confirmAction,
|
||||
setConfirmAction,
|
||||
executeConfirmAction,
|
||||
bucketMonth,
|
||||
setBucketMonth,
|
||||
bucketYear,
|
||||
setBucketYear,
|
||||
} = props;
|
||||
const { onWishlist, markCountry, markRegion, unmarkRegion, addBucket, removeBucket } = useAtlasCountryActions(props);
|
||||
const addBucketForMonth = () =>
|
||||
addBucket(bucketMonthTarget(bucketMonth, bucketYear), () => {
|
||||
setBucketMonth(0);
|
||||
setBucketYear(0);
|
||||
});
|
||||
if (!confirmAction) return null;
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={() => setConfirmAction(null)}
|
||||
labelledBy={COUNTRY_DIALOG_TITLE}
|
||||
width="narrow"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<span className="grid h-11 w-11 place-items-center">
|
||||
{confirmAction.code.length === 2 ? (
|
||||
<img
|
||||
src={`https://flagcdn.com/w80/${confirmAction.code.toLowerCase()}.png`}
|
||||
alt={confirmAction.code}
|
||||
className="h-6 w-[34px] rounded-[5px] object-cover ring-1 ring-edge-faint"
|
||||
/>
|
||||
) : (
|
||||
<span className="leading-none" style={fs(26, 'subtitle')}>
|
||||
{countryCodeToFlag(confirmAction.code)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
// The two removals take the danger wash ConfirmDialog asks its destructive questions in.
|
||||
tint={
|
||||
confirmAction.type === 'unmark' || confirmAction.type === 'unmark-region'
|
||||
? 'var(--danger-soft)'
|
||||
: NEUTRAL_TINT
|
||||
}
|
||||
labelId={COUNTRY_DIALOG_TITLE}
|
||||
onClose={() => setConfirmAction(null)}
|
||||
title={confirmAction.name}
|
||||
sub={confirmAction.countryName || undefined}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<DialogButton
|
||||
onClick={() =>
|
||||
setConfirmAction({ ...confirmAction, type: confirmAction.regionCode ? 'choose-region' : 'choose' })
|
||||
}
|
||||
icon={<ArrowLeft size={14} strokeWidth={2.2} />}
|
||||
>
|
||||
{t('common.back')}
|
||||
</DialogButton>
|
||||
)}
|
||||
<FooterSpacer />
|
||||
{confirmAction.type !== 'bucket' && (
|
||||
<DialogButton onClick={() => setConfirmAction(null)}>{t('common.cancel')}</DialogButton>
|
||||
)}
|
||||
{confirmAction.type === 'mark' && (
|
||||
<DialogButton variant="primary" onClick={executeConfirmAction}>
|
||||
{t('atlas.markVisited')}
|
||||
</DialogButton>
|
||||
)}
|
||||
{confirmAction.type === 'unmark' && (
|
||||
<button type="button" onClick={executeConfirmAction} className={DANGER_BUTTON} style={fs(13, 'body')}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
{confirmAction.type === 'unmark-region' && (
|
||||
<button type="button" onClick={unmarkRegion} className={DANGER_BUTTON} style={fs(13, 'body')}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<DialogButton variant="primary" icon={<Star size={14} strokeWidth={2.2} />} onClick={addBucketForMonth}>
|
||||
{t('atlas.addToBucket')}
|
||||
</DialogButton>
|
||||
)}
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{confirmAction.type === 'choose' && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<CountryChoice
|
||||
icon={MapPin}
|
||||
title={t('atlas.markVisited')}
|
||||
hint={t('atlas.markVisitedHint')}
|
||||
onClick={markCountry}
|
||||
/>
|
||||
<CountryChoice
|
||||
icon={Star}
|
||||
tone="text-warning"
|
||||
title={t('atlas.addToBucket')}
|
||||
hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...confirmAction, type: 'bucket' })}
|
||||
/>
|
||||
{onWishlist && (
|
||||
<CountryChoice
|
||||
icon={Trash2}
|
||||
tone="text-danger"
|
||||
title={t('atlas.removeFromBucket')}
|
||||
hint={t('atlas.removeFromBucketHint')}
|
||||
onClick={removeBucket}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'choose-region' && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<CountryChoice
|
||||
icon={MapPin}
|
||||
title={t('atlas.markVisited')}
|
||||
hint={t('atlas.markRegionVisitedHint')}
|
||||
onClick={() => markRegion()}
|
||||
/>
|
||||
<CountryChoice
|
||||
icon={Star}
|
||||
tone="text-warning"
|
||||
title={t('atlas.addToBucket')}
|
||||
hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...confirmAction, type: 'bucket' })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'unmark' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>
|
||||
{t('atlas.confirmUnmark')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'unmark-region' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>
|
||||
{t('atlas.confirmUnmarkRegion')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'mark' && (
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>
|
||||
{t('atlas.confirmMark')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{confirmAction.type === 'bucket' && (
|
||||
<>
|
||||
<p className="m-0 text-content-secondary" style={fs(13.5, 'body')}>
|
||||
{t('atlas.bucketWhen')}
|
||||
</p>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('atlas.month')} htmlFor={BUCKET_MONTH_ID}>
|
||||
<CustomSelect
|
||||
id={BUCKET_MONTH_ID}
|
||||
value={String(bucketMonth)}
|
||||
onChange={(v) => setBucketMonth(Number(v))}
|
||||
placeholder={t('atlas.month')}
|
||||
options={[
|
||||
{ value: '0', label: t('common.none') },
|
||||
...Array.from({ length: 12 }, (_, i) => ({
|
||||
value: String(i + 1),
|
||||
label: new Date(2000, i).toLocaleString(getIntlLanguage(language), { month: 'long' }),
|
||||
})),
|
||||
]}
|
||||
size="sm"
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t('atlas.year')} htmlFor={BUCKET_YEAR_ID}>
|
||||
<CustomSelect
|
||||
id={BUCKET_YEAR_ID}
|
||||
value={String(bucketYear)}
|
||||
onChange={(v) => setBucketYear(Number(v))}
|
||||
placeholder={t('atlas.year')}
|
||||
options={[
|
||||
{ value: '0', label: t('common.none') },
|
||||
...Array.from({ length: 20 }, (_, i) => ({
|
||||
value: String(new Date().getFullYear() + i),
|
||||
label: String(new Date().getFullYear() + i),
|
||||
})),
|
||||
]}
|
||||
size="sm"
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
|
||||
/** One answer of the country dialog, built like an export row: icon tile, what it does, and what that means. */
|
||||
function CountryChoice({
|
||||
icon: Icon,
|
||||
tone = 'text-content-secondary',
|
||||
title,
|
||||
hint,
|
||||
onClick,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
/** The icon's colour class. */
|
||||
tone?: string;
|
||||
title: string;
|
||||
hint: string;
|
||||
onClick: () => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="group flex w-full items-center gap-3 rounded-[14px] border border-edge-faint bg-surface-card px-3 py-2.5 text-start transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
<span
|
||||
className={`grid h-9 w-9 flex-none place-items-center rounded-[10px] bg-surface-tertiary transition-colors group-hover:bg-surface-card ${tone}`}
|
||||
>
|
||||
<Icon size={16} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-semibold text-content" style={fs(13.5, 'body')}>
|
||||
{title}
|
||||
</span>
|
||||
<span className="block text-content-muted" style={fs(11.5)}>
|
||||
{hint}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight
|
||||
size={15}
|
||||
strokeWidth={2}
|
||||
className="flex-none text-content-faint transition-transform group-hover:translate-x-0.5"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import AtlasCountrySearch from './AtlasCountrySearch';
|
||||
import type { AtlasPlaceHit } from './atlasModel';
|
||||
|
||||
const PLACE: AtlasPlaceHit = { name: 'Lisbon', address: 'Portugal', lat: 38.72, lng: -9.14 };
|
||||
|
||||
function renderSearch(overrides: Partial<Parameters<typeof AtlasCountrySearch>[0]> = {}) {
|
||||
const props = {
|
||||
dark: false,
|
||||
t: (key: string) => key,
|
||||
search: 'po',
|
||||
setSearch: vi.fn(),
|
||||
results: [{ code: 'PT', label: 'Portugal' }],
|
||||
setResults: vi.fn(),
|
||||
open: true,
|
||||
setOpen: vi.fn(),
|
||||
options: [],
|
||||
onSelect: vi.fn(),
|
||||
placeResults: [PLACE],
|
||||
placesLoading: false,
|
||||
onQueryChange: vi.fn(),
|
||||
onSelectPlace: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
return { props, ...render(<AtlasCountrySearch {...props} />) };
|
||||
}
|
||||
|
||||
describe('AtlasCountrySearch result rows', () => {
|
||||
it('draws a country and a place row the same way, each ending in a chevron', () => {
|
||||
renderSearch();
|
||||
const country = screen
|
||||
.getByText('Portugal', { selector: 'span.text-content' })
|
||||
.closest('button') as HTMLButtonElement;
|
||||
const place = screen.getByText('Lisbon').closest('button') as HTMLButtonElement;
|
||||
for (const row of [country, place]) {
|
||||
expect(row.style.padding).toBe('10px 12px');
|
||||
expect(row.style.borderBottom).toBe('1px solid rgba(0, 0, 0, 0.06)');
|
||||
expect(row.lastElementChild?.tagName.toLowerCase()).toBe('svg');
|
||||
}
|
||||
expect(country.querySelector('img')).toHaveAttribute('src', 'https://flagcdn.com/w40/pt.png');
|
||||
expect(place).toHaveTextContent('Portugal');
|
||||
});
|
||||
|
||||
it('selects the country or the place that was clicked', () => {
|
||||
const { props } = renderSearch();
|
||||
fireEvent.click(screen.getByAltText('PT').closest('button') as HTMLButtonElement);
|
||||
expect(props.onSelect).toHaveBeenCalledWith('PT');
|
||||
fireEvent.click(screen.getByText('Lisbon').closest('button') as HTMLButtonElement);
|
||||
expect(props.onSelectPlace).toHaveBeenCalledWith(PLACE);
|
||||
});
|
||||
|
||||
it('tints a row on hover in the colour of the scheme and clears it on leave', () => {
|
||||
renderSearch({ dark: true });
|
||||
const row = screen.getByText('Lisbon').closest('button') as HTMLButtonElement;
|
||||
expect(row.style.borderBottom).toBe('1px solid rgba(255, 255, 255, 0.06)');
|
||||
fireEvent.mouseEnter(row);
|
||||
expect(row.style.background).toBe('rgba(255, 255, 255, 0.06)');
|
||||
fireEvent.mouseLeave(row);
|
||||
expect(row.style.background).toBe('transparent');
|
||||
});
|
||||
});
|
||||
@@ -1,231 +0,0 @@
|
||||
import React, { useEffect, useRef } from 'react'
|
||||
import { Search, X, ChevronRight, MapPin, Loader2 } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { AtlasPlaceHit } from './atlasModel'
|
||||
|
||||
type CountryOption = { code: string; label: string }
|
||||
|
||||
interface AtlasCountrySearchProps {
|
||||
dark: boolean
|
||||
t: TranslationFn
|
||||
search: string
|
||||
setSearch: (v: string) => void
|
||||
results: CountryOption[]
|
||||
setResults: (v: CountryOption[]) => void
|
||||
open: boolean
|
||||
setOpen: (v: boolean) => void
|
||||
options: CountryOption[]
|
||||
onSelect: (code: string) => void
|
||||
/** Geocoded places for the same query (#1115) — a second, clearly separated
|
||||
* section below the countries, so the instant local matches stay on top. */
|
||||
placeResults: AtlasPlaceHit[]
|
||||
placesLoading: boolean
|
||||
onQueryChange: (raw: string) => void
|
||||
onSelectPlace: (hit: AtlasPlaceHit) => void
|
||||
}
|
||||
|
||||
// The floating country search box that overlays the globe (search input + results
|
||||
// dropdown). Extracted from AtlasPage as a presentational sibling — behaviour and
|
||||
// markup are byte-identical to the inline version it replaced.
|
||||
export default function AtlasCountrySearch({
|
||||
dark, t, search, setSearch, results, setResults, open, setOpen, options, onSelect,
|
||||
placeResults, placesLoading, onQueryChange, onSelectPlace,
|
||||
}: AtlasCountrySearchProps): React.ReactElement {
|
||||
const boxRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Close on a click outside rather than on mouseleave. Leaving the box used to
|
||||
// close it, which was survivable while the list was only local countries and
|
||||
// appeared complete in one go. Geocoded places arrive a moment later and make
|
||||
// the list grow under a cursor that is already resting there, so the panel
|
||||
// closed by itself seconds after opening.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onDown = (e: MouseEvent) => {
|
||||
if (!boxRef.current?.contains(e.target as Node)) setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', onDown)
|
||||
return () => document.removeEventListener('mousedown', onDown)
|
||||
}, [open, setOpen])
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute z-20 flex justify-center"
|
||||
style={{ top: 'calc(env(safe-area-inset-top, 0px) + 14px)', insetInline: 0, pointerEvents: 'none' }}
|
||||
>
|
||||
<div ref={boxRef} style={{ width: 'min(520px, calc(100vw - 28px))', pointerEvents: 'auto' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '10px 12px',
|
||||
borderRadius: 16,
|
||||
border: '1px solid ' + (dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.08)'),
|
||||
background: dark ? 'rgba(10,10,15,0.55)' : 'rgba(255,255,255,0.55)',
|
||||
backdropFilter: 'blur(18px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(18px) saturate(180%)',
|
||||
boxShadow: dark ? '0 8px 26px rgba(0,0,0,0.25)' : '0 8px 26px rgba(0,0,0,0.10)',
|
||||
}}>
|
||||
<Search size={16} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value
|
||||
setSearch(raw)
|
||||
onQueryChange(raw)
|
||||
const q = raw.trim().toLowerCase()
|
||||
if (!q) {
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
const next = options
|
||||
.filter(o => o.label.toLowerCase().includes(q) || o.code.toLowerCase() === q)
|
||||
.slice(0, 8)
|
||||
setResults(next)
|
||||
setOpen(true)
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (results.length > 0) setOpen(true)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
const first = results[0]
|
||||
if (first) { onSelect(first.code); return }
|
||||
const place = placeResults[0]
|
||||
if (place) onSelectPlace(place)
|
||||
}
|
||||
}}
|
||||
placeholder={t('atlas.searchCountry')}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className="text-content"
|
||||
style={{
|
||||
flex: 1,
|
||||
border: 'none',
|
||||
outline: 'none',
|
||||
background: 'transparent',
|
||||
fontSize: 'calc(13px * var(--fs-scale-body, 1))',
|
||||
fontFamily: 'inherit',
|
||||
}}
|
||||
/>
|
||||
{search.trim() && (
|
||||
<button type="button"
|
||||
onClick={() => {
|
||||
setSearch('')
|
||||
setResults([])
|
||||
setOpen(false)
|
||||
}}
|
||||
className="text-content-faint"
|
||||
style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 2, display: 'flex' }}
|
||||
aria-label="Clear"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && (results.length > 0 || placeResults.length > 0 || placesLoading) && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 8,
|
||||
borderRadius: 14,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid ' + (dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.08)'),
|
||||
background: dark ? 'rgba(10,10,15,0.75)' : 'rgba(255,255,255,0.75)',
|
||||
backdropFilter: 'blur(18px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(18px) saturate(180%)',
|
||||
boxShadow: dark ? '0 12px 30px rgba(0,0,0,0.35)' : '0 12px 30px rgba(0,0,0,0.12)',
|
||||
}}
|
||||
>
|
||||
{results.map((r) => (
|
||||
<ResultRow key={r.code} dark={dark} onClick={() => onSelect(r.code)}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
|
||||
<img src={`https://flagcdn.com/w40/${r.code.toLowerCase()}.png`} alt={r.code} style={{ width: 28, height: 20, borderRadius: 4, objectFit: 'cover' }} />
|
||||
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.label}
|
||||
</span>
|
||||
</span>
|
||||
</ResultRow>
|
||||
))}
|
||||
|
||||
{(placeResults.length > 0 || placesLoading) && (
|
||||
<div
|
||||
className="text-content-faint"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
padding: '7px 12px',
|
||||
fontSize: 'calc(10px * var(--fs-scale-caption, 1))',
|
||||
fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em',
|
||||
borderTop: results.length > 0 ? '1px solid ' + (dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)') : 'none',
|
||||
}}
|
||||
>
|
||||
{placesLoading && <Loader2 size={11} className="animate-spin" />}
|
||||
{t('atlas.searchPlaces')}
|
||||
</div>
|
||||
)}
|
||||
{placeResults.map((p) => (
|
||||
<ResultRow key={`${p.lat},${p.lng},${p.name}`} dark={dark} onClick={() => onSelectPlace(p)}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
|
||||
<span
|
||||
style={{
|
||||
width: 28, height: 20, borderRadius: 4, flexShrink: 0,
|
||||
display: 'grid', placeItems: 'center',
|
||||
background: dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)',
|
||||
}}
|
||||
>
|
||||
<MapPin size={13} className="text-content-faint" />
|
||||
</span>
|
||||
<span style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
|
||||
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{p.name}
|
||||
</span>
|
||||
{p.address && (
|
||||
<span className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{p.address}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
</ResultRow>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One row of the dropdown, a country or a geocoded place, with the chevron at its end. */
|
||||
function ResultRow({ dark, onClick, children }: {
|
||||
dark: boolean
|
||||
onClick: () => void
|
||||
children: React.ReactNode
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button type="button"
|
||||
onClick={onClick}
|
||||
style={{
|
||||
width: '100%',
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
cursor: 'pointer',
|
||||
padding: '10px 12px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
fontFamily: 'inherit',
|
||||
textAlign: 'start',
|
||||
borderBottom: '1px solid ' + (dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)'),
|
||||
}}
|
||||
onMouseEnter={(e) => { (e.currentTarget as HTMLButtonElement).style.background = dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)' }}
|
||||
onMouseLeave={(e) => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight size={16} className="text-content-faint" style={{ flexShrink: 0 }} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { BADGE_CATEGORIES, type Badge } from '@trek/shared';
|
||||
import { ArrowLeft, CalendarCheck, CheckCircle2, Hourglass, Target, Users } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import BadgeMedal, { TIERS } from '../../components/AtlasGlobe/BadgeMedal';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { HUB_CARD, HubBar, HubGlow, HubPill, HubSection, HubTiles, type HubTileData } from './atlasHubKit';
|
||||
import { badgeHolders, badgeLadder, formatNum } from './atlasHubModel';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/** The number a stepped medal carries under its symbol (5, 10, 25 countries; 3/5 regions; five times round). */
|
||||
export function medalLabel(b: Pick<Badge, 'motif' | 'target' | 'current'>): string | undefined {
|
||||
switch (b.motif) {
|
||||
case 'countries':
|
||||
case 'continents':
|
||||
case 'flights':
|
||||
case 'airports':
|
||||
case 'streak':
|
||||
case 'burst':
|
||||
case 'wish':
|
||||
case 'islands':
|
||||
return String(b.target);
|
||||
case 'region':
|
||||
return `${b.current}/${b.target}`;
|
||||
case 'earth':
|
||||
return b.target > 40075 ? `${Math.round(b.target / 40075)}×` : undefined;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Title params with a country code turned into the country's name. */
|
||||
function badgeParams(s: AtlasGlobeState, b: Badge): Record<string, string | number> {
|
||||
const params: Record<string, string | number> = { ...(b.params ?? {}) };
|
||||
if (typeof params.country === 'string') params.country = s.resolveName(params.country) || params.country;
|
||||
return params;
|
||||
}
|
||||
|
||||
/** Tilts a medal towards the pointer and moves its shine, like a hologram sticker. */
|
||||
function tilt(e: React.PointerEvent<HTMLElement>, strength = 9): void {
|
||||
const el = e.currentTarget;
|
||||
const r = el.getBoundingClientRect();
|
||||
const mx = ((e.clientX - r.left) / r.width) * 100;
|
||||
const my = ((e.clientY - r.top) / r.height) * 100;
|
||||
el.style.setProperty('--mx', `${mx}%`);
|
||||
el.style.setProperty('--my', `${my}%`);
|
||||
el.style.setProperty('--rx', `${Math.max(-12, Math.min(12, (50 - my) / strength))}deg`);
|
||||
el.style.setProperty('--ry', `${Math.max(-12, Math.min(12, (mx - 50) / strength))}deg`);
|
||||
}
|
||||
|
||||
function untilt(e: React.PointerEvent<HTMLElement>): void {
|
||||
e.currentTarget.style.setProperty('--rx', '0deg');
|
||||
e.currentTarget.style.setProperty('--ry', '0deg');
|
||||
}
|
||||
|
||||
/**
|
||||
* The badges of the Atlas hub, by category: each category names how many of
|
||||
* its medals are earned; a medal opens its own page with how to get it, when it
|
||||
* was reached and by what.
|
||||
*/
|
||||
export default function AtlasGlobeBadges({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const [openId, setOpenId] = React.useState<string | null>(null);
|
||||
const open = openId ? (s.badges.find((b) => b.id === openId) ?? null) : null;
|
||||
if (open) return <BadgeDetail s={s} b={open} onBack={() => setOpenId(null)} onOpen={setOpenId} />;
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{BADGE_CATEGORIES.map((cat) => {
|
||||
const list = s.badges.filter((b) => b.category === cat);
|
||||
if (!list.length) return null;
|
||||
const earned = list.filter((b) => b.earned).length;
|
||||
return (
|
||||
<section key={cat} className="flex flex-col gap-3">
|
||||
<div className="flex items-baseline justify-between border-b border-edge-faint pb-2">
|
||||
<h3 className="m-0 font-semibold text-content" style={fs(14.5, 'body')}>
|
||||
{s.t(`atlas.badgeCat.${cat}`)}
|
||||
</h3>
|
||||
<span className="tabular-nums text-content-muted" style={fs(12, 'caption')}>
|
||||
{earned} / {list.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(124px,1fr))] gap-x-3 gap-y-5">
|
||||
{list.map((b) => (
|
||||
<MedalTile key={b.id} s={s} b={b} onOpen={() => setOpenId(b.id)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MedalTile({ s, b, onOpen }: { s: AtlasGlobeState; b: Badge; onOpen: () => void }): React.ReactElement {
|
||||
const params = badgeParams(s, b);
|
||||
const sub = b.earned ? (b.year ? String(b.year) : '') : `${formatNum(b.current)} / ${formatNum(b.target)}`;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="ag-medal group flex flex-col items-center gap-2 rounded-[16px] px-1 pb-2 pt-1 text-center transition-colors hover:bg-surface-hover"
|
||||
data-earned={b.earned ? '1' : '0'}
|
||||
onPointerMove={(e) => tilt(e)}
|
||||
onPointerLeave={untilt}
|
||||
>
|
||||
<span className="ag-medal-body" style={{ width: 104, height: 117 }}>
|
||||
<span className="ag-medal-face">
|
||||
<BadgeMedal
|
||||
id={b.id}
|
||||
motif={b.motif}
|
||||
tier={b.tier}
|
||||
earned={b.earned}
|
||||
size={104}
|
||||
progress={b.target ? b.current / b.target : 0}
|
||||
label={medalLabel(b)}
|
||||
/>
|
||||
<span className="ag-medal-shine" />
|
||||
</span>
|
||||
</span>
|
||||
<span className="line-clamp-2 px-1 font-medium leading-tight text-content" style={fs(12.5, 'caption')}>
|
||||
{s.t(b.titleKey, params)}
|
||||
</span>
|
||||
{sub && (
|
||||
<span className="tabular-nums leading-none text-content-muted" style={fs(11, 'caption')}>
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function BadgeDetail({
|
||||
s,
|
||||
b,
|
||||
onBack,
|
||||
onOpen,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
b: Badge;
|
||||
onBack: () => void;
|
||||
onOpen: (id: string) => void;
|
||||
}): React.ReactElement {
|
||||
const params = badgeParams(s, b);
|
||||
const share = b.target ? Math.min(1, b.current / b.target) : 0;
|
||||
const country = b.country ? s.resolveName(b.country) || b.country : null;
|
||||
const metal = TIERS[b.tier][0];
|
||||
const { loadPeople, compareEnabled } = s;
|
||||
React.useEffect(() => {
|
||||
if (compareEnabled) loadPeople();
|
||||
}, [compareEnabled, loadPeople]);
|
||||
// The other stages of the same series (5, 10, 25 countries ...), in order.
|
||||
const ladder = badgeLadder(s.badges, b);
|
||||
const holders = compareEnabled ? badgeHolders(s.people, b) : null;
|
||||
const tiles: HubTileData[] = [
|
||||
{ Icon: Target, value: `${formatNum(b.current)} / ${formatNum(b.target)}`, label: s.t('atlas.globe.progress') },
|
||||
b.earned
|
||||
? { Icon: CalendarCheck, value: b.year ?? '✓', label: s.t('atlas.globe.reached') }
|
||||
: { Icon: Hourglass, value: formatNum(Math.max(0, b.target - b.current)), label: s.t('atlas.globe.toGo') },
|
||||
];
|
||||
if (holders)
|
||||
tiles.push({ Icon: Users, value: `${holders.holders} / ${holders.of}`, label: s.t('atlas.globe.holders') });
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="inline-flex items-center gap-1.5 self-start rounded-full px-2.5 py-1.5 text-content-secondary hover:bg-surface-hover"
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
<ArrowLeft size={14} /> {s.t(`atlas.badgeCat.${b.category}`)}
|
||||
</button>
|
||||
|
||||
<div className={`${HUB_CARD} relative grid items-center gap-6 overflow-hidden p-6 sm:grid-cols-[auto_1fr]`}>
|
||||
<HubGlow color={metal} />
|
||||
<div
|
||||
className="ag-medal relative mx-auto"
|
||||
data-earned={b.earned ? '1' : '0'}
|
||||
onPointerMove={(e) => tilt(e, 6)}
|
||||
onPointerLeave={untilt}
|
||||
>
|
||||
<span className="ag-medal-body" style={{ width: 190, height: 214 }}>
|
||||
<span className="ag-medal-face">
|
||||
<BadgeMedal
|
||||
id={`d-${b.id}`}
|
||||
motif={b.motif}
|
||||
tier={b.tier}
|
||||
earned={b.earned}
|
||||
size={190}
|
||||
progress={share}
|
||||
label={medalLabel(b)}
|
||||
/>
|
||||
<span className="ag-medal-shine" />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="relative flex min-w-0 flex-col gap-4">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<HubPill>{s.t(`atlas.badgeCat.${b.category}`)}</HubPill>
|
||||
<HubPill tone={metal}>
|
||||
<span className="size-2 rounded-full" style={{ background: metal }} /> {s.t(`atlas.badgeTier.${b.tier}`)}
|
||||
</HubPill>
|
||||
{b.earned && (
|
||||
<HubPill tone="var(--success)">
|
||||
<CheckCircle2 size={11} /> {s.t('atlas.globe.reached')}
|
||||
</HubPill>
|
||||
)}
|
||||
</div>
|
||||
<h3 className="m-0 font-bold leading-tight text-content" style={fs(26, 'title')}>
|
||||
{s.t(b.titleKey, params)}
|
||||
</h3>
|
||||
<div className="flex flex-col items-start gap-2">
|
||||
<span
|
||||
className="inline-flex rounded-full border border-edge-faint bg-surface-tertiary px-2.5 py-1 font-semibold text-content-secondary"
|
||||
style={fs(11.5, 'caption')}
|
||||
>
|
||||
{s.t('atlas.globe.howTo')}
|
||||
</span>
|
||||
<p className="m-0 text-content" style={fs(14.5, 'body')}>
|
||||
{s.t(b.descKey, { ...params, count: b.target })}
|
||||
</p>
|
||||
</div>
|
||||
{!b.earned && <HubBar share={share} color={metal} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<HubTiles tiles={tiles} cols={tiles.length === 3 ? 'grid-cols-1 sm:grid-cols-3' : 'grid-cols-2'} />
|
||||
|
||||
{country && b.earned && b.country && (
|
||||
<div className={`${HUB_CARD} flex items-center gap-4 px-5 py-4`}>
|
||||
<span className="grid size-11 flex-none place-items-center rounded-full bg-surface-tertiary">
|
||||
<CountryFlag code={b.country} size={22} />
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{s.t('atlas.globe.madeBy')}
|
||||
</span>
|
||||
<span className="block truncate font-semibold text-content" style={fs(16, 'subtitle')}>
|
||||
{country}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ladder.length > 1 && (
|
||||
<HubSection
|
||||
title={s.t('atlas.globe.stages')}
|
||||
meta={`${ladder.filter((x) => x.earned).length} / ${ladder.length}`}
|
||||
>
|
||||
<div className={`${HUB_CARD} flex gap-2 overflow-x-auto p-2`}>
|
||||
{ladder.map((x) => (
|
||||
<button
|
||||
key={x.id}
|
||||
type="button"
|
||||
onClick={() => onOpen(x.id)}
|
||||
aria-current={x.id === b.id}
|
||||
className={`flex w-[84px] flex-none flex-col items-center gap-1 rounded-[13px] px-1 py-2 transition-colors ${x.id === b.id ? 'bg-surface-tertiary ring-1 ring-edge' : 'hover:bg-surface-hover'}`}
|
||||
>
|
||||
<BadgeMedal
|
||||
id={`l-${x.id}`}
|
||||
motif={x.motif}
|
||||
tier={x.tier}
|
||||
earned={x.earned}
|
||||
size={58}
|
||||
progress={x.target ? x.current / x.target : 0}
|
||||
label={medalLabel(x)}
|
||||
/>
|
||||
<span className="w-full truncate text-center text-content-secondary" style={fs(11, 'caption')}>
|
||||
{s.t(x.titleKey, badgeParams(s, x))}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</HubSection>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared';
|
||||
import {
|
||||
Building2,
|
||||
CalendarDays,
|
||||
Check,
|
||||
Globe2,
|
||||
Hourglass,
|
||||
Info,
|
||||
Loader2,
|
||||
MapPin,
|
||||
RefreshCw,
|
||||
Star,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { cityLine, countryLabel, formatDistance } from '../../components/Dawarich/dawarichAtlasModel';
|
||||
import { formatDuration } from '../../components/Dawarich/dawarichSuggestionModel';
|
||||
import { useDawarichAtlas, type DawarichAtlasState } from '../../components/Dawarich/useDawarichAtlas';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { HUB_CARD, HubEmpty, HubGhost, HubPill, HubPrimary, HubRow, HubRows } from './atlasHubKit';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/** What Dawarich offers for one question, built once for the desktop tab; the phone builds its own rows. */
|
||||
export function dawarichNotes(d: DawarichAtlasState, t: AtlasGlobeState['t']): string[] {
|
||||
if (d.tab === 'wishes') {
|
||||
return [
|
||||
d.scan && d.scan.skippedWithoutCoordinates > 0
|
||||
? t('dawarich.bucket.skipped', { count: d.scan.skippedWithoutCoordinates })
|
||||
: null,
|
||||
d.scan?.truncated ? t('dawarich.bucket.truncated') : null,
|
||||
t('dawarich.bucket.rule', { meters: DAWARICH_BUCKET_MATCH_RADIUS_M, count: DAWARICH_BUCKET_MATCH_MIN_MINUTES }),
|
||||
].filter((n): n is string => !!n);
|
||||
}
|
||||
return [
|
||||
d.countries && d.countries.unresolved.length > 0
|
||||
? t('dawarich.atlas.unresolved', { names: d.countries.unresolved.join(', ') })
|
||||
: null,
|
||||
d.countries ? t('dawarich.atlas.window') : null,
|
||||
].filter((n): n is string => !!n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dawarich inside the Atlas hub (addon): which wishes the recordings reached,
|
||||
* which countries they went through. Every answer is an offer to tick, and
|
||||
* one button writes what is ticked.
|
||||
*/
|
||||
export default function AtlasGlobeDawarich({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const d = useDawarichAtlas({ initialTab: s.dawarichSub, onChanged: () => void s.reload() });
|
||||
const { setTab } = d;
|
||||
// An entry from the wishlist or the numbers asks its own question.
|
||||
React.useEffect(() => setTab(s.dawarichSub), [s.dawarichSub, setTab]);
|
||||
const t = s.t;
|
||||
const wishes = d.tab === 'wishes';
|
||||
const segments: Array<['wishes' | 'countries', string, number]> = [
|
||||
['wishes', t('dawarich.atlas.tab.wishes'), d.openMatches.length],
|
||||
['countries', t('dawarich.atlas.tab.countries'), d.offered.length],
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex gap-1 rounded-xl bg-surface-tertiary p-1">
|
||||
{segments.map(([k, label, n]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => d.setTab(k)}
|
||||
className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg py-2 font-medium transition-colors ${d.tab === k ? 'bg-surface-card text-content shadow-sm' : 'text-content-muted hover:text-content'}`}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{k === 'wishes' ? <Star size={14} /> : <Globe2 size={14} />} {label}
|
||||
{n > 0 && (
|
||||
<span className="rounded-full bg-accent px-1.5 tabular-nums text-accent-text" style={fs(10.5, 'caption')}>
|
||||
{n}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{d.busy ? (
|
||||
<div className={`${HUB_CARD} flex items-center gap-3 px-5 py-6 text-content-muted`} style={fs(13, 'body')}>
|
||||
<Loader2 size={16} className="animate-spin" />{' '}
|
||||
{t(wishes ? 'dawarich.bucket.scanning' : 'dawarich.atlas.loading')}
|
||||
</div>
|
||||
) : !d.loaded ? (
|
||||
<HubEmpty
|
||||
Icon={wishes ? Star : Globe2}
|
||||
title={t(wishes ? 'dawarich.bucket.title' : 'dawarich.atlas.title')}
|
||||
hint={t(wishes ? 'dawarich.bucket.description' : 'dawarich.atlas.description')}
|
||||
action={
|
||||
<HubPrimary Icon={RefreshCw} onClick={d.run}>
|
||||
{t(wishes ? 'dawarich.bucket.scan' : 'dawarich.atlas.load')}
|
||||
</HubPrimary>
|
||||
}
|
||||
/>
|
||||
) : !d.anything ? (
|
||||
<HubEmpty
|
||||
Icon={wishes ? Star : Globe2}
|
||||
title={t(wishes ? 'dawarich.bucket.noMatches' : 'dawarich.atlas.empty')}
|
||||
action={
|
||||
<HubGhost Icon={RefreshCw} onClick={d.run}>
|
||||
{t('dawarich.again')}
|
||||
</HubGhost>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<HubRows>
|
||||
{wishes
|
||||
? d.matches.map((m) => (
|
||||
<Pick
|
||||
key={m.itemId}
|
||||
name={m.name}
|
||||
checked={d.picked.has(m.itemId)}
|
||||
disabled={m.alreadyVisited}
|
||||
onToggle={() => d.togglePicked(m.itemId)}
|
||||
leading={<Star size={15} className="text-warning" />}
|
||||
>
|
||||
{m.alreadyVisited ? (
|
||||
<HubPill tone="var(--success)">
|
||||
<Check size={11} /> {t('dawarich.bucket.alreadyVisited')}
|
||||
</HubPill>
|
||||
) : m.match ? (
|
||||
<>
|
||||
<HubPill>
|
||||
<MapPin size={11} /> {formatDistance(m.match.distanceMeters, t)}
|
||||
</HubPill>
|
||||
<HubPill>
|
||||
<Hourglass size={11} /> {formatDuration(m.match.minutes, t)}
|
||||
</HubPill>
|
||||
<HubPill>
|
||||
<CalendarDays size={11} />{' '}
|
||||
{new Date(m.match.at).toLocaleDateString(s.language, {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
})}
|
||||
</HubPill>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-content-faint" style={fs(11.5, 'caption')}>
|
||||
{t('dawarich.bucket.noMatches')}
|
||||
</span>
|
||||
)}
|
||||
</Pick>
|
||||
))
|
||||
: d.offered.map((c) => (
|
||||
<Pick
|
||||
key={c.countryCode}
|
||||
name={countryLabel(c.countryCode, c.sourceName, s.language)}
|
||||
checked={d.pickedCountries.has(c.countryCode)}
|
||||
onToggle={() => d.togglePickedCountry(c.countryCode)}
|
||||
leading={<CountryFlag code={c.countryCode} size={18} />}
|
||||
>
|
||||
{c.cities.length > 0 && (
|
||||
<>
|
||||
<HubPill>
|
||||
<Building2 size={11} /> {t('dawarich.atlas.cities', { count: c.cities.length })}
|
||||
</HubPill>
|
||||
<span className="min-w-0 truncate text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{cityLine(c.cities)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Pick>
|
||||
))}
|
||||
</HubRows>
|
||||
<div className={`${HUB_CARD} sticky bottom-0 flex items-center gap-2 px-4 py-3`}>
|
||||
<span className="min-w-0 flex-1 truncate text-content-muted" style={fs(12, 'caption')}>
|
||||
{d.selected > 0 ? t('dawarich.selected', { count: d.selected }) : ''}
|
||||
</span>
|
||||
<HubGhost Icon={RefreshCw} onClick={d.run}>
|
||||
{t('dawarich.again')}
|
||||
</HubGhost>
|
||||
<HubPrimary Icon={Check} disabled={d.selected === 0 || d.writing} onClick={d.confirm}>
|
||||
{wishes
|
||||
? t('dawarich.bucket.confirm', { count: d.selected })
|
||||
: t('dawarich.atlas.accept', { count: d.selected })}
|
||||
</HubPrimary>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{d.loaded &&
|
||||
dawarichNotes(d, t).map((note) => (
|
||||
<p key={note} className="m-0 -mt-2 flex items-start gap-1.5 text-content-faint" style={fs(11.5, 'caption')}>
|
||||
<Info size={12} className="mt-0.5 flex-none" /> {note}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One offer to tick: the whole row is the control. */
|
||||
function Pick({
|
||||
name,
|
||||
checked,
|
||||
disabled = false,
|
||||
onToggle,
|
||||
leading,
|
||||
children,
|
||||
}: {
|
||||
name: string;
|
||||
checked: boolean;
|
||||
disabled?: boolean;
|
||||
onToggle: () => void;
|
||||
leading: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<HubRow muted={disabled} className="!p-0">
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
aria-label={name}
|
||||
disabled={disabled}
|
||||
onClick={onToggle}
|
||||
className="flex w-full items-center gap-3 px-3 py-2.5 text-start"
|
||||
>
|
||||
<span
|
||||
className={`grid size-5 flex-none place-items-center rounded-full border-2 transition-colors ${checked ? 'border-accent bg-accent' : 'border-edge'}`}
|
||||
>
|
||||
{checked && <Check size={12} strokeWidth={3} className="text-accent-text" />}
|
||||
</span>
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-surface-card">{leading}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-medium text-content" style={fs(13.5, 'body')}>
|
||||
{name}
|
||||
</span>
|
||||
<span className="mt-1 flex flex-wrap items-center gap-1">{children}</span>
|
||||
</span>
|
||||
</button>
|
||||
</HubRow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { Briefcase, CalendarClock, Layers } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import AtlasCountryPlaces from '../../components/Atlas/AtlasCountryPlaces';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
fs,
|
||||
} from '../../components/shared/DialogShell';
|
||||
import CountryActionDialog from './AtlasCountryActionDialog';
|
||||
import type { GlobeColorMode } from './atlasGlobePaint';
|
||||
import { countryStatus } from './atlasModel';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
const DETAIL_TITLE = 'atlas-globe-detail-title';
|
||||
const LAYERS_TITLE = 'atlas-globe-layers-title';
|
||||
|
||||
/** The classic Atlas dialogs, opened from the globe: mark, unmark, wish, and a visited country's places. */
|
||||
export function GlobeCountryDialogs({
|
||||
s,
|
||||
onOpenTrip,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
onOpenTrip: (id: number) => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<>
|
||||
<CountryActionDialog
|
||||
t={s.t}
|
||||
language={s.language}
|
||||
confirmAction={s.confirmAction}
|
||||
setConfirmAction={(v) => {
|
||||
s.setConfirmAction(v);
|
||||
if (typeof v !== 'function' && v === null) s.closeDialogs();
|
||||
}}
|
||||
executeConfirmAction={s.executeConfirmAction}
|
||||
bucketMonth={s.bucketMonth}
|
||||
setBucketMonth={s.setBucketMonth}
|
||||
bucketYear={s.bucketYear}
|
||||
setBucketYear={s.setBucketYear}
|
||||
setData={s.setData}
|
||||
visitedRegions={s.regions}
|
||||
setVisitedRegions={s.setRegions}
|
||||
bucketList={s.bucket}
|
||||
setBucketList={s.setBucket}
|
||||
handleDeleteBucketItem={s.handleDeleteBucketItem}
|
||||
/>
|
||||
{s.detail && <CountryDetailDialog s={s} onOpenTrip={onOpenTrip} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CountryDetailDialog({
|
||||
s,
|
||||
onOpenTrip,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
onOpenTrip: (id: number) => void;
|
||||
}): React.ReactElement | null {
|
||||
const d = s.detail;
|
||||
if (!d) return null;
|
||||
const row = s.data?.countries.find((c) => c.code === d.a2);
|
||||
const progress = s.progress;
|
||||
// Trips counted for this country without a place in it (a flight, a booking):
|
||||
// the places list below would leave them out, so they get a chip each.
|
||||
const placedTrips = new Set((d.data?.places ?? []).map((p) => p.trip_id));
|
||||
const tripsWithoutPlaces = (d.data?.trips ?? []).filter((trip) => !placedTrips.has(trip.id));
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={s.closeDialogs}
|
||||
labelledBy={DETAIL_TITLE}
|
||||
width="detail"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<span className="grid h-11 w-11 place-items-center">
|
||||
<CountryFlag code={d.a2} size={30} />
|
||||
</span>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={DETAIL_TITLE}
|
||||
onClose={s.closeDialogs}
|
||||
title={s.resolveName(d.a2)}
|
||||
sub={
|
||||
row
|
||||
? `${row.tripCount} ${s.t('atlas.trips', { count: row.tripCount })}, ${row.placeCount} ${s.t('atlas.places', { count: row.placeCount })}`
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
{d.data?.manually_marked && <DialogButton onClick={s.askUnmarkDetail}>{s.t('atlas.unmark')}</DialogButton>}
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={s.closeDialogs}>{s.t('common.close')}</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{row && countryStatus(row) !== 'visited' && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1.5 self-start rounded-full bg-surface-tertiary px-2.5 py-1 font-medium text-content-secondary"
|
||||
style={fs(12, 'caption')}
|
||||
>
|
||||
<CalendarClock size={12} /> {s.t('atlas.planned')}
|
||||
</span>
|
||||
)}
|
||||
{tripsWithoutPlaces.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{tripsWithoutPlaces.map((trip) => (
|
||||
<button
|
||||
key={trip.id}
|
||||
type="button"
|
||||
onClick={() => onOpenTrip(trip.id)}
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-edge-faint bg-surface-card px-3 py-1.5 font-medium text-content transition-colors hover:bg-surface-hover"
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
<Briefcase size={13} className="text-content-muted" /> {trip.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{progress && progress.total > 0 && (
|
||||
<div className="rounded-[14px] border border-edge-faint bg-surface-card px-4 py-3">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="text-content-secondary" style={fs(12.5, 'caption')}>
|
||||
{s.t('atlas.regions')}
|
||||
</span>
|
||||
<span className="font-semibold tabular-nums text-content" style={fs(13.5, 'body')}>
|
||||
{progress.visited} / {progress.total}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-surface-tertiary">
|
||||
<div
|
||||
className="h-full rounded-full bg-accent transition-[width] duration-700"
|
||||
style={{ width: `${(progress.visited / Math.max(1, progress.total)) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{d.data ? (
|
||||
<AtlasCountryPlaces detail={d.data} onOpenTrip={onOpenTrip} />
|
||||
) : (
|
||||
<div className="flex justify-center py-6">
|
||||
<div className="size-6 animate-spin rounded-full border-2 border-edge border-t-content" />
|
||||
</div>
|
||||
)}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the globe shows: planned countries, flights, and what the colours mean. */
|
||||
export function GlobeLayersDialog({ s, onClose }: { s: AtlasGlobeState; onClose: () => void }): React.ReactElement {
|
||||
const modes: Array<[GlobeColorMode, string]> = [
|
||||
['country', s.t('atlas.globe.colorCountry')],
|
||||
['status', s.t('atlas.globe.colorStatus')],
|
||||
['year', s.t('atlas.globe.colorYear')],
|
||||
];
|
||||
const row = (label: string, on: boolean, toggle: () => void) => (
|
||||
<div className="flex items-center gap-3 rounded-[14px] border border-edge-faint bg-surface-card px-4 py-3">
|
||||
<span className="flex-1 text-content" style={fs(13.5, 'body')}>
|
||||
{label}
|
||||
</span>
|
||||
<ToggleSwitch on={on} onToggle={toggle} label={label} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={LAYERS_TITLE}
|
||||
width="narrow"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Layers size={20} strokeWidth={1.9} />
|
||||
</DialogTile>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={LAYERS_TITLE}
|
||||
onClose={onClose}
|
||||
title={s.t('atlas.globe.layers')}
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton variant="primary" onClick={onClose}>
|
||||
{s.t('common.close')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
{row(s.t('atlas.showPlanned'), s.showPlanned, () => s.setShowPlanned(!s.showPlanned))}
|
||||
{!!s.flights?.routes.length &&
|
||||
row(s.t('atlas.globe.flights'), s.showFlights, () => s.setShowFlights(!s.showFlights))}
|
||||
{s.pluginLayers.map((l) => {
|
||||
const key = `${l.pluginId}:${l.id}`;
|
||||
return (
|
||||
<React.Fragment key={key}>
|
||||
{row(l.name || l.id, !s.hiddenPluginLayers.has(key), () => s.togglePluginLayer(key))}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 font-medium text-content-secondary" style={fs(12.5, 'caption')}>
|
||||
{s.t('atlas.globe.colorBy')}
|
||||
</div>
|
||||
<div className="flex gap-1 rounded-xl bg-surface-tertiary p-1">
|
||||
{modes.map(([m, label]) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
onClick={() => s.setColorMode(m)}
|
||||
className={`flex-1 rounded-lg py-1.5 font-medium transition-colors ${s.colorMode === m ? 'bg-surface-card text-content shadow-sm' : 'text-content-muted hover:text-content'}`}
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Briefcase, Building2, CalendarDays, ChevronRight, Flame, Map as MapIcon, MapPin, Plane } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { HUB_CARD, HubBar, HubDawarichEntry, HubHero, HubTiles, type HubTileData } from './atlasHubKit';
|
||||
import { WORLD_COUNTRIES, continentCounts } from './atlasHubModel';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
const CARD = HUB_CARD;
|
||||
|
||||
/**
|
||||
* The Atlas numbers: one large figure (countries, with the share of the world),
|
||||
* the continents as a small bar chart, the rest as a quiet list, and the next
|
||||
* trip counting down.
|
||||
*/
|
||||
export default function AtlasGlobeOverview({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const d = s.data;
|
||||
const st = d?.stats;
|
||||
const countries = s.totals.countries;
|
||||
const share = Math.min(1, countries / WORLD_COUNTRIES);
|
||||
const planned = (st?.totalCountriesPlanned ?? 0) + (st?.totalCountriesIdea ?? 0);
|
||||
const continents = continentCounts(d);
|
||||
const maxC = Math.max(1, ...continents.map((c) => c.n));
|
||||
// The server also sends how many days are left, which the shared type does not list yet.
|
||||
const next = d?.nextTrip as { id: number; title: string; daysUntil?: number } | null | undefined;
|
||||
|
||||
const figures: HubTileData[] = [
|
||||
{ Icon: MapIcon, value: s.totals.regions, label: s.t('atlas.regions', { count: s.totals.regions }) },
|
||||
{ Icon: Briefcase, value: st?.totalTrips ?? 0, label: s.t('atlas.trips', { count: st?.totalTrips ?? 0 }) },
|
||||
{ Icon: MapPin, value: st?.totalPlaces ?? 0, label: s.t('atlas.places', { count: st?.totalPlaces ?? 0 }) },
|
||||
{ Icon: Building2, value: st?.totalCities ?? 0, label: s.t('atlas.cities', { count: st?.totalCities ?? 0 }) },
|
||||
{ Icon: CalendarDays, value: st?.totalDays ?? 0, label: s.t('atlas.days', { count: st?.totalDays ?? 0 }) },
|
||||
{ Icon: Flame, value: d?.streak ?? 0, label: s.t('atlas.yearsInRow', { count: d?.streak ?? 0 }) },
|
||||
{
|
||||
Icon: Plane,
|
||||
value: d?.tripsThisYear ?? 0,
|
||||
label: `${s.t('atlas.tripsIn', { count: d?.tripsThisYear ?? 0 })} ${new Date().getFullYear()}`,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_1.45fr]">
|
||||
{/* The headline: countries and how much of the world that is. */}
|
||||
<HubHero value={countries} unit={s.t('atlas.countries', { count: countries })}>
|
||||
<HubBar share={share} />
|
||||
<div className="mt-2 flex items-center justify-between text-content-muted" style={fs(12, 'caption')}>
|
||||
<span>{s.t('atlas.globe.worldShare', { share: Math.round(share * 100) })}</span>
|
||||
{planned > 0 && (
|
||||
<span>
|
||||
+{planned} {s.t('atlas.planned')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</HubHero>
|
||||
|
||||
{/* Continents as a small bar chart. */}
|
||||
<div className={`${CARD} flex flex-col px-5 py-4`}>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="font-semibold text-content" style={fs(13.5, 'body')}>
|
||||
{s.t('atlas.globe.continents')}
|
||||
</span>
|
||||
<span className="tabular-nums text-content-muted" style={fs(12, 'caption')}>
|
||||
{s.totals.continents} / {continents.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-1 items-end gap-2">
|
||||
{continents.map((c) => (
|
||||
<div key={c.name} className="flex min-w-0 flex-1 flex-col items-center gap-1.5">
|
||||
<span className="tabular-nums text-content-secondary" style={fs(11, 'caption')}>
|
||||
{c.n || ''}
|
||||
</span>
|
||||
<div className="flex h-16 w-full items-end">
|
||||
<div
|
||||
className={`w-full rounded-t-[6px] transition-[height] duration-700 ${c.n ? 'bg-accent' : 'bg-surface-tertiary'}`}
|
||||
style={{
|
||||
height: `${c.n ? Math.max(12, (c.n / maxC) * 100) : 8}%`,
|
||||
opacity: c.n ? 0.35 + 0.65 * (c.n / maxC) : 1,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className="w-full truncate text-center text-content-muted"
|
||||
style={fs(10, 'caption')}
|
||||
title={s.t(c.key)}
|
||||
>
|
||||
{s.t(c.key)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Everything else, quietly. */}
|
||||
<HubTiles tiles={figures} className="sm:col-span-2" />
|
||||
|
||||
{s.dawarichEnabled && (
|
||||
<div className="sm:col-span-2">
|
||||
<HubDawarichEntry
|
||||
title={s.t('atlas.globe.dawarichCountries')}
|
||||
hint={s.t('atlas.globe.dawarichCountriesHint')}
|
||||
onClick={() => s.openDawarich('countries')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{next && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(`/trips/${next.id}`)}
|
||||
className={`${CARD} group flex items-center gap-4 px-5 py-4 text-start transition-colors hover:bg-surface-hover sm:col-span-2`}
|
||||
>
|
||||
{typeof next.daysUntil === 'number' && (
|
||||
<span className="flex flex-none flex-col items-center rounded-[14px] bg-accent px-3.5 py-2 text-accent-text">
|
||||
<span className="font-bold tabular-nums leading-none" style={fs(22, 'title')}>
|
||||
{next.daysUntil}
|
||||
</span>
|
||||
<span style={fs(10, 'caption')}>{s.t('atlas.daysLeft')}</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{s.t('atlas.nextTrip')}
|
||||
</span>
|
||||
<span className="block truncate font-semibold text-content" style={fs(16, 'subtitle')}>
|
||||
{next.title}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight size={18} className="text-content-faint transition-transform group-hover:translate-x-0.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { ArrowLeft, Globe2, Layers } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import BadgeMedal from '../../components/AtlasGlobe/BadgeMedal';
|
||||
import { DialogHeader, DialogShell, DialogTile, NEUTRAL_TINT, fs } from '../../components/shared/DialogShell';
|
||||
import AtlasGlobeBadges, { medalLabel } from './AtlasGlobeBadges';
|
||||
import AtlasGlobeDawarich from './AtlasGlobeDawarich';
|
||||
import AtlasGlobeOverview from './AtlasGlobeOverview';
|
||||
import AtlasGlobeTours from './AtlasGlobeTours';
|
||||
import AtlasGlobeTravellers from './AtlasGlobeTravellers';
|
||||
import AtlasGlobeWishlist from './AtlasGlobeWishlist';
|
||||
import { useHubTabs } from './AtlasHubRail';
|
||||
import type { AtlasGlobeState, AtlasHubTab } from './useAtlasGlobe';
|
||||
|
||||
/** The Passport: badges as glass medals, and the other travellers of this instance. */
|
||||
export default function AtlasGlobePassport({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const tab = s.passportTab;
|
||||
const hubTabs = useHubTabs(s);
|
||||
const setTab = s.setPassportTab;
|
||||
if (!s.passportOpen) return null;
|
||||
const earned = s.badges.filter((b) => b.earned).length;
|
||||
const tabs = hubTabs.map((e): [AtlasHubTab, string] => [e.tab, e.label]);
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={() => s.setPassportOpen(false)}
|
||||
labelledBy={PASSPORT_TITLE}
|
||||
width="wide"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Globe2 size={20} strokeWidth={1.9} />
|
||||
</DialogTile>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={PASSPORT_TITLE}
|
||||
onClose={() => s.setPassportOpen(false)}
|
||||
title={s.t('atlas.globe.hub')}
|
||||
sub={tab === 'badges' ? s.t('atlas.globe.collected', { earned, total: s.badges.length }) : undefined}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="flex flex-none gap-1 self-start overflow-x-auto rounded-xl bg-surface-tertiary p-1"
|
||||
style={{ maxWidth: '100%' }}
|
||||
>
|
||||
{tabs.map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setTab(k);
|
||||
s.setProfileId(null);
|
||||
}}
|
||||
className={`rounded-lg px-3 py-1.5 font-medium transition-colors ${tab === k ? 'bg-surface-card text-content shadow-sm' : 'text-content-muted hover:text-content'}`}
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{tab === 'overview' ? (
|
||||
<AtlasGlobeOverview s={s} />
|
||||
) : tab === 'wishlist' ? (
|
||||
<AtlasGlobeWishlist s={s} />
|
||||
) : tab === 'dawarich' ? (
|
||||
<AtlasGlobeDawarich s={s} />
|
||||
) : tab === 'tours' ? (
|
||||
<AtlasGlobeTours s={s} />
|
||||
) : tab === 'badges' ? (
|
||||
<AtlasGlobeBadges s={s} />
|
||||
) : s.profile ? (
|
||||
<TravellerProfile s={s} />
|
||||
) : (
|
||||
<AtlasGlobeTravellers s={s} />
|
||||
)}
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
|
||||
const PASSPORT_TITLE = 'atlas-globe-passport-title';
|
||||
|
||||
/** Another traveller's page: their numbers, their medals, and the way onto the globe next to yours. */
|
||||
function TravellerProfile({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const p = s.profile;
|
||||
if (!p) return null;
|
||||
const stat = (value: React.ReactNode, label: string) => (
|
||||
<div className="flex flex-col rounded-[14px] border border-edge-faint bg-surface-card px-3 py-2.5">
|
||||
<span className="font-semibold tabular-nums text-content" style={fs(20, 'title')}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => s.setProfileId(null)}
|
||||
className="grid size-8 place-items-center rounded-full text-content-muted hover:bg-surface-hover"
|
||||
aria-label={s.t('common.back')}
|
||||
>
|
||||
<ArrowLeft size={16} />
|
||||
</button>
|
||||
{p.avatar_url ? (
|
||||
<img src={p.avatar_url} alt="" className="size-12 rounded-full object-cover" />
|
||||
) : (
|
||||
<span
|
||||
className="grid size-12 place-items-center rounded-full font-semibold"
|
||||
style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}
|
||||
>
|
||||
{p.username.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-semibold text-content" style={fs(17, 'subtitle')}>
|
||||
{p.username}
|
||||
</div>
|
||||
<div className="text-content-muted" style={fs(12, 'caption')}>
|
||||
{s.t('atlas.globe.collected', { earned: p.badges.length, total: s.badges.length })}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => s.startCompare(p)}
|
||||
className="inline-flex items-center gap-1.5 rounded-[10px] bg-accent px-3.5 py-2 font-medium text-accent-text hover:opacity-90"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<Layers size={14} /> {s.t('atlas.globe.compareOnGlobe')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
{stat(p.countries, s.t('atlas.countries'))}
|
||||
{stat(p.continents, s.t('atlas.globe.continents'))}
|
||||
{stat(p.regions, s.t('atlas.regions'))}
|
||||
{stat(`${Math.round(p.flightKm / 1000)}k`, s.t('atlas.globe.flightKm'))}
|
||||
</div>
|
||||
{p.badges.length ? (
|
||||
<div className="grid grid-cols-[repeat(auto-fill,minmax(112px,1fr))] gap-4">
|
||||
{p.badges.map((b) => {
|
||||
const params = { ...(b.params ?? {}) };
|
||||
if (typeof params.country === 'string') params.country = s.resolveName(params.country) || params.country;
|
||||
const label = medalLabel({ motif: b.motif, target: b.target, current: b.target });
|
||||
return (
|
||||
<div key={b.id} className="flex flex-col items-center gap-2 text-center">
|
||||
<BadgeMedal id={`p${p.id}-${b.id}`} motif={b.motif} tier={b.tier} earned label={label} />
|
||||
<span className="font-medium leading-tight text-content" style={fs(12.5, 'caption')}>
|
||||
{s.t(b.titleKey, params)}
|
||||
</span>
|
||||
{b.year ? (
|
||||
<span className="leading-tight text-content-muted" style={fs(11, 'caption')}>
|
||||
{s.t('atlas.globe.reachedIn', { year: b.year })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-6 text-center text-content-muted" style={fs(12.5, 'caption')}>
|
||||
{s.t('atlas.globe.noBadgesYet')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Loader2, MapPin, Search, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/** The search pill over the globe: countries in the user's language and regions by name. */
|
||||
export default function AtlasGlobeSearch({
|
||||
s,
|
||||
className = 'start-1/2 top-[18px] w-[min(440px,calc(100%-220px))] -translate-x-1/2 rtl:translate-x-1/2',
|
||||
focusSignal = 0,
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
className?: string;
|
||||
focusSignal?: number;
|
||||
}): React.ReactElement {
|
||||
const [active, setActive] = React.useState(0);
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const results = s.results;
|
||||
|
||||
React.useEffect(() => setActive(0), [s.query]);
|
||||
|
||||
// Asked from outside (the phone dock's search button): focus the field.
|
||||
React.useEffect(() => {
|
||||
if (focusSignal > 0) inputRef.current?.focus();
|
||||
}, [focusSignal]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (
|
||||
e.key === '/' &&
|
||||
document.activeElement?.tagName !== 'INPUT' &&
|
||||
document.activeElement?.tagName !== 'TEXTAREA'
|
||||
) {
|
||||
e.preventDefault();
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setActive((a) => Math.min(results.length - 1, a + 1));
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setActive((a) => Math.max(0, a - 1));
|
||||
} else if (e.key === 'Enter' && results[active]) {
|
||||
s.pickResult(results[active]);
|
||||
inputRef.current?.blur();
|
||||
} else if (e.key === 'Enter' && !results.length && s.placeHits[0]) {
|
||||
void s.pickPlace(s.placeHits[0]);
|
||||
inputRef.current?.blur();
|
||||
} else if (e.key === 'Escape') {
|
||||
s.setQuery('');
|
||||
inputRef.current?.blur();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`absolute z-30 ${className}`}>
|
||||
<div className="ag-liquid flex h-11 items-center gap-2.5 rounded-full px-4">
|
||||
<Search size={16} className="shrink-0 text-content-muted" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={s.query}
|
||||
onChange={(e) => s.setQuery(e.target.value)}
|
||||
onFocus={s.loadRegionSearch}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={s.t('atlas.globe.search')}
|
||||
aria-label={s.t('atlas.globe.search')}
|
||||
className="min-w-0 flex-1 text-body text-content outline-none placeholder:text-content-muted"
|
||||
style={{ background: 'transparent', border: 'none', boxShadow: 'none', padding: 0, appearance: 'none' }}
|
||||
/>
|
||||
{s.query ? (
|
||||
<button
|
||||
type="button"
|
||||
className="grid size-6 place-items-center text-content-muted"
|
||||
onClick={() => s.setQuery('')}
|
||||
aria-label="Clear"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
) : (
|
||||
<kbd className="hidden rounded-md border border-edge px-1.5 text-caption text-content-faint sm:inline">/</kbd>
|
||||
)}
|
||||
</div>
|
||||
{(results.length > 0 || s.placeHits.length > 0 || s.placesLoading) && (
|
||||
<div className="ag-liquid mt-2 overflow-hidden rounded-2xl p-1.5" role="listbox">
|
||||
{results.map((r, i) => (
|
||||
<button
|
||||
key={`${r.kind}:${r.kind === 'country' ? r.a2 : `${r.a2}:${r.code ?? r.name}`}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => s.pickResult(r)}
|
||||
className={`flex w-full items-center gap-2.5 rounded-xl px-3 py-2 text-start text-body text-content ${i === active ? 'bg-surface-hover' : ''}`}
|
||||
>
|
||||
<CountryFlag code={r.a2} size={16} />
|
||||
<span className="flex-1 truncate">{r.name}</span>
|
||||
{r.kind === 'region' && (
|
||||
<span className="truncate text-caption text-content-muted">{s.resolveName(r.a2)}</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{(s.placeHits.length > 0 || s.placesLoading) && (
|
||||
<div className="flex items-center gap-1.5 px-3 pb-1 pt-2 text-caption font-medium text-content-muted">
|
||||
{s.placesLoading && <Loader2 size={11} className="animate-spin" />}
|
||||
{s.t('atlas.searchPlaces')}
|
||||
</div>
|
||||
)}
|
||||
{s.placeHits.map((p) => (
|
||||
<button
|
||||
key={`${p.lat},${p.lng}`}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={false}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => void s.pickPlace(p)}
|
||||
className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2 text-start text-body text-content hover:bg-surface-hover"
|
||||
>
|
||||
<MapPin size={15} className="shrink-0 text-content-muted" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate">{p.name}</span>
|
||||
{p.address && <span className="block truncate text-caption text-content-muted">{p.address}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Globe2, Loader2, RotateCw } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/**
|
||||
* What the globe shows while it is not ready: a quiet spinner while the data
|
||||
* and the map load, and a card that says what went wrong when the globe cannot
|
||||
* draw (no WebGL 2, a lost context, data that did not load), with a retry.
|
||||
*/
|
||||
export default function AtlasGlobeStatus({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
if (s.error) {
|
||||
const webgl = /webgl|context|shader/i.test(s.error);
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-0 z-20 grid place-items-center p-6">
|
||||
<div className="ag-liquid pointer-events-auto flex max-w-sm flex-col items-center gap-3 rounded-[22px] px-6 py-6 text-center">
|
||||
<span className="grid size-12 place-items-center rounded-full bg-surface-tertiary text-content-secondary">
|
||||
<Globe2 size={22} />
|
||||
</span>
|
||||
<div className="font-semibold text-content" style={fs(15, 'body')}>
|
||||
{s.t(webgl ? 'atlas.globe.noWebgl' : 'atlas.globe.loadFailed')}
|
||||
</div>
|
||||
<div className="text-content-muted" style={fs(12.5, 'caption')}>
|
||||
{s.t(webgl ? 'atlas.globe.noWebglHint' : 'atlas.globe.loadFailedHint')}
|
||||
</div>
|
||||
{/* The technical reason, small: what to quote in a bug report. */}
|
||||
<code
|
||||
className="max-w-full break-words rounded-lg bg-surface-tertiary px-2.5 py-1.5 text-content-faint"
|
||||
style={fs(11, 'caption')}
|
||||
>
|
||||
{s.error}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
onClick={webgl ? () => window.location.reload() : s.retryLoad}
|
||||
className="mt-1 inline-flex items-center gap-1.5 rounded-full bg-accent px-4 py-2 font-medium text-accent-text"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<RotateCw size={14} /> {s.t('atlas.globe.retry')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (s.data && s.manifest) return null;
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-0 z-20 grid place-items-center">
|
||||
<span
|
||||
className="ag-liquid inline-flex items-center gap-2 rounded-full px-4 py-2 text-content-secondary"
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
<Loader2 size={14} className="animate-spin" /> {s.t('atlas.globe.loading')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Pause, Play, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/**
|
||||
* The time scrubber: drag through the years you travelled and the globe colours
|
||||
* the countries in the order you reached them. Play runs it like a film.
|
||||
*/
|
||||
export default function AtlasGlobeTimeline({
|
||||
s,
|
||||
className = 'start-1/2 top-[72px] w-[min(520px,calc(100%-44px))] -translate-x-1/2 rtl:translate-x-1/2',
|
||||
}: {
|
||||
s: AtlasGlobeState;
|
||||
className?: string;
|
||||
}): React.ReactElement | null {
|
||||
const first = s.totals.firstYear;
|
||||
const last = new Date().getFullYear();
|
||||
const [playing, setPlaying] = React.useState(false);
|
||||
const { year, setYear, timelineOpen, setTimelineOpen } = s;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!playing) return;
|
||||
const id = window.setInterval(() => {
|
||||
setYear((y) => {
|
||||
const next = (y ?? (first ?? last) - 1) + 1;
|
||||
if (next >= last) {
|
||||
setPlaying(false);
|
||||
return last;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, 700);
|
||||
return () => window.clearInterval(id);
|
||||
}, [playing, first, last, setYear]);
|
||||
|
||||
if (!timelineOpen || !first) return null;
|
||||
const value = year ?? last;
|
||||
const newThisYear = s.totals.perYear.get(value) ?? 0;
|
||||
const upTo = [...s.totals.perYear.entries()].filter(([y]) => y <= value).reduce((n, [, c]) => n + c, 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`ag-liquid pointer-events-auto absolute z-30 flex items-center gap-3 rounded-[18px] px-3 py-2 ${className}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (!playing && value >= last) setYear(first);
|
||||
setPlaying((p) => !p);
|
||||
}}
|
||||
className="grid size-9 flex-none place-items-center rounded-full bg-accent text-accent-text"
|
||||
aria-label={playing ? 'Pause' : 'Play'}
|
||||
>
|
||||
{playing ? <Pause size={15} /> : <Play size={15} />}
|
||||
</button>
|
||||
<span className="w-[54px] flex-none font-semibold tabular-nums text-content" style={fs(20, 'title')}>
|
||||
{value}
|
||||
</span>
|
||||
<input
|
||||
type="range"
|
||||
min={first}
|
||||
max={last}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
setPlaying(false);
|
||||
setYear(Number(e.target.value));
|
||||
}}
|
||||
className="min-w-0 flex-1 accent-[color:var(--accent)]"
|
||||
aria-label={s.t('atlas.year')}
|
||||
/>
|
||||
<span className="hidden flex-none flex-col items-end sm:flex">
|
||||
<span className="font-semibold tabular-nums text-content" style={fs(13, 'body')}>
|
||||
{upTo}
|
||||
</span>
|
||||
<span className="text-content-muted" style={fs(10.5, 'caption')}>
|
||||
{newThisYear ? `+${newThisYear}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPlaying(false);
|
||||
setYear(null);
|
||||
setTimelineOpen(false);
|
||||
}}
|
||||
className="grid size-8 flex-none place-items-center rounded-full text-content-muted hover:bg-surface-hover"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X size={15} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { ArrowDownRight, ArrowUpRight, Footprints, ListOrdered, Mountain } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import {
|
||||
ActivityFilters,
|
||||
ActivityStatusLine,
|
||||
BasisBadges,
|
||||
UncountedBadges,
|
||||
} from '../../components/Atlas/tourActivity/tourActivityParts';
|
||||
import {
|
||||
distanceReading,
|
||||
heightReading,
|
||||
typeIcon,
|
||||
typeLabel,
|
||||
useDistanceUnit,
|
||||
} from '../../components/Atlas/tourActivity/tourActivityReading';
|
||||
import { TourActivityStatsDialog } from '../../components/Atlas/tourActivity/TourActivityStatsDialog';
|
||||
import { splitMeasure } from '../../components/Atlas/tourActivity/tourActivityStatsModel';
|
||||
import { useTourActivityStats } from '../../components/Atlas/tourActivity/useTourActivityStats';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { InfoDot } from '../../components/Tours/tourParts';
|
||||
import { HUB_CARD, HUB_INSET, HubEmpty, HubGhost, HubHero, HubSection, HubTiles } from './atlasHubKit';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/**
|
||||
* Your tours (STA-02) in the Atlas hub, in the same build as Statistics: the
|
||||
* distance as the headline, tours, climb and descent as tiles, every tour type
|
||||
* as a bar by distance, and the way into the full list where a tour can be
|
||||
* left out. Same data and filters as before.
|
||||
*/
|
||||
export default function AtlasGlobeTours({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const stats = useTourActivityStats(true);
|
||||
const unit = useDistanceUnit();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const summary = stats.summary;
|
||||
const t = s.t;
|
||||
const filters = (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ActivityFilters stats={stats} />
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!summary) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{filters}
|
||||
<div className={`${HUB_CARD} px-5 py-6`}>
|
||||
<ActivityStatusLine stats={stats} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const totals = summary.totals;
|
||||
if (totals.count === 0) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{filters}
|
||||
<HubEmpty Icon={Mountain} title={t(stats.data?.entries.length ? 'tours.stats.none' : 'tours.stats.empty')} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const distance = distanceReading(totals, unit);
|
||||
const hero = distance ? splitMeasure(distance.text) : { value: String(totals.count), unit: '' };
|
||||
const ascent = heightReading(totals.ascentM, unit);
|
||||
const descent = heightReading(totals.descentM, unit);
|
||||
const types = summary.types;
|
||||
const maxKm = Math.max(1e-9, ...types.map((x) => x.distanceKm.value ?? 0));
|
||||
const uncounted = stats.data?.uncounted ?? { unassigned: 0, undated: 0 };
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
{filters}
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-[1.2fr_1fr]">
|
||||
<HubHero value={hero.value} unit={hero.unit || undefined}>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<BasisBadges byBasis={totals.byBasis} />
|
||||
<InfoDot label={t('tours.stats.title')} description={t('tours.stats.basisInfo')} />
|
||||
</div>
|
||||
</HubHero>
|
||||
<HubTiles
|
||||
cols="grid-cols-3 sm:grid-cols-1"
|
||||
tiles={[
|
||||
{ Icon: Footprints, value: totals.count, label: t('tours.mode.tours') },
|
||||
{ Icon: ArrowUpRight, value: ascent?.text ?? '0', label: t('tours.detail.ascent') },
|
||||
{ Icon: ArrowDownRight, value: descent?.text ?? '0', label: t('tours.detail.descent') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{stats.type === 'all' && types.length > 0 && (
|
||||
<HubSection title={t('atlas.globe.byType')} meta={types.length}>
|
||||
<div className={`${HUB_CARD} flex flex-col gap-1.5 p-1.5`}>
|
||||
{types.map((x) => {
|
||||
const Icon = typeIcon(x.type);
|
||||
const d = distanceReading(x, unit);
|
||||
const share = (x.distanceKm.value ?? 0) / maxKm;
|
||||
return (
|
||||
<div key={x.type} className={`${HUB_INSET} flex items-center gap-3 px-3 py-2.5`}>
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-surface-card text-content-secondary">
|
||||
<Icon size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
<span className="w-28 flex-none">
|
||||
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>
|
||||
{typeLabel(x.type, t)}
|
||||
</span>
|
||||
<span className="block tabular-nums text-content-muted" style={fs(11, 'caption')}>
|
||||
{t('atlas.globe.tourCount', { count: x.count })}
|
||||
</span>
|
||||
</span>
|
||||
<div className="h-2 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-card">
|
||||
<div
|
||||
className="h-full rounded-full bg-accent transition-[width] duration-700"
|
||||
style={{ width: `${Math.max(4, share * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className="w-20 flex-none text-end font-semibold tabular-nums text-content"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{d?.text ?? ''}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</HubSection>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<UncountedBadges upcoming={summary.upcoming} {...uncounted} />
|
||||
{summary.done.length > 0 && (
|
||||
<span className="ms-auto">
|
||||
<HubGhost Icon={ListOrdered} onClick={() => setOpen(true)}>
|
||||
{t('tours.stats.showTours')}
|
||||
</HubGhost>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<TourActivityStatsDialog stats={stats} open={open} onClose={() => setOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { ChevronRight, Users } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { HUB_CARD, HUB_INSET, HubEmpty, HubSection } from './atlasHubKit';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/**
|
||||
* Everyone on this instance, ranked by countries. Each row opens the overlay
|
||||
* of their map on yours. Your own row is marked; the switch at the top takes
|
||||
* you out of everybody else's list.
|
||||
*/
|
||||
export default function AtlasGlobeTravellers({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const { loadPeople } = s;
|
||||
React.useEffect(() => {
|
||||
loadPeople();
|
||||
}, [loadPeople]);
|
||||
const rows = s.ranking;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={`${HUB_CARD} mb-5 flex items-center gap-3 px-4 py-3`}>
|
||||
<span className="flex-1 text-content" style={fs(13.5, 'body')}>
|
||||
{s.t('atlas.globe.visibleToOthers')}
|
||||
</span>
|
||||
<ToggleSwitch
|
||||
on={!s.hidden}
|
||||
onToggle={() => s.setHidden(!s.hidden)}
|
||||
label={s.t('atlas.globe.visibleToOthers')}
|
||||
/>
|
||||
</div>
|
||||
{!rows ? (
|
||||
<div className="py-6 text-center text-content-muted" style={fs(12.5, 'caption')}>
|
||||
…
|
||||
</div>
|
||||
) : rows.length <= 1 ? (
|
||||
<HubEmpty Icon={Users} title={s.t('atlas.globe.noTravellers')} />
|
||||
) : (
|
||||
<HubSection title={s.t('atlas.globe.ranking')} meta={rows.length}>
|
||||
<ol className={`${HUB_CARD} m-0 flex list-none flex-col gap-1.5 p-1.5`}>
|
||||
{rows.map((p, i) => {
|
||||
const isMe = p.id === s.me?.id;
|
||||
return (
|
||||
<li key={p.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={isMe}
|
||||
onClick={() => s.setProfileId(p.id)}
|
||||
className={`${HUB_INSET} flex w-full items-center gap-3 px-3 py-2.5 text-start transition-colors ${isMe ? '!border-accent' : 'hover:bg-surface-hover'}`}
|
||||
>
|
||||
<span
|
||||
className="w-6 text-center font-semibold tabular-nums"
|
||||
style={{ color: i < 3 ? 'var(--accent)' : 'var(--text-muted)' }}
|
||||
>
|
||||
{i + 1}
|
||||
</span>
|
||||
{p.avatar_url ? (
|
||||
<img src={p.avatar_url} alt="" className="size-8 rounded-full object-cover" />
|
||||
) : (
|
||||
<span
|
||||
className="grid size-8 place-items-center rounded-full text-caption font-semibold"
|
||||
style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}
|
||||
>
|
||||
{p.username.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(13.5, 'body')}>
|
||||
{isMe ? `${p.username} (${s.t('atlas.globe.you')})` : p.username}
|
||||
</span>
|
||||
<Stat value={p.countries} label={s.t('atlas.countries')} />
|
||||
<Stat value={p.continents} label={s.t('atlas.globe.continents')} />
|
||||
<Stat value={p.regions} label={s.t('atlas.regions')} />
|
||||
<Stat value={`${Math.round(p.flightKm / 1000)}k`} label={s.t('atlas.globe.flightKm')} />
|
||||
<ChevronRight
|
||||
size={15}
|
||||
className={`shrink-0 text-content-muted ${isMe ? 'invisible' : ''}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</HubSection>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ value, label }: { value: React.ReactNode; label: string }): React.ReactElement {
|
||||
return (
|
||||
<span className="hidden w-[72px] flex-col items-end sm:flex">
|
||||
<span className="font-semibold tabular-nums text-content" style={fs(13.5, 'body')}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="text-content-muted" style={fs(10, 'caption')}>
|
||||
{label}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Layers, Minus, Plus, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import AtlasGlobe from '../../components/AtlasGlobe/AtlasGlobe';
|
||||
import type { GlobeEngine } from '../../components/AtlasGlobe/GlobeEngine';
|
||||
import GlobePins, { type GlobePinsHandle } from '../../components/AtlasGlobe/GlobePins';
|
||||
import GlobeSky from '../../components/AtlasGlobe/GlobeSky';
|
||||
import GlobeStatsBar from '../../components/AtlasGlobe/GlobeStatsBar';
|
||||
import '../../components/AtlasGlobe/atlasGlobe.css';
|
||||
import Navbar from '../../components/Layout/Navbar';
|
||||
import { segmentStyle } from '../../components/Map/mapControlShadow';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import AtlasBadgeUnlock from './AtlasBadgeUnlock';
|
||||
import { GlobeCountryDialogs, GlobeLayersDialog } from './AtlasGlobeDialogs';
|
||||
import AtlasGlobePassport from './AtlasGlobePassport';
|
||||
import AtlasGlobeSearch from './AtlasGlobeSearch';
|
||||
import AtlasGlobeStatus from './AtlasGlobeStatus';
|
||||
import AtlasGlobeTimeline from './AtlasGlobeTimeline';
|
||||
import AtlasHubRail from './AtlasHubRail';
|
||||
import { COMPARE_COLORS, compareCounts } from './atlasGlobePaint';
|
||||
import { countryColor, countryStatus } from './atlasModel';
|
||||
import { useAtlasGlobe, type AtlasGlobeState } from './useAtlasGlobe';
|
||||
import { useGlobeStats } from './useGlobeStats';
|
||||
|
||||
const PLANNED_DOT = '#818cf8'; // theme-lint-disable: the planned map paint, so the chip matches the globe
|
||||
|
||||
/** The globe Atlas on desktop. State lives in useAtlasGlobe; this file is layout. */
|
||||
export default function AtlasGlobeView(): React.ReactElement {
|
||||
const s = useAtlasGlobe();
|
||||
const rootRef = React.useRef<HTMLDivElement>(null);
|
||||
const [layersOpen, setLayersOpen] = React.useState(false);
|
||||
const stats = useGlobeStats(s);
|
||||
const pinsRef = React.useRef<GlobePinsHandle>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onFrame = React.useCallback(
|
||||
(e: GlobeEngine) => {
|
||||
s.skyRef.current?.layout(e);
|
||||
pinsRef.current?.layout(e);
|
||||
const root = rootRef.current;
|
||||
if (root) {
|
||||
const moving = e.isMorphing() ? '1' : '0';
|
||||
if (root.dataset.moving !== moving) root.dataset.moving = moving;
|
||||
}
|
||||
},
|
||||
[s.skyRef]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<Navbar />
|
||||
<div
|
||||
ref={rootRef}
|
||||
className="atlas-globe fixed inset-x-0"
|
||||
style={{ top: 'var(--nav-h)', height: 'calc(100dvh - var(--nav-h))' }}
|
||||
>
|
||||
<AtlasGlobe
|
||||
ref={s.globeRef}
|
||||
fetchJson={s.fetchJson}
|
||||
dark
|
||||
labelFor={s.labelFor}
|
||||
labelRegionsOf={s.labelRegionsOf}
|
||||
paint={s.paint}
|
||||
paintKey={s.paintKey}
|
||||
onHover={s.onHover}
|
||||
onSelect={s.onSelect}
|
||||
onReady={s.onReady}
|
||||
onFrame={onFrame}
|
||||
onError={(err) => s.setError(err instanceof Error ? err.message : String(err))}
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-0">
|
||||
<GlobeSky ref={s.skyRef} dark />
|
||||
</div>
|
||||
<div className="pointer-events-none absolute inset-0 overflow-hidden">
|
||||
<GlobePins ref={pinsRef} pins={s.pins} />
|
||||
</div>
|
||||
<GlobeStatsBar stats={stats} />
|
||||
|
||||
<AtlasGlobeSearch s={s} />
|
||||
<div
|
||||
className="ag-liquid pointer-events-auto absolute end-[22px] top-[18px] flex items-center rounded-full p-1"
|
||||
style={{ gap: 2 }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={layersOpen ? 'bg-accent text-accent-text' : 'text-content-secondary hover:text-content'}
|
||||
style={segmentStyle(layersOpen)}
|
||||
onClick={() => setLayersOpen((o) => !o)}
|
||||
aria-expanded={layersOpen}
|
||||
title={s.t('atlas.globe.layers')}
|
||||
>
|
||||
<Layers size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<AtlasHubRail s={s} className="end-[22px] top-1/2 -translate-y-1/2" />
|
||||
{layersOpen && <GlobeLayersDialog s={s} onClose={() => setLayersOpen(false)} />}
|
||||
|
||||
<div
|
||||
className="ag-liquid pointer-events-auto absolute bottom-[22px] end-[22px] flex flex-col items-center rounded-[22px] p-1"
|
||||
style={{ gap: 2 }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="text-content-secondary hover:text-content"
|
||||
style={segmentStyle(false)}
|
||||
onClick={s.zoomIn}
|
||||
aria-label="+"
|
||||
>
|
||||
<Plus size={16} />
|
||||
</button>
|
||||
<span aria-hidden className="my-0.5 h-px w-5 bg-edge" />
|
||||
<button
|
||||
type="button"
|
||||
className="text-content-secondary hover:text-content"
|
||||
style={segmentStyle(false)}
|
||||
onClick={s.zoomOut}
|
||||
aria-label="-"
|
||||
>
|
||||
<Minus size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<CompareBanner s={s} />
|
||||
<AtlasGlobeTimeline s={s} />
|
||||
<AtlasBadgeUnlock s={s} />
|
||||
<AtlasGlobePassport s={s} />
|
||||
<HoverChip s={s} />
|
||||
<GlobeCountryDialogs s={s} onOpenTrip={(id) => navigate(`/trips/${id}`)} />
|
||||
|
||||
<AtlasGlobeStatus s={s} />
|
||||
<div className="ag-faint absolute bottom-[8px] end-[18px] flex gap-3" style={fs(10, 'caption')}>
|
||||
{(s.manifest?.attribution ?? []).map((a) => (
|
||||
<span key={a}>{a}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HoverChip({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const h = s.hover;
|
||||
if (!h) return null;
|
||||
const hit = h.hit;
|
||||
const name = hit.kind === 'country' ? (hit.a2 ? s.resolveName(hit.a2) : '') : (hit.name ?? '');
|
||||
if (!name) return null;
|
||||
const row = hit.kind === 'country' ? s.data?.countries.find((c) => c.code === hit.a2) : undefined;
|
||||
const regionRow = hit.kind === 'region' ? (s.regions[hit.a2] ?? []).find((r) => r.code === hit.code) : undefined;
|
||||
const status = row ? countryStatus(row) : regionRow ? (regionRow.status ?? 'visited') : null;
|
||||
const statusLabel = status === 'visited' ? s.t('atlas.globe.visited') : status ? s.t('atlas.planned') : null;
|
||||
const a3 = hit.kind === 'country' ? s.manifest?.countries[hit.index]?.a3 : undefined;
|
||||
const dotColor = status === 'visited' && a3 ? countryColor(a3) : status ? PLANNED_DOT : undefined;
|
||||
// What the classic tooltip told: trips and places and when, or the country of a region.
|
||||
const facts: string[] = [];
|
||||
if (row && (row.tripCount > 0 || row.placeCount > 0)) {
|
||||
facts.push(
|
||||
`${row.tripCount} ${s.t('atlas.trips', { count: row.tripCount })}, ${row.placeCount} ${s.t('atlas.places', { count: row.placeCount })}`
|
||||
);
|
||||
const first = row.firstVisit?.slice(0, 4);
|
||||
const last = row.lastVisit?.slice(0, 4);
|
||||
if (first) facts.push(first === last || !last ? first : `${first} \u2192 ${last}`);
|
||||
}
|
||||
if (hit.kind === 'region') {
|
||||
facts.push(s.resolveName(hit.a2));
|
||||
if (regionRow?.placeCount)
|
||||
facts.push(`${regionRow.placeCount} ${s.t('atlas.places', { count: regionRow.placeCount })}`);
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="ag-liquid pointer-events-none absolute z-30 whitespace-nowrap rounded-xl px-3 py-1.5"
|
||||
style={{ left: h.x, top: h.y, transform: 'translate(-50%, calc(-100% - 14px))' }} // rtl-lint-disable: a measured pointer position, physical on purpose
|
||||
>
|
||||
<div className="flex items-center gap-2 text-caption">
|
||||
{hit.kind === 'country' && hit.a2 && <CountryFlag code={hit.a2} size={14} />}
|
||||
<b className="font-semibold">{name}</b>
|
||||
</div>
|
||||
{statusLabel && (
|
||||
<div
|
||||
className="mt-0.5 flex items-center gap-1.5 text-caption font-medium"
|
||||
style={{ color: 'var(--ag-ink)', opacity: 0.9 }}
|
||||
>
|
||||
<span
|
||||
className="inline-block size-2 rounded-full"
|
||||
style={{
|
||||
background: dotColor ?? 'var(--ag-accent)',
|
||||
boxShadow: `0 0 8px ${dotColor ?? 'var(--ag-accent)'}`,
|
||||
}}
|
||||
/>
|
||||
{statusLabel}
|
||||
</div>
|
||||
)}
|
||||
{facts.map((f) => (
|
||||
<div key={f} className="ag-muted mt-0.5 text-caption tabular-nums">
|
||||
{f}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CompareBanner({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
|
||||
const p = s.compareWith;
|
||||
if (!p) return null;
|
||||
const mine = (s.data?.countries ?? []).filter((c) => countryStatus(c) === 'visited').map((c) => c.code);
|
||||
const c = compareCounts(mine, p.codes);
|
||||
const key = (color: string, n: number, label: string) => (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<i className="inline-block size-2.5 rounded-full" style={{ background: color }} />
|
||||
<b className="ag-num">{n}</b>
|
||||
<span className="ag-muted">{label}</span>
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<div className="ag-liquid absolute start-1/2 top-[72px] z-30 flex -translate-x-1/2 items-center gap-4 whitespace-nowrap rounded-full py-2 pe-2 ps-2.5 text-caption rtl:translate-x-1/2">
|
||||
<span
|
||||
className="grid size-7 place-items-center rounded-full font-semibold"
|
||||
style={{ background: AVATAR_GRADIENT, color: 'white' }}
|
||||
>
|
||||
{p.username.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
<span className="font-medium">{p.username}</span>
|
||||
{key(COMPARE_BOTH, c.both, s.t('atlas.globe.together'))}
|
||||
{key(COMPARE_THEIRS, c.theirsOnly, s.t('atlas.globe.onlyThem', { name: p.username }))}
|
||||
{key(COMPARE_MINE, c.mineOnly, s.t('atlas.globe.onlyYou'))}
|
||||
<button
|
||||
type="button"
|
||||
data-on={s.gaps ? '1' : '0'}
|
||||
className="ag-btn rounded-full px-3 py-1.5 font-medium"
|
||||
onClick={() => s.setGaps(!s.gaps)}
|
||||
>
|
||||
{s.t('atlas.globe.gaps')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="ag-muted grid size-7 place-items-center rounded-full"
|
||||
onClick={s.stopCompare}
|
||||
aria-label="Close"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { both: COMPARE_BOTH, theirs: COMPARE_THEIRS, mine: COMPARE_MINE } = COMPARE_COLORS;
|
||||
const AVATAR_GRADIENT = 'linear-gradient(135deg, #a78bfa, #f472b6)'; // theme-lint-disable: avatar of the compared traveller
|
||||
@@ -0,0 +1,251 @@
|
||||
import { getIntlLanguage } from '@trek/shared';
|
||||
import { ChevronLeft, ChevronRight, Loader2, MapPin, PenLine, Search, Sparkles, Star, X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import { HUB_CARD, HUB_FIELD, HUB_INSET, HubGhost, HubGlow, HubIconButton, HubPrimary } from './atlasHubKit';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
import { useGlobePlaceSearch } from './useGlobePlaceSearch';
|
||||
|
||||
function StepLabel({ n, children }: { n: number; children: React.ReactNode }): React.ReactElement {
|
||||
return (
|
||||
<div className="flex items-center gap-2 font-semibold text-content" style={fs(13, 'body')}>
|
||||
<span
|
||||
className="grid size-5 place-items-center rounded-full bg-surface-tertiary tabular-nums text-content-secondary"
|
||||
style={fs(11, 'caption')}
|
||||
>
|
||||
{n}
|
||||
</span>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adding a wish: where (a place from the search, or just a name), when (a year
|
||||
* alone or a month of it, past years included, or "some day") and a note. The
|
||||
* note survives picking a place; cancel clears everything.
|
||||
*/
|
||||
export default function AtlasGlobeWishAdd({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const lang = getIntlLanguage(s.language);
|
||||
const [query, setQuery] = React.useState('');
|
||||
const { placeHits, placesLoading } = useGlobePlaceSearch(query, s.placeLang);
|
||||
const picked = !!b.bucketForm.name;
|
||||
const thisYear = new Date().getFullYear();
|
||||
const year = b.bucketPoiYear;
|
||||
const month = b.bucketPoiMonth;
|
||||
const months = Array.from({ length: 12 }, (_, i) => new Date(2000, i).toLocaleString(lang, { month: 'short' }));
|
||||
|
||||
const takeName = () => {
|
||||
const name = query.trim();
|
||||
if (!name) return;
|
||||
b.setBucketForm({ ...b.bucketForm, name, lat: '', lng: '', address: undefined });
|
||||
setQuery('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`${HUB_CARD} relative flex flex-col gap-5 overflow-hidden p-5`}>
|
||||
<HubGlow color="var(--warning)" />
|
||||
<div className="relative flex items-center gap-3">
|
||||
<span className="grid size-10 place-items-center rounded-[12px] bg-warning-soft text-warning">
|
||||
<Sparkles size={18} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-semibold text-content" style={fs(16, 'subtitle')}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</div>
|
||||
<div className="text-content-muted" style={fs(12, 'caption')}>
|
||||
{s.t('atlas.globe.newWishHint')}
|
||||
</div>
|
||||
</div>
|
||||
<HubIconButton label={s.t('common.cancel')} onClick={b.resetBucketAdd}>
|
||||
<X size={15} />
|
||||
</HubIconButton>
|
||||
</div>
|
||||
|
||||
{/* 1. Where */}
|
||||
<div className="relative flex flex-col gap-2.5">
|
||||
<StepLabel n={1}>{s.t('atlas.globe.wishWhere')}</StepLabel>
|
||||
{picked ? (
|
||||
<div className={`${HUB_INSET} flex items-center gap-3 px-3 py-2.5`}>
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-surface-card text-warning">
|
||||
{b.bucketForm.lat ? <MapPin size={16} /> : <Star size={15} />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<input
|
||||
value={b.bucketForm.name}
|
||||
onChange={(e) => b.setBucketForm({ ...b.bucketForm, name: e.target.value })}
|
||||
aria-label={s.t('atlas.bucketNamePlaceholder')}
|
||||
className="w-full bg-transparent font-semibold text-content outline-none"
|
||||
style={fs(14, 'body')}
|
||||
/>
|
||||
<span className="block truncate text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{b.bucketForm.address ||
|
||||
(b.bucketForm.lat
|
||||
? `${Number(b.bucketForm.lat).toFixed(3)}, ${Number(b.bucketForm.lng).toFixed(3)}`
|
||||
: s.t('atlas.globe.wishNoPlace'))}
|
||||
</span>
|
||||
</span>
|
||||
<HubGhost
|
||||
onClick={() => b.setBucketForm({ ...b.bucketForm, name: '', lat: '', lng: '', address: undefined })}
|
||||
>
|
||||
{s.t('atlas.globe.change')}
|
||||
</HubGhost>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="relative">
|
||||
<Search
|
||||
size={15}
|
||||
className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-muted"
|
||||
/>
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
if (placeHits[0]) b.handleSelectBucketPoi(placeHits[0]);
|
||||
else takeName();
|
||||
}}
|
||||
placeholder={s.t('atlas.globe.wishSearch')}
|
||||
className={`${HUB_FIELD} py-2.5 ps-9`}
|
||||
style={fs(14, 'body')}
|
||||
/>
|
||||
{placesLoading && (
|
||||
<Loader2
|
||||
size={15}
|
||||
className="absolute end-3 top-1/2 -translate-y-1/2 animate-spin text-content-muted"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{(placeHits.length > 0 || query.trim().length > 0) && (
|
||||
<div className="flex flex-col gap-1 rounded-[13px] border border-edge-faint bg-surface-tertiary p-1">
|
||||
{placeHits.map((p) => (
|
||||
<button
|
||||
key={`${p.lat},${p.lng}`}
|
||||
type="button"
|
||||
onClick={() => b.handleSelectBucketPoi(p)}
|
||||
className="flex items-center gap-2.5 rounded-[10px] px-2.5 py-2 text-start hover:bg-surface-card"
|
||||
>
|
||||
<MapPin size={14} className="flex-none text-content-muted" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-content" style={fs(13, 'body')}>
|
||||
{p.name}
|
||||
</span>
|
||||
{p.address && (
|
||||
<span className="block truncate text-content-muted" style={fs(11, 'caption')}>
|
||||
{p.address}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{query.trim() && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={takeName}
|
||||
className="flex items-center gap-2.5 rounded-[10px] px-2.5 py-2 text-start text-content-secondary hover:bg-surface-card"
|
||||
>
|
||||
<PenLine size={14} className="flex-none" />
|
||||
<span className="truncate" style={fs(13, 'body')}>
|
||||
{s.t('atlas.globe.wishJustName', { name: query.trim() })}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 2. When */}
|
||||
<div className="relative flex flex-col gap-2.5">
|
||||
<StepLabel n={2}>{s.t('atlas.globe.wishWhen')}</StepLabel>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
b.setBucketPoiYear(0);
|
||||
b.setBucketPoiMonth(0);
|
||||
}}
|
||||
aria-pressed={year === 0}
|
||||
className={`rounded-full px-3.5 py-1.5 font-medium transition-colors ${year === 0 ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-secondary hover:text-content'}`}
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
{s.t('atlas.globe.someday')}
|
||||
</button>
|
||||
<div
|
||||
className={`inline-flex items-center rounded-full p-0.5 ${year ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-secondary'}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={s.t('atlas.globe.yearEarlier')}
|
||||
onClick={() => b.setBucketPoiYear((year || thisYear) - 1)}
|
||||
className="grid size-7 place-items-center rounded-full"
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => b.setBucketPoiYear(year || thisYear)}
|
||||
className="min-w-[52px] px-1 text-center font-semibold tabular-nums"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{year || thisYear}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={s.t('atlas.globe.yearLater')}
|
||||
onClick={() => b.setBucketPoiYear((year || thisYear) + 1)}
|
||||
className="grid size-7 place-items-center rounded-full"
|
||||
>
|
||||
<ChevronRight size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`grid grid-cols-6 gap-1.5 transition-opacity ${year ? '' : 'pointer-events-none opacity-40'}`}
|
||||
aria-disabled={!year}
|
||||
>
|
||||
{months.map((label, i) => {
|
||||
const on = month === i + 1;
|
||||
return (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={() => b.setBucketPoiMonth(on ? 0 : i + 1)}
|
||||
aria-pressed={on}
|
||||
className={`rounded-[10px] py-1.5 font-medium transition-colors ${on ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-secondary hover:text-content'}`}
|
||||
style={fs(12, 'caption')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3. Note */}
|
||||
<div className="relative flex flex-col gap-2.5">
|
||||
<StepLabel n={3}>{s.t('atlas.globe.wishNote')}</StepLabel>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={b.bucketForm.notes}
|
||||
onChange={(e) => b.setBucketForm({ ...b.bucketForm, notes: e.target.value })}
|
||||
placeholder={s.t('atlas.bucketNotesPlaceholder')}
|
||||
className={`${HUB_FIELD} resize-none`}
|
||||
style={fs(13.5, 'body')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center justify-end gap-2 border-t border-edge-faint pt-4">
|
||||
<HubGhost onClick={b.resetBucketAdd}>{s.t('common.cancel')}</HubGhost>
|
||||
<HubPrimary Icon={Star} disabled={!b.bucketForm.name.trim()} onClick={() => void b.handleAddBucketItem()}>
|
||||
{s.t('atlas.globe.wishSave')}
|
||||
</HubPrimary>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { CalendarCheck, CalendarClock, Flag, Navigation, Plus, Radar, Star, Trash2, Undo2 } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import CountryFlag from '../../components/shared/CountryFlag';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
import AtlasGlobeWishAdd from './AtlasGlobeWishAdd';
|
||||
import {
|
||||
HubBar,
|
||||
HubDawarichEntry,
|
||||
HubEmpty,
|
||||
HubGhost,
|
||||
HubHero,
|
||||
HubIconButton,
|
||||
HubPill,
|
||||
HubPrimary,
|
||||
HubRow,
|
||||
HubRows,
|
||||
HubSection,
|
||||
HubTiles,
|
||||
} from './atlasHubKit';
|
||||
import { splitWishes, visitedOn, whenLabeller, wishCountry } from './atlasHubModel';
|
||||
import type { BucketItem } from './atlasModel';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/**
|
||||
* The bucket list in the Atlas hub: how many wishes and how many came true as
|
||||
* the headline, the add form, then the open wishes (soonest first) and the
|
||||
* reached ones with when they were reached.
|
||||
*/
|
||||
export default function AtlasGlobeWishlist({ s }: { s: AtlasGlobeState }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const when = whenLabeller(s.language);
|
||||
const items = b.bucketList;
|
||||
const { open, reached, countries, nextDated } = splitWishes(items);
|
||||
const tiles = [
|
||||
{ Icon: Flag, value: countries, label: s.t('atlas.countries', { count: countries }) },
|
||||
...(nextDated
|
||||
? [{ Icon: CalendarClock, value: when(nextDated.target_date) ?? '', label: s.t('atlas.globe.nextWish') }]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
{b.showBucketAdd && <AtlasGlobeWishAdd s={s} />}
|
||||
{s.dawarichEnabled && items.length > 0 && (
|
||||
<HubDawarichEntry
|
||||
title={s.t('atlas.globe.dawarichWishes')}
|
||||
hint={s.t('atlas.globe.dawarichWishesHint')}
|
||||
onClick={() => s.openDawarich('wishes')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{items.length === 0 ? (
|
||||
!b.showBucketAdd && (
|
||||
<HubEmpty
|
||||
Icon={Star}
|
||||
title={s.t('atlas.bucketEmpty')}
|
||||
hint={s.t('atlas.bucketEmptyHint')}
|
||||
action={
|
||||
<HubPrimary Icon={Plus} onClick={() => b.setShowBucketAdd(true)}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</HubPrimary>
|
||||
}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-[1.2fr_1fr]">
|
||||
<HubHero
|
||||
value={items.length}
|
||||
unit={s.t('atlas.globe.wishes', { count: items.length })}
|
||||
glow="var(--warning)"
|
||||
>
|
||||
<HubBar share={reached.length / items.length} />
|
||||
<div className="mt-2 text-content-muted" style={fs(12, 'caption')}>
|
||||
{s.t('atlas.globe.wishesReached', { done: reached.length, count: items.length })}
|
||||
</div>
|
||||
</HubHero>
|
||||
<HubTiles cols={tiles.length > 1 ? 'grid-cols-2 sm:grid-cols-1' : 'grid-cols-1'} tiles={tiles} />
|
||||
</div>
|
||||
|
||||
{open.length > 0 && (
|
||||
<HubSection
|
||||
title={s.t('atlas.globe.wishesOpen')}
|
||||
meta={open.length}
|
||||
action={
|
||||
!b.showBucketAdd && (
|
||||
<HubGhost Icon={Plus} onClick={() => b.setShowBucketAdd(true)}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</HubGhost>
|
||||
)
|
||||
}
|
||||
>
|
||||
<HubRows>
|
||||
{open.map((item) => (
|
||||
<WishRow key={item.id} s={s} item={item} when={when(item.target_date)} />
|
||||
))}
|
||||
</HubRows>
|
||||
</HubSection>
|
||||
)}
|
||||
{reached.length > 0 && (
|
||||
<HubSection
|
||||
title={s.t('atlas.globe.wishesDone')}
|
||||
meta={reached.length}
|
||||
action={
|
||||
!open.length &&
|
||||
!b.showBucketAdd && (
|
||||
<HubGhost Icon={Plus} onClick={() => b.setShowBucketAdd(true)}>
|
||||
{s.t('atlas.globe.newWish')}
|
||||
</HubGhost>
|
||||
)
|
||||
}
|
||||
>
|
||||
<HubRows>
|
||||
{reached.map((item) => (
|
||||
<WishRow key={item.id} s={s} item={item} when={when(item.target_date)} />
|
||||
))}
|
||||
</HubRows>
|
||||
</HubSection>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WishRow({ s, item, when }: { s: AtlasGlobeState; item: BucketItem; when: string | null }): React.ReactElement {
|
||||
const b = s.bucketState;
|
||||
const done = !!item.visited_at;
|
||||
const a2 = wishCountry(item.country_code);
|
||||
const country = a2 ? s.resolveName(a2) : null;
|
||||
const byRecording = item.visited_source === 'dawarich';
|
||||
const sub = [country && country !== item.name ? country : null, item.notes].filter(Boolean).join(', ');
|
||||
return (
|
||||
<HubRow>
|
||||
<span className="grid size-9 flex-none place-items-center rounded-full bg-surface-card">
|
||||
{a2 ? <CountryFlag code={a2} size={18} /> : <Star size={15} className="text-warning" />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={`block truncate font-medium ${done ? 'text-content-muted line-through' : 'text-content'}`}
|
||||
style={fs(13.5, 'body')}
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{sub && (
|
||||
<span className="block truncate text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{done ? (
|
||||
<HubPill tone="var(--success)">
|
||||
{byRecording ? <Radar size={11} /> : <CalendarCheck size={11} />} {visitedOn(item, s.language)}
|
||||
</HubPill>
|
||||
) : (
|
||||
when && (
|
||||
<HubPill>
|
||||
<CalendarClock size={11} /> {when}
|
||||
</HubPill>
|
||||
)
|
||||
)}
|
||||
{done && byRecording && (
|
||||
<HubIconButton label={s.t('dawarich.bucket.clearVisit')} onClick={() => void b.handleClearBucketVisit(item.id)}>
|
||||
<Undo2 size={14} />
|
||||
</HubIconButton>
|
||||
)}
|
||||
{item.lat && item.lng ? (
|
||||
<HubIconButton
|
||||
label={s.t('atlas.globe.showOnGlobe')}
|
||||
onClick={() => s.flyToPoint(Number(item.lng), Number(item.lat))}
|
||||
>
|
||||
<Navigation size={14} />
|
||||
</HubIconButton>
|
||||
) : null}
|
||||
<HubIconButton
|
||||
danger
|
||||
label={s.t('atlas.removeFromBucket')}
|
||||
onClick={() => void b.handleDeleteBucketItem(item.id)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</HubIconButton>
|
||||
</HubRow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Award, BarChart3, Mountain, Star, Trophy } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { segmentStyle } from '../../components/Map/mapControlShadow';
|
||||
import DawarichIcon from '../../components/shared/DawarichIcon';
|
||||
import { Tooltip } from '../../components/shared/Tooltip';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import type { AtlasGlobeState, AtlasHubTab } from './useAtlasGlobe';
|
||||
|
||||
export interface HubTabEntry {
|
||||
tab: AtlasHubTab;
|
||||
label: string;
|
||||
/** A symbol of the icon set, or a brand mark that takes the same size. */
|
||||
Icon: React.ComponentType<{ size?: number; strokeWidth?: number }>;
|
||||
}
|
||||
|
||||
/** The tabs of the Atlas hub in their order; the map rail and the hub's tab bar both read this. */
|
||||
export function useHubTabs(s: AtlasGlobeState): HubTabEntry[] {
|
||||
const toursEnabled = useAddonStore((st) => st.isEnabled('tours'));
|
||||
return [
|
||||
{ tab: 'overview', label: s.t('atlas.statsTab'), Icon: BarChart3 },
|
||||
{ tab: 'badges', label: s.t('atlas.globe.badges'), Icon: Award },
|
||||
{ tab: 'wishlist', label: s.t('atlas.bucketTab'), Icon: Star },
|
||||
...(s.dawarichEnabled ? [{ tab: 'dawarich' as const, label: s.t('dawarich.title'), Icon: DawarichMark }] : []),
|
||||
...(toursEnabled ? [{ tab: 'tours' as const, label: s.t('tours.mode.tours'), Icon: Mountain }] : []),
|
||||
...(s.compareEnabled ? [{ tab: 'travellers' as const, label: s.t('atlas.globe.travellers'), Icon: Trophy }] : []),
|
||||
];
|
||||
}
|
||||
|
||||
/** Dawarich's mark at an icon's size, round like the symbols beside it. */
|
||||
function DawarichMark({ size = 16 }: { size?: number }): React.ReactElement {
|
||||
return (
|
||||
<span className="flex flex-none overflow-hidden rounded-full" style={{ width: size + 2, height: size + 2 }}>
|
||||
<DawarichIcon size={size + 2} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One way into every tab of the hub, straight from the map: a column of glass
|
||||
* icon buttons. The badges button is the one a new badge flies into.
|
||||
*/
|
||||
export default function AtlasHubRail({ s, className }: { s: AtlasGlobeState; className: string }): React.ReactElement {
|
||||
const tabs = useHubTabs(s);
|
||||
return (
|
||||
<nav
|
||||
aria-label={s.t('atlas.globe.hub')}
|
||||
className={`ag-liquid pointer-events-auto absolute flex flex-col items-center rounded-full p-1 ${className}`}
|
||||
style={{ gap: 2 }}
|
||||
>
|
||||
{tabs.map(({ tab, label, Icon }) => {
|
||||
const on = s.passportOpen && s.passportTab === tab;
|
||||
return (
|
||||
<Tooltip key={tab} label={label} placement="left">
|
||||
<button
|
||||
type="button"
|
||||
className={on ? 'bg-accent text-accent-text' : 'text-content-secondary hover:text-content'}
|
||||
style={segmentStyle(on)}
|
||||
onClick={() => s.openPassport(tab)}
|
||||
aria-label={label}
|
||||
{...(tab === 'badges' ? { 'data-atlas-badges-btn': true } : {})}
|
||||
>
|
||||
<Icon size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { chromeFitPadding, chromePan } from './atlasChrome';
|
||||
|
||||
// FE-ATLAS-CHROME-001 onwards: the atlas camera beside the touch shell's rail and header.
|
||||
|
||||
describe('atlas chrome insets', () => {
|
||||
it('FE-ATLAS-CHROME-001: nothing covering the map leaves the opening view alone', () => {
|
||||
expect(chromePan(undefined, -80, false)).toBeNull();
|
||||
expect(chromePan({ top: 0, start: 0 }, 40, false)).toBeNull();
|
||||
// A tall window: the far north is already below the header.
|
||||
expect(chromePan({ top: 62, start: 0 }, 83, false)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ATLAS-CHROME-005: the north edge is measured only where there is chrome to clear', () => {
|
||||
const measure = vi.fn(() => -77);
|
||||
expect(chromePan(undefined, measure, false)).toBeNull();
|
||||
expect(measure).not.toHaveBeenCalled();
|
||||
expect(chromePan({ top: 62, start: 0 }, measure, false)).toEqual([0, -139]);
|
||||
expect(measure).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-ATLAS-CHROME-002: the world moves away from the rail, in either reading direction', () => {
|
||||
expect(chromePan({ top: 62, start: 100 }, 83, false)).toEqual([-50, 0]);
|
||||
expect(chromePan({ top: 62, start: 100 }, 83, true)).toEqual([50, 0]);
|
||||
});
|
||||
|
||||
it('FE-ATLAS-CHROME-004: on a short window the far north comes down from under the header, just as far as it needs', () => {
|
||||
expect(chromePan({ top: 62, start: 0 }, -77, false)).toEqual([0, -139]);
|
||||
});
|
||||
|
||||
it("FE-ATLAS-CHROME-003: a country is framed clear of the rail's side and the header", () => {
|
||||
expect(chromeFitPadding({ top: 62, start: 100 }, false)).toEqual({
|
||||
paddingTopLeft: [124, 86],
|
||||
paddingBottomRight: [24, 24],
|
||||
});
|
||||
expect(chromeFitPadding({ top: 62, start: 100 }, true)).toEqual({
|
||||
paddingTopLeft: [24, 86],
|
||||
paddingBottomRight: [124, 24],
|
||||
});
|
||||
expect(chromeFitPadding(undefined, false)).toEqual({ paddingTopLeft: [24, 24], paddingBottomRight: [24, 24] });
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* How much of the atlas map's edges a screen's own chrome covers, in px: the
|
||||
* touch shell's rail along the leading edge, its floating header along the top.
|
||||
* The phone screen measures them (MAtlas), the camera keeps clear of them.
|
||||
*/
|
||||
export interface AtlasChromeInsets {
|
||||
top: number;
|
||||
start: number;
|
||||
}
|
||||
|
||||
/** Arabic runs right to left, and the rail stands on the right then. */
|
||||
function documentRtl(): boolean {
|
||||
return typeof document !== 'undefined' && document.documentElement.dir === 'rtl';
|
||||
}
|
||||
|
||||
/** The northern edge of the inhabited world, which the opening view keeps below the header. */
|
||||
export const NORTH_EDGE_LAT = 75;
|
||||
|
||||
/**
|
||||
* The pan that fits the opening view to what the chrome leaves free, or null
|
||||
* when there is nothing to move. Sideways the centre moves into the middle of
|
||||
* the map beside the rail. Upwards the world moves down only as far as its
|
||||
* inhabited top (NORTH_EDGE_LAT, at `northEdgeY` in the map's own pixels) needs
|
||||
* to clear the header: a tall window shows it below the header anyway, a phone
|
||||
* had the stars of the far north under it. Leaflet pans the camera, so the
|
||||
* numbers point the other way from the world's move. `northEdgeY` may be a
|
||||
* measurement, taken only where there is chrome: the desktop atlas has none.
|
||||
*/
|
||||
export function chromePan(
|
||||
insets: AtlasChromeInsets | undefined,
|
||||
northEdgeY: number | (() => number),
|
||||
rtl = documentRtl()
|
||||
): [number, number] | null {
|
||||
if (!insets) return null;
|
||||
const x = insets.start ? (rtl ? 1 : -1) * (insets.start / 2) : 0;
|
||||
const y = Math.min(0, (typeof northEdgeY === 'function' ? northEdgeY() : northEdgeY) - insets.top);
|
||||
return x || y ? [x, y] : null;
|
||||
}
|
||||
|
||||
/** The padding a country is framed with, wider on the rail's side and under the header. */
|
||||
export function chromeFitPadding(
|
||||
insets: AtlasChromeInsets | undefined,
|
||||
rtl = documentRtl()
|
||||
): { paddingTopLeft: [number, number]; paddingBottomRight: [number, number] } {
|
||||
const start = insets?.start ?? 0;
|
||||
return {
|
||||
paddingTopLeft: [24 + (rtl ? 0 : start), 24 + (insets?.top ?? 0)],
|
||||
paddingBottomRight: [24 + (rtl ? start : 0), 24],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { GlobeEngine } from '../../components/AtlasGlobe/GlobeEngine';
|
||||
import { hexToRgb, rgbToBytes } from '../../components/AtlasGlobe/globeTheme';
|
||||
import type { AtlasRegionRow } from '../../repo/atlasRepo';
|
||||
import {
|
||||
countryColor,
|
||||
countryStatus,
|
||||
normalizeRegionName,
|
||||
wishlistRegionCodes,
|
||||
type AtlasData,
|
||||
type BucketItem,
|
||||
} from './atlasModel';
|
||||
|
||||
/**
|
||||
* What the globe paints, worked out from the Atlas data. Pure apart from the
|
||||
* engine writes at the end, so the rules (planned shows only when switched on,
|
||||
* a wished-for region hatches just that region) stay in one readable place.
|
||||
*/
|
||||
|
||||
// Map paint, not UI surfaces: planned and wishlist keep their classic colours.
|
||||
const PLANNED = '#818cf8'; // theme-lint-disable: map paint for planned countries, as the classic Atlas drew them
|
||||
const WISH = '#fbbf24'; // theme-lint-disable: map paint for the wishlist hatch, as the classic Atlas drew it
|
||||
|
||||
export type GlobeColorMode = 'country' | 'status' | 'year';
|
||||
|
||||
export interface GlobePaintInput {
|
||||
data: AtlasData | null;
|
||||
regions: Record<string, AtlasRegionRow[]>;
|
||||
bucket: BucketItem[];
|
||||
showPlanned: boolean;
|
||||
colorMode: GlobeColorMode;
|
||||
/** Only countries first visited up to this year show (time scrubber); null shows all. */
|
||||
year: number | null;
|
||||
/** Another traveller's visited countries to lay over the user's own; null for none. */
|
||||
compare?: string[] | null;
|
||||
/** With compare: show only the countries neither has been to. */
|
||||
gaps?: boolean;
|
||||
/** Country tints from plugin layers (atlasLayerProvider), by ISO A2, as hex. */
|
||||
pluginTint?: Map<string, string>;
|
||||
}
|
||||
|
||||
/** The plugin tones, the same palette the classic Atlas and the plugin map markers use. */
|
||||
export const PLUGIN_TONES: Record<string, string> = {
|
||||
default: '#818cf8', // theme-lint-disable: plugin layer map paint
|
||||
success: '#10b981', // theme-lint-disable: plugin layer map paint
|
||||
warn: '#f59e0b', // theme-lint-disable: plugin layer map paint
|
||||
danger: '#ef4444', // theme-lint-disable: plugin layer map paint
|
||||
};
|
||||
|
||||
// Overlay paint: shared countries mint, theirs only violet hatch, yours only soft blue.
|
||||
const BOTH = '#2dd4bf'; // theme-lint-disable: comparison map paint
|
||||
const THEIRS = '#a78bfa'; // theme-lint-disable: comparison map paint
|
||||
const MINE = '#60a5fa'; // theme-lint-disable: comparison map paint
|
||||
|
||||
/** The overlay's three colours, for the legends that explain them. */
|
||||
export const COMPARE_COLORS = { both: BOTH, theirs: THEIRS, mine: MINE };
|
||||
|
||||
function paintCompare(engine: GlobeEngine, input: GlobePaintInput, theirs: Set<string>): void {
|
||||
const m = engine.manifest;
|
||||
if (!m) return;
|
||||
const r = engine.renderer;
|
||||
const mine = new Set((input.data?.countries ?? []).filter((c) => countryStatus(c) === 'visited').map((c) => c.code));
|
||||
m.countries.forEach((c, i) => {
|
||||
const a2 = c.a2;
|
||||
const a = !!a2 && mine.has(a2);
|
||||
const b = !!a2 && theirs.has(a2);
|
||||
if (input.gaps) {
|
||||
if (a2 && !a && !b) r.setStatus(i, [...rgbToBytes(hexToRgb(WISH)), 70]);
|
||||
else r.setStatus(i, [0, 0, 0, 0]);
|
||||
} else if (a && b) r.setStatus(i, [...rgbToBytes(hexToRgb(BOTH)), 240]);
|
||||
else if (b) r.setStatus(i, [...rgbToBytes(hexToRgb(THEIRS)), 60], [255, 0, 0, 0]);
|
||||
else if (a) r.setStatus(i, [...rgbToBytes(hexToRgb(MINE)), 150]);
|
||||
else r.setStatus(i, [0, 0, 0, 0]);
|
||||
});
|
||||
for (const [a2, idx] of engine.regionIndex) {
|
||||
const base = engine.regionBase.get(a2);
|
||||
if (base !== undefined) r.clearStatus(base, base + idx.features.length);
|
||||
}
|
||||
}
|
||||
|
||||
/** Counts for the comparison banner. */
|
||||
export function compareCounts(
|
||||
mine: string[],
|
||||
theirs: string[]
|
||||
): { both: number; theirsOnly: number; mineOnly: number } {
|
||||
const a = new Set(mine);
|
||||
const b = new Set(theirs);
|
||||
let both = 0;
|
||||
for (const c of a) if (b.has(c)) both++;
|
||||
return { both, theirsOnly: b.size - both, mineOnly: a.size - both };
|
||||
}
|
||||
|
||||
function lighten(hex: string, f: number): [number, number, 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'; // theme-lint-disable: map paint for "colour by status"
|
||||
|
||||
function yearColor(year: number, first: number, last: number): string {
|
||||
const p = last > first ? (year - first) / (last - first) : 1;
|
||||
const hue = 200 + p * 120;
|
||||
return hslHex(hue, 0.72, 0.6);
|
||||
}
|
||||
|
||||
function hslHex(h: number, s: number, l: number): string {
|
||||
const k = (n: number) => (n + h / 30) % 12;
|
||||
const a = s * Math.min(l, 1 - l);
|
||||
const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
|
||||
const to = (x: number) =>
|
||||
Math.round(x * 255)
|
||||
.toString(16)
|
||||
.padStart(2, '0');
|
||||
return `#${to(f(0))}${to(f(8))}${to(f(4))}`;
|
||||
}
|
||||
|
||||
export function paintGlobe(engine: GlobeEngine, input: GlobePaintInput): void {
|
||||
const m = engine.manifest;
|
||||
if (!m) return;
|
||||
if (input.compare) {
|
||||
paintCompare(engine, input, new Set(input.compare));
|
||||
return;
|
||||
}
|
||||
const r = engine.renderer;
|
||||
const byCode = new Map((input.data?.countries ?? []).map((c) => [c.code, c]));
|
||||
const visitYears = (input.data?.countries ?? [])
|
||||
.map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : NaN))
|
||||
.filter((y) => !Number.isNaN(y));
|
||||
const firstYear = visitYears.length ? Math.min(...visitYears) : new Date().getFullYear();
|
||||
const lastYear = visitYears.length ? Math.max(...visitYears) : firstYear;
|
||||
const order = [...(input.data?.countries ?? [])]
|
||||
.filter((c) => countryStatus(c) === 'visited')
|
||||
.sort((a, b) => (a.firstVisit ?? '9999').localeCompare(b.firstVisit ?? '9999'))
|
||||
.map((c) => c.code);
|
||||
const wishCountries = new Set(
|
||||
input.bucket.filter((b) => !b.region_code && b.country_code).map((b) => b.country_code as string)
|
||||
);
|
||||
const wishRegions = wishlistRegionCodes(input.bucket);
|
||||
|
||||
m.countries.forEach((c, i) => {
|
||||
const a2 = c.a2;
|
||||
const hasRegions = a2 ? engine.renderer.hasRegion(`${a2}:r0`) || engine.renderer.hasRegion(`${a2}:r1`) : false;
|
||||
const reveal = a2 ? Math.round((Math.max(0, order.indexOf(a2)) / Math.max(1, order.length)) * 255) : 0;
|
||||
const row = a2 ? byCode.get(a2) : undefined;
|
||||
const status = row ? countryStatus(row) : null;
|
||||
const year = row?.firstVisit ? Number(row.firstVisit.slice(0, 4)) : null;
|
||||
const inYear = input.year === null || (year !== null && year <= input.year);
|
||||
const fx: [number, number, number, number] = [0, reveal, hasRegions ? 255 : 0, 0];
|
||||
if (status === 'visited' && inYear) {
|
||||
const hex =
|
||||
input.colorMode === 'status'
|
||||
? STATUS_VISITED
|
||||
: input.colorMode === 'year' && year
|
||||
? yearColor(year, firstYear, lastYear)
|
||||
: countryColor(c.a3);
|
||||
r.setStatus(i, [...rgbToBytes(hexToRgb(hex)), 235], fx);
|
||||
} else if (status && status !== 'visited' && input.showPlanned) {
|
||||
r.setStatus(i, [...rgbToBytes(hexToRgb(PLANNED)), 95], fx);
|
||||
} else if (a2 && input.pluginTint?.has(a2)) {
|
||||
r.setStatus(i, [...rgbToBytes(hexToRgb(input.pluginTint.get(a2) as string)), 90], fx);
|
||||
} else if (a2 && wishCountries.has(a2)) {
|
||||
r.setStatus(i, [...rgbToBytes(hexToRgb(WISH)), 0], [255, reveal, fx[2], 0]);
|
||||
} else {
|
||||
r.setStatus(i, [0, 0, 0, 0], fx);
|
||||
}
|
||||
});
|
||||
|
||||
for (const [a2, idx] of engine.regionIndex) {
|
||||
const base = engine.regionBase.get(a2);
|
||||
if (base === undefined) continue;
|
||||
const rows = input.regions[a2] ?? [];
|
||||
const country = m.countries.find((c) => c.a2 === a2);
|
||||
const countryHex = country ? countryColor(country.a3) : STATUS_VISITED;
|
||||
const codes = new Map<string, AtlasRegionRow>();
|
||||
const names = new Map<string, AtlasRegionRow>();
|
||||
for (const row of rows) {
|
||||
codes.set(row.code, row);
|
||||
names.set(normalizeRegionName(row.name), row);
|
||||
}
|
||||
idx.features.forEach((f, j) => {
|
||||
const row =
|
||||
(f.code ? codes.get(f.code) : undefined) ??
|
||||
names.get(normalizeRegionName(f.name ?? '')) ??
|
||||
(f.nameEn ? names.get(normalizeRegionName(f.nameEn)) : undefined);
|
||||
const visited = row && (row.status ?? 'visited') === 'visited';
|
||||
const planned = row && !visited && input.showPlanned;
|
||||
if (visited) r.setStatus(base + j, [...lighten(countryHex, 0.18), 245]);
|
||||
else if (planned) r.setStatus(base + j, [...rgbToBytes(hexToRgb(PLANNED)), 110]);
|
||||
else if (f.code && wishRegions.has(f.code))
|
||||
r.setStatus(base + j, [...rgbToBytes(hexToRgb(WISH)), 0], [255, 0, 0, 0]);
|
||||
else r.setStatus(base + j, [0, 0, 0, 0]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** How many of a country's counted regions are visited, for "32 of 50". */
|
||||
export function regionProgress(
|
||||
engine: GlobeEngine,
|
||||
a2: string,
|
||||
rows: AtlasRegionRow[]
|
||||
): { visited: number; total: number } | null {
|
||||
const idx = engine.regionIndex.get(a2);
|
||||
const entry = engine.manifest?.regions[a2];
|
||||
if (!entry) return null;
|
||||
const total = entry.counted;
|
||||
if (!idx) {
|
||||
const v = rows.filter((r) => (r.status ?? 'visited') === 'visited').length;
|
||||
return { visited: Math.min(v, total), total };
|
||||
}
|
||||
const codes = new Set(rows.filter((r) => (r.status ?? 'visited') === 'visited').map((r) => r.code));
|
||||
const names = new Set(
|
||||
rows.filter((r) => (r.status ?? 'visited') === 'visited').map((r) => normalizeRegionName(r.name))
|
||||
);
|
||||
let visited = 0;
|
||||
for (const f of idx.features) {
|
||||
if (!f.counted) continue;
|
||||
if (
|
||||
(f.code && codes.has(f.code)) ||
|
||||
names.has(normalizeRegionName(f.name ?? '')) ||
|
||||
(f.nameEn && names.has(normalizeRegionName(f.nameEn)))
|
||||
)
|
||||
visited++;
|
||||
}
|
||||
return { visited, total };
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import { ChevronRight, type LucideIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import DawarichIcon from '../../components/shared/DawarichIcon';
|
||||
import { fs } from '../../components/shared/DialogShell';
|
||||
|
||||
/**
|
||||
* The building blocks every tab of the Atlas hub is made of, so Statistics,
|
||||
* Badges, Wishlist, Lists, Tours and Travellers read as one piece: a card, a
|
||||
* hero figure with the accent glow, tiles set into a card, section heads with
|
||||
* a count, rows set into a card, and one empty state.
|
||||
*/
|
||||
|
||||
export const HUB_CARD = 'rounded-[18px] border border-edge-faint bg-surface-card';
|
||||
export const HUB_INSET = 'rounded-[13px] border border-edge-faint bg-surface-tertiary';
|
||||
export const HUB_FIELD =
|
||||
'w-full rounded-[11px] border border-edge bg-surface-secondary px-3 py-2 text-content outline-none placeholder:text-content-faint focus:border-content-muted';
|
||||
|
||||
/** The soft accent light in the corner of a hero card. */
|
||||
export function HubGlow({ color = 'var(--accent)' }: { color?: string }): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -end-16 -top-16 size-48 rounded-full opacity-60"
|
||||
style={{ background: `radial-gradient(circle, color-mix(in srgb, ${color} 20%, transparent), transparent 70%)` }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** One large figure with its unit, and whatever explains it underneath. */
|
||||
export function HubHero({
|
||||
value,
|
||||
unit,
|
||||
glow,
|
||||
className = '',
|
||||
children,
|
||||
}: {
|
||||
value: React.ReactNode;
|
||||
unit?: React.ReactNode;
|
||||
glow?: string;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className={`${HUB_CARD} relative overflow-hidden px-5 py-5 ${className}`}>
|
||||
<HubGlow color={glow} />
|
||||
<div className="relative flex items-end gap-2">
|
||||
<span className="font-bold tabular-nums leading-none tracking-tight text-content" style={fs(56, 'title')}>
|
||||
{value}
|
||||
</span>
|
||||
{unit && (
|
||||
<span className="mb-1.5 font-medium text-content-secondary" style={fs(16, 'subtitle')}>
|
||||
{unit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{children && <div className="relative mt-4">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A thin progress bar in the accent (or a list's own colour). */
|
||||
export function HubBar({ share, color }: { share: number; color?: string }): React.ReactElement {
|
||||
return (
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-surface-tertiary">
|
||||
<div
|
||||
className={`h-full rounded-full transition-[width] duration-700 ${color ? '' : 'bg-accent'}`}
|
||||
style={{ width: `${Math.max(0, Math.min(1, share)) * 100}%`, background: color }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export interface HubTileData {
|
||||
Icon: LucideIcon;
|
||||
value: React.ReactNode;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** Small figures set into one card: the "badge in a badge" of the Atlas. */
|
||||
export function HubTiles({
|
||||
tiles,
|
||||
cols = 'grid-cols-2 sm:grid-cols-4',
|
||||
className = '',
|
||||
}: {
|
||||
tiles: HubTileData[];
|
||||
cols?: string;
|
||||
className?: string;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className={`${HUB_CARD} grid gap-1.5 p-1.5 ${cols} ${className}`}>
|
||||
{tiles.map(({ Icon, value, label }) => (
|
||||
<div key={label} className={`${HUB_INSET} flex items-center gap-3 px-3 py-2.5`}>
|
||||
<Icon size={16} strokeWidth={1.9} className="flex-none text-content-muted" />
|
||||
<span className="min-w-0">
|
||||
<span className="block font-semibold tabular-nums leading-tight text-content" style={fs(17, 'subtitle')}>
|
||||
{value}
|
||||
</span>
|
||||
<span className="block truncate text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{label}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A section with its title, a count on the right and an optional action. */
|
||||
export function HubSection({
|
||||
title,
|
||||
meta,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
meta?: React.ReactNode;
|
||||
action?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<section className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-edge-faint pb-2">
|
||||
<h3 className="m-0 font-semibold text-content" style={fs(14.5, 'body')}>
|
||||
{title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
{meta != null && (
|
||||
<span className="tabular-nums text-content-muted" style={fs(12, 'caption')}>
|
||||
{meta}
|
||||
</span>
|
||||
)}
|
||||
{action}
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Rows set into one card, each on its own inset. */
|
||||
export function HubRows({ children }: { children: React.ReactNode }): React.ReactElement {
|
||||
return <ul className={`${HUB_CARD} m-0 flex list-none flex-col gap-1.5 p-1.5`}>{children}</ul>;
|
||||
}
|
||||
|
||||
export function HubRow({
|
||||
children,
|
||||
muted = false,
|
||||
className = '',
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
muted?: boolean;
|
||||
className?: string;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<li className={`${HUB_INSET} group flex items-center gap-3 px-3 py-2.5 ${muted ? 'opacity-70' : ''} ${className}`}>
|
||||
{children}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** A round icon button for row actions. */
|
||||
export function HubIconButton({
|
||||
label,
|
||||
onClick,
|
||||
danger = false,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
danger?: boolean;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={`grid size-8 flex-none place-items-center rounded-full text-content-muted transition-colors hover:bg-surface-card ${danger ? 'hover:text-danger' : 'hover:text-content'}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The small text pill rows carry (a month, a country). */
|
||||
export function HubPill({ children, tone }: { children: React.ReactNode; tone?: string }): React.ReactElement {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full border border-edge-faint bg-surface-card px-2 py-0.5 text-content-secondary"
|
||||
style={{ ...fs(11, 'caption'), color: tone }}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** One empty state for every tab: an icon in a soft disc, what is missing and what to do. */
|
||||
export function HubEmpty({
|
||||
Icon,
|
||||
title,
|
||||
hint,
|
||||
action,
|
||||
}: {
|
||||
Icon: LucideIcon;
|
||||
title: string;
|
||||
hint?: string;
|
||||
action?: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div className={`${HUB_CARD} relative flex flex-col items-center gap-2 overflow-hidden px-6 py-9 text-center`}>
|
||||
<HubGlow />
|
||||
<span className="relative grid size-12 place-items-center rounded-full bg-surface-tertiary text-content-secondary">
|
||||
<Icon size={20} strokeWidth={1.8} />
|
||||
</span>
|
||||
<div className="relative font-semibold text-content" style={fs(14.5, 'body')}>
|
||||
{title}
|
||||
</div>
|
||||
{hint && (
|
||||
<div className="relative max-w-sm text-content-muted" style={fs(12.5, 'caption')}>
|
||||
{hint}
|
||||
</div>
|
||||
)}
|
||||
{action && <div className="relative mt-2">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A way out to Dawarich (addon): its logo, what it does here, and the arrow. */
|
||||
export function HubDawarichEntry({
|
||||
title,
|
||||
hint,
|
||||
onClick,
|
||||
}: {
|
||||
title: string;
|
||||
hint: string;
|
||||
onClick: () => void;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`${HUB_CARD} group flex items-center gap-3.5 px-4 py-3 text-start transition-colors hover:bg-surface-hover`}
|
||||
>
|
||||
<span className="flex size-9 flex-none overflow-hidden rounded-full">
|
||||
<DawarichIcon size={36} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-semibold text-content" style={fs(13.5, 'body')}>
|
||||
{title}
|
||||
</span>
|
||||
<span className="block truncate text-content-muted" style={fs(11.5, 'caption')}>
|
||||
{hint}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronRight
|
||||
size={16}
|
||||
className="flex-none text-content-faint transition-transform group-hover:translate-x-0.5"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The one primary action of a tab, in the accent. */
|
||||
export function HubPrimary({
|
||||
onClick,
|
||||
disabled,
|
||||
Icon,
|
||||
children,
|
||||
type = 'button',
|
||||
}: {
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
Icon?: LucideIcon;
|
||||
children: React.ReactNode;
|
||||
type?: 'button' | 'submit';
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="inline-flex items-center justify-center gap-1.5 rounded-[11px] bg-accent px-3.5 py-2 font-medium text-accent-text transition-opacity hover:opacity-90 disabled:opacity-40"
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{Icon && <Icon size={14} strokeWidth={2.2} />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function HubGhost({
|
||||
onClick,
|
||||
Icon,
|
||||
children,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
Icon?: LucideIcon;
|
||||
children: React.ReactNode;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 font-medium text-content-secondary transition-colors hover:bg-surface-hover hover:text-content"
|
||||
style={fs(12.5, 'caption')}
|
||||
>
|
||||
{Icon && <Icon size={14} />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { getIntlLanguage, type Badge } from '@trek/shared';
|
||||
import { A2_TO_A3, type AtlasData, type BucketItem } from './atlasModel';
|
||||
|
||||
/**
|
||||
* What the Atlas hub derives from its data, once for both shells: the desktop
|
||||
* tabs and the phone sheet render this, each in its own markup.
|
||||
*/
|
||||
|
||||
export const CONTINENTS: Array<[string, string]> = [
|
||||
['Europe', 'atlas.europe'],
|
||||
['Asia', 'atlas.asia'],
|
||||
['North America', 'atlas.northAmerica'],
|
||||
['South America', 'atlas.southAmerica'],
|
||||
['Africa', 'atlas.africa'],
|
||||
['Oceania', 'atlas.oceania'],
|
||||
['Antarctica', 'atlas.antarctica'],
|
||||
];
|
||||
|
||||
/** Sovereign states the world share is counted against. */
|
||||
export const WORLD_COUNTRIES = 195;
|
||||
|
||||
/** The continents with how many countries each holds; Antarctica only once it has one. */
|
||||
export function continentCounts(data: AtlasData | null): Array<{ name: string; key: string; n: number }> {
|
||||
return CONTINENTS.map(([name, key]) => ({ name, key, n: data?.continents?.[name] ?? 0 })).filter(
|
||||
(c) => c.name !== 'Antarctica' || c.n > 0
|
||||
);
|
||||
}
|
||||
|
||||
/** 12400 as "12k", smaller numbers in the reader's grouping. */
|
||||
export function formatNum(n: number): string {
|
||||
return n >= 10000 ? `${Math.round(n / 1000)}k` : n.toLocaleString();
|
||||
}
|
||||
|
||||
/** The flag code of a wish: its country as ISO A2, also when it was stored as A3. */
|
||||
export function wishCountry(code: string | null | undefined): string | null {
|
||||
if (!code) return null;
|
||||
if (code.length === 2) return code.toUpperCase();
|
||||
return Object.entries(A2_TO_A3).find(([, a3]) => a3 === code.toUpperCase())?.[0] ?? null;
|
||||
}
|
||||
|
||||
/** A label maker for target dates: "Apr 2027" for a month, "2027" for a year alone. */
|
||||
export function whenLabeller(language: string): (date: string | null | undefined) => string | null {
|
||||
const lang = getIntlLanguage(language);
|
||||
return (date) => {
|
||||
if (!date) return null;
|
||||
const m = /^(\d{4})(?:-(\d{2}))?/.exec(date);
|
||||
if (!m) return null;
|
||||
if (!m[2]) return m[1] ?? null;
|
||||
return new Date(Number(m[1]), Number(m[2]) - 1).toLocaleString(lang, { month: 'short', year: 'numeric' });
|
||||
};
|
||||
}
|
||||
|
||||
/** The day a wish came true, in the reader's language. */
|
||||
export function visitedOn(item: BucketItem, language: string): string | null {
|
||||
if (!item.visited_at) return null;
|
||||
return new Date(item.visited_at.replace(' ', 'T')).toLocaleDateString(getIntlLanguage(language), {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
/** The wishes split for the hub: still open (soonest first), reached (latest first), and the headline figures. */
|
||||
export function splitWishes(items: BucketItem[]) {
|
||||
const open = items
|
||||
.filter((i) => !i.visited_at)
|
||||
.sort((x, y) => (x.target_date ?? '9999').localeCompare(y.target_date ?? '9999'));
|
||||
const reached = items
|
||||
.filter((i) => i.visited_at)
|
||||
.sort((x, y) => (y.visited_at ?? '').localeCompare(x.visited_at ?? ''));
|
||||
const countries = new Set(items.map((i) => wishCountry(i.country_code)).filter(Boolean)).size;
|
||||
const nextDated = open.find((i) => i.target_date) ?? null;
|
||||
return { open, reached, countries, nextDated };
|
||||
}
|
||||
|
||||
/** The stages of the series a badge belongs to (5, 10, 25 countries ...), smallest first. */
|
||||
export function badgeLadder(badges: Badge[], b: Badge): Badge[] {
|
||||
return badges
|
||||
.filter((x) => x.category === b.category && x.motif === b.motif && x.motif !== 'region')
|
||||
.sort((x, y) => x.target - y.target);
|
||||
}
|
||||
|
||||
/** How many of the instance's travellers hold a badge, the reader included. */
|
||||
export function badgeHolders(
|
||||
people: Array<{ badges: Array<{ id: string }> }> | null,
|
||||
b: Badge
|
||||
): { holders: number; of: number } | null {
|
||||
if (!people) return null;
|
||||
return {
|
||||
holders: people.filter((p) => p.badges.some((x) => x.id === b.id)).length + (b.earned ? 1 : 0),
|
||||
of: people.length + 1,
|
||||
};
|
||||
}
|
||||
@@ -99,14 +99,6 @@ export function withCountryMarkedVisited(prev: AtlasData, code: string): AtlasDa
|
||||
}
|
||||
}
|
||||
|
||||
/** A geocoded hit in the atlas search box (#1115), before it is resolved to a region. */
|
||||
export interface AtlasPlaceHit {
|
||||
name: string
|
||||
address: string | null
|
||||
lat: number
|
||||
lng: number
|
||||
}
|
||||
|
||||
export interface BucketItem {
|
||||
id: number
|
||||
name: string
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createWishlistPattern, hexToRgba, svgWishlistFill } from './atlasWishlistFill';
|
||||
|
||||
describe('hexToRgba', () => {
|
||||
it('turns a hex colour into an rgba string with the given alpha', () => {
|
||||
expect(hexToRgba('#ff8000', 0.2)).toBe('rgba(255,128,0,0.2)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('svgWishlistFill', () => {
|
||||
afterEach(() => {
|
||||
document.getElementById('trek-wish-patterns')?.remove();
|
||||
});
|
||||
|
||||
it('references a pattern it adds once to a hidden defs block', () => {
|
||||
expect(svgWishlistFill('#123456', false)).toBe('url(#trek-wish-123456-l)');
|
||||
expect(svgWishlistFill('#123456', false)).toBe('url(#trek-wish-123456-l)');
|
||||
const host = document.getElementById('trek-wish-patterns');
|
||||
expect(host?.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(host?.querySelectorAll('pattern')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps one pattern per theme, with a lighter tint in the dark theme', () => {
|
||||
svgWishlistFill('#123456', false);
|
||||
expect(svgWishlistFill('#123456', true)).toBe('url(#trek-wish-123456-d)');
|
||||
const dark = document.getElementById('trek-wish-123456-d');
|
||||
expect(dark?.querySelector('rect')?.getAttribute('fill')).toBe('rgba(18,52,86,0.14)');
|
||||
expect(document.querySelectorAll('#trek-wish-patterns pattern')).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createWishlistPattern', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns null where the canvas has no 2D context', () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
expect(createWishlistPattern('#123456', false)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when building the pattern throws', () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => {
|
||||
throw new Error('no canvas');
|
||||
});
|
||||
expect(createWishlistPattern('#123456', false)).toBeNull();
|
||||
});
|
||||
|
||||
it('paints the tint and the stripes, then repeats them', () => {
|
||||
const pattern = {} as CanvasPattern;
|
||||
const ctx = {
|
||||
fillRect: vi.fn(),
|
||||
beginPath: vi.fn(),
|
||||
moveTo: vi.fn(),
|
||||
lineTo: vi.fn(),
|
||||
stroke: vi.fn(),
|
||||
createPattern: vi.fn(() => pattern),
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx as never);
|
||||
expect(createWishlistPattern('#123456', true)).toBe(pattern);
|
||||
expect(ctx.fillStyle).toBe('rgba(18,52,86,0.14)');
|
||||
expect(ctx.strokeStyle).toBe('#123456');
|
||||
expect(ctx.createPattern).toHaveBeenCalledWith(expect.any(HTMLCanvasElement), 'repeat');
|
||||
});
|
||||
});
|
||||
@@ -1,85 +0,0 @@
|
||||
/**
|
||||
* The striped fill that marks a wishlist country or region on the atlas map. It
|
||||
* lives apart from useAtlas because it only touches the DOM and a canvas, never
|
||||
* the hook's state.
|
||||
*/
|
||||
|
||||
export function hexToRgba(hex: string, alpha: number): string {
|
||||
const clean = hex.replace('#', '');
|
||||
const r = Number.parseInt(clean.substring(0, 2), 16);
|
||||
const g = Number.parseInt(clean.substring(2, 4), 16);
|
||||
const b = Number.parseInt(clean.substring(4, 6), 16);
|
||||
return `rgba(${r},${g},${b},${alpha})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same diagonal stripes for the region layer, which draws with SVG where a
|
||||
* CanvasPattern means nothing (#1901): an SVG pattern kept in one hidden defs
|
||||
* block, referenced by `url(#id)`. Built once per colour and theme.
|
||||
*/
|
||||
export function svgWishlistFill(color: string, dark: boolean): string {
|
||||
const id = `trek-wish-${color.replace('#', '')}-${dark ? 'd' : 'l'}`;
|
||||
if (typeof document === 'undefined') return color;
|
||||
if (!document.getElementById(id)) {
|
||||
const ns = 'http://www.w3.org/2000/svg';
|
||||
let host: Element | null = document.getElementById('trek-wish-patterns');
|
||||
if (!host) {
|
||||
host = document.createElementNS(ns, 'svg');
|
||||
host.id = 'trek-wish-patterns';
|
||||
host.setAttribute('width', '0');
|
||||
host.setAttribute('height', '0');
|
||||
host.setAttribute('aria-hidden', 'true');
|
||||
host.setAttribute('style', 'position:absolute');
|
||||
host.appendChild(document.createElementNS(ns, 'defs'));
|
||||
document.body.appendChild(host);
|
||||
}
|
||||
const pattern = document.createElementNS(ns, 'pattern');
|
||||
pattern.id = id;
|
||||
pattern.setAttribute('patternUnits', 'userSpaceOnUse');
|
||||
pattern.setAttribute('width', '8');
|
||||
pattern.setAttribute('height', '8');
|
||||
const bg = document.createElementNS(ns, 'rect');
|
||||
bg.setAttribute('width', '8');
|
||||
bg.setAttribute('height', '8');
|
||||
bg.setAttribute('fill', hexToRgba(color, dark ? 0.14 : 0.2));
|
||||
const stripes = document.createElementNS(ns, 'path');
|
||||
stripes.setAttribute('d', 'M-1,9 L9,-1 M-1,1 L1,-1 M7,9 L9,7');
|
||||
stripes.setAttribute('stroke', color);
|
||||
stripes.setAttribute('stroke-width', '2');
|
||||
pattern.append(bg, stripes);
|
||||
host.firstElementChild!.appendChild(pattern);
|
||||
}
|
||||
return `url(#${id})`;
|
||||
}
|
||||
|
||||
// Diagonal-stripe CanvasPattern for the wishlist country fill, in that
|
||||
// country's own "if visited" color — built once per render pass so it
|
||||
// survives Leaflet's Canvas renderer (ctx.fillStyle accepts a CanvasPattern
|
||||
// object same as a color string). Returns null in environments without a
|
||||
// real 2D canvas context (e.g. jsdom in tests), so callers must fall back to
|
||||
// a plain color.
|
||||
export function createWishlistPattern(color: string, dark: boolean): CanvasPattern | null {
|
||||
try {
|
||||
const size = 8;
|
||||
const patternCanvas = document.createElement('canvas');
|
||||
patternCanvas.width = size;
|
||||
patternCanvas.height = size;
|
||||
const ctx = patternCanvas.getContext('2d');
|
||||
if (!ctx) return null;
|
||||
ctx.fillStyle = hexToRgba(color, dark ? 0.14 : 0.2);
|
||||
ctx.fillRect(0, 0, size, size);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-1, size + 1);
|
||||
ctx.lineTo(size + 1, -1);
|
||||
ctx.moveTo(-1, 1);
|
||||
ctx.lineTo(1, -1);
|
||||
ctx.moveTo(size - 1, size + 1);
|
||||
ctx.lineTo(size + 1, size - 1);
|
||||
ctx.stroke();
|
||||
return ctx.createPattern(patternCanvas, 'repeat');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,169 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { atlasBucketRepo, type BucketPlaceHit } from '../../repo/atlasBucketRepo';
|
||||
import { atlasRepo } from '../../repo/atlasRepo';
|
||||
import { getApiErrorMessage, type TranslationFn } from '../../types';
|
||||
import { findBucketDuplicate, isBucketDuplicateError, type BucketItem } from './atlasModel';
|
||||
|
||||
interface BucketForm {
|
||||
name: string;
|
||||
notes: string;
|
||||
lat: string;
|
||||
lng: string;
|
||||
target_date: string;
|
||||
/** The picked place's address, shown in the form only. */
|
||||
address?: string;
|
||||
}
|
||||
|
||||
const EMPTY_FORM: BucketForm = { name: '', notes: '', lat: '', lng: '', target_date: '' };
|
||||
|
||||
/** A wish's target: a month of a year, or a year alone; nothing without a year. */
|
||||
function bucketTarget(month: number, year: number): string | null {
|
||||
if (year <= 0) return null;
|
||||
return month > 0 ? `${year}-${String(month).padStart(2, '0')}` : String(year);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bucket list of the Atlas: the items, the add form with its place search
|
||||
* and target month, deleting, and undoing a wish a Dawarich recording ticked
|
||||
* off. Shared by the classic Atlas, its phone sheet and the globe.
|
||||
*/
|
||||
export function useAtlasBucket({ t, placeLang }: { t: TranslationFn; placeLang: string }) {
|
||||
const toast = useToast();
|
||||
const [bucketList, setBucketList] = useState<BucketItem[]>([]);
|
||||
const [showBucketAdd, setShowBucketAdd] = useState(false);
|
||||
const [bucketForm, setBucketForm] = useState<BucketForm>(EMPTY_FORM);
|
||||
const [bucketSearch, setBucketSearch] = useState('');
|
||||
const [bucketSearchResults, setBucketSearchResults] = useState<BucketPlaceHit[]>([]);
|
||||
const [bucketSearching, setBucketSearching] = useState(false);
|
||||
const [bucketPoiMonth, setBucketPoiMonth] = useState(0);
|
||||
const [bucketPoiYear, setBucketPoiYear] = useState(0);
|
||||
|
||||
/**
|
||||
* Undo a wish that a recording ticked off. The row is kept; only the visit is
|
||||
* cleared, since the wishlist is the one list here somebody curates by hand.
|
||||
*/
|
||||
const handleClearBucketVisit = useCallback(
|
||||
async (itemId: number) => {
|
||||
try {
|
||||
await atlasBucketRepo.clearVisit(itemId);
|
||||
setBucketList((prev) =>
|
||||
prev.map((item) => (item.id === itemId ? { ...item, visited_at: null, visited_source: null } : item))
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
}
|
||||
},
|
||||
[t, toast]
|
||||
);
|
||||
|
||||
const handleAddBucketItem = async (): Promise<void> => {
|
||||
if (!bucketForm.name.trim()) return;
|
||||
const hasCoords = !!(bucketForm.lat && bucketForm.lng);
|
||||
const lat = hasCoords ? Number.parseFloat(bucketForm.lat) : null;
|
||||
const lng = hasCoords ? Number.parseFloat(bucketForm.lng) : null;
|
||||
// The month and year as they are now; a date stored when a place was picked
|
||||
// would go stale once the user changes the month afterwards.
|
||||
const targetDate = bucketTarget(bucketPoiMonth, bucketPoiYear) ?? (bucketForm.target_date || null);
|
||||
// #1898: this form never sends a country code, so the entry it would create is
|
||||
// identified by name, date and coordinates alone. Keep the form filled so the
|
||||
// user can just pick another date.
|
||||
if (
|
||||
findBucketDuplicate(bucketList, { name: bucketForm.name, country_code: null, target_date: targetDate, lat, lng })
|
||||
) {
|
||||
toast.error(t('atlas.bucketDuplicate'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data: Record<string, unknown> = { name: bucketForm.name.trim() };
|
||||
if (bucketForm.notes.trim()) data.notes = bucketForm.notes.trim();
|
||||
if (hasCoords) {
|
||||
data.lat = lat;
|
||||
data.lng = lng;
|
||||
}
|
||||
if (targetDate) data.target_date = targetDate;
|
||||
const item = await atlasRepo.addBucketItem(data);
|
||||
setBucketList((prev) => [item as BucketItem, ...prev]);
|
||||
setBucketForm(EMPTY_FORM);
|
||||
setBucketSearch('');
|
||||
setBucketSearchResults([]);
|
||||
setBucketPoiMonth(0);
|
||||
setBucketPoiYear(0);
|
||||
setShowBucketAdd(false);
|
||||
} catch (err) {
|
||||
// The 409 used to vanish into a silent catch, leaving the button looking broken.
|
||||
toast.error(
|
||||
isBucketDuplicateError(err) ? t('atlas.bucketDuplicate') : getApiErrorMessage(err, t('common.error'))
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteBucketItem = async (id: number): Promise<void> => {
|
||||
try {
|
||||
await atlasRepo.deleteBucketItem(id);
|
||||
setBucketList((prev) => prev.filter((i) => i.id !== id));
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
|
||||
const handleBucketPoiSearch = async () => {
|
||||
if (!bucketSearch.trim()) return;
|
||||
setBucketSearching(true);
|
||||
try {
|
||||
setBucketSearchResults(await atlasBucketRepo.searchPlaces(bucketSearch, placeLang));
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
} finally {
|
||||
setBucketSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** Takes a searched place into the form; notes typed so far stay. */
|
||||
const handleSelectBucketPoi = (result: { name?: string; lat?: number; lng?: number; address?: string | null }) => {
|
||||
setBucketForm((prev) => ({
|
||||
name: result.name || bucketSearch,
|
||||
notes: prev.notes,
|
||||
lat: String(result.lat ?? ''),
|
||||
lng: String(result.lng ?? ''),
|
||||
target_date: '',
|
||||
address: result.address ?? undefined,
|
||||
}));
|
||||
setBucketSearchResults([]);
|
||||
setBucketSearch('');
|
||||
};
|
||||
|
||||
/** Clears the add form and closes it. */
|
||||
const resetBucketAdd = useCallback(() => {
|
||||
setBucketForm(EMPTY_FORM);
|
||||
setBucketSearch('');
|
||||
setBucketSearchResults([]);
|
||||
setBucketPoiMonth(0);
|
||||
setBucketPoiYear(0);
|
||||
setShowBucketAdd(false);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
bucketList,
|
||||
setBucketList,
|
||||
showBucketAdd,
|
||||
setShowBucketAdd,
|
||||
bucketForm,
|
||||
setBucketForm,
|
||||
bucketSearch,
|
||||
setBucketSearch,
|
||||
bucketSearchResults,
|
||||
setBucketSearchResults,
|
||||
bucketSearching,
|
||||
bucketPoiMonth,
|
||||
setBucketPoiMonth,
|
||||
bucketPoiYear,
|
||||
setBucketPoiYear,
|
||||
handleClearBucketVisit,
|
||||
handleAddBucketItem,
|
||||
handleDeleteBucketItem,
|
||||
handleBucketPoiSearch,
|
||||
handleSelectBucketPoi,
|
||||
resetBucketAdd,
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { continentForCountry, type VisitStatus } from '@trek/shared';
|
||||
import type React from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import apiClient from '../../api/client';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { atlasRepo } from '../../repo/atlasRepo';
|
||||
import { getApiErrorMessage, type TranslationFn } from '../../types';
|
||||
import {
|
||||
findBucketDuplicate,
|
||||
@@ -102,8 +102,8 @@ export function withCountryDroppedAfterRegionUnmark(
|
||||
*/
|
||||
async function isCountryStillMarked(code: string): Promise<boolean> {
|
||||
try {
|
||||
const r = await apiClient.get(`/addons/atlas/country/${code}`);
|
||||
return r.data?.manually_marked !== false;
|
||||
const detail = (await atlasRepo.countryDetail(code)) as { manually_marked?: boolean } | null;
|
||||
return detail?.manually_marked !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
@@ -138,7 +138,8 @@ export function useAtlasCountryActions({
|
||||
if (!confirmAction) return;
|
||||
const { code } = confirmAction;
|
||||
try {
|
||||
await apiClient.post(`/addons/atlas/country/${code}/mark`);
|
||||
// Through the repo: offline it queues behind any older write to this country.
|
||||
await atlasRepo.markCountry(code);
|
||||
setData((prev) => (prev ? withCountryMarkedVisited(prev, code) : prev));
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
@@ -152,7 +153,7 @@ export function useAtlasCountryActions({
|
||||
const { code: countryCode, name: regionName, regionCode } = confirmAction;
|
||||
if (!regionCode) return;
|
||||
try {
|
||||
await apiClient.post(`/addons/atlas/region/${regionCode}/mark`, { name: regionName, country_code: countryCode });
|
||||
await atlasRepo.markRegion(regionCode, regionName, countryCode);
|
||||
const region: VisitedRegion = withVisitedStatus
|
||||
? { code: regionCode, name: regionName, placeCount: 0, status: 'visited', manuallyMarked: true }
|
||||
: { code: regionCode, name: regionName, placeCount: 0, manuallyMarked: true };
|
||||
@@ -169,7 +170,7 @@ export function useAtlasCountryActions({
|
||||
const { code: countryCode, regionCode } = confirmAction;
|
||||
if (!regionCode) return;
|
||||
try {
|
||||
await apiClient.delete(`/addons/atlas/region/${regionCode}/mark`);
|
||||
await atlasRepo.unmarkRegion(regionCode);
|
||||
setVisitedRegions((prev) => withRegionUnmarked(prev, countryCode, regionCode));
|
||||
if (!(await isCountryStillMarked(countryCode))) {
|
||||
setData((prev) => withCountryDroppedAfterRegionUnmark(prev, countryCode, regionCode, visitedRegions));
|
||||
@@ -195,11 +196,11 @@ export function useAtlasCountryActions({
|
||||
}
|
||||
try {
|
||||
// A region wish hatches that region on the map, not the whole country (#1901).
|
||||
const r = await apiClient.post('/addons/atlas/bucket-list', {
|
||||
const item = (await atlasRepo.addBucketItem({
|
||||
...entry,
|
||||
region_code: confirmAction.regionCode ?? null,
|
||||
});
|
||||
setBucketList((prev) => [r.data.item, ...prev]);
|
||||
})) as BucketItem;
|
||||
setBucketList((prev) => [item, ...prev]);
|
||||
} catch (err) {
|
||||
if (isBucketDuplicateError(err)) {
|
||||
toast.error(t('atlas.bucketDuplicate'));
|
||||
@@ -219,7 +220,8 @@ export function useAtlasCountryActions({
|
||||
const wishlistItems = confirmAction ? bucketList.filter((b) => b.country_code === confirmAction.code) : [];
|
||||
const removeBucket = async (): Promise<void> => {
|
||||
if (!confirmAction) return;
|
||||
await Promise.all(wishlistItems.map((item) => handleDeleteBucketItem(item.id)));
|
||||
// Each delete reports its own failure; one failing must not leave the others undone.
|
||||
await Promise.allSettled(wishlistItems.map((item) => handleDeleteBucketItem(item.id)));
|
||||
setConfirmAction(null);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,716 @@
|
||||
import { computeBadges, continentForCountry, crossesDateline, type Badge } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { AtlasGlobeHandle } from '../../components/AtlasGlobe/AtlasGlobe';
|
||||
import type { AtlasMeshManifest, GlobeEngine, GlobeHit } from '../../components/AtlasGlobe/GlobeEngine';
|
||||
import { arcSegments } from '../../components/AtlasGlobe/globeMath';
|
||||
import type { GlobePin } from '../../components/AtlasGlobe/GlobePins';
|
||||
import type { ArcLayer } from '../../components/AtlasGlobe/GlobeRenderer';
|
||||
import type { GlobeSkyHandle } from '../../components/AtlasGlobe/GlobeSky';
|
||||
import { useToast } from '../../components/shared/Toast';
|
||||
import { useIsDark } from '../../hooks/useIsDark';
|
||||
import { usePlaceLanguage } from '../../hooks/usePlaceLanguage';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { atlasPluginLayersRepo, type PluginAtlasLayer } from '../../repo/atlasPluginLayersRepo';
|
||||
import { atlasRepo, type AtlasFlights, type AtlasPerson } from '../../repo/atlasRepo';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
import { getApiErrorMessage } from '../../types';
|
||||
import { PLUGIN_TONES, paintGlobe, regionProgress, type GlobeColorMode } from './atlasGlobePaint';
|
||||
import { countryStatus, type AtlasData, type BucketItem, type CountryDetail } from './atlasModel';
|
||||
import { useAtlasBucket } from './useAtlasBucket';
|
||||
import type { AtlasConfirmAction, VisitedRegionMap } from './useAtlasCountryActions';
|
||||
import { useCountryNames } from './useCountryNames';
|
||||
import { locatePlace, useGlobePlaceSearch, type GlobePlaceHit } from './useGlobePlaceSearch';
|
||||
|
||||
/** Lower case without diacritics, so "zurich" finds Zürich. */
|
||||
function foldSearch(s: string): string {
|
||||
return s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();
|
||||
}
|
||||
|
||||
const SHOW_PLANNED_KEY = 'trek_atlas_show_planned';
|
||||
/** Tries of the first read after the first one fails (1, 2, 4, 8, 16 s apart). */
|
||||
const LOAD_RETRIES = 5;
|
||||
|
||||
/** Whether planned countries show: what this device chose before, off until then (#1048). */
|
||||
function readShowPlanned(): boolean {
|
||||
try {
|
||||
return window.localStorage.getItem(SHOW_PLANNED_KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export type AtlasHubTab = 'overview' | 'badges' | 'wishlist' | 'dawarich' | 'tours' | 'travellers';
|
||||
|
||||
type GlobeSelection =
|
||||
| { kind: 'country'; a2: string; index: number }
|
||||
| { kind: 'region'; a2: string; code: string | null; name: string | null };
|
||||
|
||||
interface GlobeHover {
|
||||
hit: GlobeHit;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* State of the globe Atlas: the user's Atlas data, what is selected and
|
||||
* hovered, the layer switches, and the mark/unmark flows. The engine itself
|
||||
* lives in AtlasGlobe; this hook only paints it and reacts to it.
|
||||
*/
|
||||
export function useAtlasGlobe() {
|
||||
const { t, language } = useTranslation();
|
||||
const dark = useIsDark();
|
||||
const toast = useToast();
|
||||
const resolveName = useCountryNames(language);
|
||||
const globeRef = useRef<AtlasGlobeHandle>(null);
|
||||
const skyRef = useRef<GlobeSkyHandle>(null);
|
||||
const [data, setData] = useState<AtlasData | null>(null);
|
||||
const [regions, setRegions] = useState<VisitedRegionMap>({});
|
||||
const placeLang = usePlaceLanguage();
|
||||
const bucketState = useAtlasBucket({ t, placeLang });
|
||||
const bucket = bucketState.bucketList;
|
||||
const setBucket = bucketState.setBucketList;
|
||||
const [manifest, setManifest] = useState<AtlasMeshManifest | null>(null);
|
||||
const [selection, setSelection] = useState<GlobeSelection | null>(null);
|
||||
const [hover, setHover] = useState<GlobeHover | null>(null);
|
||||
const [showPlanned, setShowPlannedState] = useState(readShowPlanned);
|
||||
const setShowPlanned = useCallback((on: boolean) => {
|
||||
setShowPlannedState(on);
|
||||
try {
|
||||
window.localStorage.setItem(SHOW_PLANNED_KEY, on ? '1' : '0');
|
||||
} catch {
|
||||
// Storage blocked: the switch still works for this visit.
|
||||
}
|
||||
}, []);
|
||||
const [colorMode, setColorMode] = useState<GlobeColorMode>('country');
|
||||
const [year, setYear] = useState<number | null>(null);
|
||||
const [timelineOpen, setTimelineOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [regionTick, setRegionTick] = useState(0);
|
||||
const [flights, setFlights] = useState<AtlasFlights | null>(null);
|
||||
const [showFlights, setShowFlights] = useState(false);
|
||||
// Dawarich (addon) is a tab of the hub; an entry from the wishlist or the
|
||||
// numbers opens it on the question it asked, as the classic side panel did.
|
||||
const dawarichEnabled = useAddonStore((st) => st.isEnabled('dawarich'));
|
||||
const [dawarichSub, setDawarichSub] = useState<'wishes' | 'countries'>('wishes');
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
const [stats, regs, items, fl] = await Promise.all([
|
||||
atlasRepo.stats(),
|
||||
atlasRepo.regions(),
|
||||
atlasRepo.bucketList(),
|
||||
atlasRepo.flights().catch(() => null),
|
||||
]);
|
||||
setData(stats as AtlasData);
|
||||
setRegions(regs as VisitedRegionMap);
|
||||
setBucket(items as BucketItem[]);
|
||||
setFlights(fl);
|
||||
}, []);
|
||||
|
||||
// Flight arcs, grouped by how often a route was flown so busy routes draw thicker (#1369).
|
||||
const arcLayers = useMemo<ArcLayer[]>(() => {
|
||||
if (!flights?.routes.length) return [];
|
||||
const buckets = new Map<number, Array<{ a: [number, number]; b: [number, number] }>>();
|
||||
for (const r of flights.routes) {
|
||||
const w = Math.min(4, 1 + Math.floor(Math.log2(r.count)));
|
||||
const list = buckets.get(w) ?? [];
|
||||
list.push({ a: [r.a.lng, r.a.lat], b: [r.b.lng, r.b.lat] });
|
||||
buckets.set(w, list);
|
||||
}
|
||||
return [...buckets.entries()].map(([w, routes]) => ({ ...arcSegments(routes), width: 0.9 + w * 0.7 }));
|
||||
}, [flights]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!manifest) return;
|
||||
globeRef.current?.engine?.setArcs(showFlights ? arcLayers : []);
|
||||
}, [arcLayers, showFlights, manifest]);
|
||||
|
||||
// The first read, tried again with growing pauses before it counts as failed:
|
||||
// a server that restarts or a connection that drops for a moment answers
|
||||
// the next try, and the error card is only for a read that really failed.
|
||||
const [loadTry, setLoadTry] = useState(0);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let timer = 0;
|
||||
const attempt = (n: number) => {
|
||||
reload()
|
||||
.then(() => {
|
||||
if (!cancelled) setError(null);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
if (n < LOAD_RETRIES) timer = window.setTimeout(() => attempt(n + 1), 1000 * 2 ** n);
|
||||
else setError(getApiErrorMessage(err, t('common.error')));
|
||||
});
|
||||
};
|
||||
attempt(0);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [reload, t, loadTry]);
|
||||
/** The error card's retry: read the Atlas again, without reloading the page. */
|
||||
const retryLoad = useCallback(() => {
|
||||
setError(null);
|
||||
setLoadTry((n) => n + 1);
|
||||
}, []);
|
||||
|
||||
// Another tab, the assistant or a Dawarich scan changed the Atlas: read it again.
|
||||
useServerPing('atlas:changed', true, async () => {
|
||||
await reload();
|
||||
setError(null);
|
||||
});
|
||||
|
||||
const fetchJson = useCallback((path: string) => atlasRepo.mesh(path), []);
|
||||
|
||||
// Plugin tints (atlasLayerProvider), as the classic Atlas drew them; each can be switched off.
|
||||
const [pluginLayers, setPluginLayers] = useState<PluginAtlasLayer[]>([]);
|
||||
const [hiddenPluginLayers, setHiddenPluginLayers] = useState<Set<string>>(new Set());
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void atlasPluginLayersRepo.layers().then((layers) => {
|
||||
if (!cancelled) setPluginLayers(layers);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
const togglePluginLayer = useCallback((key: string) => {
|
||||
setHiddenPluginLayers((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const pluginTint = useMemo(() => {
|
||||
const tint = new Map<string, string>();
|
||||
// The last layer naming a country wins, as on the classic map.
|
||||
for (const layer of pluginLayers) {
|
||||
if (hiddenPluginLayers.has(`${layer.pluginId}:${layer.id}`)) continue;
|
||||
for (const c of layer.countries)
|
||||
tint.set(c.code.toUpperCase(), PLUGIN_TONES[c.tone] ?? PLUGIN_TONES.default ?? '#818cf8'); // theme-lint-disable: plugin layer fallback
|
||||
}
|
||||
return tint;
|
||||
}, [pluginLayers, hiddenPluginLayers]);
|
||||
|
||||
const [compareCodes, setCompareCodes] = useState<string[] | null>(null);
|
||||
const [gapsOn, setGapsOn] = useState(false);
|
||||
const paintInput = useMemo(
|
||||
() => ({ data, regions, bucket, showPlanned, colorMode, year, compare: compareCodes, gaps: gapsOn, pluginTint }),
|
||||
[data, regions, bucket, showPlanned, colorMode, year, compareCodes, gapsOn, pluginTint]
|
||||
);
|
||||
const paint = useCallback((engine: GlobeEngine) => paintGlobe(engine, paintInput), [paintInput]);
|
||||
const paintKey = useMemo(() => [paintInput, regionTick], [paintInput, regionTick]);
|
||||
|
||||
const labelFor = useCallback((a2: string) => resolveName(a2) || null, [resolveName]);
|
||||
const labelRegionsOf = useCallback(
|
||||
(a2: string) => !!data?.countries.some((c) => c.code === a2) || !!regions[a2]?.length || selection?.a2 === a2,
|
||||
[data, regions, selection]
|
||||
);
|
||||
|
||||
const onReady = useCallback((m: AtlasMeshManifest) => setManifest(m), []);
|
||||
|
||||
const onHover = useCallback((hit: GlobeHit | null, x: number, y: number) => {
|
||||
setHover(hit ? { hit, x, y } : null);
|
||||
}, []);
|
||||
|
||||
const engine = (): GlobeEngine | null => globeRef.current?.engine ?? null;
|
||||
|
||||
// Once the globe and the data are there, fetch in the background the regions
|
||||
// of the countries this user is most likely to zoom into: the visited ones
|
||||
// first, then the planned and the wished-for.
|
||||
useEffect(() => {
|
||||
const e = engine();
|
||||
if (!e || !manifest || !data) return;
|
||||
const visited = data.countries.filter((c) => countryStatus(c) === 'visited').map((c) => c.code);
|
||||
const planned = data.countries.filter((c) => countryStatus(c) !== 'visited').map((c) => c.code);
|
||||
const wished = bucket.map((b) => b.country_code).filter((c): c is string => !!c && c.length === 2);
|
||||
e.prefetchRegions([...visited, ...planned, ...wished]);
|
||||
}, [manifest, data, bucket]);
|
||||
|
||||
const selectCountry = useCallback((a2: string, fly = true) => {
|
||||
const e = engine();
|
||||
const m = e?.manifest;
|
||||
if (!e || !m) return;
|
||||
const index = m.countries.findIndex((c) => c.a2 === a2);
|
||||
if (index < 0) return;
|
||||
setSelection({ kind: 'country', a2, index });
|
||||
e.setSelected(index, null);
|
||||
if (fly) {
|
||||
const c = m.countries[index];
|
||||
if (c.anchor) e.flyTo(c.anchor[0], c.anchor[1], Math.max(e.zoom, 1.15));
|
||||
}
|
||||
void e.loadRegionIndex(a2).then(() => setRegionTick((n) => n + 1));
|
||||
}, []);
|
||||
|
||||
// ---- the classic Atlas dialogs: choose / unmark / bucket (shared with the phone) and the country detail
|
||||
const [confirmAction, setConfirmAction] = useState<AtlasConfirmAction | null>(null);
|
||||
const [bucketMonth, setBucketMonth] = useState(0);
|
||||
const [bucketYear, setBucketYear] = useState(0);
|
||||
const [detail, setDetail] = useState<{ a2: string; data: CountryDetail | null } | null>(null);
|
||||
|
||||
/**
|
||||
* What a country opens, from a click or the search: its trips and places when
|
||||
* it has any (visited or planned), the unmark question for a bare mark, and
|
||||
* mark or wish for any other.
|
||||
*/
|
||||
const openCountry = useCallback(
|
||||
(a2: string) => {
|
||||
const row = data?.countries.find((c) => c.code === a2);
|
||||
const name = resolveName(a2);
|
||||
const hasTrips = !!row && (row.placeCount > 0 || row.tripCount > 0);
|
||||
if (row && hasTrips && (countryStatus(row) === 'visited' || showPlanned)) {
|
||||
setDetail({ a2, data: null });
|
||||
atlasRepo
|
||||
.countryDetail(a2)
|
||||
.then((d) => setDetail((cur) => (cur?.a2 === a2 ? { a2, data: d as CountryDetail } : cur)))
|
||||
.catch(() => setDetail(null));
|
||||
} else if (row && countryStatus(row) === 'visited') {
|
||||
setConfirmAction({ type: 'unmark', code: a2, name });
|
||||
} else {
|
||||
setConfirmAction({ type: 'choose', code: a2, name });
|
||||
}
|
||||
},
|
||||
[data, resolveName, showPlanned]
|
||||
);
|
||||
|
||||
const onSelect = useCallback(
|
||||
(hit: GlobeHit | null) => {
|
||||
const e = engine();
|
||||
if (!hit || !e) {
|
||||
setSelection(null);
|
||||
e?.setSelected(-1, null);
|
||||
return;
|
||||
}
|
||||
if (hit.kind === 'region') {
|
||||
setSelection(hit);
|
||||
e.setSelected(e.idOf(hit), null);
|
||||
if (!hit.code) return;
|
||||
const rows = regions[hit.a2] ?? [];
|
||||
const row = rows.find((r) => r.code === hit.code);
|
||||
const visited = !!row && (row.status ?? 'visited') === 'visited';
|
||||
const name = hit.name ?? hit.code;
|
||||
// Every visited region can be taken off, also one its places put there: a
|
||||
// place can sit in the wrong region, as the classic map allowed for.
|
||||
setConfirmAction({
|
||||
type: visited ? 'unmark-region' : 'choose-region',
|
||||
code: hit.a2,
|
||||
name,
|
||||
regionCode: hit.code,
|
||||
countryName: resolveName(hit.a2),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!hit.a2) return;
|
||||
selectCountry(hit.a2, false);
|
||||
openCountry(hit.a2);
|
||||
},
|
||||
[selectCountry, openCountry, regions, resolveName]
|
||||
);
|
||||
|
||||
/** From the detail of a country marked by hand: ask to take the mark off. */
|
||||
const askUnmarkDetail = useCallback(() => {
|
||||
if (!detail) return;
|
||||
const a2 = detail.a2;
|
||||
setDetail(null);
|
||||
setConfirmAction({ type: 'unmark', code: a2, name: resolveName(a2) });
|
||||
}, [detail, resolveName]);
|
||||
|
||||
const closeDialogs = useCallback(() => {
|
||||
setConfirmAction(null);
|
||||
setDetail(null);
|
||||
setSelection(null);
|
||||
engine()?.setSelected(-1, null);
|
||||
}, []);
|
||||
|
||||
const executeConfirmAction = useCallback(async () => {
|
||||
const a = confirmAction;
|
||||
if (!a) return;
|
||||
try {
|
||||
if (a.type === 'mark') await atlasRepo.markCountry(a.code);
|
||||
if (a.type === 'unmark') await atlasRepo.unmarkCountry(a.code);
|
||||
setConfirmAction(null);
|
||||
await reload();
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
}
|
||||
}, [confirmAction, reload, toast, t]);
|
||||
|
||||
// The bucket hook's delete: it reports a failure itself, so taking a country
|
||||
// off the wishlist from the dialog never fails silently.
|
||||
const handleDeleteBucketItem = bucketState.handleDeleteBucketItem;
|
||||
|
||||
// A country that just turned visited, whichever dialog did it, gets the colour
|
||||
// running out from its centre and a shooting star.
|
||||
const visitedBefore = useRef<Set<string> | null>(null);
|
||||
useEffect(() => {
|
||||
const now = new Set((data?.countries ?? []).filter((c) => countryStatus(c) === 'visited').map((c) => c.code));
|
||||
const before = visitedBefore.current;
|
||||
visitedBefore.current = now;
|
||||
if (!before) return;
|
||||
const e = engine();
|
||||
const m = e?.manifest;
|
||||
if (!e || !m) return;
|
||||
for (const code of now) {
|
||||
if (before.has(code)) continue;
|
||||
const i = m.countries.findIndex((c) => c.a2 === code);
|
||||
const anchor = m.countries[i]?.anchor;
|
||||
if (i >= 0 && anchor) e.startInk(i, anchor[0], anchor[1]);
|
||||
skyRef.current?.shootingStar();
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
const countryRow = useMemo(() => {
|
||||
if (selection?.kind !== 'country') return null;
|
||||
return data?.countries.find((c) => c.code === selection.a2) ?? null;
|
||||
}, [selection, data]);
|
||||
|
||||
const progress = useMemo(() => {
|
||||
const e = engine();
|
||||
if (!selection || !e) return null;
|
||||
return regionProgress(e, selection.a2, regions[selection.a2] ?? []);
|
||||
// regionTick: the index arrives after the selection
|
||||
}, [selection, regions, regionTick]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const selectedRegionVisited = useMemo(() => {
|
||||
if (selection?.kind !== 'region') return false;
|
||||
const rows = regions[selection.a2] ?? [];
|
||||
return rows.some((r) => r.code === selection.code && (r.status ?? 'visited') === 'visited');
|
||||
}, [selection, regions]);
|
||||
|
||||
const totals = useMemo(() => {
|
||||
const visited = (data?.countries ?? []).filter((c) => countryStatus(c) === 'visited');
|
||||
const continents = new Set(visited.map((c) => continentForCountry(c.code)).filter(Boolean));
|
||||
let regionCount = 0;
|
||||
for (const rows of Object.values(regions))
|
||||
regionCount += rows.filter((r) => (r.status ?? 'visited') === 'visited').length;
|
||||
const years = visited
|
||||
.map((c) => (c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : NaN))
|
||||
.filter((y) => !Number.isNaN(y));
|
||||
const perYear = new Map<number, number>();
|
||||
for (const y of years) perYear.set(y, (perYear.get(y) ?? 0) + 1);
|
||||
return {
|
||||
countries: visited.length,
|
||||
continents: continents.size,
|
||||
regions: regionCount,
|
||||
regionCountries: Object.keys(regions).length,
|
||||
trips: data?.stats.totalTrips ?? 0,
|
||||
places: data?.stats.totalPlaces ?? 0,
|
||||
days: data?.stats.totalDays ?? 0,
|
||||
firstYear: years.length ? Math.min(...years) : null,
|
||||
perYear,
|
||||
};
|
||||
}, [data, regions]);
|
||||
|
||||
// ---- search: countries by their localised name, regions by either of their names
|
||||
const [query, setQuery] = useState('');
|
||||
const [regionRows, setRegionRows] = useState<Array<
|
||||
[string, string | null, string | null, string | null, number, number]
|
||||
> | null>(null);
|
||||
const loadRegionSearch = useCallback(() => {
|
||||
if (regionRows || !manifest?.regionSearch) return;
|
||||
atlasRepo
|
||||
.mesh(manifest.regionSearch)
|
||||
.then((rows) =>
|
||||
setRegionRows(rows as Array<[string, string | null, string | null, string | null, number, number]>)
|
||||
)
|
||||
.catch(() => setRegionRows([]));
|
||||
}, [regionRows, manifest]);
|
||||
|
||||
/** A region's name by its ISO code, once the region search rows are loaded. */
|
||||
const regionNameOf = useCallback(
|
||||
(code: string) => {
|
||||
const row = regionRows?.find((r) => r[1] === code);
|
||||
return row ? (row[3] ?? row[2] ?? code) : code;
|
||||
},
|
||||
[regionRows]
|
||||
);
|
||||
|
||||
const results = useMemo(() => {
|
||||
const q = foldSearch(query);
|
||||
if (!q || !manifest) return [];
|
||||
const out: Array<
|
||||
| { kind: 'country'; a2: string; name: string }
|
||||
| { kind: 'region'; a2: string; code: string | null; name: string; lon: number; lat: number }
|
||||
> = [];
|
||||
for (const c of manifest.countries) {
|
||||
if (!c.a2) continue;
|
||||
const name = resolveName(c.a2) || c.name;
|
||||
// As on the classic map: from the first letter, and the exact ISO code ("de") too.
|
||||
const byCode = q.length === 2 && c.a2.toLowerCase() === q;
|
||||
if (byCode || foldSearch(name).includes(q) || foldSearch(c.name).includes(q))
|
||||
out.push({ kind: 'country', a2: c.a2, name });
|
||||
}
|
||||
out.sort((a, b) => Number(!foldSearch(a.name).startsWith(q)) - Number(!foldSearch(b.name).startsWith(q)));
|
||||
const countries = out.slice(0, 8);
|
||||
const regionsHit: typeof out = [];
|
||||
for (const [a2, code, name, nameEn, lon, lat] of q.length < 2 ? [] : (regionRows ?? [])) {
|
||||
if (regionsHit.length >= 6) break;
|
||||
if ((name && foldSearch(name).includes(q)) || (nameEn && foldSearch(nameEn).includes(q))) {
|
||||
regionsHit.push({ kind: 'region', a2, code, name: nameEn ?? name ?? code ?? '', lon, lat });
|
||||
}
|
||||
}
|
||||
return [...countries, ...regionsHit];
|
||||
}, [query, manifest, regionRows, resolveName]);
|
||||
|
||||
const pickResult = useCallback(
|
||||
(r: (typeof results)[number]) => {
|
||||
setQuery('');
|
||||
const e = engine();
|
||||
if (!e) return;
|
||||
if (r.kind === 'country') {
|
||||
const c = e.manifest?.countries.find((x) => x.a2 === r.a2);
|
||||
selectCountry(r.a2, false);
|
||||
if (c) e.flyToBox(c.bbox, 1.2, 6);
|
||||
// The search is the one way to tiny countries (Vatican City, Singapore),
|
||||
// so it opens what a click would.
|
||||
openCountry(r.a2);
|
||||
return;
|
||||
}
|
||||
e.flyTo(r.lon, r.lat, Math.max(e.zoom, 6.5));
|
||||
void e.loadRegionIndex(r.a2).then(() => {
|
||||
const hit = { kind: 'region' as const, a2: r.a2, code: r.code, name: r.name };
|
||||
setSelection(hit);
|
||||
e.setSelected(e.idOf(hit), null);
|
||||
setRegionTick((n) => n + 1);
|
||||
});
|
||||
},
|
||||
[selectCountry, openCountry]
|
||||
);
|
||||
|
||||
// Places from the geocoder under the countries and regions (#1115): the globe flies
|
||||
// there and the region's dialog opens, as on the classic map.
|
||||
const { placeHits, placesLoading } = useGlobePlaceSearch(query, placeLang);
|
||||
const pickPlace = useCallback(
|
||||
async (hit: GlobePlaceHit) => {
|
||||
setQuery('');
|
||||
const e = engine();
|
||||
if (e) e.flyTo(hit.lng, hit.lat, Math.max(e.zoom, 6.5));
|
||||
const info = await locatePlace(hit);
|
||||
if (!info?.country_code) return;
|
||||
if (!info.region_code || !info.region_name) {
|
||||
selectCountry(info.country_code, false);
|
||||
return;
|
||||
}
|
||||
const visited = (regions[info.country_code] ?? []).some((r) => r.code === info.region_code);
|
||||
setConfirmAction({
|
||||
type: visited ? 'unmark-region' : 'choose-region',
|
||||
code: info.country_code,
|
||||
name: info.region_name,
|
||||
regionCode: info.region_code,
|
||||
countryName: resolveName(info.country_code),
|
||||
});
|
||||
},
|
||||
[regions, resolveName, selectCountry]
|
||||
);
|
||||
|
||||
// Badges are rules over the data on screen; nothing is stored (shared/src/atlas/atlas-badges.ts).
|
||||
const badges = useMemo<Badge[]>(() => {
|
||||
const visited = (data?.countries ?? []).filter((c) => countryStatus(c) === 'visited');
|
||||
const regionTotals = manifest?.regions ?? {};
|
||||
return computeBadges({
|
||||
countries: visited.map((c) => ({ code: c.code, year: c.firstVisit ? Number(c.firstVisit.slice(0, 4)) : null })),
|
||||
continents: visited.map((c) => continentForCountry(c.code)).filter((x): x is string => !!x),
|
||||
regions: Object.entries(regions).map(([a2, rows]) => ({
|
||||
country: a2,
|
||||
visited: rows.filter((r) => (r.status ?? 'visited') === 'visited').length,
|
||||
total: regionTotals[a2]?.counted ?? rows.length,
|
||||
})),
|
||||
flights: {
|
||||
count: flights?.totals.flights ?? 0,
|
||||
km: flights?.totals.km ?? 0,
|
||||
longestKm: flights?.totals.longestKm ?? 0,
|
||||
crossesDateline: !!flights?.routes.some((r) => crossesDateline(r.a.lng, r.b.lng)),
|
||||
airports: flights?.totals.airports ?? 0,
|
||||
},
|
||||
streak: data?.streak ?? 0,
|
||||
wishesReached: bucket.filter((b) => !!b.visited_at).length,
|
||||
});
|
||||
}, [data, regions, manifest, flights, bucket]);
|
||||
const [passportOpen, setPassportOpen] = useState(false);
|
||||
const [passportTab, setPassportTab] = useState<AtlasHubTab>('overview');
|
||||
const [profileId, setProfileId] = useState<number | null>(null);
|
||||
const openPassport = useCallback((tab: AtlasHubTab) => {
|
||||
setPassportTab(tab);
|
||||
setProfileId(null);
|
||||
setPassportOpen(true);
|
||||
}, []);
|
||||
|
||||
// ---- travellers: everyone on the instance is visible unless they hide themselves
|
||||
type Person = AtlasPerson & { username: string; avatar_url: string | null };
|
||||
const [people, setPeople] = useState<Person[] | null>(null);
|
||||
const [compareWith, setCompareWith] = useState<Person | null>(null);
|
||||
const hidden = useSettingsStore((st) => (st.settings as Record<string, unknown>).atlas_hidden === true);
|
||||
const updateSetting = useSettingsStore((st) => st.updateSetting);
|
||||
const me = useAuthStore((st) => st.user);
|
||||
const compareEnabled = useAuthStore((st) => st.atlasCompareEnabled);
|
||||
const loadPeople = useCallback(() => {
|
||||
atlasRepo
|
||||
.people()
|
||||
.then(setPeople)
|
||||
.catch(() => setPeople([]));
|
||||
}, []);
|
||||
const setHidden = useCallback(
|
||||
(v: boolean) => {
|
||||
void (updateSetting as (k: string, v: unknown) => Promise<void>)('atlas_hidden', v);
|
||||
},
|
||||
[updateSetting]
|
||||
);
|
||||
const ranking = useMemo(() => {
|
||||
if (!people) return null;
|
||||
const mine: Person = {
|
||||
id: me?.id ?? 0,
|
||||
username: me?.username ?? '',
|
||||
avatar_url: (me as { avatar_url?: string } | null)?.avatar_url ?? null,
|
||||
countries: totals.countries,
|
||||
continents: totals.continents,
|
||||
regions: totals.regions,
|
||||
flightKm: flights?.totals.km ?? 0,
|
||||
codes: [],
|
||||
badges: [],
|
||||
};
|
||||
return [...people, mine].sort((a, b) => b.countries - a.countries || b.continents - a.continents);
|
||||
}, [people, me, totals, flights]);
|
||||
|
||||
const flyToPoint = useCallback((lon: number, lat: number) => {
|
||||
setPassportOpen(false);
|
||||
engine()?.flyTo(lon, lat, 6);
|
||||
}, []);
|
||||
|
||||
const pins = useMemo<GlobePin[]>(
|
||||
() =>
|
||||
bucket
|
||||
.filter((b) => b.lat != null && b.lng != null)
|
||||
.map((b): GlobePin => ({
|
||||
key: String(b.id),
|
||||
lon: Number(b.lng),
|
||||
lat: Number(b.lat),
|
||||
title: b.name,
|
||||
reached: !!b.visited_at,
|
||||
onClick: () => openPassport('wishlist'),
|
||||
})),
|
||||
[bucket, openPassport]
|
||||
);
|
||||
|
||||
const zoomIn = useCallback(() => engine()?.zoomBy(1.6), []);
|
||||
const zoomOut = useCallback(() => engine()?.zoomBy(1 / 1.6), []);
|
||||
|
||||
return {
|
||||
t,
|
||||
dark,
|
||||
globeRef,
|
||||
skyRef,
|
||||
data,
|
||||
regions,
|
||||
bucket,
|
||||
manifest,
|
||||
error,
|
||||
setError,
|
||||
retryLoad,
|
||||
fetchJson,
|
||||
paint,
|
||||
paintKey,
|
||||
labelFor,
|
||||
labelRegionsOf,
|
||||
resolveName,
|
||||
onReady,
|
||||
onHover,
|
||||
onSelect,
|
||||
hover,
|
||||
selection,
|
||||
setSelection,
|
||||
selectCountry,
|
||||
countryRow,
|
||||
progress,
|
||||
selectedRegionVisited,
|
||||
confirmAction,
|
||||
setConfirmAction,
|
||||
executeConfirmAction,
|
||||
bucketMonth,
|
||||
setBucketMonth,
|
||||
bucketYear,
|
||||
setBucketYear,
|
||||
setData,
|
||||
setRegions,
|
||||
setBucket,
|
||||
handleDeleteBucketItem,
|
||||
askUnmarkDetail,
|
||||
detail,
|
||||
closeDialogs,
|
||||
language,
|
||||
placeLang,
|
||||
showPlanned,
|
||||
setShowPlanned,
|
||||
flights,
|
||||
showFlights,
|
||||
setShowFlights,
|
||||
colorMode,
|
||||
setColorMode,
|
||||
year,
|
||||
setYear,
|
||||
timelineOpen,
|
||||
setTimelineOpen,
|
||||
totals,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
bucketState,
|
||||
flyToPoint,
|
||||
pluginLayers,
|
||||
hiddenPluginLayers,
|
||||
togglePluginLayer,
|
||||
pins,
|
||||
reload,
|
||||
people,
|
||||
loadPeople,
|
||||
compareEnabled,
|
||||
dawarichEnabled,
|
||||
dawarichSub,
|
||||
openDawarich: (sub: 'wishes' | 'countries') => {
|
||||
setDawarichSub(sub);
|
||||
setProfileId(null);
|
||||
setPassportTab('dawarich');
|
||||
setPassportOpen(true);
|
||||
},
|
||||
ranking,
|
||||
me,
|
||||
hidden,
|
||||
setHidden,
|
||||
compareWith,
|
||||
startCompare: (p: AtlasPerson & { username: string; avatar_url: string | null }) => {
|
||||
setCompareWith(p);
|
||||
setCompareCodes(p.codes);
|
||||
setGapsOn(false);
|
||||
setPassportOpen(false);
|
||||
},
|
||||
stopCompare: () => {
|
||||
setCompareWith(null);
|
||||
setCompareCodes(null);
|
||||
setGapsOn(false);
|
||||
},
|
||||
gaps: gapsOn,
|
||||
setGaps: setGapsOn,
|
||||
badges,
|
||||
passportTab,
|
||||
setPassportTab,
|
||||
openPassport,
|
||||
profileId,
|
||||
setProfileId,
|
||||
profile: profileId === null ? null : ((people ?? []).find((p) => p.id === profileId) ?? null),
|
||||
passportOpen,
|
||||
setPassportOpen,
|
||||
query,
|
||||
setQuery,
|
||||
regionNameOf,
|
||||
placeHits,
|
||||
placesLoading,
|
||||
pickPlace,
|
||||
results,
|
||||
pickResult,
|
||||
loadRegionSearch,
|
||||
};
|
||||
}
|
||||
|
||||
export type AtlasGlobeState = ReturnType<typeof useAtlasGlobe>;
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { atlasBucketRepo, type AtlasLocation } from '../../repo/atlasBucketRepo';
|
||||
|
||||
export interface GlobePlaceHit {
|
||||
name: string;
|
||||
address: string | null;
|
||||
lat: number;
|
||||
lng: number;
|
||||
}
|
||||
|
||||
const MIN_CHARS = 3;
|
||||
const DEBOUNCE_MS = 350;
|
||||
const MAX_HITS = 5;
|
||||
|
||||
/**
|
||||
* Places for the globe's search (#1115), as the classic Atlas had them: from
|
||||
* three characters on, a debounced geocoder lookup; a slow answer for an older
|
||||
* query never overwrites a newer one.
|
||||
*/
|
||||
export function useGlobePlaceSearch(query: string, lang: string) {
|
||||
const [hits, setHits] = useState<GlobePlaceHit[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const seq = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const q = query.trim();
|
||||
const mine = ++seq.current;
|
||||
if (q.length < MIN_CHARS) {
|
||||
setHits([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const timer = window.setTimeout(() => {
|
||||
atlasBucketRepo
|
||||
.searchPlaces(q, lang)
|
||||
.then((places) => {
|
||||
if (mine !== seq.current) return;
|
||||
const out: GlobePlaceHit[] = [];
|
||||
for (const p of places) {
|
||||
if (typeof p.lat !== 'number' || typeof p.lng !== 'number') continue;
|
||||
out.push({ name: p.name || q, address: p.address || null, lat: p.lat, lng: p.lng });
|
||||
if (out.length === MAX_HITS) break;
|
||||
}
|
||||
setHits(out);
|
||||
})
|
||||
.catch(() => {
|
||||
if (mine === seq.current) setHits([]);
|
||||
})
|
||||
.finally(() => {
|
||||
if (mine === seq.current) setLoading(false);
|
||||
});
|
||||
}, DEBOUNCE_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [query, lang]);
|
||||
|
||||
return { placeHits: hits, placesLoading: loading };
|
||||
}
|
||||
|
||||
/** Where a picked place lies; null when the lookup fails (the globe has already moved there). */
|
||||
export async function locatePlace(hit: GlobePlaceHit): Promise<AtlasLocation | null> {
|
||||
try {
|
||||
return await atlasBucketRepo.locate(hit.lat, hit.lng);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Award, Briefcase, CalendarRange, Flag, Globe, MapIcon, Plane, Star } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { GlobeStat } from '../../components/AtlasGlobe/GlobeStatsBar';
|
||||
import type { AtlasGlobeState } from './useAtlasGlobe';
|
||||
|
||||
/** The numbers of the globe Atlas, shared by the desktop view and the phone screen. */
|
||||
export function useGlobeStats(s: AtlasGlobeState): GlobeStat[] {
|
||||
const { t, totals, flights, setShowFlights, badges, openPassport, setTimelineOpen } = s;
|
||||
const bucketCount = s.bucket.filter((b) => !b.visited_at).length;
|
||||
return React.useMemo(() => {
|
||||
const yearsSpan = totals.firstYear ? new Date().getFullYear() - totals.firstYear + 1 : 0;
|
||||
const stats: GlobeStat[] = [
|
||||
{
|
||||
key: 'countries',
|
||||
icon: Flag,
|
||||
value: totals.countries,
|
||||
label: t('atlas.countries'),
|
||||
onClick: () => openPassport('overview'),
|
||||
},
|
||||
{
|
||||
key: 'continents',
|
||||
icon: Globe,
|
||||
value: totals.continents,
|
||||
label: t('atlas.globe.continents'),
|
||||
onClick: () => openPassport('overview'),
|
||||
},
|
||||
{
|
||||
key: 'regions',
|
||||
icon: MapIcon,
|
||||
value: totals.regions,
|
||||
label: t('atlas.regions'),
|
||||
onClick: () => openPassport('overview'),
|
||||
},
|
||||
];
|
||||
if (flights?.totals.flights) {
|
||||
stats.push({
|
||||
key: 'flights',
|
||||
icon: Plane,
|
||||
value: `${Math.round(flights.totals.km / 1000)}k`,
|
||||
label: t('atlas.globe.flightKm'),
|
||||
onClick: () => setShowFlights((v) => !v),
|
||||
});
|
||||
} else {
|
||||
stats.push({
|
||||
key: 'trips',
|
||||
icon: Briefcase,
|
||||
value: totals.trips,
|
||||
label: t('atlas.trips'),
|
||||
onClick: () => openPassport('overview'),
|
||||
});
|
||||
}
|
||||
stats.push({
|
||||
key: 'badges',
|
||||
icon: Award,
|
||||
value: badges.filter((b) => b.earned).length,
|
||||
label: t('atlas.globe.badges'),
|
||||
onClick: () => openPassport('badges'),
|
||||
});
|
||||
stats.push({
|
||||
key: 'wishlist',
|
||||
icon: Star,
|
||||
value: bucketCount,
|
||||
label: t('atlas.bucketTab'),
|
||||
onClick: () => openPassport('wishlist'),
|
||||
});
|
||||
if (yearsSpan)
|
||||
stats.push({
|
||||
key: 'years',
|
||||
icon: CalendarRange,
|
||||
value: yearsSpan,
|
||||
label: t('atlas.years'),
|
||||
onClick: () => setTimelineOpen((o) => !o),
|
||||
});
|
||||
return stats;
|
||||
}, [t, totals, flights, setShowFlights, badges, openPassport, bucketCount, setTimelineOpen]);
|
||||
}
|
||||
@@ -72,6 +72,8 @@ interface AuthState {
|
||||
/** Server policy: all users must enable MFA */
|
||||
appRequireMfa: boolean
|
||||
tripRemindersEnabled: boolean
|
||||
/** The admin's switch for the Atlas ranking and traveller profiles. */
|
||||
atlasCompareEnabled: boolean
|
||||
placesPhotosEnabled: boolean
|
||||
placesAutocompleteEnabled: boolean
|
||||
placesDetailsEnabled: boolean
|
||||
@@ -103,6 +105,7 @@ interface AuthState {
|
||||
setServerTimezone: (tz: string) => void
|
||||
setAppRequireMfa: (val: boolean) => void
|
||||
setTripRemindersEnabled: (val: boolean) => void
|
||||
setAtlasCompareEnabled: (val: boolean) => void
|
||||
setPlacesPhotosEnabled: (val: boolean) => void
|
||||
setPlacesAutocompleteEnabled: (val: boolean) => void
|
||||
setPlacesDetailsEnabled: (val: boolean) => void
|
||||
@@ -159,6 +162,7 @@ export const useAuthStore = create<AuthState>()(
|
||||
serverTimezone: browserTimeZone() ?? '',
|
||||
appRequireMfa: false,
|
||||
tripRemindersEnabled: false,
|
||||
atlasCompareEnabled: true,
|
||||
placesPhotosEnabled: true,
|
||||
placesAutocompleteEnabled: true,
|
||||
placesDetailsEnabled: true,
|
||||
@@ -447,6 +451,7 @@ export const useAuthStore = create<AuthState>()(
|
||||
setServerTimezone: (tz: string) => set({ serverTimezone: tz }),
|
||||
setAppRequireMfa: (val: boolean) => set({ appRequireMfa: val }),
|
||||
setTripRemindersEnabled: (val: boolean) => set({ tripRemindersEnabled: val }),
|
||||
setAtlasCompareEnabled: (val: boolean) => set({ atlasCompareEnabled: val }),
|
||||
setPlacesPhotosEnabled: (val: boolean) => set({ placesPhotosEnabled: val }),
|
||||
setPlacesAutocompleteEnabled: (val: boolean) => set({ placesAutocompleteEnabled: val }),
|
||||
setPlacesDetailsEnabled: (val: boolean) => set({ placesDetailsEnabled: val }),
|
||||
|
||||
Reference in New Issue
Block a user