Files
Genarrative/src/persistence/gameSettingsStorage.ts
T
kdletters 071faa482c 统一 Rust 与 TypeScript 格式化门禁
纳入 AGC Cargo workspace 的统一 rustfmt 检查与格式化入口

完成项目 TypeScript/Prettier 与 Rust 全量格式化

修复 Pingora expected executable 门禁的空白敏感误报

同步开发运维文档与 AGC skill pack 格式化忽略规则
2026-09-01 16:28:34 +08:00

80 lines
1.9 KiB
TypeScript

import {
DEFAULT_MUSIC_VOLUME,
DEFAULT_PLATFORM_THEME,
type PlatformTheme,
type RuntimeSettings,
} from '../../packages/shared/src/contracts/runtime';
import { isRecord, readStoredJson, writeStoredJson } from './storage';
const SETTINGS_STORAGE_KEY = 'tavernrealms.settings.v1';
const SETTINGS_STORAGE_VERSION = 1;
export type SavedGameSettings = RuntimeSettings;
export { DEFAULT_MUSIC_VOLUME };
type StoredGameSettings = SavedGameSettings & {
version: number;
};
export function clampVolume(value: number) {
if (!Number.isFinite(value)) {
return DEFAULT_MUSIC_VOLUME;
}
return Math.max(0, Math.min(1, value));
}
export function normalizePlatformTheme(value: unknown): PlatformTheme {
return value === 'dark' ? 'dark' : DEFAULT_PLATFORM_THEME;
}
function parseSavedSettings(value: unknown): SavedGameSettings | null {
if (!isRecord(value)) {
return null;
}
if (
value.version === SETTINGS_STORAGE_VERSION &&
typeof value.musicVolume === 'number'
) {
return {
musicVolume: clampVolume(value.musicVolume),
platformTheme: normalizePlatformTheme(value.platformTheme),
};
}
if (typeof value.musicVolume === 'number') {
return {
musicVolume: clampVolume(value.musicVolume),
platformTheme: normalizePlatformTheme(value.platformTheme),
};
}
return null;
}
export function readSavedSettings() {
return (
readStoredJson({
key: SETTINGS_STORAGE_KEY,
parse: parseSavedSettings,
}) ?? {
musicVolume: DEFAULT_MUSIC_VOLUME,
platformTheme: DEFAULT_PLATFORM_THEME,
}
);
}
export function writeSavedSettings(settings: SavedGameSettings) {
const payload: StoredGameSettings = {
version: SETTINGS_STORAGE_VERSION,
musicVolume: clampVolume(settings.musicVolume),
platformTheme: normalizePlatformTheme(settings.platformTheme),
};
return writeStoredJson({
key: SETTINGS_STORAGE_KEY,
value: payload,
});
}