diff --git a/client/src/components/Map/MapViewAuto.tsx b/client/src/components/Map/MapViewAuto.tsx index 0a97124d7..57f5ca0ac 100644 --- a/client/src/components/Map/MapViewAuto.tsx +++ b/client/src/components/Map/MapViewAuto.tsx @@ -1,23 +1,18 @@ -import { Suspense, useState } from 'react' +import { Suspense } from 'react' import { AlertTriangle, Clock, CloudOff, Info } from 'lucide-react' import { Tooltip } from '../shared/Tooltip' -import { useSettingsStore } from '../../store/settingsStore' import { MapView } from './MapView' import ErrorBoundary from '../shared/ErrorBoundary' import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy' -import { useGlRenderer } from './glSupport' +import { useEffectiveMapEngine } from './useEffectiveMapEngine' import { useRoadtripHazards } from './useRoadtripHazards' import { useTranslation } from '../../i18n/TranslationContext' import type { MapViewAutoProps, MapViewProps } from './mapViewContract' -import { useNetworkMode } from '../../hooks/useNetworkMode' -import { useIsDark } from '../../hooks/useIsDark' -import { OFM_POSITRON } from '../../constants/mapDefaults' -import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap' -import { glTileStoreActive, tileCacheActive } from '../../native/tileCache' -// Auto-selects the map renderer based on user settings. Keeps the existing -// Leaflet MapView untouched so the Mapbox GL variant can mature iteratively -// behind a toggle. Atlas is not affected — it imports Leaflet directly. +// Picks the renderer for the trip map from the user's settings, Leaflet or one +// of the two GL engines, and keeps a usable map whatever happens to the chosen +// one: no WebGL2, a failed GL chunk, or no connection. The choice itself lives +// in useEffectiveMapEngine, which the journey map shares. // // Offline maps: "prepare for offline" stores the OpenFreeMap basemap for every // trip, whatever the provider (sync/tilePrefetcher.ts). Offline, a map whose own @@ -34,36 +29,17 @@ export function MapViewAuto(props: MapViewAutoProps) { // The one cast between what callers pass and what the renderers type: pins // without trip_id (see MapViewAutoProps). Neither renderer reads trip_id. const mapProps = { ...props, hazards: hazards.feed?.hazards } as MapViewProps - const provider = useSettingsStore(s => s.settings.map_provider) - const token = useSettingsStore(s => s.settings.mapbox_access_token) - // Fall back to Leaflet when Mapbox is selected but no token is set, or when the - // browser has no WebGL2 (both GL engines need it), so the trip planner never - // shows an empty map or one that fails to start. - const configuredGl = useGlRenderer(provider, token) - const maplibreStyle = useSettingsStore(s => s.settings.maplibre_style) - const { offline } = useNetworkMode() - const dark = useIsDark() - const offlineStyle = offlineStyleFor(dark) - // In the iOS app with its tile store, a Mapbox map keeps what was viewed for 30 - // days, so offline it stays Mapbox, and the pill offers the stored trip region - // instead for the places never looked at. Everywhere else a basemap with - // nothing stored is swapped for the stored one straight away. - const nativeStore = tileCacheActive() - const [preferStored, setPreferStored] = useState(false) - const mapboxKept = configuredGl === 'mapbox-gl' && glTileStoreActive() - const glFallback = !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) && (!mapboxKept || preferStored) - const glProvider = glFallback ? 'maplibre-gl' : configuredGl - const leafletFallback = !configuredGl && offline && !leafletWorksOffline(mapProps.tileUrl ?? OFM_POSITRON, nativeIosWithoutStore(nativeStore)) - if (leafletFallback) mapProps.tileUrl = offlineStyle - const pill = offline && mapboxKept + const { engine: glProvider, styleOverride, tileUrlOverride, pill: pillState } = useEffectiveMapEngine(mapProps.tileUrl) + if (tileUrlOverride) mapProps.tileUrl = tileUrlOverride + const pill = pillState?.kind === 'toggle' ? ( setPreferStored(v => !v)} + label={pillState.pressed ? t('map.offlineBasemap') : t('map.offlineShowStored')} + pressed={pillState.pressed} + onToggle={pillState.onToggle} /> ) - : (glFallback || leafletFallback) && + : pillState && // One chunk per engine: picking the binding here is what keeps mapbox-gl and // maplibre-gl out of each other's downloads. const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox @@ -79,7 +55,7 @@ export function MapViewAuto(props: MapViewAutoProps) { <> }> }> - + {pill} @@ -94,11 +70,6 @@ export function MapViewAuto(props: MapViewAutoProps) { ) } -/** A raster template cannot be served offline in the iOS app unless it has its tile store. */ -function nativeIosWithoutStore(nativeStore: boolean): boolean | undefined { - return nativeStore ? false : undefined -} - const PILL = 'absolute inset-x-0 z-[5] mx-auto flex w-fit items-center gap-1.5 rounded-full border border-edge bg-surface-card px-3 py-1 text-caption font-semibold text-content-secondary shadow-sm backdrop-blur-md bottom-[calc(var(--bottom-nav-h,0px)+12px)]' /** diff --git a/client/src/components/Map/useEffectiveMapEngine.test.ts b/client/src/components/Map/useEffectiveMapEngine.test.ts new file mode 100644 index 000000000..344d84f05 --- /dev/null +++ b/client/src/components/Map/useEffectiveMapEngine.test.ts @@ -0,0 +1,175 @@ +/** + * Which engine draws a map, and what it draws offline (FE-MAP-EFFENGINE-*). + * + * The same cases as MapViewAuto.offline.test.tsx, asked of the hook alone, plus + * the online choice it took over from MapViewAuto: the user's provider where it + * can run, Leaflet where it cannot. No case writes a setting. + */ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'; +import { useSettingsStore } from '../../store/settingsStore'; +import { resetWebGLProbe } from '../../utils/webgl'; +import { useEffectiveMapEngine } from './useEffectiveMapEngine'; + +const env = vi.hoisted(() => ({ offline: false, dark: false, tileStore: false })); + +vi.mock('../../hooks/useNetworkMode', () => ({ + useNetworkMode: () => ({ offline: env.offline, forced: false, setForced: () => {} }), +})); +vi.mock('../../hooks/useIsDark', () => ({ useIsDark: () => env.dark })); +vi.mock('../../native/tileCache', () => ({ + tileCacheActive: () => env.tileStore, + glTileStoreActive: () => env.tileStore, +})); +vi.mock('../../native/platform', async (importOriginal) => ({ + ...(await importOriginal()), + isNativeIos: () => false, +})); + +const OSM = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; +const OWN_RASTER = 'https://tiles.example.com/{z}/{x}/{y}.png'; +const realGetContext = HTMLCanvasElement.prototype.getContext; + +function withWebGL2(available: boolean) { + const ctx = { getExtension: () => ({ loseContext: () => {} }) }; + HTMLCanvasElement.prototype.getContext = vi.fn((type: string) => + available && type === 'webgl2' ? ctx : null + ) as unknown as typeof realGetContext; +} + +function settings(values: Record) { + seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, ...values } }); +} + +beforeEach(() => { + resetAllStores(); + resetWebGLProbe(); + env.offline = false; + env.dark = false; + env.tileStore = false; + withWebGL2(true); +}); + +afterEach(() => { + HTMLCanvasElement.prototype.getContext = realGetContext; + resetWebGLProbe(); +}); + +describe('useEffectiveMapEngine online', () => { + it('FE-MAP-EFFENGINE-001: Leaflet, the code default, draws with Leaflet and swaps nothing', () => { + const { result } = renderHook(() => useEffectiveMapEngine(OSM)); + expect(result.current).toEqual({ + engine: null, + styleOverride: undefined, + tileUrlOverride: undefined, + pill: null, + }); + }); + + it('FE-MAP-EFFENGINE-002: MapLibre draws with MapLibre', () => { + settings({ map_provider: 'maplibre-gl', maplibre_style: 'https://tiles.openfreemap.org/styles/bright' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ engine: 'maplibre-gl', styleOverride: undefined, pill: null }); + }); + + it('FE-MAP-EFFENGINE-003: Mapbox with a token draws with Mapbox', () => { + settings({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ engine: 'mapbox-gl', styleOverride: undefined, pill: null }); + }); + + it('FE-MAP-EFFENGINE-004: Mapbox without a token falls back to Leaflet', () => { + settings({ map_provider: 'mapbox-gl', mapbox_access_token: '' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current.engine).toBeNull(); + }); + + it('FE-MAP-EFFENGINE-005: without WebGL2 either GL provider falls back to Leaflet, the setting untouched', () => { + withWebGL2(false); + settings({ map_provider: 'maplibre-gl' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current.engine).toBeNull(); + expect(useSettingsStore.getState().settings.map_provider).toBe('maplibre-gl'); + }); +}); + +describe('useEffectiveMapEngine offline', () => { + beforeEach(() => { + env.offline = true; + }); + + it('FE-MAP-EFFENGINE-010: a Mapbox map draws the stored basemap with MapLibre and says so', () => { + env.dark = true; + settings({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ engine: 'maplibre-gl', styleOverride: OFM_DARK, pill: { kind: 'stored' } }); + }); + + it('FE-MAP-EFFENGINE-011: a MapLibre map already on a stored style stays as it is', () => { + settings({ map_provider: 'maplibre-gl', maplibre_style: OFM_POSITRON }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ engine: 'maplibre-gl', styleOverride: undefined, pill: null }); + }); + + it('FE-MAP-EFFENGINE-012: a MapLibre map on another OpenFreeMap style swaps to the stored one', () => { + settings({ map_provider: 'maplibre-gl', maplibre_style: 'https://tiles.openfreemap.org/styles/liberty' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ + engine: 'maplibre-gl', + styleOverride: OFM_POSITRON, + pill: { kind: 'stored' }, + }); + }); + + it('FE-MAP-EFFENGINE-013: Leaflet on OpenStreetMap tiles switches to the stored basemap', () => { + const { result } = renderHook(() => useEffectiveMapEngine(OSM)); + expect(result.current).toMatchObject({ engine: null, tileUrlOverride: OFM_POSITRON, pill: { kind: 'stored' } }); + }); + + it('FE-MAP-EFFENGINE-014: a raster template the service worker stored stays', () => { + const { result } = renderHook(() => useEffectiveMapEngine(OWN_RASTER)); + expect(result.current).toMatchObject({ engine: null, tileUrlOverride: undefined, pill: null }); + }); + + it('FE-MAP-EFFENGINE-015: Leaflet with no template of its own draws the stored default and needs no pill', () => { + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ engine: null, tileUrlOverride: undefined, pill: null }); + }); + + it('FE-MAP-EFFENGINE-016: a Leaflet fallback (no WebGL2) is checked as Leaflet, not as the GL provider', () => { + withWebGL2(false); + settings({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' }); + const { result } = renderHook(() => useEffectiveMapEngine(OSM)); + expect(result.current).toMatchObject({ engine: null, styleOverride: undefined, tileUrlOverride: OFM_POSITRON }); + }); + + it('FE-MAP-EFFENGINE-017: in the iOS app with its tile store, Mapbox stays and the pill switches to the stored map', () => { + env.tileStore = true; + settings({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.test' }); + const { result } = renderHook(() => useEffectiveMapEngine(undefined)); + expect(result.current).toMatchObject({ + engine: 'mapbox-gl', + styleOverride: undefined, + pill: { kind: 'toggle', pressed: false }, + }); + + const { pill } = result.current; + act(() => { + if (pill?.kind === 'toggle') pill.onToggle(); + }); + expect(result.current).toMatchObject({ + engine: 'maplibre-gl', + styleOverride: OFM_POSITRON, + pill: { kind: 'toggle', pressed: true }, + }); + }); + + it('FE-MAP-EFFENGINE-018: with the tile store, a raster template stays offline in the app too', () => { + env.tileStore = true; + const { result } = renderHook(() => useEffectiveMapEngine(OWN_RASTER)); + expect(result.current).toMatchObject({ engine: null, tileUrlOverride: undefined, pill: null }); + }); +}); diff --git a/client/src/components/Map/useEffectiveMapEngine.ts b/client/src/components/Map/useEffectiveMapEngine.ts new file mode 100644 index 000000000..acd69ef0c --- /dev/null +++ b/client/src/components/Map/useEffectiveMapEngine.ts @@ -0,0 +1,76 @@ +import { useState } from 'react'; + +import { OFM_POSITRON } from '../../constants/mapDefaults'; +import { useIsDark } from '../../hooks/useIsDark'; +import { useNetworkMode } from '../../hooks/useNetworkMode'; +import { glTileStoreActive, tileCacheActive } from '../../native/tileCache'; +import { useSettingsStore } from '../../store/settingsStore'; +import type { GlMapProvider } from './glProviders'; +import { useGlRenderer } from './glSupport'; +import { glWorksOffline, leafletWorksOffline, offlineStyleFor } from './offlineBasemap'; + +/** What the map says about the basemap on screen when it is not the user's own. */ +type OfflineBasemapPill = + /** The stored basemap stands in, and that is all there is to say. */ + | { kind: 'stored' } + /** The user's map is kept as far as it was viewed; the pill switches to the stored region and back. */ + | { kind: 'toggle'; pressed: boolean; onToggle: () => void }; + +export interface EffectiveMapEngine { + /** The GL engine that draws this render, or null for Leaflet. */ + engine: GlMapProvider | null; + /** The style a GL map draws instead of the user's: the stored offline basemap. */ + styleOverride?: string; + /** The basemap the Leaflet map draws instead of the user's template, for the same reason. */ + tileUrlOverride?: string; + pill: OfflineBasemapPill | null; +} + +/** + * Which engine draws a map and what it draws, for this render. + * + * The user's provider decides, as far as it can run here: Mapbox needs a token, + * and both GL engines need WebGL2, so a map never fails to start and falls back + * to Leaflet with the user's template instead. Nothing here writes a setting. + * + * Offline, a basemap with nothing stored to draw from switches to the stored + * OpenFreeMap one ("prepare for offline" keeps it for every trip, whatever the + * provider, sync/tilePrefetcher.ts), with the same markers and routes, and says + * so with a pill. It switches back once the connection returns. In the iOS app + * with its tile store, a Mapbox map keeps what was viewed for 30 days, so offline + * it stays Mapbox and the pill offers the stored trip region instead. + * + * `tileUrl` is the template the caller resolved for Leaflet. The offline checks + * run on the engine that actually draws, so the decision and the fallback can + * never disagree. + */ +export function useEffectiveMapEngine(tileUrl: string | undefined): EffectiveMapEngine { + const provider = useSettingsStore((s) => s.settings.map_provider); + const token = useSettingsStore((s) => s.settings.mapbox_access_token); + const maplibreStyle = useSettingsStore((s) => s.settings.maplibre_style); + const configuredGl = useGlRenderer(provider, token); + const { offline } = useNetworkMode(); + const offlineStyle = offlineStyleFor(useIsDark()); + const [preferStored, setPreferStored] = useState(false); + + const mapboxKept = configuredGl === 'mapbox-gl' && glTileStoreActive(); + const glFallback = + !!configuredGl && offline && !glWorksOffline(configuredGl, maplibreStyle) && (!mapboxKept || preferStored); + // A raster template cannot be served offline in the iOS app unless it has its tile store. + const nativeIos = tileCacheActive() ? false : undefined; + const leafletFallback = !configuredGl && offline && !leafletWorksOffline(tileUrl ?? OFM_POSITRON, nativeIos); + + let pill: OfflineBasemapPill | null = null; + if (offline && mapboxKept) { + pill = { kind: 'toggle', pressed: preferStored, onToggle: () => setPreferStored((v) => !v) }; + } else if (glFallback || leafletFallback) { + pill = { kind: 'stored' }; + } + + return { + engine: glFallback ? 'maplibre-gl' : configuredGl, + styleOverride: glFallback ? offlineStyle : undefined, + tileUrlOverride: leafletFallback ? offlineStyle : undefined, + pill, + }; +}