mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
feat(settings): keep the account's settings for a start without a connection
/api/settings is never cached, so an app started offline ran on DEFAULT_SETTINGS until the server answered: Leaflet instead of the map the user chose, and the default units. The answer the server gave last time now stands in until the next one arrives. - Dexie v18 adds accountSettings, one row in the signed-in user's own database, so another account on the device never reads it and logout deletes it with the database. The anonymous database never holds one. A new table only; the upgrade test covers it. - loadSettings lays the kept answer over the defaults while nothing newer arrived and keeps every server answer. A key the server then leaves out goes back to its default, so the server stays the source of truth. - A setting the server accepted is laid over the kept answer, so a change made online is what the next offline start shows. A refused save keeps nothing. Keeping is best effort: where IndexedDB is refused the app starts on the defaults as before.
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The settings on a start without a connection (FE-STORE-SETTINGS-OFFLINE-*).
|
||||
*
|
||||
* Until the server answers, the answer it gave last time stands in, so the map
|
||||
* shows the provider, style and template the user chose instead of
|
||||
* DEFAULT_SETTINGS (Leaflet). The server stays the source of truth: its answer
|
||||
* replaces the stand-in, and only what it accepted is kept for next time.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { settingsApi } from '../api/client';
|
||||
import { cacheAccountSettings, cachedAccountSettings } from '../db/cacheAccountSettings';
|
||||
import { deleteCurrentUserDb, reopenAnonymous, reopenForUser } from '../db/offlineDb';
|
||||
import { DEFAULT_SETTINGS, useSettingsStore } from './settingsStore';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
settingsApi: {
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
setBulk: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../sync/tilePrefetcher', () => ({ clearTileCache: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const BRIGHT = 'https://tiles.openfreemap.org/styles/bright';
|
||||
const OSM_DE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
const initialState = useSettingsStore.getState();
|
||||
const settings = () => useSettingsStore.getState().settings;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.mocked(settingsApi.get).mockReset();
|
||||
vi.mocked(settingsApi.set).mockReset().mockResolvedValue(undefined);
|
||||
vi.mocked(settingsApi.setBulk).mockReset().mockResolvedValue(undefined);
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
useSettingsStore.setState(initialState, true);
|
||||
await reopenForUser(801);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await deleteCurrentUserDb();
|
||||
await reopenAnonymous();
|
||||
});
|
||||
|
||||
describe('settings without a connection', () => {
|
||||
it('FE-STORE-SETTINGS-OFFLINE-001: the kept answer stands in when the server cannot be reached', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT, map_tile_url: OSM_DE });
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
|
||||
await vi.waitFor(() => expect(settings().map_provider).toBe('maplibre-gl'));
|
||||
expect(settings()).toMatchObject({ maplibre_style: BRIGHT, map_tile_url: OSM_DE });
|
||||
// Still not loaded, so the reconnect triggers keep asking the server.
|
||||
expect(useSettingsStore.getState().isLoaded).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-002: with nothing kept the defaults stay, as before', async () => {
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe(DEFAULT_SETTINGS.map_provider);
|
||||
});
|
||||
|
||||
it("FE-STORE-SETTINGS-OFFLINE-003: the server's answer wins over the kept one and is kept in its place", async () => {
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT });
|
||||
vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'mapbox-gl' } } as never);
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
// Let the read of the kept answer settle, whichever of the two came first.
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe('mapbox-gl');
|
||||
// A key the server no longer sends is not set any more: back to its default.
|
||||
expect(settings().maplibre_style).toBe(DEFAULT_SETTINGS.maplibre_style);
|
||||
await vi.waitFor(async () => expect(await cachedAccountSettings()).toEqual({ map_provider: 'mapbox-gl' }));
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-004: a kept answer arriving after the server answered changes nothing', async () => {
|
||||
vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'leaflet' } } as never);
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl' });
|
||||
|
||||
// A second load (a reconnect trigger) while the first answer is in place.
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe('leaflet');
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-005: a setting the server accepted is kept for the next start', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'leaflet', distance_unit: 'imperial' });
|
||||
|
||||
await useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl');
|
||||
|
||||
await vi.waitFor(async () =>
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', distance_unit: 'imperial' })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-006: several settings saved at once are kept together', async () => {
|
||||
await useSettingsStore.getState().updateSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT });
|
||||
|
||||
await vi.waitFor(async () =>
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-007: a save the server refused is not kept', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'leaflet' });
|
||||
vi.mocked(settingsApi.set).mockRejectedValue(new Error('Network Error'));
|
||||
vi.mocked(settingsApi.setBulk).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await expect(useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl')).rejects.toThrow();
|
||||
await expect(useSettingsStore.getState().updateSettings({ map_provider: 'mapbox-gl' })).rejects.toThrow();
|
||||
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet' });
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
|
||||
import { detectBrowserLanguage } from '../i18n/detectBrowserLanguage'
|
||||
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'
|
||||
|
||||
interface SettingsState {
|
||||
@@ -115,6 +116,11 @@ export const DEFAULT_SETTINGS: Settings = {
|
||||
// periodic) can all fire a retry at once — collapse them into one in-flight GET.
|
||||
let _loadInFlight: Promise<void> | null = null
|
||||
|
||||
// The keys the kept answer laid over the defaults while the server was still out
|
||||
// (see loadSettings). A key the server then leaves out is one the account no
|
||||
// longer sets, so it goes back to its default rather than keeping the old value.
|
||||
let _standInKeys: (keyof Settings)[] = []
|
||||
|
||||
// Every tile consumer (planner map, journey map, tile prefetcher, the settings
|
||||
// preview) reads the template from this store, so the retired
|
||||
// {s}.tile.openstreetmap.org host is rewritten here — on the way in from the
|
||||
@@ -139,15 +145,29 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
loadSettings: async () => {
|
||||
if (_loadInFlight !== null) return _loadInFlight
|
||||
_loadInFlight = (async () => {
|
||||
// Until the server answers, the settings it answered last time stand in, so
|
||||
// a start without a connection draws the user's own map and units instead
|
||||
// of the defaults (DEFAULT_SETTINGS means Leaflet). Laid only while nothing
|
||||
// newer arrived: once the server answered, its answer is the truth.
|
||||
void cachedAccountSettings().then((kept) => {
|
||||
if (!kept || get().isLoaded) return
|
||||
_standInKeys = Object.keys(kept) as (keyof Settings)[]
|
||||
set((state) => ({ settings: { ...state.settings, ...kept } }))
|
||||
})
|
||||
try {
|
||||
const data = await settingsApi.get()
|
||||
// Rewritten here so the Map settings input already shows the host that
|
||||
// still resolves, and persists it on the next save.
|
||||
const incoming = withNormalizedTileUrl({ ...data.settings } as Partial<Settings>)
|
||||
const unset = Object.fromEntries(
|
||||
_standInKeys.filter((key) => !(key in incoming)).map((key) => [key, DEFAULT_SETTINGS[key]])
|
||||
) as Partial<Settings>
|
||||
_standInKeys = []
|
||||
set((state) => ({
|
||||
settings: { ...state.settings, ...incoming },
|
||||
settings: { ...state.settings, ...unset, ...incoming },
|
||||
isLoaded: true,
|
||||
}))
|
||||
void cacheAccountSettings(incoming)
|
||||
// The startup redirect runs before this ever resolves, so keep a mirror
|
||||
// it can read synchronously on the next launch.
|
||||
rememberStartDestination(incoming)
|
||||
@@ -189,6 +209,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
rememberStartDestination({ [key]: next } as Partial<Settings>)
|
||||
try {
|
||||
await settingsApi.set(key, next)
|
||||
void cacheAccountSettingsPatch({ [key]: next } as Partial<Settings>)
|
||||
} catch (err: unknown) {
|
||||
console.error('Failed to save setting:', err)
|
||||
throw new Error(getApiErrorMessage(err, 'Error saving setting'))
|
||||
@@ -221,6 +242,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
rememberStartDestination(patch)
|
||||
try {
|
||||
await settingsApi.setBulk(patch)
|
||||
void cacheAccountSettingsPatch(patch)
|
||||
} catch (err: unknown) {
|
||||
console.error('Failed to save settings:', err)
|
||||
throw new Error(getApiErrorMessage(err, 'Error saving settings'))
|
||||
|
||||
Reference in New Issue
Block a user