mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-24 07:04:41 +00:00
bcc453e8cf
## 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
230 lines
6.7 KiB
TypeScript
230 lines
6.7 KiB
TypeScript
import type { TemplateResult } from "lit";
|
|
import { html } from "lit";
|
|
import { customElement, state } from "lit/decorators.js";
|
|
import { UserMeResponse } from "../core/ApiSchemas";
|
|
import { Cosmetics } from "../core/CosmeticSchemas";
|
|
import {
|
|
PATTERN_KEY,
|
|
USER_SETTINGS_CHANGED_EVENT,
|
|
UserSettings,
|
|
} from "../core/game/UserSettings";
|
|
import { PlayerPattern } from "../core/Schemas";
|
|
import { BaseModal } from "./components/BaseModal";
|
|
import "./components/CosmeticButton";
|
|
import "./components/NotLoggedInWarning";
|
|
import { modalHeader } from "./components/ui/ModalHeader";
|
|
import {
|
|
fetchCosmetics,
|
|
getPlayerCosmetics,
|
|
resolveCosmetics,
|
|
ResolvedCosmetic,
|
|
resolvedToPlayerPattern,
|
|
} from "./Cosmetics";
|
|
import { translateText } from "./Utils";
|
|
|
|
@customElement("territory-patterns-modal")
|
|
export class TerritoryPatternsModal extends BaseModal {
|
|
protected routerName = "territory-patterns";
|
|
public previewButton: HTMLElement | null = null;
|
|
|
|
@state() private selectedPattern: PlayerPattern | null;
|
|
@state() private selectedColor: string | null = null;
|
|
@state() private search = "";
|
|
|
|
private cosmetics: Cosmetics | null = null;
|
|
private userSettings: UserSettings = new UserSettings();
|
|
private userMeResponse: UserMeResponse | false = false;
|
|
|
|
private _onPatternSelected = async () => {
|
|
await this.updateFromSettings();
|
|
this.refresh();
|
|
};
|
|
|
|
connectedCallback() {
|
|
super.connectedCallback();
|
|
document.addEventListener(
|
|
"userMeResponse",
|
|
(event: CustomEvent<UserMeResponse | false>) => {
|
|
this.onUserMe(event.detail);
|
|
},
|
|
);
|
|
window.addEventListener(
|
|
`${USER_SETTINGS_CHANGED_EVENT}:${PATTERN_KEY}`,
|
|
this._onPatternSelected,
|
|
);
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
super.disconnectedCallback();
|
|
window.removeEventListener(
|
|
`${USER_SETTINGS_CHANGED_EVENT}:${PATTERN_KEY}`,
|
|
this._onPatternSelected,
|
|
);
|
|
}
|
|
|
|
private async updateFromSettings() {
|
|
const cosmetics = await getPlayerCosmetics();
|
|
this.selectedPattern = cosmetics.pattern ?? null;
|
|
this.selectedColor = cosmetics.color?.color ?? null;
|
|
}
|
|
|
|
async onUserMe(userMeResponse: UserMeResponse | false) {
|
|
this.userMeResponse = userMeResponse;
|
|
this.cosmetics = await fetchCosmetics();
|
|
await this.updateFromSettings();
|
|
this.refresh();
|
|
}
|
|
|
|
private includedInSearch(name: string): boolean {
|
|
const displayName = name.replace(/_/g, " ");
|
|
return displayName.toLowerCase().includes(this.search.toLowerCase());
|
|
}
|
|
|
|
private handleSearch(event: Event) {
|
|
this.search = (event.target as HTMLInputElement).value;
|
|
}
|
|
|
|
private renderPatternGrid(): TemplateResult {
|
|
const items = resolveCosmetics(
|
|
this.cosmetics,
|
|
this.userMeResponse,
|
|
null,
|
|
).filter(
|
|
(r) =>
|
|
r.type === "pattern" &&
|
|
r.relationship === "owned" &&
|
|
(r.cosmetic === null
|
|
? !this.search
|
|
: this.includedInSearch(r.cosmetic.name)),
|
|
);
|
|
|
|
return html`
|
|
<div class="flex flex-col">
|
|
<div
|
|
class="flex flex-wrap gap-4 p-8 justify-center items-stretch content-start"
|
|
>
|
|
${items.map((r) => {
|
|
const isSelected =
|
|
(r.cosmetic === null && this.selectedPattern === null) ||
|
|
(r.cosmetic !== null &&
|
|
this.selectedPattern?.name === r.cosmetic.name &&
|
|
(this.selectedPattern?.colorPalette?.name ?? null) ===
|
|
(r.colorPalette?.name ?? null));
|
|
return html`
|
|
<cosmetic-button
|
|
.resolved=${r}
|
|
.selected=${isSelected}
|
|
.onSelect=${(rc: ResolvedCosmetic) => this.selectCosmetic(rc)}
|
|
></cosmetic-button>
|
|
`;
|
|
})}
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
protected renderHeaderSlot() {
|
|
return html`
|
|
<div
|
|
class="relative flex flex-col border-b border-white/10 pb-4 shrink-0"
|
|
>
|
|
${modalHeader({
|
|
title: translateText("territory_patterns.title"),
|
|
onBack: () => this.close(),
|
|
ariaLabel: translateText("common.back"),
|
|
rightContent: html`<not-logged-in-warning></not-logged-in-warning>`,
|
|
})}
|
|
|
|
<div class="md:flex items-center gap-2 justify-center mt-4">
|
|
<input
|
|
class="h-12 w-full max-w-md border border-white/10 bg-black/60
|
|
rounded-xl shadow-inner text-xl text-center focus:outline-none
|
|
focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 text-white placeholder-white/30 transition-all"
|
|
type="text"
|
|
placeholder=${translateText("territory_patterns.search")}
|
|
.value=${this.search}
|
|
@change=${this.handleSearch}
|
|
@keyup=${this.handleSearch}
|
|
/>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
protected renderBody() {
|
|
return html`
|
|
<div class="flex justify-center py-3 shrink-0">
|
|
<o-button
|
|
class="no-crazygames"
|
|
variant="primary"
|
|
size="sm"
|
|
translationKey="main.store"
|
|
@click=${() => {
|
|
this.close();
|
|
window.showPage?.("page-item-store");
|
|
}}
|
|
></o-button>
|
|
</div>
|
|
<div class="px-3 pb-3">${this.renderPatternGrid()}</div>
|
|
`;
|
|
}
|
|
|
|
protected async onOpen(): Promise<void> {
|
|
await this.refresh();
|
|
}
|
|
|
|
protected onClose(): void {
|
|
this.search = "";
|
|
}
|
|
|
|
private selectCosmetic(resolved: ResolvedCosmetic) {
|
|
if (resolved.type !== "pattern") return;
|
|
this.selectPattern(resolvedToPlayerPattern(resolved));
|
|
}
|
|
|
|
private selectPattern(pattern: PlayerPattern | null) {
|
|
this.selectedColor = null;
|
|
if (pattern === null) {
|
|
this.userSettings.setSelectedPatternName(undefined);
|
|
} else {
|
|
const name =
|
|
pattern.colorPalette?.name === undefined
|
|
? pattern.name
|
|
: `${pattern.name}:${pattern.colorPalette.name}`;
|
|
this.userSettings.setSelectedPatternName(`pattern:${name}`);
|
|
}
|
|
this.selectedPattern = pattern;
|
|
this.refresh();
|
|
this.showSkinSelectedPopup();
|
|
this.close();
|
|
}
|
|
|
|
private showSkinSelectedPopup() {
|
|
let skinName = translateText("territory_patterns.pattern.default");
|
|
if (this.selectedPattern && this.selectedPattern.name) {
|
|
skinName = this.selectedPattern.name
|
|
.split("_")
|
|
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
.join(" ");
|
|
if (
|
|
this.selectedPattern.colorPalette &&
|
|
this.selectedPattern.colorPalette.name
|
|
) {
|
|
skinName += ` (${this.selectedPattern.colorPalette.name})`;
|
|
}
|
|
}
|
|
window.dispatchEvent(
|
|
new CustomEvent("show-message", {
|
|
detail: {
|
|
message: `${skinName} ${translateText("territory_patterns.selected")}`,
|
|
duration: 2000,
|
|
},
|
|
}),
|
|
);
|
|
}
|
|
|
|
public async refresh() {
|
|
this.requestUpdate();
|
|
}
|
|
}
|