Skip to content

Cache User Settings #896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed

Cache User Settings #896

wants to merge 2 commits into from

Conversation

1brucben
Copy link
Contributor

Description:

An alternative implementation of PR#760 by @robert-pitt-foodhub. Caches user settings which seem to be a heavy draw on main thread.

Please complete the following:

  • I have added screenshots for all UI updates
  • I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced
  • I understand that submitting code with bugs that could have been caught through manual testing blocks releases and new features for all contributors

Please put your Discord username so you can be contacted if a bug or regression is found:

1brucben

Sorry, something went wrong.

Copy link
Contributor

coderabbitai bot commented May 27, 2025

Walkthrough

The codebase was refactored to use a shared singleton instance of UserSettings instead of creating new instances in multiple places. All components and modules now import and use the userSettings singleton, and explicit setter methods were added for updating settings. Internal caching was introduced for efficient access.

Changes

Files / Areas Change Summary
src/client/ClientGameRunner.ts, src/client/InputHandler.ts, src/client/Main.ts, src/client/DarkModeButton.ts, src/client/UserSettingModal.ts, src/client/graphics/layers/OptionsMenu.ts, src/core/game/GameView.ts Switched from creating new UserSettings instances to using the singleton userSettings. Removed per-class properties and updated all references.
src/core/game/UserSettings.ts Refactored UserSettings to use an internal cache for settings, added explicit setter methods, and exported the singleton userSettings.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Component
    participant userSettings
    participant localStorage

    Component->>userSettings: get or set setting
    userSettings->>userSettings: read/write from cache
    userSettings->>localStorage: (on first load or update) read/write value
    userSettings-->>Component: return setting value

Possibly related PRs

Suggested labels

Feature - New

Suggested reviewers

  • evanpelle

Poem

In a world of settings, scattered and lone,
Now they gather, together, as one tone.
A singleton rises, with cache in its chest,
Making user choices easy, and code much less stressed.
No more new instances, just one to rule—
This refactor is simple, clean, and cool!
🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-27T16_53_34_197Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2414de0 and faf858b.

📒 Files selected for processing (1)
  • src/core/game/UserSettings.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/game/UserSettings.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd52351 and 2414de0.

📒 Files selected for processing (8)
  • src/client/ClientGameRunner.ts (2 hunks)
  • src/client/DarkModeButton.ts (1 hunks)
  • src/client/InputHandler.ts (2 hunks)
  • src/client/Main.ts (2 hunks)
  • src/client/UserSettingModal.ts (11 hunks)
  • src/client/graphics/layers/OptionsMenu.ts (3 hunks)
  • src/core/game/GameView.ts (1 hunks)
  • src/core/game/UserSettings.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
src/client/Main.ts (1)
src/core/game/UserSettings.ts (1)
  • userSettings (115-115)
src/client/graphics/layers/OptionsMenu.ts (2)
src/core/game/UserSettings.ts (1)
  • userSettings (115-115)
src/client/InputHandler.ts (1)
  • RefreshGraphicsEvent (64-64)
src/client/UserSettingModal.ts (1)
src/core/game/UserSettings.ts (1)
  • userSettings (115-115)
src/client/InputHandler.ts (1)
src/core/game/UserSettings.ts (1)
  • userSettings (115-115)
src/client/ClientGameRunner.ts (1)
src/core/game/UserSettings.ts (1)
  • userSettings (115-115)
src/core/game/UserSettings.ts (1)
src/core/configuration/DefaultConfig.ts (1)
  • userSettings (205-210)
🪛 GitHub Actions: 🧪 CI
src/core/game/UserSettings.ts

[error] 19-19: ReferenceError: localStorage is not defined. The test suite failed to run due to usage of localStorage in a Node environment where it is not available.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy to openfront.dev
🔇 Additional comments (14)
src/core/game/UserSettings.ts (2)

29-46: Cache implementation looks good for performance.

The getter methods correctly read from the cache instead of repeatedly accessing localStorage. This should significantly improve performance as intended by the PR.


115-115: Singleton pattern correctly implemented.

The singleton instance export provides a clean way to share state across the application without creating multiple instances.

src/core/game/GameView.ts (2)

35-35: Import change correctly implements singleton pattern.

The change from importing the UserSettings class to importing the userSettings singleton instance is correct and aligns with the caching refactor.


183-191: Singleton usage in player name methods looks good.

The methods correctly use the singleton instance to check the anonymousNames setting. This maintains the same functionality while using the cached values.

src/client/Main.ts (2)

7-7: Import change correctly adopts singleton pattern.

The change from importing the UserSettings class to importing the userSettings singleton instance is correct and consistent with the refactor.


234-238: Good separation of concerns for DOM manipulation.

The dark mode DOM manipulation is appropriately handled in the client code rather than inside the settings class. This is better architecture than having DOM manipulation in the core settings class.

src/client/graphics/layers/OptionsMenu.ts (3)

7-7: Import change correctly adopts singleton pattern.

The change from importing the UserSettings class to importing the userSettings singleton instance is correct and maintains consistency across the codebase.


98-124: Toggle methods correctly use singleton instance.

All toggle methods have been updated to use the singleton instance instead of a local instance. The calls are consistent and maintain the same functionality.


202-232: Render methods correctly use singleton for display values.

The render logic correctly uses the singleton instance to check current setting values for display. The event emission for dark mode toggle (RefreshGraphicsEvent) is a good approach for handling UI updates without tight coupling.

src/client/DarkModeButton.ts (1)

3-3: Good refactoring to use singleton pattern!

The changes correctly replace the local UserSettings instance with the shared singleton. This improves performance by avoiding duplicate instances and enables centralized caching of settings.

Also applies to: 7-7, 14-15

src/client/InputHandler.ts (1)

3-3: Correct singleton usage!

The change properly replaces the local UserSettings instance with the shared singleton, maintaining the same functionality while enabling performance improvements through caching.

Also applies to: 307-307

src/client/ClientGameRunner.ts (1)

27-27: Good singleton usage in game creation!

The refactoring correctly passes the shared singleton to the game creation function, eliminating the need for local instantiation.

Also applies to: 94-96

src/client/UserSettingModal.ts (2)

4-4: Excellent singleton adoption for getters!

The getter calls correctly use the shared singleton instance, ensuring consistent state access across the application.

Also applies to: 222-222, 232-232, 241-241, 250-250, 259-259


83-83: Correct implementation for dark mode toggle.

This setter properly uses the enabled parameter from the event, maintaining the expected toggle behavior.

Comment on lines 76 to 84
toggleDarkMode() {
this.set("settings.darkMode", !this.darkMode());
if (this.darkMode()) {
this.cache.darkMode = !this.cache.darkMode;
this.setToStorage("settings.darkMode", this.cache.darkMode);
if (this.cache.darkMode) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

DOM manipulation should be handled outside the settings class.

The toggleDarkMode method directly manipulates the DOM by adding/removing CSS classes. This creates tight coupling between settings logic and UI concerns.

Consider moving DOM manipulation to the caller or using an event system:

  toggleDarkMode() {
    this.cache.darkMode = !this.cache.darkMode;
    this.setToStorage("settings.darkMode", this.cache.darkMode);
-   if (this.cache.darkMode) {
-     document.documentElement.classList.add("dark");
-   } else {
-     document.documentElement.classList.remove("dark");
-   }
  }

Then handle DOM updates in the client code that calls this method.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
toggleDarkMode() {
this.set("settings.darkMode", !this.darkMode());
if (this.darkMode()) {
this.cache.darkMode = !this.cache.darkMode;
this.setToStorage("settings.darkMode", this.cache.darkMode);
if (this.cache.darkMode) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
toggleDarkMode() {
this.cache.darkMode = !this.cache.darkMode;
this.setToStorage("settings.darkMode", this.cache.darkMode);
}
🤖 Prompt for AI Agents
In src/core/game/UserSettings.ts lines 76 to 84, the toggleDarkMode method
directly manipulates the DOM by adding or removing the "dark" class, which
couples settings logic with UI concerns. Refactor by removing the DOM
manipulation from this method so it only updates the darkMode setting and
storage. Instead, emit an event or return the new darkMode state so the caller
can handle updating the DOM accordingly.

Comment on lines 18 to 27
private getFromStorage(key: string, defaultValue: boolean): boolean {
const value = localStorage.getItem(key);
if (value === "true") return true;
if (value === "false") return false;

return defaultValue;
}

set(key: string, value: boolean) {
private setToStorage(key: string, value: boolean) {
localStorage.setItem(key, value ? "true" : "false");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add localStorage availability check to helper methods.

The private helper methods also need protection against localStorage being undefined in Node.js environments.

Apply this fix to both helper methods:

  private getFromStorage(key: string, defaultValue: boolean): boolean {
+   if (typeof localStorage === 'undefined') {
+     return defaultValue;
+   }
    const value = localStorage.getItem(key);
    if (value === "true") return true;
    if (value === "false") return false;
    return defaultValue;
  }

  private setToStorage(key: string, value: boolean) {
+   if (typeof localStorage === 'undefined') {
+     return;
+   }
    localStorage.setItem(key, value ? "true" : "false");
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private getFromStorage(key: string, defaultValue: boolean): boolean {
const value = localStorage.getItem(key);
if (value === "true") return true;
if (value === "false") return false;
return defaultValue;
}
set(key: string, value: boolean) {
private setToStorage(key: string, value: boolean) {
localStorage.setItem(key, value ? "true" : "false");
}
private getFromStorage(key: string, defaultValue: boolean): boolean {
if (typeof localStorage === 'undefined') {
return defaultValue;
}
const value = localStorage.getItem(key);
if (value === "true") return true;
if (value === "false") return false;
return defaultValue;
}
private setToStorage(key: string, value: boolean) {
if (typeof localStorage === 'undefined') {
return;
}
localStorage.setItem(key, value ? "true" : "false");
}
🧰 Tools
🪛 GitHub Actions: 🧪 CI

[error] 19-19: ReferenceError: localStorage is not defined. The test suite failed to run due to usage of localStorage in a Node environment where it is not available.

🤖 Prompt for AI Agents
In src/core/game/UserSettings.ts lines 18 to 27, the private helper methods
getFromStorage and setToStorage access localStorage without checking if it is
available, which can cause errors in Node.js environments. Add a check at the
start of each method to verify if localStorage is defined; if not, return the
default value in getFromStorage and skip setting in setToStorage. This will
prevent runtime errors when localStorage is unavailable.

Comment on lines 100 to 108
setDarkMode(value: boolean) {
this.cache.darkMode = value;
this.setToStorage("settings.darkMode", value);
if (value) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Same DOM coupling issue in setDarkMode setter.

The explicit setter method has the same tight coupling to DOM manipulation as the toggle method.

Apply the same separation of concerns here:

  setDarkMode(value: boolean) {
    this.cache.darkMode = value;
    this.setToStorage("settings.darkMode", value);
-   if (value) {
-     document.documentElement.classList.add("dark");
-   } else {
-     document.documentElement.classList.remove("dark");
-   }
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setDarkMode(value: boolean) {
this.cache.darkMode = value;
this.setToStorage("settings.darkMode", value);
if (value) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
setDarkMode(value: boolean) {
this.cache.darkMode = value;
this.setToStorage("settings.darkMode", value);
}
🤖 Prompt for AI Agents
In src/core/game/UserSettings.ts around lines 100 to 108, the setDarkMode method
directly manipulates the DOM by adding or removing the "dark" class on
document.documentElement, causing tight coupling. Refactor this method to remove
direct DOM manipulation and instead update only the internal state and storage.
Move the DOM update logic to a separate function or layer responsible for UI
changes, ensuring separation of concerns between state management and UI
rendering.

Comment on lines 4 to 16
constructor() {
this.cache = {
emojis: this.getFromStorage("settings.emojis", true),
anonymousNames: this.getFromStorage("settings.anonymousNames", false),
specialEffects: this.getFromStorage("settings.specialEffects", true),
darkMode: this.getFromStorage("settings.darkMode", false),
leftClickOpensMenu: this.getFromStorage(
"settings.leftClickOpensMenu",
false,
),
focusLocked: this.getFromStorage("settings.focusLocked", true),
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix localStorage access for Node.js test environment.

The pipeline failure shows localStorage is not defined in Node.js test environment. The constructor directly accesses localStorage during class instantiation, which breaks in server-side environments.

Consider adding a runtime check for localStorage availability:

  constructor() {
+   if (typeof localStorage === 'undefined') {
+     // Fallback for Node.js or server environments
+     this.cache = {
+       emojis: true,
+       anonymousNames: false,
+       specialEffects: true,
+       darkMode: false,
+       leftClickOpensMenu: false,
+       focusLocked: true,
+     };
+     return;
+   }
    this.cache = {
      emojis: this.getFromStorage("settings.emojis", true),
      anonymousNames: this.getFromStorage("settings.anonymousNames", false),
      specialEffects: this.getFromStorage("settings.specialEffects", true),
      darkMode: this.getFromStorage("settings.darkMode", false),
      leftClickOpensMenu: this.getFromStorage(
        "settings.leftClickOpensMenu",
        false,
      ),
      focusLocked: this.getFromStorage("settings.focusLocked", true),
    };
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constructor() {
this.cache = {
emojis: this.getFromStorage("settings.emojis", true),
anonymousNames: this.getFromStorage("settings.anonymousNames", false),
specialEffects: this.getFromStorage("settings.specialEffects", true),
darkMode: this.getFromStorage("settings.darkMode", false),
leftClickOpensMenu: this.getFromStorage(
"settings.leftClickOpensMenu",
false,
),
focusLocked: this.getFromStorage("settings.focusLocked", true),
};
}
constructor() {
if (typeof localStorage === 'undefined') {
// Fallback for Node.js or server environments
this.cache = {
emojis: true,
anonymousNames: false,
specialEffects: true,
darkMode: false,
leftClickOpensMenu: false,
focusLocked: true,
};
return;
}
this.cache = {
emojis: this.getFromStorage("settings.emojis", true),
anonymousNames: this.getFromStorage("settings.anonymousNames", false),
specialEffects: this.getFromStorage("settings.specialEffects", true),
darkMode: this.getFromStorage("settings.darkMode", false),
leftClickOpensMenu: this.getFromStorage(
"settings.leftClickOpensMenu",
false,
),
focusLocked: this.getFromStorage("settings.focusLocked", true),
};
}
🤖 Prompt for AI Agents
In src/core/game/UserSettings.ts around lines 4 to 16, the constructor directly
accesses localStorage, causing errors in Node.js test environments where
localStorage is undefined. Modify the getFromStorage method or the constructor
to first check if localStorage is available (e.g., typeof localStorage !==
'undefined') before accessing it. If localStorage is not available, return
default values or handle gracefully to avoid runtime errors during server-side
execution.

@@ -108,7 +107,7 @@ export async function createClientGame(
lobbyConfig: LobbyConfig,
eventBus: EventBus,
transport: Transport,
userSettings: UserSettings,
userSettings,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add type annotation for better type safety.

The parameter type annotation was removed, which reduces type safety. Consider adding it back to maintain clear interfaces.

- userSettings,
+ userSettings: UserSettings,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
userSettings,
userSettings: UserSettings,
🤖 Prompt for AI Agents
In src/client/ClientGameRunner.ts at line 110, the parameter userSettings is
missing a type annotation, reducing type safety. Add the appropriate type
annotation back to the userSettings parameter to ensure clear and safe
interfaces.

@@ -97,7 +95,7 @@ export class UserSettingModal extends LitElement {
const enabled = e.detail?.checked;
if (typeof enabled !== "boolean") return;

this.userSettings.set("settings.emojis", enabled);
userSettings.setEmojis(true);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix hardcoded values in toggle methods.

These setter calls hardcode true instead of using the enabled parameter from the event. This breaks the toggle functionality - users won't be able to turn these settings off.

- userSettings.setEmojis(true);
+ userSettings.setEmojis(enabled);

- userSettings.setFxLayer(true);
+ userSettings.setFxLayer(enabled);

- userSettings.setAnonymousNames(true);
+ userSettings.setAnonymousNames(enabled);

- userSettings.setLeftClickOpensMenu(true);
+ userSettings.setLeftClickOpensMenu(enabled);

Also applies to: 107-107, 116-116, 125-125

🤖 Prompt for AI Agents
In src/client/UserSettingModal.ts at lines 98, 107, 116, and 125, the setter
methods like setEmojis are called with hardcoded true values, which disables
toggling off the settings. Replace the hardcoded true with the appropriate
boolean parameter (likely named enabled) from the event handler to correctly
reflect the user's toggle action and allow both enabling and disabling of these
settings.

@github-project-automation github-project-automation bot moved this from Triage to Development in OpenFront Release Management May 27, 2025
Copy link
Collaborator

@evanpelle evanpelle left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have two threads: main & worker, so UserSettings actually has two instances, one in each thread. caching it locally will cause them to get out of sync.

What I recommend is to keep the local cache, and then have a invalidate() method that is called once per tick.

Instead of having a separate field for each value, just do:

cache = Map<string, string>(), and then on invalidate() call cache.clear()

@VariableVince
Copy link
Contributor

Closing this PR as it doesn't look like this PR it its current form will be implemented anymore.

@github-project-automation github-project-automation bot moved this from Development to Complete in OpenFront Release Management Jun 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Complete
Development

Successfully merging this pull request may close these issues.

None yet

3 participants