fix(atlas): clear the client gates of the globe Atlas

Client lint, checks and tests were red on the globe Atlas:

- The views own the globe and sky refs and hand them into useAtlasGlobe,
  so reading its state while rendering no longer counts as reading refs.
- Helpers that shared a file with components move to their own modules
  (badge tiers, medal label, Dawarich notes, hub tabs, period label).
- The place search derives its loading state, the search resets its
  active row on input, and the two silenced hook dependencies are named.
- placeLabels, the hover chip and the overview figures are split up.
- Raw text sizes become type tiers, the badge unlock docks on --z-overlay.
- The stats card test follows the GlobeStat props; baselines lowered to
  the counts the run reported.
This commit is contained in:
Maurice
2026-11-28 23:14:17 +01:00
parent d78dc79e21
commit 10713e41cd
52 changed files with 478 additions and 390 deletions
+2 -2
View File
@@ -2,7 +2,7 @@ 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 { medalLabel } from './atlasHubModel';
import type { AtlasGlobeState } from './useAtlasGlobe';
const KEY = (userId: number) => `trek_atlas_badges_seen_${userId}`;
@@ -90,7 +90,7 @@ export default function AtlasBadgeUnlock({ s }: { s: AtlasGlobeState }): React.R
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 className="pointer-events-none fixed inset-0 z-[var(--z-overlay)] 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
+3 -23
View File
@@ -1,34 +1,14 @@
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 BadgeMedal from '../../components/AtlasGlobe/BadgeMedal';
import { TIERS } from '../../components/AtlasGlobe/badgeTiers';
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 { badgeHolders, badgeLadder, formatNum, medalLabel } 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 ?? {}) };
+1 -21
View File
@@ -1,4 +1,3 @@
import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared';
import {
Building2,
CalendarDays,
@@ -14,31 +13,12 @@ import {
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 { dawarichNotes, useDawarichAtlas } 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
+3 -15
View File
@@ -1,9 +1,9 @@
import { Briefcase, Building2, CalendarDays, ChevronRight, Flame, Map as MapIcon, MapPin, Plane } from 'lucide-react';
import { ChevronRight } 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 { WORLD_COUNTRIES, continentCounts, overviewFigures } from './atlasHubModel';
import type { AtlasGlobeState } from './useAtlasGlobe';
const CARD = HUB_CARD;
@@ -25,19 +25,7 @@ export default function AtlasGlobeOverview({ s }: { s: AtlasGlobeState }): React
// 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()}`,
},
];
const figures: HubTileData[] = overviewFigures(s.t, s.totals.regions, d);
return (
<div className="grid gap-3 sm:grid-cols-[1fr_1.45fr]">
@@ -2,14 +2,15 @@ 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 AtlasGlobeBadges 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 { medalLabel } from './atlasHubModel';
import type { AtlasGlobeState, AtlasHubTab } from './useAtlasGlobe';
import { useHubTabs } from './useHubTabs';
/** The Passport: badges as glass medals, and the other travellers of this instance. */
export default function AtlasGlobePassport({ s }: { s: AtlasGlobeState }): React.ReactElement | null {
+4 -3
View File
@@ -17,8 +17,6 @@ export default function AtlasGlobeSearch({
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();
@@ -65,7 +63,10 @@ export default function AtlasGlobeSearch({
<input
ref={inputRef}
value={s.query}
onChange={(e) => s.setQuery(e.target.value)}
onChange={(e) => {
s.setQuery(e.target.value);
setActive(0);
}}
onFocus={s.loadRegionSearch}
onKeyDown={onKeyDown}
placeholder={s.t('atlas.globe.search')}
+56 -38
View File
@@ -1,10 +1,10 @@
import { Layers, Minus, Plus, X } from 'lucide-react';
import React from 'react';
import { useNavigate } from 'react-router';
import AtlasGlobe from '../../components/AtlasGlobe/AtlasGlobe';
import AtlasGlobe, { type AtlasGlobeHandle } 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 GlobeSky, { type GlobeSkyHandle } from '../../components/AtlasGlobe/GlobeSky';
import GlobeStatsBar from '../../components/AtlasGlobe/GlobeStatsBar';
import '../../components/AtlasGlobe/atlasGlobe.css';
import Navbar from '../../components/Layout/Navbar';
@@ -27,25 +27,26 @@ const PLANNED_DOT = '#818cf8'; // theme-lint-disable: the planned map paint, so
/** The globe Atlas on desktop. State lives in useAtlasGlobe; this file is layout. */
export default function AtlasGlobeView(): React.ReactElement {
const s = useAtlasGlobe();
const globeRef = React.useRef<AtlasGlobeHandle>(null);
const skyRef = React.useRef<GlobeSkyHandle>(null);
const s = useAtlasGlobe({ globeRef, skyRef });
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]
);
// A plain function: AtlasGlobe reads its props through a ref, so a new one
// each render costs nothing.
const onFrame = (e: GlobeEngine) => {
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;
}
};
return (
<div className="min-h-screen">
@@ -56,7 +57,7 @@ export default function AtlasGlobeView(): React.ReactElement {
style={{ top: 'var(--nav-h)', height: 'calc(100dvh - var(--nav-h))' }}
>
<AtlasGlobe
ref={s.globeRef}
ref={globeRef}
fetchJson={s.fetchJson}
dark
labelFor={s.labelFor}
@@ -70,7 +71,7 @@ export default function AtlasGlobeView(): React.ReactElement {
onError={(err) => s.setError(err instanceof Error ? err.message : String(err))}
/>
<div className="pointer-events-none absolute inset-0">
<GlobeSky ref={s.skyRef} dark />
<GlobeSky ref={skyRef} dark />
</div>
<div className="pointer-events-none absolute inset-0 overflow-hidden">
<GlobePins ref={pinsRef} pins={s.pins} />
@@ -139,33 +140,50 @@ export default function AtlasGlobeView(): React.ReactElement {
);
}
type HoverHit = NonNullable<AtlasGlobeState['hover']>['hit'];
/** What the hover chip says under the name: trips and places and when, or a region's country and places. */
function hoverFacts(s: AtlasGlobeState, hit: HoverHit): string[] {
const facts: string[] = [];
if (hit.kind === 'region') {
const regionRow = (s.regions[hit.a2] ?? []).find((r) => r.code === hit.code);
facts.push(s.resolveName(hit.a2));
if (regionRow?.placeCount)
facts.push(`${regionRow.placeCount} ${s.t('atlas.places', { count: regionRow.placeCount })}`);
return facts;
}
const row = s.data?.countries.find((c) => c.code === hit.a2);
if (!row || (row.tripCount === 0 && row.placeCount === 0)) return facts;
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}`);
return facts;
}
/** Whether what is under the pointer is visited or planned, and the colour of its dot. */
function hoverStatus(s: AtlasGlobeState, hit: HoverHit): { label: string; dot: string | undefined } | 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;
if (!status) return null;
const a3 = hit.kind === 'country' ? s.manifest?.countries[hit.index]?.a3 : undefined;
if (status === 'visited') return { label: s.t('atlas.globe.visited'), dot: a3 ? countryColor(a3) : undefined };
return { label: s.t('atlas.planned'), dot: PLANNED_DOT };
}
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 })}`);
}
const status = hoverStatus(s, hit);
const statusLabel = status?.label ?? null;
const dotColor = status?.dot;
const facts = hoverFacts(s, hit);
return (
<div
className="ag-liquid pointer-events-none absolute z-30 whitespace-nowrap rounded-xl px-3 py-1.5"
+2 -33
View File
@@ -1,39 +1,8 @@
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>
);
}
import type { AtlasGlobeState } from './useAtlasGlobe';
import { useHubTabs } from './useHubTabs';
/**
* One way into every tab of the hub, straight from the map: a column of glass
+3 -1
View File
@@ -196,7 +196,9 @@ export function paintGlobe(engine: GlobeEngine, input: GlobePaintInput): void {
export function regionProgress(
engine: GlobeEngine,
a2: string,
rows: AtlasRegionRow[]
rows: AtlasRegionRow[],
// Which arrival of region files this answer is for; the memo above keys on it.
_loaded?: number
): { visited: number; total: number } | null {
const idx = engine.regionIndex.get(a2);
const entry = engine.manifest?.regions[a2];
+56
View File
@@ -1,4 +1,14 @@
import { getIntlLanguage, type Badge } from '@trek/shared';
import {
Briefcase,
Building2,
CalendarDays,
Flame,
Map as MapIcon,
MapPin,
Plane,
type LucideIcon,
} from 'lucide-react';
import { A2_TO_A3, type AtlasData, type BucketItem } from './atlasModel';
/**
@@ -26,6 +36,31 @@ export function continentCounts(data: AtlasData | null): Array<{ name: string; k
);
}
/** The small figures under the headline of the hub's statistics, for both shells. */
export function overviewFigures(
t: (key: string, params?: Record<string, string | number>) => string,
regions: number,
data: AtlasData | null
): Array<{ Icon: LucideIcon; value: number; label: string }> {
const st = data?.stats;
const n = (v: number | null | undefined) => v ?? 0;
const trips = n(st?.totalTrips);
const places = n(st?.totalPlaces);
const cities = n(st?.totalCities);
const days = n(st?.totalDays);
const streak = n(data?.streak);
const thisYear = n(data?.tripsThisYear);
return [
{ Icon: MapIcon, value: regions, label: t('atlas.regions', { count: regions }) },
{ Icon: Briefcase, value: trips, label: t('atlas.trips', { count: trips }) },
{ Icon: MapPin, value: places, label: t('atlas.places', { count: places }) },
{ Icon: Building2, value: cities, label: t('atlas.cities', { count: cities }) },
{ Icon: CalendarDays, value: days, label: t('atlas.days', { count: days }) },
{ Icon: Flame, value: streak, label: t('atlas.yearsInRow', { count: streak }) },
{ Icon: Plane, value: thisYear, label: `${t('atlas.tripsIn', { count: thisYear })} ${new Date().getFullYear()}` },
];
}
/** 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();
@@ -91,3 +126,24 @@ export function badgeHolders(
of: people.length + 1,
};
}
/** 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;
}
}
+18 -10
View File
@@ -1,4 +1,5 @@
import { computeBadges, continentForCountry, crossesDateline, type Badge } from '@trek/shared';
import type React from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { AtlasGlobeHandle } from '../../components/AtlasGlobe/AtlasGlobe';
import type { AtlasMeshManifest, GlobeEngine, GlobeHit } from '../../components/AtlasGlobe/GlobeEngine';
@@ -59,13 +60,21 @@ interface GlobeHover {
* 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() {
/**
* The refs of the globe and the sky, made by the view that renders them and
* handed in: kept out of the returned state, so reading that state while
* rendering never counts as reading a ref.
*/
export interface AtlasGlobeRefs {
globeRef: React.RefObject<AtlasGlobeHandle | null>;
skyRef: React.RefObject<GlobeSkyHandle | null>;
}
export function useAtlasGlobe({ globeRef, skyRef }: AtlasGlobeRefs) {
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();
@@ -217,7 +226,7 @@ export function useAtlasGlobe() {
setHover(hit ? { hit, x, y } : null);
}, []);
const engine = (): GlobeEngine | null => globeRef.current?.engine ?? null;
const engine = useCallback((): GlobeEngine | null => globeRef.current?.engine ?? null, [globeRef]);
// 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
@@ -368,12 +377,13 @@ export function useAtlasGlobe() {
return data?.countries.find((c) => c.code === selection.a2) ?? null;
}, [selection, data]);
// regionTick counts the region files arrived: the index of a selected country
// can arrive after the selection, and the progress must follow it.
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
return regionProgress(e, selection.a2, regions[selection.a2] ?? [], regionTick);
}, [engine, selection, regions, regionTick]);
const selectedRegionVisited = useMemo(() => {
if (selection?.kind !== 'region') return false;
@@ -543,7 +553,7 @@ export function useAtlasGlobe() {
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 hidden = useSettingsStore((st) => (st.settings as unknown 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);
@@ -601,8 +611,6 @@ export function useAtlasGlobe() {
return {
t,
dark,
globeRef,
skyRef,
data,
regions,
bucket,
+13 -18
View File
@@ -14,23 +14,19 @@ 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.
* three characters on, a debounced geocoder lookup. The answer is kept with
* the query it answers, so what shows (and whether it is still loading) is
* derived, and a slow answer for an older query never shows for a newer one.
*/
export function useGlobePlaceSearch(query: string, lang: string) {
const [hits, setHits] = useState<GlobePlaceHit[]>([]);
const [loading, setLoading] = useState(false);
const [answer, setAnswer] = useState<{ q: string; hits: GlobePlaceHit[] }>({ q: '', hits: [] });
const seq = useRef(0);
const q = query.trim();
const asking = q.length >= MIN_CHARS;
useEffect(() => {
const q = query.trim();
const mine = ++seq.current;
if (q.length < MIN_CHARS) {
setHits([]);
setLoading(false);
return;
}
setLoading(true);
if (!asking) return;
const timer = window.setTimeout(() => {
atlasBucketRepo
.searchPlaces(q, lang)
@@ -42,19 +38,18 @@ export function useGlobePlaceSearch(query: string, lang: string) {
out.push({ name: p.name || q, address: p.address || null, lat: p.lat, lng: p.lng });
if (out.length === MAX_HITS) break;
}
setHits(out);
setAnswer({ q, hits: out });
})
.catch(() => {
if (mine === seq.current) setHits([]);
})
.finally(() => {
if (mine === seq.current) setLoading(false);
// A failed lookup answers with no places; the search box itself stays usable.
if (mine === seq.current) setAnswer({ q, hits: [] });
});
}, DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [query, lang]);
}, [q, asking, lang]);
return { placeHits: hits, placesLoading: loading };
const current = asking && answer.q === q;
return { placeHits: current ? answer.hits : [], placesLoading: asking && !current };
}
/** Where a picked place lies; null when the lookup fails (the globe has already moved there). */
+25
View File
@@ -0,0 +1,25 @@
import { Award, BarChart3, Mountain, Star, Trophy } from 'lucide-react';
import type React from 'react';
import DawarichMark from '../../components/AtlasGlobe/DawarichMark';
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 }] : []),
];
}