mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-21 10:32:41 +00:00
df05d21fc2
## Description: Continuation from #3276 Adds the complete client-side clan UI as a Lit web component (`<clan-modal>`), a typed API client with Zod-validated responses, shared response schemas, and a reusable `<confirm-dialog>` component. ### New: `ClanModal.ts` | View | What it does | |------|-------------| | **My Clans** | Lists joined clans + pending join requests (built from `/users/@me`, no extra fetches) | | **Browse** | Search by tag (min 3 chars), paginated results, configurable per-page (10/25/50) | | **Clan Detail** | Stats, paginated + searchable member list, role badges, join/leave/request actions | | **Manage** | Edit name (max 35 chars) + description, toggle open/invite-only, disband | | **Transfer** | Leadership transfer with member selector + confirmation | | **Requests** | Approve/deny join requests (leader/officer) | | **Bans** | View and unban (leader/officer) | | **My Requests** | View and withdraw outgoing requests | ### New: `ConfirmDialog.ts` Reusable `<confirm-dialog>` Lit component — replaces native `confirm()`/`prompt()` which are blocked or broken on mobile and CrazyGames iframes. Supports danger/warning variants and an optional textarea (used for ban reasons). Fires `confirm`/`cancel` events. ### New: `ClanApi.ts` Typed API client covering all clan endpoints. Every response is Zod-validated. Auth header is always last in the spread (can't be overridden by callers). Unknown server error messages always fall back to a generic client-side string — never displayed verbatim. ### New: `ClanApiSchemas.ts` (in `src/core/`) Shared Zod schemas for clan API responses with max-length constraints on `name` (35) and `description` (200). Lives in `core/` so it can be consumed by both client code and the leaderboard table. ### Modified: `ApiSchemas.ts` - Added `clans` and `clanRequests` arrays to `UserMeResponseSchema` - Moved clan leaderboard schemas out to `ClanApiSchemas.ts` - Renamed `LeaderboardClanTagSchema` → `RequiredClanTagSchema` ### Modified: `Api.ts` - Added `invalidateUserMe()` to bust the cached `/users/me` response after mutations - Removed `fetchClanLeaderboard` (moved to `ClanApi.ts`) ### Tests - `ClanModal.test.ts` — rendering, view navigation, user actions - `ClanApiQueries.test.ts` — fetch functions, error handling, pagination - `ClanApiMutations.test.ts` — join, leave, kick, ban, promote, transfer, etc. - `ClanApiBans.test.ts` — ban/unban calls and error paths - `ClanApiSchemas.test.ts` — Zod schema validation edge cases - `LeaderboardModal.test.ts` — updated imports ## Notable design decisions - **Not-logged-in state** — shows "Sign in to join clans" instead of false "no clans" empty state - **Rate limit feedback** — reads `Retry-After` header and surfaces wait time to the user ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory - [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: w.o.n --------- Co-authored-by: evanpelle <evanpelle@gmail.com>
167 lines
4.9 KiB
TypeScript
167 lines
4.9 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
vi.mock("../../../src/client/Api", () => ({
|
|
getApiBase: vi.fn(() => "http://localhost:3000"),
|
|
}));
|
|
|
|
vi.mock("../../../src/client/Auth", () => ({
|
|
getAuthHeader: vi.fn(async () => "Bearer test-token"),
|
|
}));
|
|
|
|
import {
|
|
banClanMember,
|
|
fetchClanBans,
|
|
unbanClanMember,
|
|
} from "../../../src/client/ClanApi";
|
|
|
|
const okJson = (data: unknown, status = 200) => ({
|
|
ok: true,
|
|
status,
|
|
json: async () => data,
|
|
});
|
|
|
|
const failRes = (status: number, data: unknown = {}) => ({
|
|
ok: false,
|
|
status,
|
|
json: async () => data,
|
|
});
|
|
|
|
const mockFetch = (impl: (...args: unknown[]) => unknown) =>
|
|
vi.stubGlobal("fetch", vi.fn(impl));
|
|
|
|
beforeEach(() => {
|
|
vi.unstubAllGlobals();
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
describe("banClanMember", () => {
|
|
it("returns true on 204 success", async () => {
|
|
mockFetch(() => ({ ok: true, status: 204, json: async () => ({}) }));
|
|
const result = await banClanMember("TEST", "player-1");
|
|
expect(result).toBe(true);
|
|
});
|
|
|
|
it("sends reason in request body when provided", async () => {
|
|
const fetchSpy = vi.fn(
|
|
(_input: string | URL | Request, _init?: RequestInit) =>
|
|
Promise.resolve({ ok: true, status: 204, json: async () => ({}) }),
|
|
);
|
|
vi.stubGlobal("fetch", fetchSpy);
|
|
|
|
await banClanMember("TEST", "player-1", "spamming");
|
|
|
|
const body = JSON.parse(fetchSpy.mock.calls[0]![1]?.body as string);
|
|
expect(body).toEqual({ targetPublicId: "player-1", reason: "spamming" });
|
|
});
|
|
|
|
it("omits reason from request body when not provided", async () => {
|
|
const fetchSpy = vi.fn(
|
|
(_input: string | URL | Request, _init?: RequestInit) =>
|
|
Promise.resolve({ ok: true, status: 204, json: async () => ({}) }),
|
|
);
|
|
vi.stubGlobal("fetch", fetchSpy);
|
|
|
|
await banClanMember("TEST", "player-1");
|
|
|
|
const body = JSON.parse(fetchSpy.mock.calls[0]![1]?.body as string);
|
|
expect(body).toEqual({ targetPublicId: "player-1" });
|
|
expect(body).not.toHaveProperty("reason");
|
|
});
|
|
|
|
it("returns error object on failure", async () => {
|
|
mockFetch(() => failRes(403, { message: "insufficient permissions" }));
|
|
const result = await banClanMember("TEST", "player-1");
|
|
expect(result).toEqual({ error: "clan_modal.error_failed" });
|
|
});
|
|
|
|
it("returns network error on fetch failure", async () => {
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn(() => Promise.reject(new Error("offline"))),
|
|
);
|
|
const result = await banClanMember("TEST", "player-1");
|
|
expect(result).toEqual({ error: "clan_modal.error_network" });
|
|
});
|
|
});
|
|
|
|
describe("unbanClanMember", () => {
|
|
it("returns true on success", async () => {
|
|
mockFetch(() => ({ ok: true, status: 204, json: async () => ({}) }));
|
|
const result = await unbanClanMember("TEST", "player-1");
|
|
expect(result).toBe(true);
|
|
});
|
|
|
|
it("returns error object on failure", async () => {
|
|
mockFetch(() => failRes(409, { message: "Player not currently banned" }));
|
|
const result = await unbanClanMember("TEST", "player-1");
|
|
expect(result).toEqual({ error: "clan_modal.error_failed" });
|
|
});
|
|
|
|
it("returns network error on fetch failure", async () => {
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn(() => Promise.reject(new Error("offline"))),
|
|
);
|
|
const result = await unbanClanMember("TEST", "player-1");
|
|
expect(result).toEqual({ error: "clan_modal.error_network" });
|
|
});
|
|
});
|
|
|
|
describe("fetchClanBans", () => {
|
|
const bansResponse = {
|
|
results: [
|
|
{
|
|
publicId: "banned-1",
|
|
bannedBy: "officer-1",
|
|
reason: "toxic",
|
|
createdAt: "2024-06-01T00:00:00.000Z",
|
|
},
|
|
],
|
|
total: 1,
|
|
page: 1,
|
|
limit: 20,
|
|
};
|
|
|
|
it("returns parsed data on success", async () => {
|
|
mockFetch(() => okJson(bansResponse));
|
|
const result = await fetchClanBans("TEST");
|
|
expect(result).toEqual(bansResponse);
|
|
});
|
|
|
|
it("passes page and limit as query params", async () => {
|
|
const fetchSpy = vi.fn(
|
|
(_input: string | URL | Request, _init?: RequestInit) =>
|
|
Promise.resolve(okJson(bansResponse)),
|
|
);
|
|
vi.stubGlobal("fetch", fetchSpy);
|
|
|
|
await fetchClanBans("TEST", 2, 10);
|
|
|
|
const calledUrl = fetchSpy.mock.calls[0]![0] as string;
|
|
const url = new URL(calledUrl);
|
|
expect(url.searchParams.get("page")).toBe("2");
|
|
expect(url.searchParams.get("limit")).toBe("10");
|
|
});
|
|
|
|
it("returns false on non-ok response", async () => {
|
|
mockFetch(() => failRes(403));
|
|
const result = await fetchClanBans("TEST");
|
|
expect(result).toBe(false);
|
|
});
|
|
|
|
it("returns false when Zod validation fails", async () => {
|
|
mockFetch(() => okJson({ results: "not-an-array", total: 0 }));
|
|
const result = await fetchClanBans("TEST");
|
|
expect(result).toBe(false);
|
|
});
|
|
|
|
it("returns false on network error", async () => {
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn(() => Promise.reject(new Error("offline"))),
|
|
);
|
|
const result = await fetchClanBans("TEST");
|
|
expect(result).toBe(false);
|
|
});
|
|
});
|