Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,9 @@
<events-display
class="w-full sm:w-auto pointer-events-auto"
></events-display>
<actionable-events
class="w-full sm:w-auto pointer-events-auto"
></actionable-events>
</div>
</div>

Expand Down
2 changes: 2 additions & 0 deletions resources/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,8 @@
"betrayed_you": "{name} broke their alliance with you",
"about_to_expire": "Your alliance with {name} is about to expire!",
"alliance_expired": "Your alliance with {name} expired",
"atom_bomb_detonated": "{name} - atom bomb detonated",
"hydrogen_bomb_detonated": "{name} - hydrogen bomb detonated",
"attack_request": "{name} requests you attack {target}",
"sent_emoji": "Sent {name}: {emoji}",
"renew_alliance": "Request to renew",
Expand Down
1 change: 1 addition & 0 deletions src/client/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ export function getMessageTypeClasses(type: MessageType): string {
case MessageType.ALLIANCE_BROKEN:
case MessageType.UNIT_CAPTURED_BY_ENEMY:
case MessageType.UNIT_DESTROYED:
case MessageType.NUKE_DETONATED:
return severityColors["fail"];
case MessageType.ATTACK_CANCELLED:
case MessageType.ATTACK_REQUEST:
Expand Down
12 changes: 12 additions & 0 deletions src/client/hud/GameRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { HoverHighlightController } from "../controllers/HoverHighlightControlle
import { WarshipSelectionController } from "../controllers/WarshipSelectionController";
import { GameView as WebGLGameView } from "../render/gl";
import { FrameProfiler } from "./FrameProfiler";
import { ActionableEvents } from "./layers/ActionableEvents";
import { AlertFrame } from "./layers/AlertFrame";
import { AttackingTroopsOverlay } from "./layers/AttackingTroopsOverlay";
import { AttacksDisplay } from "./layers/AttacksDisplay";
Expand Down Expand Up @@ -120,6 +121,16 @@ export function createRenderer(
eventsDisplay.game = game;
eventsDisplay.uiState = uiState;

const actionableEvents = document.querySelector(
"actionable-events",
) as ActionableEvents;
if (!(actionableEvents instanceof ActionableEvents)) {
console.error("actionable events not found");
}
actionableEvents.eventBus = eventBus;
actionableEvents.game = game;
actionableEvents.uiState = uiState;
Comment on lines +124 to +132
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 | 🟠 Major | ⚡ Quick win

Guard actionableEvents before property writes and layer insertion.

The null/type check only logs, then Line 139 still dereferences the value. If the element is missing, renderer init crashes.

Suggested fix
-  const actionableEvents = document.querySelector(
+  const actionableEvents = document.querySelector(
     "actionable-events",
-  ) as ActionableEvents;
-  if (!(actionableEvents instanceof ActionableEvents)) {
+  ) as ActionableEvents | null;
+  if (!(actionableEvents instanceof ActionableEvents)) {
     console.error("actionable events not found");
-  }
-  actionableEvents.eventBus = eventBus;
-  actionableEvents.game = game;
-  actionableEvents.uiState = uiState;
+  } else {
+    actionableEvents.eventBus = eventBus;
+    actionableEvents.game = game;
+    actionableEvents.uiState = uiState;
+  }
@@
-    actionableEvents,
+    ...(actionableEvents instanceof ActionableEvents
+      ? [actionableEvents]
+      : []),

Also applies to: 304-305

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/client/graphics/GameRenderer.ts` around lines 133 - 141, The code
currently logs if document.querySelector("actionable-events") is not an instance
of ActionableEvents but then continues to dereference actionableEvents (setting
actionableEvents.eventBus, .game, .uiState and later inserting layers), causing
a crash if missing; update the guard around actionableEvents in GameRenderer
(the variable actionableEvents and type ActionableEvents) to perform an early
return or throw after the console.error so no property writes or layer insertion
run when actionableEvents is falsy/incorrect, and apply the same guarded pattern
to the other occurrence around lines where layer insertion happens (the second
actionableEvents usage) to ensure eventBus, game and uiState are only assigned
when actionableEvents is a valid ActionableEvents instance.


const attacksDisplay = document.querySelector(
"attacks-display",
) as AttacksDisplay;
Expand Down Expand Up @@ -265,6 +276,7 @@ export function createRenderer(
new HoverHighlightController(game, eventBus, transformHandler, view),
new AttackingTroopsOverlay(game, transformHandler, eventBus, userSettings),
eventsDisplay,
actionableEvents,
attacksDisplay,
chatDisplay,
buildMenu,
Expand Down
325 changes: 325 additions & 0 deletions src/client/hud/layers/ActionableEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,325 @@
import { html, LitElement } from "lit";
import { customElement, state } from "lit/decorators.js";
import { EventBus } from "../../../core/EventBus";
import { MessageType, Tick } from "../../../core/game/Game";
import {
AllianceExtensionUpdate,
AllianceRequestUpdate,
BrokeAllianceUpdate,
GameUpdateType,
} from "../../../core/game/GameUpdates";
import { GameView, PlayerView } from "../../../core/game/GameView";
import { PlaySoundEffectEvent } from "../../sound/Sounds";
import {
SendAllianceExtensionIntentEvent,
SendAllianceRejectIntentEvent,
SendAllianceRequestIntentEvent,
} from "../../Transport";
import { getMessageTypeClasses, translateText } from "../../Utils";
import { Controller } from "../../Controller";
import { GoToPlayerEvent } from "../../TransformHandler";
import { UIState } from "../../UIState";

interface ActionableEvent {
description: string;
type: MessageType;
createdAt: number;
focusID: number;
buttons: {
text: string;
className: string;
action: () => void;
preventClose?: boolean;
}[];
priority?: number;
allianceID?: number;
duration?: Tick;
}

@customElement("actionable-events")
export class ActionableEvents extends LitElement implements Controller {
public eventBus: EventBus;
public game: GameView;
public uiState: UIState;

private active = false;
private events: ActionableEvent[] = [];
// allianceID -> last checked at tick
private alliancesCheckedAt = new Map<number, Tick>();
@state() private _isVisible = false;

private updateMap = [
[GameUpdateType.AllianceRequest, this.onAllianceRequestEvent.bind(this)],
[GameUpdateType.BrokeAlliance, this.onBrokeAllianceEvent.bind(this)],
[
GameUpdateType.AllianceExtension,
this.onAllianceExtensionEvent.bind(this),
],
] as const;

createRenderRoot() {
return this;
}

private addEvent(event: ActionableEvent) {
this.events = [...this.events, event];
this.requestUpdate();
}

private removeEvent(index: number) {
this.events = [
...this.events.slice(0, index),
...this.events.slice(index + 1),
];
}

private removeAllianceRenewalEvents(allianceID: number) {
this.events = this.events.filter(
(event) =>
!(
event.type === MessageType.RENEW_ALLIANCE &&
event.allianceID === allianceID
),
);
}

tick() {
this.active = true;

if (!this._isVisible && !this.game.inSpawnPhase()) {
this._isVisible = true;
this.requestUpdate();
}

const myPlayer = this.game.myPlayer();
if (!myPlayer || !myPlayer.isAlive()) {
if (this._isVisible) {
this._isVisible = false;
this.requestUpdate();
}
return;
}

this.checkForAllianceExpirations();

const updates = this.game.updatesSinceLastTick();
if (updates) {
for (const [ut, fn] of this.updateMap) {
updates[ut]?.forEach(fn as (event: unknown) => void);
}
}

const remainingEvents = this.events.filter(
(event) =>
event.duration === undefined ||
this.game.ticks() - event.createdAt < event.duration,
);

if (this.events.length !== remainingEvents.length) {
this.events = remainingEvents;
this.requestUpdate();
}
}

private checkForAllianceExpirations() {
const myPlayer = this.game.myPlayer();
if (!myPlayer?.isAlive()) return;

const currentAllianceIds = new Set<number>();

for (const alliance of myPlayer.alliances()) {
currentAllianceIds.add(alliance.id);

if (
alliance.expiresAt >
this.game.ticks() + this.game.config().allianceExtensionPromptOffset()
) {
continue;
}

if (
(this.alliancesCheckedAt.get(alliance.id) ?? 0) >=
this.game.ticks() - this.game.config().allianceExtensionPromptOffset()
) {
// Already prompted for this alliance in the current window.
continue;
}

this.alliancesCheckedAt.set(alliance.id, this.game.ticks());

const other = this.game.player(alliance.other) as PlayerView;

this.addEvent({
description: translateText("events_display.about_to_expire", {
name: other.displayName(),
}),
type: MessageType.RENEW_ALLIANCE,
buttons: [
{
text: translateText("events_display.focus"),
className: "btn-gray",
action: () => this.eventBus.emit(new GoToPlayerEvent(other)),
preventClose: true,
},
{
text: translateText("events_display.renew_alliance", {
name: other.displayName(),
}),
className: "btn",
action: () =>
this.eventBus.emit(new SendAllianceExtensionIntentEvent(other)),
},
{
text: translateText("events_display.ignore"),
className: "btn-info",
action: () => {},
},
],
createdAt: this.game.ticks(),
focusID: other.smallID(),
allianceID: alliance.id,
});
}

for (const [allianceId] of this.alliancesCheckedAt) {
if (!currentAllianceIds.has(allianceId)) {
this.removeAllianceRenewalEvents(allianceId);
this.alliancesCheckedAt.delete(allianceId);
}
Comment on lines +184 to +188
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 | 🟠 Major | ⚡ Quick win

Trigger a re-render when stale alliance prompts are removed.

At Line 186, cleanup can remove entries from this.events, but this path does not call requestUpdate(). A removed renewal prompt can stay visible until another unrelated update occurs.

Proposed fix
   for (const [allianceId] of this.alliancesCheckedAt) {
     if (!currentAllianceIds.has(allianceId)) {
+      const before = this.events.length;
       this.removeAllianceRenewalEvents(allianceId);
+      if (this.events.length !== before) {
+        this.requestUpdate();
+      }
       this.alliancesCheckedAt.delete(allianceId);
     }
   }

Also applies to: 76-84

🧰 Tools
🪛 GitHub Actions: 🧪 CI / 🎨 Prettier

[warning] Prettier reported formatting issues in this file.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/client/hud/layers/ActionableEvents.ts` around lines 184 - 188, The loop
that cleans stale alliances (iterating this.alliancesCheckedAt and calling
removeAllianceRenewalEvents(allianceId)) doesn't call requestUpdate(), so
removed renewal prompts remain visible until another update; update the cleanup
paths (the loop at the top of ActionableEvents and the similar code around lines
76-84) to call this.requestUpdate() after deletions (or call requestUpdate()
inside removeAllianceRenewalEvents when it actually mutates this.events) so the
component re-renders immediately when alliance renewal events are removed.

}
}

onAllianceRequestEvent(update: AllianceRequestUpdate) {
const myPlayer = this.game.myPlayer();
if (!myPlayer || update.recipientID !== myPlayer.smallID()) {
return;
}

const requestor = this.game.playerBySmallID(
update.requestorID,
) as PlayerView;
const recipient = this.game.playerBySmallID(
update.recipientID,
) as PlayerView;

if (!requestor.isAlliedWith(recipient)) {
this.eventBus.emit(new PlaySoundEffectEvent("alliance-suggested"));
}
this.addEvent({
description: translateText("events_display.request_alliance", {
name: requestor.displayName(),
}),
buttons: [
{
text: translateText("events_display.focus"),
className: "btn-gray",
action: () => this.eventBus.emit(new GoToPlayerEvent(requestor)),
preventClose: true,
},
{
text: translateText("events_display.accept_alliance"),
className: "btn",
action: () =>
this.eventBus.emit(
new SendAllianceRequestIntentEvent(recipient, requestor),
),
},
{
text: translateText("events_display.reject_alliance"),
className: "btn-info",
action: () =>
this.eventBus.emit(new SendAllianceRejectIntentEvent(requestor)),
},
],
type: MessageType.ALLIANCE_REQUEST,
createdAt: this.game.ticks(),
priority: 0,
duration: this.game.config().allianceRequestDuration(),
focusID: update.requestorID,
});
}

onBrokeAllianceEvent(update: BrokeAllianceUpdate) {
// Cleanup-only: any open renewal prompt for this alliance is now moot.
this.removeAllianceRenewalEvents(update.allianceID);
this.alliancesCheckedAt.delete(update.allianceID);
this.requestUpdate();
}

private onAllianceExtensionEvent(update: AllianceExtensionUpdate) {
const myPlayer = this.game.myPlayer();
if (!myPlayer || myPlayer.smallID() !== update.playerID) return;
this.removeAllianceRenewalEvents(update.allianceID);
this.requestUpdate();
}

private emitGoToPlayerEvent(focusID: number) {
const target = this.game.playerBySmallID(focusID) as PlayerView;
if (!target) return;
this.eventBus.emit(new GoToPlayerEvent(target));
}

render() {
if (!this.active || !this._isVisible || this.events.length === 0) {
return html``;
}

const sorted = [...this.events].sort((a, b) => {
const aPrior = a.priority ?? 100000;
const bPrior = b.priority ?? 100000;
if (aPrior === bPrior) {
return a.createdAt - b.createdAt;
}
return bPrior - aPrior;
});

return html`
<div
class="flex flex-col gap-2 w-full min-[1200px]:w-96 pointer-events-auto mt-2"
>
${sorted.map(
(event) => html`
<div
class="bg-gray-800/92 backdrop-blur-sm rounded-lg shadow-lg border-l-4 border-yellow-400 p-3 lg:p-4 text-white"
>
<button
class="text-left text-sm lg:text-base font-semibold w-full cursor-pointer ${getMessageTypeClasses(
event.type,
)}"
@click=${() => this.emitGoToPlayerEvent(event.focusID)}
>
${event.description}
</button>
<div class="flex flex-wrap gap-1.5 mt-2">
${event.buttons.map(
(btn) => html`
<button
class="inline-block px-3 py-1 text-white rounded-sm text-xs lg:text-sm cursor-pointer transition-colors duration-300
${btn.className.includes("btn-info")
? "bg-blue-500 hover:bg-blue-600"
: btn.className.includes("btn-gray")
? "bg-gray-500 hover:bg-gray-600"
: "bg-green-600 hover:bg-green-700"}"
@click=${() => {
btn.action();
if (!btn.preventClose) {
const index = this.events.findIndex(
(e) => e === event,
);
if (index !== -1) this.removeEvent(index);
}
this.requestUpdate();
}}
>
${btn.text}
</button>
`,
)}
</div>
</div>
`,
)}
</div>
`;
}
}
Loading
Loading