summaryrefslogtreecommitdiff
path: root/web/src/lib/settings.ts
blob: 224aef9e2930bc7b7b9c8e2b05ed1fb0e61cb6a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
 * Settings, Phase 6 split (PLAN.md section 4).
 *
 * The reference app keeps every setting in one `Settings` class; the web
 * version splits it:
 *
 * - **Server-side (game-relevant)** settings — everything the engine reads
 *   (initiative gating, standee tracking/spawning, condition expiry, the loot
 *   deck, the style, the reminder flags, AMD visibility, the OG-Gloom
 *   hazard-terrain calculation, the description locale) — live on the server
 *   and arrive in the `settings` payload of `welcome` / the `settings`
 *   broadcast. They are stored in {@link serverSettings} (set by the
 *   session from the wire) and changed with `session.setSetting(...)`
 *   (player-gated on the server).
 * - **Client-side (pure UI)** settings — the per-browser preferences (list /
 *   bar scaling, fullscreen, shimmer, power mode, no-calculations display,
 *   custom-content display, scenario-name display, character-AMD display) —
 *   live in this file's {@link clientSettings} store, persisted in
 *   localStorage (the reference's shared_preferences UI subset).
 *
 * {@link styleTheme} is a special case: it is *server*-owned (the style
 * affects every screen), so it mirrors the server `settings.style` field;
 * before the first welcome arrives it falls back to the last locally stored
 * value so the page never flashes a wrong theme.
 */

import { derived, get, writable, type Readable, type Writable } from 'svelte/store';

import type { SettingsPayload } from './protocol/types';

export type StyleTheme = 'frosthaven' | 'gloomhaven' | 'original';

/** The reference `PowerMode` enum (web tier: display-only). */
export type PowerMode = 'normal' | 'dimWhenIdle' | 'reducePower';

// --- Server-side settings (wire-driven) -------------------------------------

/**
 * The server-side settings as last received (`welcome` / `settings`
 * message). `null` before the first welcome.
 */
export const serverSettings: Writable<SettingsPayload | null> =
	writable<SettingsPayload | null>(null);

// --- Client-side settings (localStorage) ------------------------------------

export interface ClientSettings {
	/** Main-list width multiplier (0.2–3.0, default 1.0). */
	mainListScaling: number;
	/** Top-bar content scale (0.8–3.0, default 1.0). */
	barScaling: number;
	/** Fullscreen intent (the browser may need a gesture to grant it). */
	fullScreen: boolean;
	/** The card shimmer animation. */
	shimmer: boolean;
	/** The display power mode (dim when idle / reduce power). */
	powerMode: PowerMode;
	/** Hide computed numbers (no calculations display). */
	noCalculation: boolean;
	/** Show custom (non-original) campaign content in the menus. */
	showCustomContent: boolean;
	/** Show full scenario names (vs. the first word only). */
	showScenarioNames: boolean;
	/** Show each character's personal AMD deck header. */
	showCharacterAMD: boolean;
}

const SETTINGS_KEY = 'x-haven-settings';

export const CLIENT_SETTINGS_DEFAULTS: ClientSettings = {
	mainListScaling: 1.0,
	barScaling: 1.0,
	fullScreen: true,
	shimmer: false,
	powerMode: 'normal',
	noCalculation: false,
	showCustomContent: true,
	showScenarioNames: true,
	showCharacterAMD: true
};

function loadClientSettings(): ClientSettings {
	let stored: Record<string, unknown> | null = null;
	try {
		const raw = window.localStorage.getItem(SETTINGS_KEY);
		if (raw) {
			const parsed: unknown = JSON.parse(raw);
			if (parsed != null && typeof parsed === 'object') {
				stored = parsed as Record<string, unknown>;
			}
		}
	} catch {
		/* private browsing / corrupt value — fall back to defaults */
	}
	// Merge field-by-field over the defaults so a partially written file
	// never leaves a field at a wrong type.
	const d = CLIENT_SETTINGS_DEFAULTS;
	if (stored == null) return { ...d };
	const num = (v: unknown) => (typeof v === 'number' && isFinite(v) ? v : undefined);
	const bool = (v: unknown) => (typeof v === 'boolean' ? v : undefined);
	const mode = (v: unknown) =>
		v === 'normal' || v === 'dimWhenIdle' || v === 'reducePower' ? v : undefined;
	return {
		mainListScaling: num(stored.mainListScaling) ?? d.mainListScaling,
		barScaling: num(stored.barScaling) ?? d.barScaling,
		fullScreen: bool(stored.fullScreen) ?? d.fullScreen,
		shimmer: bool(stored.shimmer) ?? d.shimmer,
		powerMode: mode(stored.powerMode) ?? d.powerMode,
		noCalculation: bool(stored.noCalculation) ?? d.noCalculation,
		showCustomContent: bool(stored.showCustomContent) ?? d.showCustomContent,
		showScenarioNames: bool(stored.showScenarioNames) ?? d.showScenarioNames,
		showCharacterAMD: bool(stored.showCharacterAMD) ?? d.showCharacterAMD
	};
}

export const clientSettings: Writable<ClientSettings> =
	writable<ClientSettings>(loadClientSettings());

clientSettings.subscribe((value) => {
	try {
		window.localStorage.setItem(SETTINGS_KEY, JSON.stringify(value));
	} catch {
		/* ignore */
	}
});

/** Patch one or more client-side settings. */
export function setClientSetting<K extends keyof ClientSettings>(
	name: K,
	value: ClientSettings[K]
): void {
	clientSettings.update((s) => ({ ...s, [name]: value }));
}

/** The reference `reducePowerEnabled()`: may the UI degrade its visuals? */
export function reducePowerEnabled(): boolean {
	return get(clientSettings).powerMode === 'reducePower';
}

// --- Style theme (server-owned) ---------------------------------------------

const STYLE_KEY = 'x-haven-style';

/** Server `Style` enum index → theme name (`Style.values[i]`). */
export const STYLE_BY_INDEX: StyleTheme[] = ['frosthaven', 'gloomhaven', 'original'];

/** Theme name → server `Style` enum index. */
export function styleIndex(theme: StyleTheme): number {
	const i = STYLE_BY_INDEX.indexOf(theme);
	return i < 0 ? 0 : i;
}

function fallbackStyle(): StyleTheme {
	try {
		const stored = window.localStorage.getItem(STYLE_KEY);
		if (stored === 'frosthaven' || stored === 'gloomhaven' || stored === 'original') {
			return stored;
		}
	} catch {
		/* private browsing / disabled storage */
	}
	return 'frosthaven';
}

/**
 * The active visual style. Server-driven: `Style.values[settings.style]`
 * once the first welcome has arrived; the localStorage fallback before that
 * (so the very first frame already looks right).
 */
export const styleTheme: Readable<StyleTheme> = derived(serverSettings, (s) =>
	s != null ? STYLE_BY_INDEX[s.style] ?? 'original' : fallbackStyle()
);