The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(admin): a default setting reset right after typing is the value that stays
Maurice692659111214
diff --git a/client/src/components/Admin/DefaultUserSettingsTab.test.tsx b/client/src/components/Admin/DefaultUserSettingsTab.test.tsxindex d7b75e021..213d8885e 100644--- a/client/src/components/Admin/DefaultUserSettingsTab.test.tsx+++ b/client/src/components/Admin/DefaultUserSettingsTab.test.tsx@@ -1,7 +1,7 @@// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';-import { http, HttpResponse } from 'msw';+import { delay, http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildAdmin } from '../../../tests/helpers/factories';@@ -352,6 +352,35 @@ describe('DefaultUserSettingsTab', () => {await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));});+ it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {+ const user = userEvent.setup();+ const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });+ // The save is the slower request: sent at once, the reset would overtake it.+ const done: string[] = [];+ server.use(+ http.put('/api/admin/default-user-settings', async ({ request }) => {+ const body = await request.json() as Record<string, unknown>;+ if (body.mapbox_access_token !== null) await delay(100);+ if (body.mapbox_access_token === null) delete state.mapbox_access_token;+ else state.mapbox_access_token = body.mapbox_access_token;+ done.push(body.mapbox_access_token === null ? 'reset' : 'save');+ return HttpResponse.json({ ...state });+ }),+ );+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Shared Mapbox token');++ const input = screen.getByPlaceholderText('pk.eyJ…');+ await user.clear(input);+ await user.type(input, 'pk.new');+ // The click leaves the field, which saves it, and resets it right after.+ await user.click(resetLink('Shared Mapbox token'));++ await waitFor(() => expect(done).toEqual(['save', 'reset']));+ expect(state.mapbox_access_token).toBeUndefined();+ await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));+ });+it('FE-ADMIN-DUS-020: a hand-typed MapLibre style is normalised to OpenFreeMap on blur', async () => {const user = userEvent.setup();const { puts } = stubDefaults({ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY });diff --git a/client/src/components/Admin/useDefaultUserSettings.test.ts b/client/src/components/Admin/useDefaultUserSettings.test.tsindex ee91ecfe4..77b8ceebd 100644--- a/client/src/components/Admin/useDefaultUserSettings.test.ts+++ b/client/src/components/Admin/useDefaultUserSettings.test.ts@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {act(() => result.current.pickTilePreset(''));act(() => result.current.pickStylePreset(''));+ // Writes go out in order, a microtask later: let any that was queued start first.+ await act(async () => {});expect(update).not.toHaveBeenCalled();act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');- expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });+ await waitFor(() =>+ expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })+ );act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));- expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });+ await waitFor(() =>+ expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })+ );act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));act(() => result.current.commitStyle());expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);- expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });+ await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));});});diff --git a/client/src/components/Admin/useDefaultUserSettings.ts b/client/src/components/Admin/useDefaultUserSettings.tsindex 03ec42d0e..278a15180 100644--- a/client/src/components/Admin/useDefaultUserSettings.ts+++ b/client/src/components/Admin/useDefaultUserSettings.ts@@ -1,6 +1,7 @@import { useEffect, useState } from 'react';import { adminApi } from '../../api/client';+import { useWritesInOrder } from '../../hooks/useWritesInOrder';import { useTranslation } from '../../i18n';import { useAuthStore } from '../../store/authStore';import { useSettingsStore } from '../../store/settingsStore';@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau.catch(() => setLoaded(true));}, []);- const save = async (patch: Partial<Defaults>) => {- try {- const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);- setDefaults(updated);- toast.success(t('admin.defaultSettings.saved'));- } catch (err: unknown) {- toast.error(errorMessage(err, t('common.error')));- }- };-- const reset = async (key: keyof Defaults) => {- try {- const updated = await adminApi.updateDefaultUserSettings({ [key]: null });- setDefaults(updated);- if (key === 'map_tile_url') setMapTileUrl('');- if (key === 'mapbox_access_token') setMapboxToken('');- if (key === 'carto_api_key') setCartoKey('');- if (key === 'mapbox_style' || key === 'maplibre_style') {- const provider = normalizeProvider(defaults.map_provider);- setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));+ // A field's save on blur and the reset clicked right after it reach the server in+ // that order, or the save landing last would store the old value again.+ const inOrder = useWritesInOrder();++ const save = (patch: Partial<Defaults>) =>+ inOrder(async () => {+ try {+ const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);+ setDefaults(updated);+ toast.success(t('admin.defaultSettings.saved'));+ } catch (err: unknown) {+ toast.error(errorMessage(err, t('common.error')));}- toast.success(t('admin.defaultSettings.reset'));- } catch (err: unknown) {- toast.error(errorMessage(err, t('common.error')));- }- };+ });++ const reset = (key: keyof Defaults) =>+ inOrder(async () => {+ try {+ const updated = await adminApi.updateDefaultUserSettings({ [key]: null });+ setDefaults(updated);+ if (key === 'map_tile_url') setMapTileUrl('');+ if (key === 'mapbox_access_token') setMapboxToken('');+ if (key === 'carto_api_key') setCartoKey('');+ if (key === 'mapbox_style' || key === 'maplibre_style') {+ const provider = normalizeProvider(defaults.map_provider);+ setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));+ }+ toast.success(t('admin.defaultSettings.reset'));+ } catch (err: unknown) {+ toast.error(errorMessage(err, t('common.error')));+ }+ });const isSet = (key: keyof Defaults) => defaults[key] !== undefined;diff --git a/client/src/hooks/useWritesInOrder.test.ts b/client/src/hooks/useWritesInOrder.test.tsnew file mode 100644index 000000000..16115eb18--- /dev/null+++ b/client/src/hooks/useWritesInOrder.test.ts@@ -0,0 +1,73 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useWritesInOrder } from './useWritesInOrder';++/** A write that only finishes when the test says so, and notes when it starts and ends. */+function heldWrite(log: string[], name: string) {+ let finish!: () => void;+ let fail!: (err: Error) => void;+ const done = new Promise<void>((resolve, reject) => {+ finish = resolve;+ fail = reject;+ });+ const write = async () => {+ log.push(`${name} start`);+ await done;+ log.push(`${name} end`);+ };+ return { write, finish, fail };+}++describe('useWritesInOrder', () => {+ it('FE-HOOK-WRITES-001: a write starts only once the one before it has finished', async () => {+ const { result } = renderHook(() => useWritesInOrder());+ const log: string[] = [];+ const first = heldWrite(log, 'first');+ const second = heldWrite(log, 'second');++ const firstDone = result.current(first.write);+ const secondDone = result.current(second.write);+ await Promise.resolve();+ expect(log).toEqual(['first start']);++ second.finish();+ first.finish();+ await Promise.all([firstDone, secondDone]);+ expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);+ });++ it('FE-HOOK-WRITES-002: a failed write does not hold up the next one, and its caller sees the failure', async () => {+ const { result } = renderHook(() => useWritesInOrder());+ const log: string[] = [];+ const first = heldWrite(log, 'first');+ const second = heldWrite(log, 'second');++ const firstDone = result.current(first.write);+ const secondDone = result.current(second.write);+ first.fail(new Error('offline'));+ await expect(firstDone).rejects.toThrow('offline');++ second.finish();+ await secondDone;+ expect(log).toEqual(['first start', 'second start', 'second end']);+ });++ it('FE-HOOK-WRITES-003: the order holds across renders of the component using it', async () => {+ const { result, rerender } = renderHook(() => useWritesInOrder());+ const log: string[] = [];+ const first = heldWrite(log, 'first');+ const second = heldWrite(log, 'second');++ const firstDone = result.current(first.write);+ rerender();+ const secondDone = result.current(second.write);+ await Promise.resolve();+ expect(log).toEqual(['first start']);++ first.finish();+ second.finish();+ await Promise.all([firstDone, secondDone]);+ expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);+ });+});diff --git a/client/src/hooks/useWritesInOrder.ts b/client/src/hooks/useWritesInOrder.tsnew file mode 100644index 000000000..61b4635c8--- /dev/null+++ b/client/src/hooks/useWritesInOrder.ts@@ -0,0 +1,18 @@+import { useRef } from 'react';++/**+ * Runs async writes one after another, in the order they were started.+ *+ * Two writes to the same record that leave close together, such as a field saved on+ * blur and a reset clicked right after it, otherwise race: the server may handle them+ * in either order, and whichever it handles last is what stays. A write that fails+ * does not hold up the ones queued behind it.+ */+export function useWritesInOrder(): (write: () => Promise<void>) => Promise<void> {+ const tail = useRef<Promise<void>>(Promise.resolve());+ return (write) => {+ const next = tail.current.then(write, write);+ tail.current = next;+ return next;+ };+}