mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-02 22:48:25 +00:00
318d1e2c44
## Description: 1) Have last localstorage calls for keybinds and attack ratio also use UserSettings cache instead, after #3481. Remaining calls to localstorage are for different things than user settings, so they are left as is. 2) Consolidate and centralize keybinds logic. And three fixes for it. - **UnitDisplay** and **UserSettingsModal**: _parsedUserKeybinds_ is introduced in **UserSettings** to centralize their logic. It is also used by _normalizedUserKeybinds_, see point below. - **UserSettingsModal** -- replaced unwanted cast `as SettingKeybind` by a typed QuerySelector. -- renamed this.keybinds to this.userKeybinds for more clarity, and distinction from defaultKeybinds. -- state private _userKeybinds_: remove type string[] since loadKeybindsFromStorage replaces a value array by its first string element, so it can not contain string[] anymore. -- _handleKeybindChange_ and _getKeyValue_: no need to check for Array.isArray anymore, see above reason. -- **Fix**: checks after calling _parsedUserKeybinds_ are improved a bit: don't delete all keybinds and print a console warning when finding just one invalid keybind and (i think i have seen people complaining about things being removed). Instead it now migrates or throws out the invalid ones but keeps the valid ones. Also works with the "Null" value expected and removed within **UserSettingsModal**._handleyKeybindChange_() and in **HelpModal**. When legacy value is an array and key is empty, don't put value as key but get first array element or empty string as key name. So that check on line 68 is true. - **HelpModal** and **InputHandler**: Also centralize/consolidate their logic more, by having __keybinds()_ from **UserSettings** perform fetching _getDefaultKeybinds_ and _normalizedUserKeybinds_. -- Functionality in _normalizedUserKeybinds_ is the same: Where HelpModal did return [k, v.value] if typeof (v as any).value === "string", this is now handled by lines 309-310 of normalizedKeybinds still the same but with less lines. Same for old HelplModal if (typeof v === "string") return [k, v], this is stil returned by line 112 of normalizedKeybinds. And return [k, undefined] when (typeof val !== "string") as was done in InputHandler, isn't needed as values that weren't strings were already filtered out right after which we still do on line 314 of normalizedKeybinds. -- **Fix** in _normalizedUserKeybinds_: added one extra thing that was a discrepancy between **HelpModal**/**InputHandler** and **UserSettingsModal** before: **UserSettingsModal** would handle array values, and normalize them by picking only the first value if it is a string. Now have _normalizedKeybinds_ do the same. Otherwise it would have thrown those values out while **UserSettingsModal** would have kept the first value. This may still help a returning player who hasn't played in the last version (i think i have seen people complaining about things being removed, but that may not have been about this). And makes the logic more consistent between **UserSettingsModal** and **HelpModal**/**InputHandler**. - **UserSettings**: -- _getDefaultKeybinds_: centralized/consolidated logic, accepts Platform.isMac parameter. In **HelpModal**, **InputHandler** and **UserSettingsModal** the same list with default keybinds was hardcoded. Now they all read from _getDefaultKeybinds_. The list of default keybinds in **HelpModal** was a little shorter, but that doesn't matter since its _render_() function has hardcoded which of the hotkeys **HelpModal** shows. Have thought about putting default keybinds in **DefaultConfig** but with all the logic handled through **UserSettings**, this seemed the better place in the current refactor. -- _removeCached_: make public, now that **InputHandler.test.ts** needs to be able to call it. We could instead make a public function like removeKeybinds() and keep removeCached() private, but went with this for now. -- _parsedUserKeybinds_: centralized/consolidated logic for **UserSettingsModal**/**UserDisplay**. Always returns an object, even an empty one if the JSON wasn't parsable. -- _normalizedKeybinds_: centralized/consolidated logic. Used by _keybinds_() which is now called by **HelpModal**/**InputHandler**. -- _keybinds_: now uses getDefaultKeybinds() and normalizedKeybinds() to get the default and user changed keybinds. -- **Fix** in _keybinds_: it now removes a key if it is Unbound by the user in **UserSettingsModal**. Instead of first loading the parsedUserKeybinds, removing "Null" keys from it, and then merging that with defaultKeybinds (so default key would overwrite an unbound key), we now merge parsedUserKeybinds with defaultKeybinds and after that remove "Null" keys from it (so that unbound key stays removed). For example if Boat Attack Up is set to "None" ("Null") by clicking Unbind, there is now no hotkey working for it anymore. Even when the default is "B". Why? This prevents the user from being confused, they have deliberately Unbound it, they don't understand why it still works (have seen bug reports and game feedback about this)? Also more importantly: they used to now be able to bind "B" to another action. Effectively making key "B" bound to two actions: the user choosen one and Boat Attack. This also makes the logic more consistent. Because building hotkeys in **UnitDisplay** already didn't work when unbound, eg. when Build Missile Silo was Unbound, the "5" key did not do anything anymore (there is a fallback in **UnitDisplay** in case the key is actually null, but it does respect "Null" as it should). -- _setKeybinds_: have it accept an object, it stringifies it itself. Callers UserSettingsModal and InputHandler.test.ts now just send either a string or an object. - **InputHandler.test.ts**: -- use **UserSettings** functions instead of localStorage for more real-world testing. -- change test "ignores non-string values and preserves defaults, removes 'Null' for unbound keys". As explained above, as a fix we no longer preserve unbound ("Null") keys within InputHandler. UserSettings.keybinds() now removes "Null" keys as explained above. - ControlPanel: use UserSettings to fetch initial attack ratio. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory - [x] I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced ## Please put your Discord username so you can be contacted if a bug or regression is found: tryout33
390 lines
11 KiB
TypeScript
390 lines
11 KiB
TypeScript
import { Cosmetics } from "../CosmeticSchemas";
|
|
import { PlayerPattern } from "../Schemas";
|
|
|
|
export function getDefaultKeybinds(isMac: boolean): Record<string, string> {
|
|
return {
|
|
toggleView: "Space",
|
|
coordinateGrid: "KeyM",
|
|
buildCity: "Digit1",
|
|
buildFactory: "Digit2",
|
|
buildPort: "Digit3",
|
|
buildDefensePost: "Digit4",
|
|
buildMissileSilo: "Digit5",
|
|
buildSamLauncher: "Digit6",
|
|
buildWarship: "Digit7",
|
|
buildAtomBomb: "Digit8",
|
|
buildHydrogenBomb: "Digit9",
|
|
buildMIRV: "Digit0",
|
|
attackRatioDown: "KeyT",
|
|
attackRatioUp: "KeyY",
|
|
boatAttack: "KeyB",
|
|
groundAttack: "KeyG",
|
|
swapDirection: "KeyU",
|
|
zoomOut: "KeyQ",
|
|
zoomIn: "KeyE",
|
|
centerCamera: "KeyC",
|
|
moveUp: "KeyW",
|
|
moveLeft: "KeyA",
|
|
moveDown: "KeyS",
|
|
moveRight: "KeyD",
|
|
modifierKey: isMac ? "MetaLeft" : "ControlLeft",
|
|
altKey: "AltLeft",
|
|
shiftKey: "ShiftLeft",
|
|
resetGfx: "KeyR",
|
|
pauseGame: "KeyP",
|
|
gameSpeedUp: "Period",
|
|
gameSpeedDown: "Comma",
|
|
};
|
|
}
|
|
|
|
export const USER_SETTINGS_CHANGED_EVENT = "event:user-settings-changed";
|
|
export const PATTERN_KEY = "territoryPattern";
|
|
export const FLAG_KEY = "flag";
|
|
export const COLOR_KEY = "settings.territoryColor";
|
|
export const DARK_MODE_KEY = "settings.darkMode";
|
|
export const PERFORMANCE_OVERLAY_KEY = "settings.performanceOverlay";
|
|
export const KEYBINDS_KEY = "settings.keybinds";
|
|
|
|
export class UserSettings {
|
|
private static cache = new Map<string, string | null>();
|
|
|
|
private emitChange(key: string, value: any): void {
|
|
try {
|
|
const maybeDispatch = (globalThis as any)?.dispatchEvent;
|
|
if (typeof maybeDispatch !== "function") return;
|
|
(globalThis as any).dispatchEvent(
|
|
new CustomEvent(`${USER_SETTINGS_CHANGED_EVENT}:${key}`, {
|
|
detail: value,
|
|
}),
|
|
);
|
|
} catch {
|
|
// Ignore - settings should still be applied even if event dispatch fails.
|
|
}
|
|
}
|
|
|
|
private getCached(key: string): string | null {
|
|
if (!UserSettings.cache.has(key)) {
|
|
UserSettings.cache.set(key, localStorage.getItem(key));
|
|
}
|
|
return UserSettings.cache.get(key) ?? null;
|
|
}
|
|
|
|
private setCached(key: string, value: string, emitChange: boolean = true) {
|
|
localStorage.setItem(key, value);
|
|
UserSettings.cache.set(key, value);
|
|
if (emitChange) {
|
|
this.emitChange(key, value);
|
|
}
|
|
}
|
|
|
|
public removeCached(key: string, emitChange: boolean = true) {
|
|
localStorage.removeItem(key);
|
|
UserSettings.cache.set(key, null);
|
|
if (emitChange) {
|
|
this.emitChange(key, null);
|
|
}
|
|
}
|
|
|
|
private getBool(key: string, defaultValue: boolean): boolean {
|
|
const value = this.getCached(key);
|
|
if (!value) return defaultValue;
|
|
if (value === "true") return true;
|
|
if (value === "false") return false;
|
|
return defaultValue;
|
|
}
|
|
|
|
private setBool(key: string, value: boolean) {
|
|
this.setCached(key, value ? "true" : "false");
|
|
}
|
|
|
|
private getString(key: string, defaultValue: string = ""): string {
|
|
const value = this.getCached(key);
|
|
if (value === null) return defaultValue;
|
|
return value;
|
|
}
|
|
|
|
private setString(key: string, value: string) {
|
|
this.setCached(key, value);
|
|
}
|
|
|
|
private getFloat(key: string, defaultValue: number): number {
|
|
const value = this.getCached(key);
|
|
if (!value) return defaultValue;
|
|
|
|
const floatValue = parseFloat(value);
|
|
if (isNaN(floatValue)) return defaultValue;
|
|
return floatValue;
|
|
}
|
|
|
|
private setFloat(key: string, value: number) {
|
|
this.setCached(key, value.toString());
|
|
}
|
|
|
|
emojis() {
|
|
return this.getBool("settings.emojis", true);
|
|
}
|
|
|
|
performanceOverlay() {
|
|
return this.getBool(PERFORMANCE_OVERLAY_KEY, false);
|
|
}
|
|
|
|
alertFrame() {
|
|
return this.getBool("settings.alertFrame", true);
|
|
}
|
|
|
|
anonymousNames() {
|
|
return this.getBool("settings.anonymousNames", false);
|
|
}
|
|
|
|
lobbyIdVisibility() {
|
|
return this.getBool("settings.lobbyIdVisibility", true);
|
|
}
|
|
|
|
fxLayer() {
|
|
return this.getBool("settings.specialEffects", true);
|
|
}
|
|
|
|
structureSprites() {
|
|
return this.getBool("settings.structureSprites", true);
|
|
}
|
|
|
|
darkMode() {
|
|
return this.getBool(DARK_MODE_KEY, false);
|
|
}
|
|
|
|
leftClickOpensMenu() {
|
|
return this.getBool("settings.leftClickOpensMenu", false);
|
|
}
|
|
|
|
territoryPatterns() {
|
|
return this.getBool("settings.territoryPatterns", true);
|
|
}
|
|
|
|
attackingTroopsOverlay() {
|
|
return this.getBool("settings.attackingTroopsOverlay", true);
|
|
}
|
|
|
|
toggleAttackingTroopsOverlay() {
|
|
this.setBool(
|
|
"settings.attackingTroopsOverlay",
|
|
!this.attackingTroopsOverlay(),
|
|
);
|
|
}
|
|
|
|
cursorCostLabel() {
|
|
const legacy = this.getBool("settings.ghostPricePill", true);
|
|
return this.getBool("settings.cursorCostLabel", legacy);
|
|
}
|
|
|
|
toggleLeftClickOpenMenu() {
|
|
this.setBool("settings.leftClickOpensMenu", !this.leftClickOpensMenu());
|
|
}
|
|
|
|
toggleEmojis() {
|
|
this.setBool("settings.emojis", !this.emojis());
|
|
}
|
|
|
|
// Performance overlay specifically needs a direct setter for Shift-D
|
|
setPerformanceOverlay(value: boolean) {
|
|
this.setBool(PERFORMANCE_OVERLAY_KEY, value);
|
|
}
|
|
|
|
togglePerformanceOverlay() {
|
|
this.setBool(PERFORMANCE_OVERLAY_KEY, !this.performanceOverlay());
|
|
}
|
|
|
|
toggleAlertFrame() {
|
|
this.setBool("settings.alertFrame", !this.alertFrame());
|
|
}
|
|
|
|
toggleRandomName() {
|
|
this.setBool("settings.anonymousNames", !this.anonymousNames());
|
|
}
|
|
|
|
toggleLobbyIdVisibility() {
|
|
this.setBool("settings.lobbyIdVisibility", !this.lobbyIdVisibility());
|
|
}
|
|
|
|
toggleFxLayer() {
|
|
this.setBool("settings.specialEffects", !this.fxLayer());
|
|
}
|
|
|
|
toggleStructureSprites() {
|
|
this.setBool("settings.structureSprites", !this.structureSprites());
|
|
}
|
|
|
|
toggleCursorCostLabel() {
|
|
this.setBool("settings.cursorCostLabel", !this.cursorCostLabel());
|
|
}
|
|
|
|
toggleTerritoryPatterns() {
|
|
this.setBool("settings.territoryPatterns", !this.territoryPatterns());
|
|
}
|
|
|
|
toggleDarkMode() {
|
|
this.setBool(DARK_MODE_KEY, !this.darkMode());
|
|
}
|
|
|
|
// For development only. Used for testing patterns, set in the console manually.
|
|
getDevOnlyPattern(): PlayerPattern | undefined {
|
|
const data = localStorage.getItem("dev-pattern") ?? undefined;
|
|
if (data === undefined) return undefined;
|
|
return {
|
|
name: "dev-pattern",
|
|
patternData: data,
|
|
colorPalette: {
|
|
name: "dev-color-palette",
|
|
primaryColor: localStorage.getItem("dev-primary") ?? "#ffffff",
|
|
secondaryColor: localStorage.getItem("dev-secondary") ?? "#000000",
|
|
},
|
|
} satisfies PlayerPattern;
|
|
}
|
|
|
|
getSelectedPatternName(cosmetics: Cosmetics | null): PlayerPattern | null {
|
|
if (cosmetics === null) return null;
|
|
let data = this.getCached(PATTERN_KEY);
|
|
if (data === null) return null;
|
|
const patternPrefix = "pattern:";
|
|
if (data.startsWith(patternPrefix)) {
|
|
data = data.slice(patternPrefix.length);
|
|
}
|
|
const [patternName, colorPalette] = data.split(":");
|
|
const pattern = cosmetics.patterns[patternName];
|
|
if (pattern === undefined) return null;
|
|
return {
|
|
name: patternName,
|
|
patternData: pattern.pattern,
|
|
colorPalette: cosmetics.colorPalettes?.[colorPalette],
|
|
} satisfies PlayerPattern;
|
|
}
|
|
|
|
setSelectedPatternName(patternName: string | undefined): void {
|
|
if (patternName === undefined) {
|
|
this.removeCached(PATTERN_KEY);
|
|
} else {
|
|
this.setCached(PATTERN_KEY, patternName);
|
|
}
|
|
}
|
|
|
|
getFlag(): string | null {
|
|
let flag = this.getCached(FLAG_KEY);
|
|
if (!flag) return null;
|
|
// Migrate bare country codes to country: prefix
|
|
if (!flag.startsWith("flag:") && !flag.startsWith("country:")) {
|
|
flag = `country:${flag}`;
|
|
// Silent migration: don't emit change event for FlagInput
|
|
this.setCached(FLAG_KEY, flag, false);
|
|
}
|
|
return flag;
|
|
}
|
|
|
|
setFlag(flag: string): void {
|
|
if (flag === "country:xx") {
|
|
this.clearFlag(true);
|
|
} else {
|
|
this.setCached(FLAG_KEY, flag);
|
|
}
|
|
}
|
|
|
|
clearFlag(emitChange: boolean = false): void {
|
|
this.removeCached(FLAG_KEY, emitChange);
|
|
}
|
|
|
|
backgroundMusicVolume(): number {
|
|
return this.getFloat("settings.backgroundMusicVolume", 0);
|
|
}
|
|
|
|
setBackgroundMusicVolume(volume: number): void {
|
|
this.setFloat("settings.backgroundMusicVolume", volume);
|
|
}
|
|
|
|
// What % attack ratio increments per click/scroll
|
|
attackRatioIncrement(): number {
|
|
const increment = Math.round(
|
|
this.getFloat("settings.attackRatioIncrement", 10),
|
|
);
|
|
if (!Number.isFinite(increment) || increment <= 0) return 10;
|
|
return increment;
|
|
}
|
|
|
|
setAttackRatioIncrement(value: number): void {
|
|
this.setFloat("settings.attackRatioIncrement", value);
|
|
}
|
|
|
|
// What % attack ratio is set to
|
|
attackRatio(): number {
|
|
return this.getFloat("settings.attackRatio", 0.2);
|
|
}
|
|
|
|
setAttackRatio(value: number): void {
|
|
this.setFloat("settings.attackRatio", value);
|
|
}
|
|
|
|
// In case localStorage was manually edited to be invalid, return an empty object
|
|
parsedUserKeybinds(): Record<string, any> {
|
|
const raw = this.getString(KEYBINDS_KEY, "{}");
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
return parsed;
|
|
}
|
|
} catch (e) {
|
|
console.warn("Invalid keybinds JSON:", e);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
// Returns a flat keybind map { action: "keyCode" }, handling nested objects and legacy strings
|
|
private normalizedUserKeybinds(): Record<string, string> {
|
|
const parsed = this.parsedUserKeybinds();
|
|
return Object.fromEntries(
|
|
Object.entries(parsed)
|
|
// Extract value from nested object or plain string, filter out non-string values
|
|
.map(([k, v]) => {
|
|
let val = v;
|
|
if (v && typeof v === "object" && !Array.isArray(v) && "value" in v) {
|
|
val = v.value;
|
|
}
|
|
if (Array.isArray(val) && typeof val[0] === "string") {
|
|
val = val[0];
|
|
}
|
|
return [k, val];
|
|
})
|
|
.filter(([, v]) => typeof v === "string"),
|
|
) as Record<string, string>;
|
|
}
|
|
|
|
keybinds(isMac: boolean): Record<string, string> {
|
|
const merged = {
|
|
...getDefaultKeybinds(isMac),
|
|
...this.normalizedUserKeybinds(),
|
|
};
|
|
// Actually unbind key: if Unbind is clicked in UserSettingsModal, eg. for Attack Ratio Up,
|
|
// keybind is "Null". Even if it is in default kindbinds (Y), it should not work anymore.
|
|
// The key (Y) can now be bound to another action like Boat Attack, and no two actions listen to the same key.
|
|
for (const k in merged) {
|
|
if (merged[k] === "Null") {
|
|
delete merged[k];
|
|
}
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
setKeybinds(value: string | Record<string, any>): void {
|
|
if (typeof value === "string") {
|
|
this.setString(KEYBINDS_KEY, value);
|
|
} else {
|
|
this.setString(KEYBINDS_KEY, JSON.stringify(value));
|
|
}
|
|
}
|
|
|
|
soundEffectsVolume(): number {
|
|
return this.getFloat("settings.soundEffectsVolume", 1);
|
|
}
|
|
|
|
setSoundEffectsVolume(volume: number): void {
|
|
this.setFloat("settings.soundEffectsVolume", volume);
|
|
}
|
|
}
|