Records a person manages
A page of accounts an admin manages: searched, filtered, sorted and paged on your server, changed one at a time from a row or many at once, including everyone a search matches on pages never opened. The same shape fits invitations, jobs, keys or anything else your own server holds. It is built from DataTable, SelectionBar, Pagination, useConfirm, StatusBadge, SegmentedControl and ActionReceipt, with no table, dialog or bar of its own.
How it works:
- The page holds the query (search, filter, order, page) and asks your server for one page at a time.
DataTablesorts nothing: a press on a heading callsonSortChange, and the page asks the server again.Paginationdoes the same for Previous and Next. A new search, filter or order goes back to the first page with nothing chosen. - Ticking boxes chooses rows on this page. Once the page is ticked,
SelectionBaroffers "Select all N that match". The action then goes to the server as the search and filter, not as a list of ids, so it reaches people the browser never loaded, and the server runs the same search again to find them. - The server applies its own rules to each person (no one turns themselves off) and says whom it left alone and why.
ActionReceiptshows that,partialwhen some were skipped. - Turning accounts off is hard to undo, so the page asks first with
useConfirm, naming the button for the action. Turning them back on does not ask.
Your server, as the page sees it, is two calls. The stand-in here keeps the accounts in memory; yours does the same in its database:
api.ts:
/** One account, as the server sends it. */
export interface Account {
id: string;
name: string;
email: string;
off: boolean;
owns: number;
}
export type AccountSort = "name" | "email" | "owns";
/** What the page asks for: the search, the filter, the order and the page. The server does all four. */
export interface AccountQuery {
q: string;
status: "" | "on" | "off";
sort: AccountSort;
desc: boolean;
offset: number;
limit: number;
}
/** Whom an action is for: the rows ticked, or everyone the search and filter match. */
export type Target = { ids: string[] } | { match: { q: string; status: AccountQuery["status"] } };
export type BulkAction = "turn-off" | "turn-on";
export interface BulkResult {
done: number;
/** Everyone left alone, with the reason, in a sentence. */
skipped: { name: string; reason: string }[];
}
/** Your server, as the page sees it: two calls. */
export interface AccountsApi {
list(query: AccountQuery): Promise<{ accounts: Account[]; total: number }>;
bulk(action: BulkAction, target: Target): Promise<BulkResult>;
}
/**
* A stand-in for your server, in memory, for the test and the docs. A real one does the same in its database: it
* searches, filters, sorts and pages, and it applies an action to "everyone who matches" by running the same search
* again, never by trusting a list the browser built. The rules (no one turns themselves off) are checked here, on the
* server, for each person.
*/
export function memoryAccounts(accounts: Account[], me: string): AccountsApi & { accounts: Account[] } {
const matching = (q: string, status: AccountQuery["status"]) => {
const words = q.trim().toLowerCase();
return accounts.filter((a) => (!words || `${a.name} ${a.email}`.toLowerCase().includes(words)) && (!status || (status === "off") === a.off));
};
return {
accounts,
async list({ q, status, sort, desc, offset, limit }) {
const found = matching(q, status).sort((a, b) => {
const order = sort === "owns" ? a.owns - b.owns : a[sort].localeCompare(b[sort]);
return (desc ? -order : order) || a.id.localeCompare(b.id);
});
return { accounts: found.slice(offset, offset + limit).map((a) => ({ ...a })), total: found.length };
},
async bulk(action, target) {
const people = "ids" in target ? accounts.filter((a) => target.ids.includes(a.id)) : matching(target.match.q, target.match.status);
const result: BulkResult = { done: 0, skipped: [] };
for (const person of people) {
const off = action === "turn-off";
if (off && person.id === me) result.skipped.push({ name: person.name, reason: "you cannot turn off your own account" });
else if (person.off === off) result.skipped.push({ name: person.name, reason: off ? "already turned off" : "already on" });
else {
person.off = off;
result.done++;
}
}
return result;
},
};
}The page:
Accounts.tsx:
import {
ActionReceipt,
type DataTableColumn,
type DataTableSort,
DataTable,
Pagination,
SegmentedControl,
SelectionBar,
StatusBadge,
useConfirm,
} from "@surfaces-ui/components";
import { useCallback, useEffect, useState } from "react";
import type { Account, AccountQuery, AccountSort, AccountsApi, BulkAction, BulkResult, Target } from "./api.js";
const PAGE = 50;
const COLUMNS: DataTableColumn<Account>[] = [
{ id: "name", label: "Name", sortable: true },
{ id: "email", label: "Email", sortable: true, show: "medium" },
{ id: "status", label: "Status", cell: (a) => <StatusBadge label={a.off ? "Turned off" : "On"} tone={a.off ? "danger" : "success"} /> },
{ id: "owns", label: "Owns", sortable: true, align: "end", show: "wide" },
];
const WORDS: Record<BulkAction, { button: string; done: string }> = {
"turn-off": { button: "Turn off", done: "Turned off" },
"turn-on": { button: "Turn back on", done: "Turned back on" },
};
/** Accounts a person manages: searched, filtered, sorted and paged on the server, changed one at a time or many at once. */
export function Accounts({ api, me }: { api: AccountsApi; me: string }) {
const [q, setQ] = useState("");
const [status, setStatus] = useState<AccountQuery["status"]>("");
const [sort, setSort] = useState<DataTableSort>({ column: "name", desc: false });
const [offset, setOffset] = useState(0);
const [page, setPage] = useState<{ accounts: Account[]; total: number }>({ accounts: [], total: 0 });
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [allMatching, setAllMatching] = useState(false);
const [busy, setBusy] = useState(false);
const [receipt, setReceipt] = useState<{ action: BulkAction; result: BulkResult }>();
const { confirm, element } = useConfirm();
const load = useCallback(async () => {
setLoading(true);
const query: AccountQuery = { q, status, sort: sort.column as AccountSort, desc: sort.desc, offset, limit: PAGE };
setPage(await api.list(query));
setLoading(false);
}, [api, q, status, sort, offset]);
useEffect(() => void load(), [load]);
// A new search, filter or order starts again from the first page with nothing chosen.
const changeQuery = (change: () => void) => {
change();
setOffset(0);
setSelected(new Set());
setAllMatching(false);
};
const run = async (action: BulkAction, target: Target, count: number) => {
if (action === "turn-off") {
const ok = await confirm({
title: count === 1 ? "Turn off 1 account?" : `Turn off ${count} accounts?`,
body: "They are signed out everywhere now and cannot sign in until turned back on. What they own stays theirs.",
confirmLabel: "Turn off",
danger: true,
});
if (!ok) return;
}
setBusy(true);
try {
setReceipt({ action, result: await api.bulk(action, target) });
setSelected(new Set());
setAllMatching(false);
} finally {
setBusy(false);
await load();
}
};
const ticked = page.accounts.filter((a) => selected.has(a.id));
const count = allMatching ? page.total : ticked.length;
const target = (): Target => (allMatching ? { match: { q, status } } : { ids: ticked.map((a) => a.id) });
const choosable = page.accounts.filter((a) => a.id !== me);
return (
<section aria-label="Accounts" className="accounts">
<div className="accounts-tools">
<label>
Find someone <input className="sf-input" type="search" value={q} onChange={(e) => changeQuery(() => setQ(e.target.value))} />
</label>
<SegmentedControl
label="Show"
value={status}
onChange={(next) => changeQuery(() => setStatus(next))}
options={[
{ value: "", label: "Everyone" },
{ value: "on", label: "On" },
{ value: "off", label: "Turned off" },
]}
/>
</div>
{receipt && (
<ActionReceipt
title={`${WORDS[receipt.action].done} ${receipt.result.done === 1 ? "1 account" : `${receipt.result.done} accounts`}`}
outcome={receipt.result.skipped.length === 0 ? "done" : receipt.result.done === 0 ? "failed" : "partial"}
summary={receipt.result.skipped.length ? `Left ${receipt.result.skipped.length} alone.` : undefined}
changes={receipt.result.skipped.map((s) => ({ label: s.name, after: `Skipped: ${s.reason}` }))}
/>
)}
<SelectionBar
count={count}
total={page.total}
pageSelected={choosable.length > 0 && choosable.every((a) => selected.has(a.id))}
allMatching={allMatching}
onAllMatchingChange={setAllMatching}
busy={busy}
onClear={() => (setSelected(new Set()), setAllMatching(false))}
actions={(["turn-on", "turn-off"] as const).map((action) => ({
id: action,
label: WORDS[action].button,
danger: action === "turn-off",
onSelect: () => void run(action, target(), count),
}))}
/>
<DataTable
label="Accounts"
columns={COLUMNS}
rows={page.accounts}
rowKey={(a) => a.id}
rowName={(a) => a.name}
rowState={(a) => (a.off ? "off" : undefined)}
loading={loading}
empty="No one matches."
sort={sort}
onSortChange={(next) => changeQuery(() => setSort(next))}
selected={selected}
allSelected={allMatching}
selectable={(a) => a.id !== me}
onSelectedChange={(next) => (setAllMatching(false), setSelected(next))}
rowControls={(a) => [
a.off
? { id: "turn-on", label: `Turn ${a.name} back on`, icon: "power", onSelect: () => void run("turn-on", { ids: [a.id] }, 1) }
: { id: "turn-off", label: `Turn off ${a.name}`, icon: "power", onSelect: () => void run("turn-off", { ids: [a.id] }, 1), disabled: a.id === me },
]}
/>
<Pagination offset={offset} pageSize={PAGE} total={page.total} busy={loading} onChange={setOffset} />
{element}
</section>
);
}<Accounts api={yourAccountsApi} me={signedInUserId} />The test draws the page in jsdom against the stand-in with 120 accounts. It checks that sorting and paging ask the server, that "everyone who matches" reaches the server as a search, and that the receipt names the four people left alone:
accounts.test.tsx:
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Accounts } from "./Accounts.js";
import { type Account, memoryAccounts } from "./api.js";
afterEach(cleanup);
/** 120 accounts: Ana (the person using the page) and 119 others, three of them already turned off. */
function accounts(): Account[] {
const people: Account[] = [{ id: "ana", name: "Ana Admin", email: "ana@example.com", off: false, owns: 3 }];
for (let i = 1; i < 120; i++) {
const n = String(i).padStart(3, "0");
people.push({ id: `p${n}`, name: `Person ${n}`, email: `person${n}@example.com`, off: i <= 3, owns: i % 7 });
}
return people;
}
const table = () => screen.getByRole("table", { name: "Accounts" });
const names = () => within(table()).queryAllByRole("rowheader").map((cell) => cell.textContent);
const settle = () => act(async () => {});
describe("accounts a person manages", () => {
it("shows one page the server sorted, and asks the server again to sort or page", async () => {
const api = memoryAccounts(accounts(), "ana");
const list = vi.spyOn(api, "list");
render(<Accounts api={api} me="ana" />);
await settle();
expect(names()).toHaveLength(50);
expect(names()[0]).toBe("Ana Admin");
expect(screen.getByText("1–50 of 120")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: /^Owns/ }));
await settle();
expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ sort: "owns", desc: false, offset: 0 }));
fireEvent.click(screen.getByRole("button", { name: "Next" }));
await settle();
expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 50, limit: 50 }));
expect(screen.getByText("51–100 of 120")).toBeTruthy();
});
it("turns off everyone who matches, past this page, after asking, and says whom it left alone", async () => {
const api = memoryAccounts(accounts(), "ana");
const bulk = vi.spyOn(api, "bulk");
render(<Accounts api={api} me="ana" />);
await settle();
fireEvent.click(screen.getByRole("checkbox", { name: "Select every row on this page" }));
fireEvent.click(screen.getByRole("button", { name: "Select all 120 that match" }));
expect(screen.getByText("120 selected")).toBeTruthy();
fireEvent.click(within(screen.getByRole("group", { name: "With the selected rows" })).getByRole("button", { name: "Turn off" }));
const dialog = screen.getByRole("dialog", { name: "Turn off 120 accounts?" });
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Turn off" })));
// The server got the search, not 120 ids, and checked its own rules for each person.
expect(bulk).toHaveBeenCalledWith("turn-off", { match: { q: "", status: "" } });
expect(api.accounts.filter((a) => a.off)).toHaveLength(119);
expect(api.accounts.find((a) => a.id === "ana")!.off).toBe(false);
expect(screen.getByText("Turned off 116 accounts")).toBeTruthy();
expect(screen.getByText("Left 4 alone.")).toBeTruthy();
expect(screen.getByText("Skipped: you cannot turn off your own account")).toBeTruthy();
expect(screen.getAllByText("Skipped: already turned off")).toHaveLength(3);
});
it("does nothing when the person thinks better of it", async () => {
const api = memoryAccounts(accounts(), "ana");
render(<Accounts api={api} me="ana" />);
await settle();
fireEvent.click(screen.getByRole("button", { name: "Turn off Person 010" }));
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
expect(api.accounts.find((a) => a.id === "p010")!.off).toBe(false);
expect(screen.queryByRole("dialog")).toBeNull();
});
it("starts a new search from the first page with nothing chosen", async () => {
const api = memoryAccounts(accounts(), "ana");
render(<Accounts api={api} me="ana" />);
await settle();
fireEvent.click(screen.getByRole("button", { name: "Next" }));
await settle();
fireEvent.click(screen.getByRole("checkbox", { name: "Select Person 060" }));
fireEvent.change(screen.getByRole("searchbox", { name: "Find someone" }), { target: { value: "Person 06" } });
await settle();
expect(names()).toEqual(["Person 060", "Person 061", "Person 062", "Person 063", "Person 064", "Person 065", "Person 066", "Person 067", "Person 068", "Person 069"]);
expect(screen.queryByRole("group", { name: "With the selected rows" })).toBeNull();
expect(screen.queryByRole("navigation", { name: "Pages" })).toBeNull();
});
});Things to know:
- Check who may act on the server, for every person in the batch, as you would for one. The browser's list of ids is a convenience, not permission, and "everyone who matches" must be bounded on the server (refuse a batch past a limit rather than run it partly).
- The selection belongs to the page. When the rows change under it (another admin turned someone off), "select all that match" acts on the rows that match when the server runs the action, not those shown when it was chosen.
- Keep the row's own actions to the everyday ones. Anything rarer belongs on the record's own page, reached from its name.
Source and test: apps/recipes/src/manage-records