Files
OpenFrontIO/src/client/LeaderboardModal.ts
T
Evan bcc453e8cf Add modal URL router (#modal=name&tab=key) (#3924)
## Description

Adds a modal URL router so modals can be opened, deep-linked, and
bookmarked via the hash. URLs of the form `#modal=<name>&tab=<key>&...`
open the named modal and pass remaining keys as args to `onOpen`. The
reverse direction also syncs: opening a modal via the UI updates the
URL, closing it clears the hash, and switching tabs updates `&tab=`.

Builds on the BaseModal refactor from #3923.

### What's new

**`ModalRouter.ts`** — small registry + two-way sync helper.
- `register(name, { tag, pageId? })` declares a modal as router-managed
- `routeFromHash()` parses `#modal=...` and dispatches to
`modal.open(args)`
- `syncOpened/syncClosed/syncTab` push state back into the URL via
`history.replaceState` (no history entries)
- A `routingFromUrl` flag prevents URL→modal→URL feedback loops
- Unknown modal names silently strip the hash

**`BaseModal`** — opt-in URL sync via a `routerName` property.
- When set, BaseModal calls into
`modalRouter.syncOpened/syncClosed/syncTab` from `open` / `close` /
`setActiveTab`
- Modals that own their own URL state (lobby modals) just leave
`routerName` undefined

**`Main.ts`** — registers all routable modals and wires the router.
- `handleUrl()`: adds a `modalRouter.routeFromHash()` branch after the
path-based lobby join
- `onHashUpdate`: when the hash is router-managed, routes via the router
instead of tearing down lobby state

### Routable modals

13 inline modals: store, settings, leaderboard, clan, account, help,
news, language, single-player, ranked, troubleshooting,
territory-patterns, flag-input.

Excluded by design: join-lobby, host-lobby (own URL state via
`/game/<id>`), matchmaking (no URL state).

### Example uses

- Deep link to store flags tab: `/#modal=store&tab=flags`
- Settings keybinds tab: `/#modal=settings&tab=keybinds`
- Cosmetics.ts now redirects to `#modal=store&tab=packs` when a
hard-currency purchase fails for insufficient plutonium (after the
alert), so users can top up directly

### URL behavior

- `replaceState` everywhere — no history entries added when modals open
/ close / switch tabs
- Browser back/forward still works for the existing path-based game flow
- `hashchange` events are router-aware so external hash changes (back
button, manual edit) correctly switch between routed modals without
tearing down lobby state

## Please complete the following:

- [x] I have added screenshots for all UI updates _(no visual changes;
smoke-tested in dev)_
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file _(no new user-visible strings)_
- [ ] I have added relevant tests to the test directory _(no test
coverage; manually tested URL load, UI open, tab switch, close,
hashchange, insufficient-plutonium redirect)_
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced

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

DISCORD_USERNAME
2026-05-14 16:49:44 -07:00

128 lines
3.8 KiB
TypeScript

import { html } from "lit";
import { customElement, query, state } from "lit/decorators.js";
import { BaseModal } from "./components/BaseModal";
import "./components/leaderboard/LeaderboardClanTable";
import type { LeaderboardClanTable } from "./components/leaderboard/LeaderboardClanTable";
import "./components/leaderboard/LeaderboardPlayerList";
import type { LeaderboardPlayerList } from "./components/leaderboard/LeaderboardPlayerList";
import { modalHeader } from "./components/ui/ModalHeader";
import { translateText } from "./Utils";
@customElement("leaderboard-modal")
export class LeaderboardModal extends BaseModal {
protected routerName = "leaderboard";
@state()
private clanDateRange: { start: string; end: string } | null = null;
@query("leaderboard-player-list")
private playerList?: LeaderboardPlayerList;
@query("leaderboard-clan-table")
private clanTable?: LeaderboardClanTable;
private loadToken = 0;
protected modalConfig() {
return {
tabs: [
{
key: "players",
label: translateText("leaderboard_modal.ranked_tab"),
},
{ key: "clans", label: translateText("leaderboard_modal.clans_tab") },
],
};
}
protected onOpen(): void {
this.loadActiveTabData();
}
protected onTabEnter(): void {
this.loadActiveTabData();
}
private loadActiveTabData() {
const token = ++this.loadToken;
const run = async () => {
if (token !== this.loadToken) return;
if (this.activeTab === "players") {
await this.playerList?.ensureLoaded();
if (token !== this.loadToken) return;
this.playerList?.handleTabActivated();
} else {
await this.clanTable?.ensureLoaded();
}
queueMicrotask(() => {
if (token !== this.loadToken) return;
if (this.activeTab === "players") void this.clanTable?.ensureLoaded();
else void this.playerList?.ensureLoaded();
});
};
void (async () => {
if (!(this.activeTab === "players" ? this.playerList : this.clanTable)) {
await this.updateComplete;
}
await run();
})();
}
private handleClanDateRangeChange(
event: CustomEvent<{ start: string; end: string }>,
) {
this.clanDateRange = event.detail;
}
protected renderHeaderSlot() {
let dateRange = html``;
if (this.clanDateRange) {
const start = new Date(this.clanDateRange.start).toLocaleDateString();
const end = new Date(this.clanDateRange.end).toLocaleDateString();
dateRange = html`<span
class="text-sm font-normal text-white/40 ml-2 wrap-break-words"
>(${start} - ${end})</span
>`;
}
const refreshTime = html`<span
class="text-sm font-normal text-white/40 ml-2 wrap-break-words italic"
>(${translateText("leaderboard_modal.refresh_time")})</span
>`;
return modalHeader({
titleContent: html`
<div class="flex flex-wrap items-center gap-2">
<span
class="text-white text-xl sm:text-2xl font-bold uppercase tracking-widest"
>
${translateText("leaderboard_modal.title")}
</span>
${this.activeTab === "clans" ? dateRange : ""}
${this.activeTab === "players" ? refreshTime : ""}
</div>
`,
onBack: () => this.close(),
ariaLabel: translateText("common.close"),
});
}
protected renderBody() {
return html`
<div class="flex-1 min-h-0 h-full">
<leaderboard-player-list
class=${this.activeTab === "players" ? "h-full" : "hidden"}
></leaderboard-player-list>
<leaderboard-clan-table
class=${this.activeTab === "clans" ? "h-full" : "hidden"}
@date-range-change=${(
event: CustomEvent<{ start: string; end: string }>,
) => this.handleClanDateRangeChange(event)}
></leaderboard-clan-table>
</div>
`;
}
}