Skip to content

Added a new base game modal that both host and single player modals i… - #1027

Closed
shaan150 wants to merge 2 commits into
openfrontio:mainfrom
shaan150:feature/single-player-and-host-lobby-modal-rewrite
Closed

shaan150 wants to merge 2 commits into
openfrontio:mainfrom
shaan150:feature/single-player-and-host-lobby-modal-rewrite

Conversation

@shaan150

@shaan150 shaan150 commented Jun 4, 2025

Copy link
Copy Markdown
Contributor

…nherit from it

Description:

Please complete the following:

  • I have added screenshots for all UI updates
  • I process any text displayed to the user through translateText() and I've added it to the en.json file
  • I have added relevant tests to the test directory
  • 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:

@coderabbitai

coderabbitai Bot commented Jun 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

A new abstract base modal, BaseGameModal, was introduced to manage shared game configuration logic and UI. Both HostLobbyModal and SinglePlayerModal were refactored to extend this base class, offloading state and rendering logic. Rendering was modularized, event handling was unified, and polling/player update logic was improved for the host lobby. A new checkbox rendering utility was added.

Changes

File(s) Change Summary
src/client/HostLobbyModal.ts, src/client/SinglePlayerModal.ts Refactored to extend BaseGameModal, removed local state, modularized rendering, unified event handling.
src/client/components/baseComponents/BaseGameModal.ts Added new abstract class for shared modal logic, state, rendering, and event handling.
src/client/utilities/RenderCheckboxOption.ts Added utility function for rendering checkbox options using Lit templates.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Modal (HostLobby/SinglePlayer)
    participant BaseGameModal
    participant Server

    User->>Modal: Open modal
    Modal->>BaseGameModal: open()
    BaseGameModal->>BaseGameModal: Initialize state/render UI

    User->>BaseGameModal: Change game config (map, mode, etc.)
    BaseGameModal->>BaseGameModal: Update state
    BaseGameModal->>Modal: Call override handler (if needed)
    Modal->>Server: putGameConfig() (HostLobby only)

    User->>Modal: Start game
    Modal->>BaseGameModal: startGame()
    Modal->>Server: POST /start (HostLobby) or dispatch join event (SinglePlayer)
Loading

Possibly related PRs

  • openfrontio/OpenFrontIO#991: Refactors HostLobbyModal to add a toggleUnit method and use a utility function for rendering unit options, overlapping with changes to class structure and rendering logic in this PR.

Suggested labels

Feature - New, UI/UX

Suggested reviewers

  • evanpelle

Poem

In the land of modals, a base was born,
To gather the options, from dusk until morn.
Host and Single now share their fate,
With checkboxes neat and logic first-rate.
Polling and toggling, all in a row—
The game setup’s smoother, onward we go!
🕹️✨

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 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-06-04T02_00_16_697Z-debug-0.log


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Nitpick comments (2)
src/client/components/baseComponents/BaseGameModal.ts (1)

329-333: Rename method for clarity.

The method name botsChangeTimer() doesn't clearly indicate its purpose. Consider renaming to be more descriptive:

-protected botsChangeTimer() {
+protected setupBotsDebounceTimer() {
   this.botsUpdateTimer = window.setTimeout(() => {
     this.botsUpdateTimer = null;
   }, 300);
 }
src/client/HostLobbyModal.ts (1)

278-282: Consider adaptive polling interval

Polling every second might be too frequent. Consider starting with a longer interval or making it adaptive based on activity.

   private startPolling() {
     if (!this.playersInterval) {
-      this.playersInterval = setInterval(() => this.pollPlayers(), 1000);
+      // Start with 2s, could be made adaptive
+      const POLL_INTERVAL = 2000;
+      this.playersInterval = setInterval(() => this.pollPlayers(), POLL_INTERVAL);
     }
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 270244c and 31e0688.

📒 Files selected for processing (4)
  • src/client/HostLobbyModal.ts (1 hunks)
  • src/client/SinglePlayerModal.ts (2 hunks)
  • src/client/components/baseComponents/BaseGameModal.ts (1 hunks)
  • src/client/utilities/RenderCheckboxOption.ts (1 hunks)
🔇 Additional comments (4)
src/client/utilities/RenderCheckboxOption.ts (1)

3-16: Clean utility function for checkbox rendering.

Good work creating a simple, reusable function for checkbox rendering. The implementation is clean and easy to understand.

src/client/SinglePlayerModal.ts (1)

16-19: Good use of template method pattern.

The implementation of getTranslationPrefix() is clean and follows the template method pattern well.

src/client/HostLobbyModal.ts (2)

274-276: Why disable shadow DOM?

Returning this disables shadow DOM encapsulation. This can cause style conflicts. Is there a specific reason for disabling it?

If you need to disable shadow DOM for styling reasons, consider using CSS custom properties or ::part for styling instead.


53-139: Clean render structure

Good job breaking down the render into focused helper methods. This makes the code easy to read and maintain.

Comment on lines +20 to +364
export abstract class BaseGameModal extends LitElement {
@query("o-modal") protected modalEl!: HTMLElement & {
open: () => void;
close: () => void;
};

@state() protected selectedMap: GameMapType = GameMapType.World;
@state() protected selectedDifficulty: Difficulty = Difficulty.Medium;
@state() protected useRandomMap = false;
@state() protected gameMode: GameMode = GameMode.FFA;
@state() protected teamCount: number | typeof Duos = 2;
@state() protected disabledUnits: UnitType[] = [];

@state() protected gameOptions = {
disableNPCs: false,
bots: 400,
infiniteGold: false,
infiniteTroops: false,
instantBuild: false,
};

private randomMap =
typeof window !== "undefined"
? require("../../../../resources/images/RandomMap.webp")
: "";

protected botsUpdateTimer: number | null = null;

// Translation helper
protected t(key: string): string {
return translateText(`${this.getTranslationPrefix()}.${key}`);
}

// Public interface
public open() {
this.modalEl?.open();
this.useRandomMap = false;
}

public close() {
this.modalEl?.close();
if (this.botsUpdateTimer !== null) {
clearTimeout(this.botsUpdateTimer);
this.botsUpdateTimer = null;
}
}

public getGameConfig(): GameConfig {
return {
gameMap: this.useRandomMap ? this.getRandomMap() : this.selectedMap,
difficulty: this.selectedDifficulty,
disableNPCs: this.gameOptions.disableNPCs,
bots: this.gameOptions.bots,
infiniteGold: this.gameOptions.infiniteGold,
infiniteTroops: this.gameOptions.infiniteTroops,
instantBuild: this.gameOptions.instantBuild,
gameMode: this.gameMode,
playerTeams: this.teamCount,
disabledUnits: this.disabledUnits,
gameType: GameType.Singleplayer,
};
}

// Rendering Methods
protected renderMapSelection() {
return html`
<div class="options-section">
<div class="option-title">${translateText("map.map")}</div>
<div class="option-cards flex-col">
${Object.entries(mapCategories).map(
([categoryKey, maps]) => html`
<div class="w-full mb-4">
<h3
class="text-lg font-semibold mb-2 text-center text-gray-300"
>
${translateText(`map_categories.${categoryKey}`)}
</h3>
<div class="flex flex-row flex-wrap justify-center gap-4">
${maps.map((mapValue) => {
const mapKey = Object.keys(GameMapType).find(
(k) => GameMapType[k] === mapValue,
);
return html`
<div @click=${() => this.handleMapSelection(mapValue)}>
<map-display
.mapKey=${mapKey}
.selected=${!this.useRandomMap &&
this.selectedMap === mapValue}
.translation=${translateText(
`map.${mapKey?.toLowerCase()}`,
)}
></map-display>
</div>
`;
})}
</div>
</div>
`,
)}
<div
class="option-card random-map ${this.useRandomMap
? "selected"
: ""}"
@click=${() => (this.useRandomMap = true)}
>
<div class="option-image">
<img
src=${this.randomMap}
alt="Random Map"
class="map-thumbnail"
/>
</div>
<div class="option-card-title">${translateText("map.random")}</div>
</div>
</div>
</div>
`;
}

protected renderDifficultySelection() {
return html`
<div class="options-section">
<div class="option-title">
${translateText("difficulty.difficulty")}
</div>
<div class="option-cards">
${Object.entries(Difficulty)
.filter(([key]) => isNaN(Number(key)))
.map(
([key, value]) => html`
<div
class="option-card ${this.selectedDifficulty === value
? "selected"
: ""}"
@click=${() => this.handleDifficultySelection(value)}
>
<difficulty-display
.difficultyKey=${key}
></difficulty-display>
<p class="option-card-title">
${translateText(`difficulty.${DifficultyDescription[key]}`)}
</p>
</div>
`,
)}
</div>
</div>
`;
}

protected renderGameModeSelection() {
return html`
<div class="options-section">
<div class="option-title">${translateText("host_modal.mode")}</div>
<div class="option-cards">
<div
class="option-card ${this.gameMode === GameMode.FFA
? "selected"
: ""}"
@click=${() => this.handleGameModeSelection(GameMode.FFA)}
>
<div class="option-card-title">
${translateText("game_mode.ffa")}
</div>
</div>
<div
class="option-card ${this.gameMode === GameMode.Team
? "selected"
: ""}"
@click=${() => this.handleGameModeSelection(GameMode.Team)}
>
<div class="option-card-title">
${translateText("game_mode.teams")}
</div>
</div>
</div>
</div>
`;
}

protected renderTeamSelectionIfApplicable() {
if (this.gameMode === GameMode.FFA) return null;
return html`
<div class="options-section">
<div class="option-title">${this.t("team_count")}</div>
<div class="option-cards">
${[Duos, 2, 3, 4, 5, 6, 7].map(
(count) => html`
<div
class="option-card ${this.teamCount === count
? "selected"
: ""}"
@click=${() => this.handleTeamCountSelection(count)}
>
<div class="option-card-title">${count}</div>
</div>
`,
)}
</div>
</div>
`;
}

protected renderGameOptions() {
const checkboxOptions = [
{
id: "disable-npcs",
key: "disableNPCs",
label: this.t("disable_nations"),
},
{
id: "instant-build",
key: "instantBuild",
label: this.t("instant_build"),
},
{
id: "infinite-gold",
key: "infiniteGold",
label: this.t("infinite_gold"),
},
{
id: "infinite-troops",
key: "infiniteTroops",
label: this.t("infinite_troops"),
},
];

return html`
<div class="options-section">
<div class="option-title">${this.t("options_title")}</div>
<div class="option-cards">
<label for="bots-count" class="option-card">
<input
type="range"
id="bots-count"
min="0"
max="400"
step="1"
@input=${this.handleBotsChange}
@change=${this.handleBotsChange}
.value="${String(this.gameOptions.bots)}"
/>
<div class="option-card-title">
<span>${this.t("bots")}</span>
${this.gameOptions.bots === 0
? this.t("bots_disabled")
: this.gameOptions.bots}
</div>
</label>
${checkboxOptions.map((opt) =>
renderCheckboxOption(
opt.id,
this.gameOptions[opt.key],
opt.label,
(e: Event) =>
this.handleToggleOption(
opt.key as keyof typeof this.gameOptions,
e,
),
),
)}
</div>

<hr style="width: 100%; border-top: 1px solid #444; margin: 16px 0;" />
<div
style="margin: 8px 0 12px 0; font-weight: bold; color: #ccc; text-align: center;"
>
${this.t("enables_title")}
</div>
<div
style="display: flex; flex-wrap: wrap; justify-content: center; gap: 12px;"
>
${renderUnitTypeOptions({
disabledUnits: this.disabledUnits,
toggleUnit: this.toggleUnit.bind(this),
})}
</div>
</div>
`;
}

// Event Handlers
protected handleMapSelection(value: GameMapType) {
this.selectedMap = value;
this.useRandomMap = false;
}

protected handleDifficultySelection(value: Difficulty) {
this.selectedDifficulty = value;
}

protected handleBotsChange(e: Event) {
const value = parseInt((e.target as HTMLInputElement).value);
if (isNaN(value) || value < 0 || value > 400) {
return;
}

this.gameOptions = {
...this.gameOptions,
bots: value,
};

if (this.botsUpdateTimer !== null) {
clearTimeout(this.botsUpdateTimer);
}

this.botsChangeTimer();
}

protected botsChangeTimer() {
this.botsUpdateTimer = window.setTimeout(() => {
this.botsUpdateTimer = null;
}, 300);
}

protected handleToggleOption(
option: keyof typeof this.gameOptions,
e: Event,
) {
const checked = (e.target as HTMLInputElement).checked;
this.gameOptions = { ...this.gameOptions, [option]: checked };
}

protected handleGameModeSelection(value: GameMode) {
this.gameMode = value;
}

protected handleTeamCountSelection(value: number | typeof Duos) {
this.teamCount = value;
}

protected toggleUnit(unit: UnitType, checked: boolean): void {
this.disabledUnits = checked
? [...this.disabledUnits, unit]
: this.disabledUnits.filter((u) => u !== unit);
}

protected getRandomMap(): GameMapType {
const maps = Object.values(GameMapType);
return maps[Math.floor(Math.random() * maps.length)] as GameMapType;
}

protected abstract getTranslationPrefix(): string;
protected abstract startGame(): void;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider composition instead of inheritance for BaseGameModal.

This abstract class forces inheritance on consumers, which makes the code harder to test and less flexible. Consider refactoring to use composition:

  1. Extract game configuration state into a separate store or hook
  2. Create individual components for each UI section (MapSelector, DifficultySelector, etc.)
  3. Use a container component that composes these pieces together

This approach would make the code more modular and easier to test without forcing inheritance.

🤖 Prompt for AI Agents
In src/client/components/baseComponents/BaseGameModal.ts from lines 20 to 364,
the current design uses an abstract class that enforces inheritance, reducing
flexibility and testability. To fix this, refactor by extracting the game
configuration state into a separate store or hook, create individual components
for each UI section like MapSelector and DifficultySelector, and then build a
container component that composes these smaller components together. This
composition approach will modularize the code and improve maintainability and
testing without relying on inheritance.

Comment on lines +41 to +44
private randomMap =
typeof window !== "undefined"
? require("../../../../resources/images/RandomMap.webp")
: "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace require() with ES module import.

Using require() in TypeScript can cause build issues. Consider using a static import at the top of the file or dynamic import():

-private randomMap =
-  typeof window !== "undefined"
-    ? require("../../../../resources/images/RandomMap.webp")
-    : "";
+private randomMap = "";
+
+async connectedCallback() {
+  super.connectedCallback();
+  if (typeof window !== "undefined") {
+    const module = await import("../../../../resources/images/RandomMap.webp");
+    this.randomMap = module.default;
+  }
+}
🤖 Prompt for AI Agents
In src/client/components/baseComponents/BaseGameModal.ts around lines 41 to 44,
replace the use of require() for loading the image with an ES module import.
Move the import statement to the top of the file using a static import for the
image, or if conditional loading is necessary, use a dynamic import() instead of
require(). This will ensure compatibility with TypeScript and avoid build
issues.

Comment on lines +57 to +61
disableNPCs: this.gameOptions["disableNPCs"],
bots: this.gameOptions["bots"],
infiniteGold: this.gameOptions["infiniteGold"],
infiniteTroops: this.gameOptions["infiniteTroops"],
instantBuild: this.gameOptions["instantBuild"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use dot notation for better type safety.

Replace bracket notation with dot notation for accessing gameOptions properties:

-disableNPCs: this.gameOptions["disableNPCs"],
-bots: this.gameOptions["bots"],
-infiniteGold: this.gameOptions["infiniteGold"],
-infiniteTroops: this.gameOptions["infiniteTroops"],
-instantBuild: this.gameOptions["instantBuild"],
+disableNPCs: this.gameOptions.disableNPCs,
+bots: this.gameOptions.bots,
+infiniteGold: this.gameOptions.infiniteGold,
+infiniteTroops: this.gameOptions.infiniteTroops,
+instantBuild: this.gameOptions.instantBuild,
📝 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
disableNPCs: this.gameOptions["disableNPCs"],
bots: this.gameOptions["bots"],
infiniteGold: this.gameOptions["infiniteGold"],
infiniteTroops: this.gameOptions["infiniteTroops"],
instantBuild: this.gameOptions["instantBuild"],
disableNPCs: this.gameOptions.disableNPCs,
bots: this.gameOptions.bots,
infiniteGold: this.gameOptions.infiniteGold,
infiniteTroops: this.gameOptions.infiniteTroops,
instantBuild: this.gameOptions.instantBuild,
🤖 Prompt for AI Agents
In src/client/SinglePlayerModal.ts around lines 57 to 61, replace the bracket
notation used to access properties of gameOptions with dot notation to improve
type safety. Change expressions like this.gameOptions["disableNPCs"] to
this.gameOptions.disableNPCs for all listed properties.

Comment on lines +241 to 272
protected override handleMapSelection(value) {
super.handleMapSelection(value);
this.putGameConfig();
}

private getRandomMap(): GameMapType {
const maps = Object.values(GameMapType);
const randIdx = Math.floor(Math.random() * maps.length);
return maps[randIdx] as GameMapType;
protected override handleDifficultySelection(value) {
super.handleDifficultySelection(value);
this.putGameConfig();
}

private async startGame() {
if (this.useRandomMap) {
this.selectedMap = this.getRandomMap();
}
protected override handleGameModeSelection(value) {
super.handleGameModeSelection(value);
this.putGameConfig();
}

await this.putGameConfig();
consolex.log(
`Starting private game with map: ${GameMapType[this.selectedMap]} ${this.useRandomMap ? " (Randomly selected)" : ""}`,
);
this.close();
const config = await getServerConfigFromClient();
const response = await fetch(
`${window.location.origin}/${config.workerPath(this.lobbyId)}/api/start_game/${this.lobbyId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
},
);
return response;
protected override handleTeamCountSelection(value) {
super.handleTeamCountSelection(value);
this.putGameConfig();
}

private async copyToClipboard() {
try {
//TODO: Convert id to url and copy
await navigator.clipboard.writeText(
`${location.origin}/join/${this.lobbyId}`,
);
this.copySuccess = true;
setTimeout(() => {
this.copySuccess = false;
}, 2000);
} catch (err) {
consolex.error(`Failed to copy text: ${err}`);
}
protected override handleToggleOption(
option: keyof typeof this.gameOptions,
e: Event,
) {
super.handleToggleOption(option, e);
this.putGameConfig();
}

private async pollPlayers() {
const config = await getServerConfigFromClient();
fetch(`/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((data: GameInfo) => {
console.log(`got game info response: ${JSON.stringify(data)}`);
this.players = data.clients?.map((p) => p.username) ?? [];
});
protected override toggleUnit(unit, checked) {
super.toggleUnit(unit, checked);
this.putGameConfig();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace override pattern with events

Instead of overriding every method to call putGameConfig(), use events. This removes tight coupling and repetitive code.

Instead of multiple overrides:

// In constructor or connectedCallback
this.addEventListener('game-config-changed', () => this.putGameConfig());

// Base class emits event when config changes
// Remove all these override methods

This makes the code cleaner and less coupled to base class implementation.

🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts between lines 241 and 272, instead of overriding
multiple methods just to call putGameConfig(), refactor to use an event-driven
approach. Remove all these override methods and add a single event listener for
a custom event like 'game-config-changed' in the constructor or
connectedCallback. Ensure the base class emits this event whenever the game
configuration changes, so putGameConfig() is called in response to the event,
reducing code duplication and coupling.

@state() private infiniteTroops: boolean = false;
@state() private instantBuild: boolean = false;
export class HostLobbyModal extends BaseGameModal {
@state() private lobbyId = "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider composition instead of inheritance

The current design uses inheritance (extends BaseGameModal) but composition would be better. Inheritance creates tight coupling and makes testing harder. Consider refactoring to use BaseGameModal as a composed component or service instead.

Example approach using composition:

-export class HostLobbyModal extends BaseGameModal {
+export class HostLobbyModal extends LitElement {
+  private gameConfig = new BaseGameModalService();

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts at line 13, refactor the HostLobbyModal class to
use composition instead of extending BaseGameModal. Remove the "extends
BaseGameModal" inheritance and instead create an instance of BaseGameModal
inside HostLobbyModal. Delegate necessary modal-related functionality to this
instance, reducing tight coupling and improving testability.

Comment on lines 211 to 232
const config = await getServerConfigFromClient();
const response = await fetch(
await fetch(
`${window.location.origin}/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
gameMap: this.selectedMap,
difficulty: this.selectedDifficulty,
disableNPCs: this.disableNPCs,
bots: this.bots,
infiniteGold: this.infiniteGold,
infiniteTroops: this.infiniteTroops,
instantBuild: this.instantBuild,
disableNPCs: this.gameOptions["disableNPCs"],
bots: this.gameOptions["bots"],
infiniteGold: this.gameOptions["infiniteGold"],
infiniteTroops: this.gameOptions["infiniteTroops"],
instantBuild: this.gameOptions["instantBuild"],
gameMode: this.gameMode,
disabledUnits: this.disabledUnits,
playerTeams: this.teamCount,
disabledUnits: this.disabledUnits,
} satisfies Partial<GameConfig>),
},
);
return response;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for config updates

The putGameConfig method doesn't handle errors. If the server update fails, users won't know their settings weren't saved.

   private async putGameConfig() {
     const config = await getServerConfigFromClient();
-    await fetch(
+    try {
+      const response = await fetch(
       `${window.location.origin}/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`,
       {
         method: "PUT",
         headers: { "Content-Type": "application/json" },
         body: JSON.stringify({
           gameMap: this.selectedMap,
           difficulty: this.selectedDifficulty,
           disableNPCs: this.gameOptions["disableNPCs"],
           bots: this.gameOptions["bots"],
           infiniteGold: this.gameOptions["infiniteGold"],
           infiniteTroops: this.gameOptions["infiniteTroops"],
           instantBuild: this.gameOptions["instantBuild"],
           gameMode: this.gameMode,
           playerTeams: this.teamCount,
           disabledUnits: this.disabledUnits,
         } satisfies Partial<GameConfig>),
       },
     );
+      if (!response.ok) {
+        throw new Error(`Failed to update config: ${response.status}`);
+      }
+    } catch (error) {
+      consolex.error("Failed to update game config:", error);
+      // Notify user of failure
+      this.dispatchEvent(new CustomEvent('config-update-error', {
+        detail: { error },
+        bubbles: true,
+        composed: true
+      }));
+    }
   }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts around lines 210 to 231, the putGameConfig
method lacks error handling for the fetch request updating the game
configuration. To fix this, wrap the fetch call in a try-catch block, and in the
catch block, handle any errors by logging them or notifying the user that the
update failed. Additionally, check the fetch response status and handle
non-successful responses appropriately to ensure users are informed if their
settings were not saved.

Comment on lines +25 to 46
try {
const lobby = await this.createLobby();
this.lobbyId = lobby.gameID;

this.dispatchEvent(
new CustomEvent("join-lobby", {
detail: {
gameID: this.lobbyId,
clientID: generateID(),
} as JoinLobbyEvent,
bubbles: true,
composed: true,
}),
);

</div>
</o-modal>
`;
super.open();
this.startPolling();
} catch (error) {
consolex.error("Failed to create/join lobby:", error);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add user feedback for errors

When lobby creation fails, users only see console errors. They need visible feedback to understand what went wrong.

     } catch (error) {
       consolex.error("Failed to create/join lobby:", error);
+      // Show error to user
+      this.dispatchEvent(new CustomEvent('show-error', {
+        detail: { message: translateText("host_modal.create_lobby_error") },
+        bubbles: true,
+        composed: true
+      }));
+      this.close();
     }
📝 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
public override async open() {
try {
const lobby = await this.createLobby();
this.lobbyId = lobby.gameID;
this.dispatchEvent(
new CustomEvent("join-lobby", {
detail: {
gameID: this.lobbyId,
clientID: generateID(),
} as JoinLobbyEvent,
bubbles: true,
composed: true,
}),
);
</div>
</o-modal>
`;
super.open();
this.startPolling();
} catch (error) {
consolex.error("Failed to create/join lobby:", error);
}
}
public override async open() {
try {
const lobby = await this.createLobby();
this.lobbyId = lobby.gameID;
this.dispatchEvent(
new CustomEvent("join-lobby", {
detail: {
gameID: this.lobbyId,
clientID: generateID(),
} as JoinLobbyEvent,
bubbles: true,
composed: true,
}),
);
super.open();
this.startPolling();
} catch (error) {
consolex.error("Failed to create/join lobby:", error);
// Show error to user
this.dispatchEvent(new CustomEvent('show-error', {
detail: { message: translateText("host_modal.create_lobby_error") },
bubbles: true,
composed: true
}));
this.close();
}
}
🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts around lines 24 to 45, the open method logs
errors to the console but does not provide any visible feedback to users when
lobby creation fails. Modify the catch block to display a user-friendly error
message in the UI, such as showing an alert or rendering an error notification
component, so users are informed about the failure instead of only seeing
console errors.

Comment on lines +180 to 195
if (this.lobbyId) {
const config = await getServerConfigFromClient();
fetch(`/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((data: GameInfo) => {
console.log(`got game info response: ${JSON.stringify(data)}`);
this.players = data.clients?.map((p) => p.username) ?? [];
});
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix polling issues

The pollPlayers method has several problems:

  1. Debug console.log left in code (line 190)
  2. No error handling if fetch fails
  3. No cleanup if component unmounts during fetch
   private async pollPlayers() {
     if (this.lobbyId) {
       const config = await getServerConfigFromClient();
-      fetch(`/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`, {
+      try {
+        const response = await fetch(`/${config.workerPath(this.lobbyId)}/api/game/${this.lobbyId}`, {
           method: "GET",
           headers: {
             "Content-Type": "application/json",
           },
-        })
-        .then((response) => response.json())
-        .then((data: GameInfo) => {
-          console.log(`got game info response: ${JSON.stringify(data)}`);
+        });
+        if (!response.ok) return;
+        const data: GameInfo = await response.json();
+        // Check if component is still connected
+        if (this.isConnected) {
           this.players = data.clients?.map((p) => p.username) ?? [];
-        });
+        }
+      } catch (error) {
+        consolex.error("Failed to poll players:", error);
+      }
     }
   }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts lines 179 to 194, remove the debug console.log
statement on line 190, add error handling for the fetch call to catch and handle
any fetch failures gracefully, and implement a cleanup mechanism to cancel or
ignore the fetch response if the component unmounts during the fetch operation
to prevent state updates on unmounted components.

Comment on lines +142 to 163
if (this.useRandomMap) {
this.selectedMap = this.getRandomMap();
}

// Update the display value immediately
this.bots = value;
await this.putGameConfig();

// Clear any existing timer
if (this.botsUpdateTimer !== null) {
clearTimeout(this.botsUpdateTimer);
}
consolex.log(
`Starting private game with map: ${GameMapType[this.selectedMap]}${this.useRandomMap ? " (random)" : ""}`,
);

// Set a new timer to call putGameConfig after 300ms of inactivity
this.botsUpdateTimer = window.setTimeout(() => {
this.putGameConfig();
this.botsUpdateTimer = null;
}, 300);
}
this.close();

private handleInstantBuildChange(e: Event) {
this.instantBuild = Boolean((e.target as HTMLInputElement).checked);
this.putGameConfig();
const config = await getServerConfigFromClient();
await fetch(
`${window.location.origin}/${config.workerPath(this.lobbyId)}/api/start_game/${this.lobbyId}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
},
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for game start

The POST request to start the game has no error handling. If it fails, users won't know the game didn't start.

     const config = await getServerConfigFromClient();
-    await fetch(
+    try {
+      const response = await fetch(
       `${window.location.origin}/${config.workerPath(this.lobbyId)}/api/start_game/${this.lobbyId}`,
       {
         method: "POST",
         headers: { "Content-Type": "application/json" },
       },
     );
+      if (!response.ok) {
+        throw new Error(`Failed to start game: ${response.status}`);
+      }
+    } catch (error) {
+      consolex.error("Failed to start game:", error);
+      this.open(); // Reopen modal
+      // Show error to user
+      this.dispatchEvent(new CustomEvent('show-error', {
+        detail: { message: translateText("host_modal.start_game_error") },
+        bubbles: true,
+        composed: 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
protected override async startGame() {
if (this.useRandomMap) {
this.selectedMap = this.getRandomMap();
}
// Update the display value immediately
this.bots = value;
await this.putGameConfig();
// Clear any existing timer
if (this.botsUpdateTimer !== null) {
clearTimeout(this.botsUpdateTimer);
}
consolex.log(
`Starting private game with map: ${GameMapType[this.selectedMap]}${this.useRandomMap ? " (random)" : ""}`,
);
// Set a new timer to call putGameConfig after 300ms of inactivity
this.botsUpdateTimer = window.setTimeout(() => {
this.putGameConfig();
this.botsUpdateTimer = null;
}, 300);
}
this.close();
private handleInstantBuildChange(e: Event) {
this.instantBuild = Boolean((e.target as HTMLInputElement).checked);
this.putGameConfig();
const config = await getServerConfigFromClient();
await fetch(
`${window.location.origin}/${config.workerPath(this.lobbyId)}/api/start_game/${this.lobbyId}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
},
);
}
protected override async startGame() {
if (this.useRandomMap) {
this.selectedMap = this.getRandomMap();
}
await this.putGameConfig();
consolex.log(
`Starting private game with map: ${GameMapType[this.selectedMap]}${this.useRandomMap ? " (random)" : ""}`,
);
this.close();
const config = await getServerConfigFromClient();
try {
const response = await fetch(
`${window.location.origin}/${config.workerPath(this.lobbyId)}/api/start_game/${this.lobbyId}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
},
);
if (!response.ok) {
throw new Error(`Failed to start game: ${response.status}`);
}
} catch (error) {
consolex.error("Failed to start game:", error);
this.open(); // Reopen modal
// Show error to user
this.dispatchEvent(new CustomEvent('show-error', {
detail: { message: translateText("host_modal.start_game_error") },
bubbles: true,
composed: true
}));
}
}
🤖 Prompt for AI Agents
In src/client/HostLobbyModal.ts between lines 141 and 162, the POST request to
start the game lacks error handling, so failures are silent to users. Wrap the
fetch call in a try-catch block, catch any errors or non-OK responses, and
provide user feedback such as logging the error or showing an alert to indicate
the game start failed.

@github-project-automation github-project-automation Bot moved this from Triage to Development in OpenFront Release Management Jun 4, 2025

@evanpelle evanpelle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I prefer composition over inheritance

@VariableVince

VariableVince commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

With the above comment, is it still to be expected that this pull request will be merged in this form? Just asking since there's been no update on this in the last weeks

Edit: Sorry if i spoke before my turn. I just found a discussion about its contents and you being busy with work and wanting to take things in consideration.
https://discord.com/channels/1359946986937258015/1359946989046989063/1379893456394129468

@shaan150

shaan150 commented Jun 20, 2025 via email

Copy link
Copy Markdown
Contributor Author

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@ryanbarlow97 ryanbarlow97 added the Stale PRs that haven't been touched for over two weeks. label Nov 19, 2025
@ryanbarlow97
ryanbarlow97 changed the base branch from v24 to main November 19, 2025 09:40
@evanpelle evanpelle closed this Dec 24, 2025
@github-project-automation github-project-automation Bot moved this from Development to Complete in OpenFront Release Management Dec 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Stale PRs that haven't been touched for over two weeks.

Projects

Status: Complete

Development

Successfully merging this pull request may close these issues.

5 participants