mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-25 06:46:59 +00:00
feat: enhance settings persistence with platform provider integration
- Updated `persistSettings` to accept a `PlatformProvider`, enabling dynamic loading and saving of production settings. - Refactored settings loading to handle null cases and invalid JSON gracefully. - Introduced a new `browserSettingsIo` module for managing settings storage in the browser. - Added comprehensive tests for `persistSettings` and `browserSettingsIo` to ensure correct functionality and error handling. - Integrated the updated settings persistence into `AppRoot` for improved platform-specific behavior.
This commit is contained in:
1 parent
cc688b85bd
commit
cb5531e9e4
7 files changed
+262
-24
No files matched your search
@@ -27,7 +27,7 @@ setPlatform(platform);
|
||||
const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${isActive ? 'tab-active' : ''}`;
|
||||
|
||||
export function AppRoot() {
|
||||
useEffect(() => persistSettings(store), []);
|
||||
useEffect(() => persistSettings(store, platform), []);
|
||||
|
||||
return (
|
||||
<BrowserRouter basename={window.BASE_URL || '/'}>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import { afterEach, vi } from 'vitest';
|
||||
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import type { SettingsStorage } from '~/platform/browser/browserSettingsIo';
|
||||
import { persistSettings, mergeSettings } from '../persistSettings';
|
||||
import { settingsSlice, setProductionChanges, type ProductionSettings } from '../settingsSlice';
|
||||
|
||||
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||
const data = { ...initial };
|
||||
return {
|
||||
data,
|
||||
getItem(key: string) {
|
||||
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||
},
|
||||
setItem(key: string, value: string) {
|
||||
data[key] = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createStore() {
|
||||
return configureStore({
|
||||
reducer: { settings: settingsSlice.reducer },
|
||||
});
|
||||
}
|
||||
|
||||
describe('persistSettings', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('loads via provider, merges, and dispatches production', async () => {
|
||||
const stored: ProductionSettings = {
|
||||
...settingsSlice.getInitialState().production,
|
||||
qmc2: {
|
||||
allowFuzzyNameSearch: false,
|
||||
keys: { 'a.mflac': 'ek' },
|
||||
},
|
||||
};
|
||||
const storage = createMemoryStorage({ 'um-react-settings': JSON.stringify(stored) });
|
||||
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||
const store = createStore();
|
||||
|
||||
const unsubscribe = persistSettings(store, provider);
|
||||
await vi.waitFor(() => {
|
||||
expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': 'ek' });
|
||||
expect(store.getState().settings.production.qmc2.allowFuzzyNameSearch).toBe(false);
|
||||
});
|
||||
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('ignores failed loads and keeps defaults', async () => {
|
||||
const storage = createMemoryStorage({ 'um-react-settings': '{bad' });
|
||||
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||
const store = createStore();
|
||||
const defaults = settingsSlice.getInitialState().production;
|
||||
|
||||
const unsubscribe = persistSettings(store, provider);
|
||||
// Give the rejected load a turn to settle.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(store.getState().settings.production).toEqual(defaults);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('debounced save writes production through provider', async () => {
|
||||
vi.useFakeTimers();
|
||||
const storage = createMemoryStorage();
|
||||
const provider = createBrowserProvider({ settingsStorage: storage });
|
||||
const store = createStore();
|
||||
|
||||
const unsubscribe = persistSettings(store, provider);
|
||||
await Promise.resolve();
|
||||
|
||||
const next = mergeSettings({
|
||||
...settingsSlice.getInitialState().production,
|
||||
qmc2: { allowFuzzyNameSearch: true, keys: { 'b.mflac': 'x' } },
|
||||
});
|
||||
store.dispatch(setProductionChanges(next));
|
||||
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(JSON.parse(storage.data['um-react-settings'])).toEqual(next);
|
||||
unsubscribe();
|
||||
});
|
||||
});
|
||||
@@ -13,8 +13,7 @@ import { getLogger } from '~/util/logUtils';
|
||||
import { parseKwm2ProductionKey } from '~/features/kwm/types';
|
||||
import { sanitizeQtfmAndroidKey } from '~/features/qtfm/types';
|
||||
import { deepClone } from '~/util/deepClone';
|
||||
|
||||
const DEFAULT_STORAGE_KEY = 'um-react-settings';
|
||||
import type { PlatformProvider } from '~/platform/PlatformProvider';
|
||||
|
||||
function mergeBatchDownload(source: Partial<BatchDownloadSettings> | undefined): BatchDownloadSettings {
|
||||
const result = { ...DEFAULT_BATCH_DOWNLOAD_SETTINGS };
|
||||
@@ -75,28 +74,47 @@ export function mergeSettings(settings: ProductionSettings): ProductionSettings
|
||||
return draft;
|
||||
}
|
||||
|
||||
export function persistSettings(store: AppStore, storageKey = DEFAULT_STORAGE_KEY) {
|
||||
/**
|
||||
* Load production settings via `provider.settings`, merge into the store, and
|
||||
* debounce-save on production changes. Storage details stay inside the provider.
|
||||
*/
|
||||
export function persistSettings(store: AppStore, provider: PlatformProvider) {
|
||||
let lastSettings: unknown;
|
||||
let cancelled = false;
|
||||
|
||||
try {
|
||||
const loadedSettings = JSON.parse(localStorage.getItem(storageKey) ?? '') as ProductionSettings;
|
||||
if (loadedSettings) {
|
||||
const mergedSettings = mergeSettings(loadedSettings);
|
||||
store.dispatch(setProductionChanges(mergedSettings));
|
||||
getLogger().debug('settings loaded');
|
||||
}
|
||||
} catch {
|
||||
// load failed, ignore.
|
||||
}
|
||||
|
||||
return store.subscribe(
|
||||
const unsubscribe = store.subscribe(
|
||||
debounce({ delay: 150 }, () => {
|
||||
const currentSettings = store.getState().settings.production;
|
||||
if (lastSettings !== currentSettings) {
|
||||
lastSettings = currentSettings;
|
||||
localStorage.setItem(storageKey, JSON.stringify(currentSettings));
|
||||
getLogger().debug('settings saved');
|
||||
void provider.settings.save(currentSettings).then(
|
||||
() => getLogger().debug('settings saved'),
|
||||
() => {
|
||||
// save failed; keep lastSettings so we do not spin-retry on every tick
|
||||
},
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
void provider.settings
|
||||
.load()
|
||||
.then((loadedSettings) => {
|
||||
if (cancelled || !loadedSettings) {
|
||||
return;
|
||||
}
|
||||
const mergedSettings = mergeSettings(loadedSettings);
|
||||
store.dispatch(setProductionChanges(mergedSettings));
|
||||
// Avoid an immediate rewrite of the same production snapshot after load.
|
||||
lastSettings = store.getState().settings.production;
|
||||
getLogger().debug('settings loaded');
|
||||
})
|
||||
.catch(() => {
|
||||
// load failed, ignore.
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}
|
||||
@@ -37,8 +37,21 @@ describe('BrowserProvider', () => {
|
||||
test('unwired browser methods throw NotImplementedError', async () => {
|
||||
const provider = createBrowserProvider();
|
||||
|
||||
await expect(provider.settings.load()).rejects.toBeInstanceOf(NotImplementedError);
|
||||
await expect(provider.crypto.request('VERSION', null)).rejects.toBeInstanceOf(NotImplementedError);
|
||||
await expect(provider.download.saveOne({ url: 'blob:x', fileName: 'a.flac' })).rejects.toBeInstanceOf(
|
||||
NotImplementedError,
|
||||
);
|
||||
});
|
||||
|
||||
test('settings.load returns null when storage is empty', async () => {
|
||||
const provider = createBrowserProvider({
|
||||
settingsStorage: {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(provider.settings.load()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
test('createPlatformProvider defaults to browser', () => {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||
import {
|
||||
createBrowserSettingsIo,
|
||||
DEFAULT_SETTINGS_STORAGE_KEY,
|
||||
type SettingsStorage,
|
||||
} from '~/platform/browser/browserSettingsIo';
|
||||
import { settingsSlice, type ProductionSettings } from '~/features/settings/settingsSlice';
|
||||
|
||||
function createMemoryStorage(initial: Record<string, string> = {}): SettingsStorage & { data: Record<string, string> } {
|
||||
const data = { ...initial };
|
||||
return {
|
||||
data,
|
||||
getItem(key: string) {
|
||||
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null;
|
||||
},
|
||||
setItem(key: string, value: string) {
|
||||
data[key] = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function sampleProduction(): ProductionSettings {
|
||||
const production = structuredClone(settingsSlice.getInitialState().production);
|
||||
production.qmc2.keys['demo.mflac'] = 'ekey-demo';
|
||||
production.qmc2.allowFuzzyNameSearch = false;
|
||||
production.general.batchDownload.blobZip = false;
|
||||
return production;
|
||||
}
|
||||
|
||||
describe('createBrowserSettingsIo', () => {
|
||||
test('load returns null when key is missing or empty', async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const io = createBrowserSettingsIo(storage);
|
||||
|
||||
await expect(io.load()).resolves.toBeNull();
|
||||
|
||||
storage.setItem(DEFAULT_SETTINGS_STORAGE_KEY, '');
|
||||
await expect(io.load()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
test('save then load round-trips production settings', async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const io = createBrowserSettingsIo(storage, 'test-settings');
|
||||
const settings = sampleProduction();
|
||||
|
||||
await io.save(settings);
|
||||
|
||||
expect(storage.data['test-settings']).toBe(JSON.stringify(settings));
|
||||
await expect(io.load()).resolves.toEqual(settings);
|
||||
});
|
||||
|
||||
test('load rejects on invalid JSON', async () => {
|
||||
const storage = createMemoryStorage({ [DEFAULT_SETTINGS_STORAGE_KEY]: '{not-json' });
|
||||
const io = createBrowserSettingsIo(storage);
|
||||
|
||||
await expect(io.load()).rejects.toBeInstanceOf(SyntaxError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BrowserProvider.settings', () => {
|
||||
test('round-trips through injected storage', async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const provider = createBrowserProvider({ settingsStorage: storage, settingsStorageKey: 'um-test' });
|
||||
const settings = sampleProduction();
|
||||
|
||||
await provider.settings.save(settings);
|
||||
await expect(provider.settings.load()).resolves.toEqual(settings);
|
||||
expect(JSON.parse(storage.data['um-test'])).toEqual(settings);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
NativeImportResult,
|
||||
PlatformCapabilities,
|
||||
} from '~/platform/types';
|
||||
import { createBrowserSettingsIo, DEFAULT_SETTINGS_STORAGE_KEY, type SettingsStorage } from './browserSettingsIo';
|
||||
import { detectBrowserDownloadTypes } from './detectDownloadCapabilities';
|
||||
|
||||
function notImplemented(capability: string): Promise<never> {
|
||||
@@ -18,20 +19,33 @@ function notSupported(capability: string): Promise<never> {
|
||||
return Promise.reject(new NotSupportedMethod(capability));
|
||||
}
|
||||
|
||||
export interface BrowserProviderOptions {
|
||||
/** Defaults to `localStorage`. Injected in tests. */
|
||||
settingsStorage?: SettingsStorage;
|
||||
/** Defaults to `um-react-settings`. */
|
||||
settingsStorageKey?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-browser `PlatformProvider`.
|
||||
* Capabilities follow runtime File System Access / save-picker probing (no DirectWrite).
|
||||
* crypto / settings / download currently throw `NotImplementedError` (not yet delegated to
|
||||
* the existing worker / localStorage / download helpers).
|
||||
* `settings` persists production settings via localStorage (or injected storage).
|
||||
* crypto / download currently throw `NotImplementedError` (not yet delegated to
|
||||
* the existing worker / download helpers).
|
||||
* Native and ADB key import throw `NotSupportedMethod` (`nativeKeyAccess` empty, `androidKeyAccess` None).
|
||||
*/
|
||||
export function createBrowserProvider(): PlatformProvider {
|
||||
export function createBrowserProvider(options: BrowserProviderOptions = {}): PlatformProvider {
|
||||
const capabilities: PlatformCapabilities = Object.freeze({
|
||||
downloadTypes: Object.freeze(detectBrowserDownloadTypes()),
|
||||
androidKeyAccess: AndroidImportType.None,
|
||||
nativeKeyAccess: Object.freeze([] as NativeImportType[]),
|
||||
});
|
||||
|
||||
const settingsIo = createBrowserSettingsIo(
|
||||
options.settingsStorage ?? localStorage,
|
||||
options.settingsStorageKey ?? DEFAULT_SETTINGS_STORAGE_KEY,
|
||||
);
|
||||
|
||||
return {
|
||||
id: 'browser',
|
||||
capabilities,
|
||||
@@ -42,8 +56,8 @@ export function createBrowserProvider(): PlatformProvider {
|
||||
},
|
||||
|
||||
settings: {
|
||||
load: () => notImplemented('settings.load'),
|
||||
save: () => notImplemented('settings.save'),
|
||||
load: () => settingsIo.load(),
|
||||
save: (settings) => settingsIo.save(settings),
|
||||
},
|
||||
|
||||
download: {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { ProductionSettings } from '~/features/settings/settingsSlice';
|
||||
|
||||
export const DEFAULT_SETTINGS_STORAGE_KEY = 'um-react-settings';
|
||||
|
||||
/** Minimal storage surface used by browser settings persistence. */
|
||||
export type SettingsStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
/**
|
||||
* localStorage-backed settings IO for the browser provider.
|
||||
* `load` returns `null` when the key is missing or empty; invalid JSON rejects.
|
||||
*/
|
||||
export function createBrowserSettingsIo(
|
||||
storage: SettingsStorage = localStorage,
|
||||
storageKey = DEFAULT_SETTINGS_STORAGE_KEY,
|
||||
) {
|
||||
return {
|
||||
// async: matches PlatformProvider.settings.load(): Promise<...> (sync localStorage).
|
||||
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||
async load(): Promise<ProductionSettings | null> {
|
||||
const raw = storage.getItem(storageKey);
|
||||
if (raw == null || raw === '') {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(raw) as ProductionSettings;
|
||||
},
|
||||
|
||||
// async: matches PlatformProvider.settings.save(): Promise<void> (sync localStorage).
|
||||
// eslint-disable-next-line @typescript-eslint/require-await -- interface requires Promise
|
||||
async save(settings: ProductionSettings): Promise<void> {
|
||||
storage.setItem(storageKey, JSON.stringify(settings));
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user