Repository navigation
Conversation
WalkthroughA new abstract base modal, Changes
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)
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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
npm error Exit handler never called! 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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 intervalPolling 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
📒 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
thisdisables 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 structureGood job breaking down the render into focused helper methods. This makes the code easy to read and maintain.
| 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; | ||
| } |
There was a problem hiding this comment.
🛠️ 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:
- Extract game configuration state into a separate store or hook
- Create individual components for each UI section (MapSelector, DifficultySelector, etc.)
- 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.
| private randomMap = | ||
| typeof window !== "undefined" | ||
| ? require("../../../../resources/images/RandomMap.webp") | ||
| : ""; |
There was a problem hiding this comment.
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.
| disableNPCs: this.gameOptions["disableNPCs"], | ||
| bots: this.gameOptions["bots"], | ||
| infiniteGold: this.gameOptions["infiniteGold"], | ||
| infiniteTroops: this.gameOptions["infiniteTroops"], | ||
| instantBuild: this.gameOptions["instantBuild"], |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| 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(); | ||
| } |
There was a problem hiding this comment.
🛠️ 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 methodsThis 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 = ""; |
There was a problem hiding this comment.
🛠️ 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.
| 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; | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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); | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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.
| 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) ?? []; | ||
| }); | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
Fix polling issues
The pollPlayers method has several problems:
- Debug console.log left in code (line 190)
- No error handling if fetch fails
- 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.
| 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" }, | ||
| }, | ||
| ); | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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.
evanpelle
left a comment
There was a problem hiding this comment.
I prefer composition over inheritance
|
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. |
|
Just had some hospital visits and personal stuff going on, plan to do a
rewrite of it to be more composition next week
…On Fri, 20 Jun 2025, 21:42 VariableVince, ***@***.***> wrote:
*VariableVince* left a comment (openfrontio/OpenFrontIO#1027)
<#1027 (comment)>
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
—
Reply to this email directly, view it on GitHub
<#1027 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AJPNHAEI24DCUZBV4VZPFGD3ERW4LAVCNFSM6AAAAAB6RINGFKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDSOJSG44DEOBWGQ>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
|
|
…nherit from it
Description:
Please complete the following:
Please put your Discord username so you can be contacted if a bug or regression is found: