diff --git a/client/src/components/Map/VectorBasemap.tsx b/client/src/components/Map/VectorBasemap.tsx index c53b8de61..5ed18cc24 100644 --- a/client/src/components/Map/VectorBasemap.tsx +++ b/client/src/components/Map/VectorBasemap.tsx @@ -264,12 +264,14 @@ export function VectorBasemap({ style, hideLabels = false }: { style: string; hi // The style is read through a ref, never from the dependency list: a style // change must retile in place rather than tear the layer down, the same // reason the raster maps keep their template out of the build effect (#2097). - const layer = maplibreGL({ + const options = { style: offlineStyle(styleRef.current), interactive: false, attributionControl: false, + // The Leaflet bridge reads this option. Its published type lists only GL options. padding: mapDeviceTier() === 'full' ? 0.25 : 0.1, - }) + } satisfies Parameters[0] & { padding: number } + const layer = maplibreGL(options) if (!attachGlLayer(map, layer, styleRef.current)) { setGlUsable(false) return diff --git a/client/src/components/Map/glLazy.tsx b/client/src/components/Map/glLazy.tsx index 6b734b79b..3818cdd99 100644 --- a/client/src/components/Map/glLazy.tsx +++ b/client/src/components/Map/glLazy.tsx @@ -48,7 +48,7 @@ export function preloadTripMapRenderer(provider: string | undefined, token: stri const engine = pickGlRenderer(provider, token) if (!engine) return const view = engine === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox - void view.preload().catch(() => { /* The map boundary handles this if the user opens a map. */ }) + void view.preload().catch((error: unknown) => console.debug('[map] renderer preload failed', error)) } export const JourneyMapGLMapbox = lazyWithRetry(async () => { diff --git a/client/src/components/Map/glSupport.ts b/client/src/components/Map/glSupport.ts index 6add08850..a0840575d 100644 --- a/client/src/components/Map/glSupport.ts +++ b/client/src/components/Map/glSupport.ts @@ -1,10 +1,17 @@ import { useSyncExternalStore } from 'react'; import { offlineStyle } from '../../native/offlineTiles'; -import { hasWebGL, reportWebGLFailure, subscribeWebGL, webGLFailures } from '../../utils/webgl'; +import { + hasGlEngineFailure, + hasWebGL, + reportGlEngineFailure, + reportWebGLFailure, + subscribeWebGL, + webGLFailures, +} from '../../utils/webgl'; import { isGlRasterStyle, type GlStyle } from './glBasemap'; import { rememberMapLibreBasemap } from './glBasemapSwap'; import type { GlMapProvider } from './glProviders'; -import { hasGlEngineFailure, reportGlEngineFailure, subscribeGlEngineFailure, watchGlEngine } from './glWatchdog'; +import { watchGlEngine } from './glWatchdog'; import { watchRasterHealth } from './rasterHealth'; /* @@ -50,7 +57,7 @@ export function useGlRenderer( export function useGlEngineFailed(provider: GlMapProvider | null): boolean { const snapshot = () => provider !== null && hasGlEngineFailure(provider); - return useSyncExternalStore(subscribeGlEngineFailure, snapshot, snapshot); + return useSyncExternalStore(subscribeWebGL, snapshot, snapshot); } /** Whether 3D (the GL terrain map) can run here, kept current the same way. */ diff --git a/client/src/components/Map/glWatchdog.test.ts b/client/src/components/Map/glWatchdog.test.ts index 4c0ee3f99..1e1329012 100644 --- a/client/src/components/Map/glWatchdog.test.ts +++ b/client/src/components/Map/glWatchdog.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { clearGlEngineFailure, hasGlEngineFailure, watchGlEngine } from './glWatchdog'; +import { clearGlEngineFailure, hasGlEngineFailure } from '../../utils/webgl'; +import { watchGlEngine } from './glWatchdog'; function fixture() { const canvas = document.createElement('canvas'); diff --git a/client/src/components/Map/glWatchdog.ts b/client/src/components/Map/glWatchdog.ts index 8354e71d3..7adacf46d 100644 --- a/client/src/components/Map/glWatchdog.ts +++ b/client/src/components/Map/glWatchdog.ts @@ -1,50 +1,11 @@ import { OPENFREEMAP_HOST } from '@trek/shared'; +import { reportGlEngineFailure } from '../../utils/webgl'; import type { GlMapProvider } from './glProviders'; const RESTORE_GRACE_MS = 3000; const REPEATED_LOSS_MS = 60_000; -const sessionKey = (provider: GlMapProvider) => `glBlank:${provider}`; -const failures = new Set(); -const listeners = new Set<() => void>(); - -export function hasGlEngineFailure(provider: GlMapProvider): boolean { - if (failures.has(provider)) return true; - try { - return globalThis.sessionStorage?.getItem(sessionKey(provider)) === '1'; - } catch { - return false; - } -} - -export function subscribeGlEngineFailure(listener: () => void): () => void { - listeners.add(listener); - return () => listeners.delete(listener); -} - -export function reportGlEngineFailure(provider: GlMapProvider): void { - if (hasGlEngineFailure(provider)) return; - failures.add(provider); - try { - globalThis.sessionStorage?.setItem(sessionKey(provider), '1'); - } catch { - // A browser that blocks storage still falls back on this page. - } - for (const listener of listeners) listener(); -} - -export function clearGlEngineFailure(provider: GlMapProvider): void { - if (!hasGlEngineFailure(provider)) return; - failures.delete(provider); - try { - globalThis.sessionStorage?.removeItem(sessionKey(provider)); - } catch { - // The in-memory flag has already been cleared. - } - for (const listener of listeners) listener(); -} - interface WatchedGlMap { getCanvas(): HTMLCanvasElement; getContainer(): HTMLElement; diff --git a/client/src/components/Map/leafletRasterTuning.ts b/client/src/components/Map/leafletRasterTuning.ts index e7123c024..9939e2ef0 100644 --- a/client/src/components/Map/leafletRasterTuning.ts +++ b/client/src/components/Map/leafletRasterTuning.ts @@ -3,7 +3,7 @@ import L from 'leaflet'; import { templateHost } from '../../utils/tileUrl'; -export function rasterUpdatesWhenIdle(template: string, mobile = L.Browser.mobile): boolean { +export function rasterUpdatesWhenIdle(template: string, mobile = L.Browser?.mobile ?? true): boolean { const host = templateHost(template); return mobile || (host !== 'tile.openstreetmap.de' && host !== OPENFREEMAP_HOST); } diff --git a/client/src/components/Map/useEffectiveMapEngine.ts b/client/src/components/Map/useEffectiveMapEngine.ts index 6acc5ca32..05678929d 100644 --- a/client/src/components/Map/useEffectiveMapEngine.ts +++ b/client/src/components/Map/useEffectiveMapEngine.ts @@ -94,10 +94,15 @@ export function useEffectiveMapEngine(tileUrl: string | undefined): EffectiveMap pill = { kind: 'classic' }; } + if (glFallback) { + return maplibreFailed + ? { engine: null, tileUrlOverride: offlineStyle, pill } + : { engine: 'maplibre-gl', styleOverride: offlineStyle, pill }; + } return { - engine: glFallback ? (maplibreFailed ? null : 'maplibre-gl') : drawn.engine, - styleOverride: glFallback && !maplibreFailed ? offlineStyle : drawn.style, - tileUrlOverride: leafletFallback || (glFallback && maplibreFailed) ? offlineStyle : undefined, + engine: drawn.engine, + styleOverride: drawn.style, + tileUrlOverride: leafletFallback ? offlineStyle : undefined, pill, }; } diff --git a/client/src/components/Map/useGlStyle.ts b/client/src/components/Map/useGlStyle.ts index 5a2c8a981..9d191e5f4 100644 --- a/client/src/components/Map/useGlStyle.ts +++ b/client/src/components/Map/useGlStyle.ts @@ -1,4 +1,4 @@ -import { useEffect, useRef, type RefObject } from 'react'; +import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'; import { useSettingsStore } from '../../store/settingsStore'; import type { GlStyle } from './glBasemap'; @@ -16,7 +16,9 @@ export function useGlStyle(provider: GlMapProvider, override: GlStyle | undefine const maplibreStyle = useSettingsStore((s) => s.settings.maplibre_style || ''); const style = override ?? styleForActiveProvider(provider, mapboxStyle, maplibreStyle); const latestStyle = useRef(style); - latestStyle.current = style; + useLayoutEffect(() => { + latestStyle.current = style; + }, [style]); const canSwap = provider === 'maplibre-gl' && preservesMapLibreLayers(style); useEffect(() => { if (canSwap) swapMapLibreBasemap(map.current, style); diff --git a/client/src/store/settingsStore.ts b/client/src/store/settingsStore.ts index 505c0f16f..5bcffa9b9 100644 --- a/client/src/store/settingsStore.ts +++ b/client/src/store/settingsStore.ts @@ -9,7 +9,7 @@ import { normalizeTileUrl, stripTileApiKey } from '../utils/tileUrl' import { clearTileCache } from '../sync/tilePrefetcher' import { cacheAccountSettings, cacheAccountSettingsPatch, cachedAccountSettings } from '../db/cacheAccountSettings' import { rememberStartDestination, DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../utils/startDestination' -import { clearGlEngineFailure } from '../components/Map/glWatchdog' +import { clearGlEngineFailure } from '../utils/webgl' function retrySelectedEngine(previous: Settings['map_provider'], next: Settings[keyof Settings]) { if (previous !== next && (next === 'mapbox-gl' || next === 'maplibre-gl')) clearGlEngineFailure(next) diff --git a/client/src/sync/glTileCache.test.ts b/client/src/sync/glTileCache.test.ts index 04380b8b2..fec5ecbcb 100644 --- a/client/src/sync/glTileCache.test.ts +++ b/client/src/sync/glTileCache.test.ts @@ -58,7 +58,7 @@ describe('isGlRasterTileRequest', () => { }); it('FE-SYNC-GLTILECACHE-005: every host in the inline list is one the CSP lets a GL map fetch', () => { - const inline = [...isGlRasterTileRequest.toString().matchAll(/'([^']+\.[a-z]+)'/g)].map((m) => m[1]); + const inline = [...isGlRasterTileRequest.toString().matchAll(/(['"])([^'"]+\.[a-z]+)\1/g)].map((m) => m[2]); expect(inline.length).toBeGreaterThan(0); for (const host of inline) expect(RASTER_TILE_HOSTS, host).toContain(host); }); diff --git a/client/src/utils/webgl.ts b/client/src/utils/webgl.ts index 7804662c6..bf00fec3e 100644 --- a/client/src/utils/webgl.ts +++ b/client/src/utils/webgl.ts @@ -1,3 +1,5 @@ +import type { Settings } from '../types' + /** * Whether this browser will hand a GL map a WebGL2 context. MapLibre 6 and * Mapbox GL 3 both ask for webgl2 and nothing else. @@ -31,6 +33,40 @@ export function hasWebGL(): boolean { const listeners = new Set<() => void>() let failures = 0 +type GlEngine = Exclude, 'leaflet'> +const engineFailures = new Set() +const engineKey = (engine: GlEngine) => `glBlank:${engine}` + +export function hasGlEngineFailure(engine: GlEngine): boolean { + if (engineFailures.has(engine)) return true + try { + return globalThis.sessionStorage?.getItem(engineKey(engine)) === '1' + } catch { + return false + } +} + +export function reportGlEngineFailure(engine: GlEngine): void { + if (hasGlEngineFailure(engine)) return + engineFailures.add(engine) + try { + globalThis.sessionStorage?.setItem(engineKey(engine), '1') + } catch { + // The page still remembers the failure in memory. + } + for (const listener of listeners) listener() +} + +export function clearGlEngineFailure(engine: GlEngine): void { + if (!hasGlEngineFailure(engine)) return + engineFailures.delete(engine) + try { + globalThis.sessionStorage?.removeItem(engineKey(engine)) + } catch { + // The page's in-memory flag has already been cleared. + } + for (const listener of listeners) listener() +} /** * A GL map that failed to build although the probe said yes: a GPU that offers diff --git a/server/src/db/seeders/MapDefaultsSeeder.ts b/server/src/db/seeders/MapDefaultsSeeder.ts index 2042f4b88..a63f7f9b5 100644 --- a/server/src/db/seeders/MapDefaultsSeeder.ts +++ b/server/src/db/seeders/MapDefaultsSeeder.ts @@ -1,3 +1,5 @@ +import { resolveEngine } from '../engine'; +import { writeTransaction } from '../engine/write-transaction'; import type { DB } from '../kysely/db'; import type { EntityManager } from '@mikro-orm/core'; import { Seeder } from '@mikro-orm/seeder'; @@ -10,7 +12,7 @@ const STYLE = 'default_user_setting_maplibre_style'; /** Give a new installation a starting basemap before its first user is created. */ export class MapDefaultsSeeder extends Seeder { async run(em: EntityManager): Promise { - await em.transactional(async (tx) => { + await writeTransaction(em, resolveEngine(), async (tx) => { const db = (tx as SqlEntityManager).getKysely>(); // SchemaVersionSeeder writes this marker after the first bootstrap even on // SSO-only installations that are still waiting for their first account. diff --git a/server/src/nest/settings/settings.service.ts b/server/src/nest/settings/settings.service.ts index f2d64a1e7..7f486e9a6 100644 --- a/server/src/nest/settings/settings.service.ts +++ b/server/src/nest/settings/settings.service.ts @@ -282,7 +282,6 @@ export class SettingsService { // null/undefined means "reset to built-in default" — delete the row if (value === null || value === undefined) { await this.appSettings.deleteValue(appKey); - if (key === 'map_provider') await this.appSettings.deleteValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY); continue; } @@ -300,9 +299,11 @@ export class SettingsService { ? (maybe_encrypt_api_key(String(value)) ?? String(value)) : JSON.stringify(value); await this.appSettings.setValue(appKey, stored); - // The admin page saves a field only when the admin sets it, so a stored - // provider default is always a choice a managed install has to keep. - if (key === 'map_provider') await this.appSettings.setValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY, 'true'); + } + // An admin provider change and its marker are one transaction. + if (Object.hasOwn(partial, 'map_provider')) { + if (partial.map_provider == null) await this.appSettings.deleteValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY); + else await this.appSettings.setValue(MAP_PROVIDER_DEFAULT_CHOSEN_KEY, 'true'); } }); } diff --git a/server/tests/build-schema-snapshot.ts b/server/tests/build-schema-snapshot.ts index f59761a92..21691bdce 100644 --- a/server/tests/build-schema-snapshot.ts +++ b/server/tests/build-schema-snapshot.ts @@ -5,7 +5,9 @@ // transform pipeline, where Node's native resolver rejects the extensionless // imports these CommonJS-target modules use ('../migration-utils'). tsx resolves // them, and it is already how `gen:plugin-facts` runs TypeScript directly. +import type { DB } from '../src/db/kysely/db'; import { schemaSnapshotPath, writeSchemaSnapshot } from '../src/db/schema-snapshot'; +import type { SqlEntityManager } from '@mikro-orm/sql'; import fs from 'node:fs'; @@ -18,10 +20,8 @@ async function main(): Promise { fs.rmSync(schemaSnapshotPath(), { force: true }); const { getRawConnection } = await import('../src/db/database'); - const { AppSettings } = await import('../src/db/entities/AppSettings.entity'); const { runSchemaBootstrap } = await import('../src/db/orm'); const { createStandaloneOrm } = await import('../src/db/standalone-orm'); - const { deleteRows } = await import('./helpers/factories/rows'); // The shared driver binds to the connection database.ts opens on the ORM's // first connect, so this migrates that in-memory database and it can be @@ -29,10 +29,13 @@ async function main(): Promise { const orm = await createStandaloneOrm(); try { await runSchemaBootstrap(orm, { snapshot: true }); - // Suites using the historical snapshot opt into admin defaults themselves. - await deleteRows(orm, AppSettings, { - key: { $in: ['default_user_setting_map_provider', 'default_user_setting_maplibre_style'] }, - }); + // The snapshot ORM has no entity metadata. Suites opt into defaults themselves. + const em = orm.em.fork() as SqlEntityManager; + await em + .getKysely>() + .deleteFrom('app_settings') + .where('key', 'in', ['default_user_setting_map_provider', 'default_user_setting_maplibre_style']) + .execute(); writeSchemaSnapshot(getRawConnection().serialize()); console.log(`[test-db] schema snapshot written to ${schemaSnapshotPath()}`); } finally {