feat(admin): streamline group management
CI / validate (push) Successful in 4m16s
Release / release (push) Failing after 9m14s

This commit is contained in:
dmg
2026-08-02 11:06:55 -04:00
parent 71856bb869
commit d4afb71798
24 changed files with 1588 additions and 379 deletions
@@ -0,0 +1,59 @@
// @vitest-environment jsdom
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AdminModalForm } from "./admin-modal-form";
beforeEach(() => {
HTMLDialogElement.prototype.showModal = function showModal() { this.open = true; };
HTMLDialogElement.prototype.close = function close() {
this.open = false;
this.dispatchEvent(new Event("close"));
};
});
describe("AdminModalForm", () => {
it("renders an accessible trigger, labelled dialog, cancellation, and pending-capable submit control", () => {
const markup = renderToStaticMarkup(
<AdminModalForm
action={async () => undefined}
description="Review this policy change before applying it."
submitLabel="Apply policy"
title="Change access policy"
triggerLabel="Change"
>
<input name="groupId" type="hidden" value="group-one" />
</AdminModalForm>,
);
expect(markup).toContain("Change access policy");
expect(markup).toContain("Review this policy change before applying it.");
expect(markup).toContain("<dialog");
expect(markup).toContain("aria-haspopup=\"dialog\"");
expect(markup).toContain("Cancel");
expect(markup).toContain("Apply policy");
});
it("opens, cancels, and prevents dismissal while the action is pending", async () => {
let finishAction!: () => void;
const action = vi.fn(() => new Promise<void>((resolve) => { finishAction = resolve; }));
render(<AdminModalForm action={action} description="Confirm it." submitLabel="Apply policy" title="Change access policy" triggerLabel="Change" />);
fireEvent.click(screen.getByRole("button", { name: "Change" }));
const dialog = screen.getByRole("dialog") as HTMLDialogElement;
expect(dialog.open).toBe(true);
fireEvent.click(screen.getByRole("button", { name: "Apply policy" }));
await waitFor(() => expect(action).toHaveBeenCalledOnce());
expect((screen.getByRole("button", { name: "Change" }) as HTMLButtonElement).disabled).toBe(true);
const cancelEvent = new Event("cancel", { bubbles: false, cancelable: true });
dialog.dispatchEvent(cancelEvent);
expect(cancelEvent.defaultPrevented).toBe(true);
expect(dialog.open).toBe(true);
finishAction();
await waitFor(() => expect((screen.getByRole("button", { name: "Change" }) as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(dialog.open).toBe(false);
});
});
@@ -0,0 +1,105 @@
"use client";
import type { ReactNode, RefObject } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { useFormStatus } from "react-dom";
export function AdminModalForm({
action,
children,
description,
intent = "default",
submitLabel,
title,
triggerClassName,
triggerLabel,
triggerPressed,
}: {
action: (formData: FormData) => Promise<void>;
children?: ReactNode;
description: string;
intent?: "default" | "danger";
submitLabel: string;
title: string;
triggerClassName?: string;
triggerLabel: string;
triggerPressed?: boolean;
}) {
const dialogRef = useRef<HTMLDialogElement>(null);
const titleId = useId();
const descriptionId = useId();
const [submitting, setSubmitting] = useState(false);
return (
<>
<button
aria-haspopup="dialog"
aria-pressed={triggerPressed}
className={triggerClassName ?? "font-mono text-[10px] font-bold uppercase underline underline-offset-4"}
disabled={submitting}
onClick={() => dialogRef.current?.showModal()}
type="button"
>
{triggerLabel}
</button>
<dialog
aria-describedby={descriptionId}
aria-labelledby={titleId}
className="admin-modal m-auto w-[min(92vw,36rem)] border border-ink bg-panel p-0 text-ink shadow-[10px_10px_0_var(--color-shadow)] backdrop:bg-ink/70"
onCancel={(event) => { if (submitting) event.preventDefault(); }}
ref={dialogRef}
>
<form action={action} className="p-6 sm:p-8" onSubmit={() => setSubmitting(true)}>
<p className="font-mono text-[9px] font-bold uppercase tracking-[0.2em] text-accent">Confirm operation</p>
<h2 className="mt-3 font-display text-3xl font-black uppercase" id={titleId}>{title}</h2>
<p className="mt-3 text-sm leading-6 text-muted" id={descriptionId}>{description}</p>
{children && <div className="mt-6">{children}</div>}
<ModalActions dialogRef={dialogRef} intent={intent} onPendingChange={setSubmitting} submitLabel={submitLabel} />
</form>
</dialog>
</>
);
}
function ModalActions({
dialogRef,
intent,
onPendingChange,
submitLabel,
}: {
dialogRef: RefObject<HTMLDialogElement | null>;
intent: "default" | "danger";
onPendingChange: (pending: boolean) => void;
submitLabel: string;
}) {
const { pending } = useFormStatus();
const observedPending = useRef(false);
useEffect(() => {
if (pending) {
observedPending.current = true;
onPendingChange(true);
} else if (observedPending.current) {
observedPending.current = false;
onPendingChange(false);
}
}, [onPendingChange, pending]);
return (
<div className="mt-8 flex flex-wrap justify-end gap-3 border-t border-line pt-5">
<button
className="border border-line px-5 py-3 font-mono text-[10px] font-bold uppercase tracking-wider disabled:opacity-50"
disabled={pending}
onClick={() => dialogRef.current?.close()}
type="button"
>
Cancel
</button>
<button
className={`px-5 py-3 font-mono text-[10px] font-bold uppercase tracking-wider text-canvas disabled:cursor-wait disabled:opacity-60 ${intent === "danger" ? "bg-accent" : "bg-ink"}`}
disabled={pending}
type="submit"
>
{pending ? "Applying…" : submitLabel}
</button>
<span aria-live="polite" className="sr-only">{pending ? "Operation in progress." : ""}</span>
</div>
);
}
@@ -0,0 +1,30 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { AdminUserTable } from "./admin-user-table";
describe("AdminUserTable", () => {
it("renders reusable identity and confirmed group controls", () => {
const markup = renderToStaticMarkup(<AdminUserTable
action={async () => undefined}
assignmentByUser={{ user1: "ops" }}
emptyMessage="No members."
groups={[{ id: "everyone", name: "everyone", isDefault: true }, { id: "ops", name: "Ops", isDefault: false }]}
returnTo="/admin/groups/11111111-1111-4111-8111-111111111111"
users={[{
id: "user1",
firstName: "Alex",
discordUsername: "alex",
discordGlobalName: "Alex Global",
discordUserId: "123",
onboardingCompletedAt: new Date("2026-08-01T00:00:00Z"),
primaryUsername: "AlexMC",
accountCount: 2,
}]}
/>);
expect(markup).toContain("Alex Global");
expect(markup).toContain("AlexMC");
expect(markup).toContain("Accounts");
expect(markup).toContain("Group for Alex");
expect(markup).toContain("Confirm move");
});
});
@@ -0,0 +1,54 @@
import Link from "next/link";
import { UserGroupSelect } from "./user-group-select";
export interface AdminUserRow {
id: string;
firstName: string | null;
discordUsername: string;
discordGlobalName: string | null;
discordUserId: string;
onboardingCompletedAt: Date | null;
primaryUsername: string | null;
accountCount: number;
}
export function AdminUserTable({
action,
assignmentByUser,
emptyMessage,
groups,
returnTo,
users,
}: {
action: (formData: FormData) => Promise<void>;
assignmentByUser: Record<string, string>;
emptyMessage: string;
groups: Array<{ id: string; name: string; isDefault: boolean }>;
returnTo: string;
users: AdminUserRow[];
}) {
const defaultGroup = groups.find((group) => group.isDefault);
return (
<div className="overflow-x-auto border border-line bg-panel shadow-[8px_8px_0_var(--color-shadow)]">
<table className="w-full min-w-[900px] border-collapse text-left">
<caption className="sr-only">Registered portal users and effective groups</caption>
<thead className="border-b border-line font-mono text-[10px] uppercase tracking-widest text-muted">
<tr><th className="p-4" scope="col">User</th><th className="p-4" scope="col">Discord</th><th className="p-4" scope="col">Primary</th><th className="p-4" scope="col">Accounts</th><th className="p-4" scope="col">Group</th><th className="p-4" scope="col">Status</th></tr>
</thead>
<tbody className="divide-y divide-line">
{users.map((user) => (
<tr className="transition-colors hover:bg-canvas/60" key={user.id}>
<th className="p-4 text-left" scope="row"><Link className="font-display text-lg font-black underline decoration-line underline-offset-4 hover:text-accent" href={`/admin/users/${user.id}`}>{user.firstName ?? "Name needed"}</Link></th>
<td className="p-4"><div className="font-mono text-xs font-bold">{user.discordGlobalName ?? user.discordUsername}</div><div className="mt-1 font-mono text-[10px] text-muted">@{user.discordUsername}</div><div className="mt-1 font-mono text-[9px] text-muted">{user.discordUserId}</div></td>
<td className="p-4 font-mono text-xs">{user.primaryUsername ?? "—"}</td>
<td className="p-4 font-mono text-xs">{user.accountCount}</td>
<td className="p-4">{defaultGroup ? <UserGroupSelect action={action} effectiveGroupId={assignmentByUser[user.id] ?? defaultGroup.id} groups={groups} returnTo={returnTo} userId={user.id} userLabel={user.firstName ?? user.discordUsername} /> : <span className="text-xs text-accent">Default group missing</span>}</td>
<td className="p-4"><span className={`border px-2 py-1 font-mono text-[9px] uppercase tracking-wider ${user.onboardingCompletedAt ? "border-line text-muted" : "border-accent text-accent"}`}>{user.onboardingCompletedAt ? "Ready" : "Onboarding"}</span></td>
</tr>
))}
{!users.length && <tr><td className="p-8 text-muted" colSpan={6}>{emptyMessage}</td></tr>}
</tbody>
</table>
</div>
);
}
@@ -0,0 +1,36 @@
import { AdminModalForm } from "./admin-modal-form";
export function GroupPolicyControl({
action,
enabled,
groupId,
groupName,
memberCount,
policy,
returnLocation,
}: {
action: (formData: FormData) => Promise<void>;
enabled: boolean;
groupId: string;
groupName: string;
memberCount: number;
policy: string;
returnLocation: "list" | "detail";
}) {
const nextState = enabled ? "deny" : "allow";
return (
<AdminModalForm
action={action}
description={`${nextState === "allow" ? "Allow" : "Deny"} ${policy.toLowerCase()} for ${memberCount} effective ${memberCount === 1 ? "member" : "members"} of ${groupName}.`}
submitLabel={`${nextState === "allow" ? "Allow" : "Deny"} access`}
title={`${nextState === "allow" ? "Allow" : "Deny"} ${policy}?`}
triggerClassName={`min-w-24 border px-3 py-2 font-mono text-[9px] font-bold uppercase tracking-wider ${enabled ? "border-signal bg-signal text-ink" : "border-accent bg-transparent text-accent"}`}
triggerLabel={enabled ? "Allowed" : "Denied"}
triggerPressed={enabled}
>
<input name="groupId" type="hidden" value={groupId} />
<input name="enabled" type="hidden" value={enabled ? "no" : "yes"} />
<input name="returnLocation" type="hidden" value={returnLocation} />
</AdminModalForm>
);
}
@@ -1,21 +1,53 @@
// @vitest-environment jsdom
import { fireEvent, render, screen } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it } from "vitest";
import { UserGroupSelect } from "./user-group-select";
const groups = [{ id: "group-everyone", name: "everyone" }, { id: "group-ops", name: "Ops" }];
beforeEach(() => {
HTMLDialogElement.prototype.showModal = function showModal() { this.open = true; };
HTMLDialogElement.prototype.close = function close() {
this.open = false;
this.dispatchEvent(new Event("close"));
};
});
describe("UserGroupSelect", () => {
it("renders the effective group and preserves the active search", () => {
it("renders the effective group and preserves the return path", () => {
const markup = renderToStaticMarkup(<UserGroupSelect
action={async () => undefined}
effectiveGroupId="group-ops"
groups={[{ id: "group-everyone", name: "everyone" }, { id: "group-ops", name: "Ops" }]}
search="alex smith"
groups={groups}
returnTo="/admin/users?q=alex%20smith"
userId="user-one"
userLabel="Alex"
/>);
expect(markup).toContain('aria-label="Group for Alex"');
expect(markup).toContain('<option value="group-ops" selected="">Ops</option>');
expect(markup).toContain('<input type="hidden" name="search" value="alex smith"/>');
expect(markup).toContain("Apply group");
expect(markup).toContain('<input type="hidden" name="returnTo" value="/admin/users?q=alex%20smith"/>');
expect(markup).toContain("Changing this selection opens a confirmation dialog.");
expect(markup).toContain("Confirm move");
});
it("requires confirmation and restores the effective group when cancelled", () => {
render(<UserGroupSelect action={async () => undefined} effectiveGroupId="group-ops" groups={groups} returnTo="/admin/users" userId="user-one" userLabel="Alex" />);
const select = screen.getByRole("combobox", { name: "Group for Alex" }) as HTMLSelectElement;
fireEvent.change(select, { target: { value: "group-everyone" } });
const dialog = screen.getByRole("dialog") as HTMLDialogElement;
expect(dialog.open).toBe(true);
expect(select.value).toBe("group-everyone");
expect(select.disabled).toBe(true);
expect(screen.getByText(/from/).textContent).toContain("Ops");
expect(screen.getByText(/from/).textContent).toContain("everyone");
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(dialog.open).toBe(false);
expect(select.value).toBe("group-ops");
expect(select.disabled).toBe(false);
});
});
+69 -30
View File
@@ -1,60 +1,99 @@
"use client";
import type { RefObject } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { useFormStatus } from "react-dom";
export function UserGroupSelect({
action,
effectiveGroupId,
groups,
search,
returnTo,
userId,
userLabel,
}: {
action: (formData: FormData) => Promise<void>;
effectiveGroupId: string;
groups: Array<{ id: string; name: string }>;
search: string;
returnTo: string;
userId: string;
userLabel: string;
}) {
const helpId = `group-help-${userId}`;
return (
<form action={action} className="flex items-center gap-2">
<input name="userId" type="hidden" value={userId} />
<input name="search" type="hidden" value={search} />
<span className="sr-only" id={helpId}>Changing this selection applies the group immediately.</span>
<GroupSelectControl effectiveGroupId={effectiveGroupId} groups={groups} helpId={helpId} userLabel={userLabel} />
</form>
);
}
const dialogRef = useRef<HTMLDialogElement>(null);
const titleId = useId();
const descriptionId = useId();
const helpId = useId();
const [selectedGroupId, setSelectedGroupId] = useState(effectiveGroupId);
const [proposedGroupId, setProposedGroupId] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const currentGroup = groups.find((group) => group.id === effectiveGroupId);
const proposedGroup = groups.find((group) => group.id === proposedGroupId);
function resetSelection() {
setSelectedGroupId(effectiveGroupId);
setProposedGroupId(null);
}
function GroupSelectControl({
effectiveGroupId,
groups,
helpId,
userLabel,
}: {
effectiveGroupId: string;
groups: Array<{ id: string; name: string }>;
helpId: string;
userLabel: string;
}) {
const { pending } = useFormStatus();
return (
<>
<span className="sr-only" id={helpId}>Changing this selection opens a confirmation dialog.</span>
<select
aria-describedby={helpId}
aria-label={`Group for ${userLabel}`}
className="max-w-44 border border-line bg-canvas px-3 py-2 font-mono text-xs outline-none focus:border-accent disabled:cursor-wait disabled:opacity-60"
defaultValue={effectiveGroupId}
disabled={pending}
name="groupId"
onChange={(event) => event.currentTarget.form?.requestSubmit()}
disabled={proposedGroupId !== null || submitting}
onChange={(event) => {
const nextGroupId = event.currentTarget.value;
if (nextGroupId === effectiveGroupId) return;
setSelectedGroupId(nextGroupId);
setProposedGroupId(nextGroupId);
dialogRef.current?.showModal();
}}
value={selectedGroupId}
>
{groups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}
</select>
<span aria-live="polite" className="sr-only">{pending ? "Updating group." : ""}</span>
<button className="sr-only focus:not-sr-only" disabled={pending} type="submit">Apply group</button>
<dialog
aria-describedby={descriptionId}
aria-labelledby={titleId}
className="admin-modal m-auto w-[min(92vw,34rem)] border border-ink bg-panel p-0 text-ink shadow-[10px_10px_0_var(--color-shadow)] backdrop:bg-ink/70"
onCancel={(event) => { if (submitting) event.preventDefault(); }}
onClose={() => { if (!submitting) resetSelection(); }}
ref={dialogRef}
>
<form action={action} className="p-6 sm:p-8" onSubmit={() => setSubmitting(true)}>
<input name="userId" type="hidden" value={userId} />
<input name="groupId" type="hidden" value={proposedGroupId ?? effectiveGroupId} />
<input name="returnTo" type="hidden" value={returnTo} />
<p className="font-mono text-[9px] font-bold uppercase tracking-[0.2em] text-accent">Confirm membership</p>
<h2 className="mt-3 font-display text-3xl font-black uppercase" id={titleId}>Move {userLabel}?</h2>
<p className="mt-3 text-sm leading-6 text-muted" id={descriptionId}>
Change the effective group from <strong className="text-ink">{currentGroup?.name ?? "unknown"}</strong> to <strong className="text-ink">{proposedGroup?.name ?? "unknown"}</strong>. Their access policy changes immediately.
</p>
<AssignmentActions dialogRef={dialogRef} onPendingChange={setSubmitting} />
</form>
</dialog>
</>
);
}
function AssignmentActions({ dialogRef, onPendingChange }: { dialogRef: RefObject<HTMLDialogElement | null>; onPendingChange: (pending: boolean) => void }) {
const { pending } = useFormStatus();
const observedPending = useRef(false);
useEffect(() => {
if (pending) {
observedPending.current = true;
onPendingChange(true);
} else if (observedPending.current) {
observedPending.current = false;
onPendingChange(false);
}
}, [onPendingChange, pending]);
return (
<div className="mt-8 flex justify-end gap-3 border-t border-line pt-5">
<button className="border border-line px-5 py-3 font-mono text-[10px] font-bold uppercase" disabled={pending} onClick={() => dialogRef.current?.close()} type="button">Cancel</button>
<button className="bg-ink px-5 py-3 font-mono text-[10px] font-bold uppercase text-canvas disabled:cursor-wait disabled:opacity-60" disabled={pending} type="submit">{pending ? "Moving…" : "Confirm move"}</button>
<span aria-live="polite" className="sr-only">{pending ? "Group change in progress." : ""}</span>
</div>
);
}