v4: every page and API URL follows one of two rules, written down in API.md — pages are a hierarchy where @name is a user and any other root word a category or an app page, tabs and views are plain segments and a default view is the bare path; API resources are /api/<plural>/<key>, a user's key being an id or @name, the caller's things under /api/me, media a sub-resource, lookups by another key a query filter. ~ is gone: the feed is /, /hot, /new, /journal, /follow and /music/hot, a profile /@bob with its overview and the tabs dumps, upvoted, playlists (her own only), follow (users, and /follow/playlists), invitees and manage (role and name, for user:manage), which replace the separate UserDumps, UserUpvoted and UserPlaylists pages; /settings holds the account (now with the username) and /manage the category manager, both linked from the user menu and one's profile. Dumps and playlists live under their owner, /@bob/dumps/<slug> and /@bob/playlists/<slug>, named by slug alone: migration 0021 re-slugs them to the bare slugify(title), unique per owner and kind (the oldest keeps it, clashes get -2), renames the categories whose slug v4 reserves (hot, follow, settings…), and rewrites this site's v3 links in dump notes, comments, chat, and playlist and profile descriptions. A slug changes only when edited, through the edit forms' new link field, which proposes slugify(title) as the title changes; a username changes from /settings or, for user:manage, from /@name/manage. Every slug or name left behind stays an alias of its item or user for good (dump_slug_aliases, playlist_slug_aliases, user_aliases), so old links redirect without chaining and nobody else can take one; slugs change 3 times a day per item, names once in 30 days, moderators exempt. An alias, or a name in another case, answers the item with its current path: the pages put it in their URL (useCanonicalPath, without fetching again), and the OG middleware answers a 301. shared/paths.ts builds and parses every page path, for the client's links, the emails' (digest-service lost its own builders and its id fallbacks, and links /follow and /settings) and the server's matchers (OG tags, self previews, backlinks, self-url); shared/slug.ts holds slugify and the format categories share. Dumps and playlists carry ownerUsername and a required slug, and notifications join their users' current names and their items' paths each time they are sent or read, so renames reach them and a deleted item's has no link. The API was renamed per the plan's table: POST /api/users and /api/sessions, /api/password-resets, /api/me (with settings, password, avatar, media-token, playlists?contains=, follow, feed?from=, notifications), /api/users/:key/{dumps,upvoted,playlists,follow/users,follow/playlists,invitees,avatar} and by path /api/users/:key/{dumps,playlists}/:slug, /api/dumps?url= and ?category=, /api/dumps/:id/{file,thumbnail,metadata}, /api/playlists/:id/cover, /api/remote/{preview,image,bandcamp,youtube} (one router), and /api/unsubscribe, the v3 POST /api/users/unsubscribe staying for the digests already sent. A stored default feed tab "followed" reads as "follow" once. dumps.slug and playlists.slug stay nullable, since SQLite can't add NOT NULL without rebuilding tables others reference; every writer sets them and unique (user_id, slug) indexes hold them. 254 backend tests (new: migration 0021 on a v3 fixture, slug aliases, swaps and rate limits, username renames, aliases and limits, reads by path and their privacy, the OG 301s, both unsubscribe paths, v4-shaped digest links with no ids, notification joins, shared paths and slugs) and 668 frontend tests (new: the profile's tabs and follow views, Settings, Manage, the link field, canonical URLs on the dump, playlist and profile pages, bare default feed paths) pass, and tsc, eslint, deno check, deno lint, deno fmt and doc:lint are clean; the migration was also run on a copy of the development database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-06 16:08:59 +00:00
parent fd0d81fe66
commit 4468438ba7
228 changed files with 7320 additions and 5193 deletions

View File

@@ -1,15 +1,14 @@
import { describe, expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
import { UserPublicProfile } from "../../pages/UserPublicProfile.tsx";
import type { PublicUser } from "../../../shared/user.ts";
import { calls, deferred, fail, route } from "../fetch.ts";
import { calls, fail, route } from "../fetch.ts";
import {
makeCategory,
makeDump,
makePlaylist,
makeSession,
makeToken,
makeUser,
page,
wire,
@@ -17,6 +16,7 @@ import {
import { currentPath, renderApp } from "../render.tsx";
import { FakeWebSocket } from "../ws.ts";
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
import { FakeIntersectionObserver } from "../setup.ts";
const ann = makeUser({
id: "ann",
@@ -34,23 +34,21 @@ function open(
{
session = null as ReturnType<typeof makeSession> | null,
user = ann as PublicUser,
url = "/users/ann",
url = "/@ann",
dumps = [makeDump({ id: "d1", title: "Her dump", userId: "ann" })],
votes = [makeDump({ id: "v1", title: "She liked this" })],
playlists = [makePlaylist({ id: "p1", title: "Her mix", userId: "ann" })],
categories = [] as ReturnType<typeof makeCategory>[],
} = {},
) {
route("GET /api/users/:u", () => wire(user));
route("GET /api/users/:u/dumps", () => page(dumps));
route("GET /api/users/:u/votes", () => page(votes));
route(
"GET /api/users/:u/playlists",
() => page([makePlaylist({ title: "Her mix", userId: "ann" })]),
);
route("GET /api/users/:u/upvoted", () => page(votes));
route("GET /api/users/:u/playlists", () => page(playlists));
const u = userEvent.setup();
renderApp(<UserPublicProfile />, {
route: url,
path: "/users/:username/*",
path: "/:handle/*",
session,
categories,
});
@@ -58,32 +56,39 @@ function open(
}
describe("UserPublicProfile", () => {
test("header, description, and the dumps tab", async () => {
test("header, description, and the overview", async () => {
open();
expect(await screen.findByRole("heading", { name: "ann" }))
.toBeInTheDocument();
expect(screen.getByRole("link", { name: "@root" })).toHaveAttribute(
"href",
"/users/root",
"/@root",
);
expect(screen.getByText("dump").tagName).toBe("STRONG");
expect(screen.getByText("Her dump")).toBeInTheDocument();
expect(screen.getByText("She liked this")).toBeInTheDocument();
expect(await screen.findByText("Her dump")).toBeInTheDocument();
expect(await screen.findByText("She liked this")).toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Dumps (1)" }))
.toBeInTheDocument();
const [dumpsAll, votesAll] = screen.getAllByRole("link", {
name: "View all →",
});
expect(dumpsAll).toHaveAttribute("href", "/@ann/dumps");
expect(votesAll).toHaveAttribute("href", "/@ann/upvoted");
await waitFor(() => expect(document.title).toMatch(/^ann · /));
expect(screen.queryByRole("button", { name: "Settings" })).not
expect(screen.queryByRole("link", { name: "Settings" })).not
.toBeInTheDocument();
// The lists are read by the user's id, which a rename doesn't change.
expect(calls("GET /api/users/:u/dumps")[0].path).toBe(
"/api/users/ann/dumps",
);
expect(calls("GET /api/users/:u")[0].path).toBe("/api/users/@ann");
});
test("an unknown user", async () => {
route("GET /api/users/:u", () => fail("User not found", 404));
route("GET /api/users/:u/dumps", () => page([]));
route("GET /api/users/:u/votes", () => page([]));
route("GET /api/users/:u/playlists", () => page([]));
renderApp(<UserPublicProfile />, {
route: "/users/nobody",
path: "/users/:username/*",
route: "/@nobody",
path: "/:handle/*",
});
expect(await screen.findByRole("alert")).toHaveTextContent(
"User not found",
@@ -95,50 +100,166 @@ describe("UserPublicProfile", () => {
expect(await screen.findByText("Moderator")).toBeInTheDocument();
});
test("tabs are in the URL", async () => {
test("tabs are plain segments, the overview the bare path", async () => {
const { user } = open();
await screen.findByRole("heading", { name: "ann" });
await user.click(screen.getByRole("button", { name: "Playlists" }));
expect(currentPath()).toBe("/users/ann/~/playlists");
expect(screen.getByText("Her mix")).toBeInTheDocument();
const tabs = document.querySelector(".profile-tabs") as HTMLElement;
await user.click(within(tabs).getByRole("button", { name: "Playlists" }));
expect(currentPath()).toBe("/@ann/playlists");
expect(await screen.findByText("Her mix")).toBeInTheDocument();
await user.click(within(tabs).getByRole("button", { name: "Overview" }));
expect(currentPath()).toBe("/@ann");
});
test("followed: people and playlists, with more people on demand", async () => {
test("a tab or view the profile hasn't is not found", async () => {
for (const url of ["/@ann/nope", "/@ann/follow/users", "/@ann/dumps/x"]) {
const { unmount } = renderApp(<UserPublicProfile />, {
route: url,
path: "/:handle/*",
});
expect(await screen.findByText("This page does not exist."))
.toBeInTheDocument();
unmount();
}
});
test("a former name or another case: the URL takes the current one", async () => {
open({ url: "/@ANN_OLD/playlists?x=1" });
await screen.findByRole("heading", { name: "ann" });
await waitFor(() => expect(currentPath()).toBe("/@ann/playlists?x=1"));
expect(await screen.findByText("Her mix")).toBeInTheDocument();
// The URL's change names the user on screen, who isn't fetched again.
expect(calls("GET /api/users/:u")).toHaveLength(1);
});
test("the dumps tab lists them all; a visitor loses one gone private, and gets it back", async () => {
const list = ["x", "y", "z"].map((id) =>
makeDump({ id, title: `T-${id}`, userId: "ann" })
);
const { socket } = open({ url: "/@ann/dumps", dumps: list });
await screen.findByText("T-z");
expect(screen.getByRole("heading", { name: "Dumps" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /New dump/ })).not
.toBeInTheDocument();
socket.welcome();
socket.receive({
type: "dump_updated",
dump: wire({ ...list[1], isPrivate: true }),
});
expect(screen.queryByText("T-y")).not.toBeInTheDocument();
socket.receive({
type: "dump_updated",
dump: wire({ ...list[1], isPrivate: false }),
});
const titles = Array.from(document.querySelectorAll(".dump-card-title"))
.map((a) => a.textContent);
expect(titles).toEqual(["T-x", "T-y", "T-z"]);
});
test("the dumps tab loads more as its end scrolls into view", async () => {
open({ url: "/@ann/dumps" });
// After open's, so that it wins.
route(
"GET /api/users/:u/followed-users",
"GET /api/users/:u/dumps",
(req) =>
req.url.searchParams.get("page") === "1"
? page([makeDump({ title: "First", userId: "ann" })], true)
: page([makeDump({ title: "Second", userId: "ann" })]),
);
await screen.findByText("First");
act(() => FakeIntersectionObserver.instances.at(-1)!.report(true));
expect(await screen.findByText("Second")).toBeInTheDocument();
expect(screen.getByText("You've reached the end.")).toBeInTheDocument();
});
test("the upvoted tab follows their votes", async () => {
route(
"GET /api/dumps/:id",
() => wire(makeDump({ id: "v3", title: "Fresh like" })),
);
const { socket } = open({ url: "/@ann/upvoted" });
await screen.findByText("She liked this");
expect(screen.getByRole("heading", { name: "Upvoted" }))
.toBeInTheDocument();
socket.welcome();
socket.receive({
type: "votes_update",
dumpId: "v3",
voteCount: 1,
voterId: "ann",
action: "cast",
});
await waitFor(() =>
expect(document.querySelector(".dump-card-title")).toHaveTextContent(
"Fresh like",
)
);
});
test("the playlists tab holds hers only, kept live", async () => {
const { socket } = open({ url: "/@ann/playlists" });
await screen.findByText("Her mix");
expect(calls("GET /api/users/:u/follow/playlists")).toHaveLength(0);
expect(screen.queryByRole("button", { name: "Delete playlist" })).not
.toBeInTheDocument();
socket.welcome();
socket.receive({
type: "playlist_created",
playlist: wire(
makePlaylist({ id: "p2", title: "Brand new mix", userId: "ann" }),
),
});
expect(screen.getByText("Brand new mix")).toBeInTheDocument();
socket.receive({
type: "playlist_updated",
playlist: wire(
makePlaylist({
id: "p1",
title: "Her mix",
userId: "ann",
isPublic: false,
}),
),
});
expect(screen.queryByText("Her mix")).not.toBeInTheDocument();
});
test("follow: users at the bare tab, playlists one segment further", async () => {
route(
"GET /api/users/:u/follow/users",
() => page([makeUser({ username: "bob" })]),
);
route(
"GET /api/users/:u/follow/playlists",
() => page([makePlaylist({ title: "Their mix" })]),
);
const { user } = open({ url: "/@ann/follow" });
expect(await screen.findByRole("link", { name: /@bob/ })).toHaveAttribute(
"href",
"/@bob",
);
expect(calls("GET /api/users/:u/follow/playlists")).toHaveLength(0);
const views = document.querySelector(".followed-sub-nav") as HTMLElement;
await user.click(within(views).getByRole("button", { name: "Playlists" }));
expect(currentPath()).toBe("/@ann/follow/playlists");
expect(await screen.findByText("Their mix")).toBeInTheDocument();
await user.click(within(views).getByRole("button", { name: "Users" }));
expect(currentPath()).toBe("/@ann/follow");
});
test("follow: more users as the list's end scrolls into view", async () => {
route(
"GET /api/users/:u/follow/users",
(req) =>
req.url.searchParams.get("page") === "1"
? page([makeUser({ username: "bob" })], true)
: page([makeUser({ username: "cy" })]),
);
route(
"GET /api/users/:u/followed-playlists",
() => page([makePlaylist({ title: "Their mix" })]),
);
const { user } = open({ url: "/users/ann/~/followed" });
expect(await screen.findByRole("link", { name: /@bob/ })).toHaveAttribute(
"href",
"/users/bob",
);
expect(screen.getByText("Their mix")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Load more" }));
open({ url: "/@ann/follow" });
await screen.findByRole("link", { name: /@bob/ });
act(() => FakeIntersectionObserver.instances.at(-1)!.report(true));
expect(await screen.findByRole("link", { name: /@cy/ }))
.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Load more" })).not
.toBeInTheDocument();
});
test("followed: leaving the tab while it loads still loads it", async () => {
const users = deferred<unknown>();
route("GET /api/users/:u/followed-users", () => users.promise);
route("GET /api/users/:u/followed-playlists", () => page([]));
const { user } = open({ url: "/users/ann/~/followed" });
await screen.findByRole("heading", { name: "ann" });
await user.click(screen.getByRole("button", { name: "Playlists" }));
users.resolve(page([makeUser({ username: "bob" })]));
await user.click(screen.getByRole("button", { name: "Followed" }));
expect(await screen.findByRole("link", { name: /@bob/ }))
.toBeInTheDocument();
});
test("invitees as a tree", async () => {
@@ -147,25 +268,25 @@ describe("UserPublicProfile", () => {
{ id: "b", username: "bob", invitedById: "ann", createdAt: new Date() },
{ id: "c", username: "cy", invitedById: "b", createdAt: new Date() },
]));
open({ url: "/users/ann/~/invitees" });
open({ url: "/@ann/invitees" });
const bob = (await screen.findByRole("link", { name: /@bob/ })).closest(
"li",
)!;
expect(within(bob).getByRole("link", { name: /@cy/ })).toBeInTheDocument();
});
test("visitors can follow; signed in, a settings tab is only on your own profile", async () => {
test("visitors can follow; a settings link is only on your own profile", async () => {
open({ session: makeSession({ id: "bob" }) });
expect(await screen.findByRole("button", { name: "Follow ann" }))
.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Settings" })).not
expect(screen.queryByRole("link", { name: "Settings" })).not
.toBeInTheDocument();
});
describe("your own profile", () => {
test("edit the description; clearing it really clears it", async () => {
route(
"PATCH /api/users/me",
"PATCH /api/me",
(req) => wire({ ...ann, ...(req.body as object) }),
);
const { user } = open({ session: annSession });
@@ -178,12 +299,12 @@ describe("UserPublicProfile", () => {
await user.clear(box);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Who am I?")).toBeInTheDocument();
expect(calls("PATCH /api/users/me")[0].body).toEqual({ description: "" });
expect(calls("PATCH /api/me")[0].body).toEqual({ description: "" });
});
test("edit the email", async () => {
route(
"PATCH /api/users/me",
"PATCH /api/me",
(req) => wire({ ...ann, ...(req.body as object) }),
);
const { user } = open({ session: annSession });
@@ -200,7 +321,7 @@ describe("UserPublicProfile", () => {
});
test("a refused email says why", async () => {
route("PATCH /api/users/me", () => fail("Email already in use", 409));
route("PATCH /api/me", () => fail("Email already in use", 409));
const { user } = open({ session: annSession });
await user.click(
await screen.findByRole("button", { name: /ann@x\.test/ }),
@@ -213,7 +334,7 @@ describe("UserPublicProfile", () => {
test("upload an avatar", async () => {
route(
"POST /api/avatars/me",
"PUT /api/me/avatar",
() =>
wire({ ...ann, avatarMime: "image/png", updatedAt: new Date(7000) }),
);
@@ -230,13 +351,13 @@ describe("UserPublicProfile", () => {
expect(document.querySelector(".profile-avatar-wrapper img"))
.toHaveAttribute(
"src",
"http://localhost:8000/api/avatars/ann?v=7000",
"http://localhost:8000/api/users/ann/avatar?v=7000",
)
);
});
test("a rejected avatar says why", async () => {
route("POST /api/avatars/me", () => fail("Not an image", 400));
route("PUT /api/me/avatar", () => fail("Not an image", 400));
const { user } = open({ session: annSession });
await screen.findByRole("heading", { name: "ann" });
const input = document.querySelector<HTMLInputElement>(
@@ -293,113 +414,22 @@ describe("UserPublicProfile", () => {
}
});
test("settings: theme, colour scheme, default tab and sounds", async () => {
const { user } = open({
session: annSession,
url: "/users/ann/~/settings",
test("your settings, and the site's tools for an admin, are a link away", async () => {
open({
session: { ...annSession, user: { ...annSession.user, role: "admin" } },
user: { ...ann, role: "admin" },
});
await user.click(
await screen.findByRole("button", { name: "Brutalist" }),
);
expect(document.documentElement.getAttribute("data-style")).toBe(
"brutalist",
);
await user.click(screen.getByRole("button", { name: "Dark" }));
expect(document.documentElement.getAttribute("data-color-scheme")).toBe(
"dark",
);
await user.click(screen.getByRole("button", { name: "New" }));
expect(localStorage.getItem("default-feed-tab")).toBe("new");
const sounds = screen.getByText("Sounds").closest(
".profile-appearance-row",
) as HTMLElement;
await user.click(within(sounds).getByRole("button", { name: "Off" }));
expect(localStorage.getItem("sounds")).toBe("off");
// Without SMTP on the server, the digests can't be switched.
const weekly = screen.getByText("Weekly digest").closest(
".profile-appearance-row",
) as HTMLElement;
expect(within(weekly).getByRole("button", { name: "On" })).toBeDisabled();
expect(screen.getByText(/doesn't send email/)).toBeInTheDocument();
document.documentElement.removeAttribute("data-style");
document.documentElement.removeAttribute("data-color-scheme");
});
test("change password keeps you signed in with the fresh tokens", async () => {
const freshToken = makeToken({ sub: "ann" });
route(
"POST /api/users/me/change-password",
() => ({ token: freshToken, mediaToken: "fresh-media" }),
);
const { user } = open({
session: annSession,
url: "/users/ann/~/settings",
});
await user.click(
await screen.findByRole("button", { name: "Change password…" }),
);
const dialog = screen.getByRole("dialog", { name: "Change password" });
await user.type(
within(dialog).getByLabelText("Current password"),
"oldpassword",
);
await user.type(
within(dialog).getByLabelText("New password"),
"newpassword",
);
await user.type(
within(dialog).getByLabelText("Confirm new password"),
"different",
);
expect(await within(dialog).findByText("Passwords do not match"))
.toBeInTheDocument();
await user.clear(within(dialog).getByLabelText("Confirm new password"));
await user.type(
within(dialog).getByLabelText("Confirm new password"),
"newpassword",
);
await user.click(
within(dialog).getByRole("button", { name: "Change password" }),
);
expect(await within(dialog).findByText("Password changed successfully."))
.toBeInTheDocument();
expect(JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY)!).token).toBe(
freshToken,
);
expect(calls("POST /api/users/me/change-password")[0].body).toEqual({
currentPassword: "oldpassword",
newPassword: "newpassword",
});
});
test("a wrong current password is reported", async () => {
route(
"POST /api/users/me/change-password",
() => fail("Current password is incorrect", 400),
);
const { user } = open({
session: annSession,
url: "/users/ann/~/settings",
});
await user.click(
await screen.findByRole("button", { name: "Change password…" }),
);
const dialog = screen.getByRole("dialog", { name: "Change password" });
await user.type(
within(dialog).getByLabelText("Current password"),
"wrong",
);
await user.type(
within(dialog).getByLabelText("New password"),
"newpassword",
);
await user.type(
within(dialog).getByLabelText("Confirm new password"),
"newpassword{Enter}",
);
expect(await within(dialog).findByRole("alert")).toHaveTextContent(
"Current password is incorrect",
expect(await screen.findByRole("link", { name: "Settings" }))
.toHaveAttribute("href", "/settings");
expect(screen.getByRole("link", { name: "Manage" })).toHaveAttribute(
"href",
"/manage",
);
// Their own profile has no manage tab: that's for others'.
expect(
within(document.querySelector(".profile-tabs") as HTMLElement)
.queryByRole("button", { name: "Manage" }),
).not.toBeInTheDocument();
});
test("log out", async () => {
@@ -417,7 +447,7 @@ describe("UserPublicProfile", () => {
);
const { user } = open({
session: makeSession({ id: "admin", role: "admin" }),
url: "/users/ann/~/manage",
url: "/@ann/manage",
});
await user.click(
await screen.findByRole("button", { name: "Moderator" }),
@@ -442,7 +472,7 @@ describe("UserPublicProfile", () => {
);
const { user } = open({
session: makeSession({ id: "admin", role: "admin" }),
url: "/users/ann/~/manage",
url: "/@ann/manage",
});
await user.click(await screen.findByRole("button", { name: "Admin" }));
expect(await screen.findByRole("alert")).toHaveTextContent(
@@ -450,90 +480,53 @@ describe("UserPublicProfile", () => {
);
});
test("non-admins get no manage tab", async () => {
test("an admin renames someone, and the URL follows", async () => {
route(
"PATCH /api/users/:id/username",
(req) =>
wire({
...ann,
username: (req.body as { username: string }).username,
}),
);
const { user } = open({
session: makeSession({ id: "admin", role: "admin" }),
url: "/@ann/manage",
});
const name = await screen.findByRole("textbox", { name: "Username" });
await user.clear(name);
await user.type(name, "annie{Enter}");
await waitFor(() => expect(currentPath()).toBe("/@annie/manage"));
expect(screen.getByRole("heading", { name: "annie" }))
.toBeInTheDocument();
expect(calls("PATCH /api/users/:id/username")[0]).toMatchObject({
path: "/api/users/ann/username",
body: { username: "annie" },
});
});
test("a refused rename says why", async () => {
route(
"PATCH /api/users/:id/username",
() => fail("Username already exists", 409),
);
const { user } = open({
session: makeSession({ id: "admin", role: "admin" }),
url: "/@ann/manage",
});
const name = await screen.findByRole("textbox", { name: "Username" });
await user.type(name, "x{Enter}");
expect(await screen.findByRole("alert")).toHaveTextContent(
"Username already exists",
);
});
test("non-admins get no manage tab, nor its page", async () => {
open({
session: makeSession({ id: "mod", role: "moderator" }),
url: "/users/ann/~/manage",
url: "/@ann/manage",
});
await screen.findByRole("heading", { name: "ann" });
expect(screen.queryByRole("button", { name: "Manage" })).not
.toBeInTheDocument();
expect(screen.getByText("Her dump")).toBeInTheDocument();
});
test("on your own profile, an admin manages categories", async () => {
const music = makeCategory({ id: "c1", slug: "music", name: "Music" });
let list = [music];
route("GET /api/categories", () => wire(list));
route("POST /api/categories", (req) => {
const c = makeCategory({ id: "c2", ...(req.body as object) });
list = [...list, c];
return wire(c);
});
route("DELETE /api/categories/:id", () => {
list = list.filter((c) => c.id !== "c1");
return null;
});
const admin = makeSession({ id: "ann", username: "ann", role: "admin" });
const { user } = open({
session: admin,
url: "/users/ann/~/manage",
user: { ...ann, role: "admin" },
});
await user.click(
await screen.findByRole("button", { name: "Add category" }),
);
await user.type(screen.getByRole("textbox", { name: "Name" }), "Cinema");
await user.type(
screen.getByRole("textbox", { name: "URL slug" }),
"cinema",
);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("button", { name: "Cinema" }))
.toBeInTheDocument();
expect(calls("POST /api/categories")[0].body).toEqual({
name: "Cinema",
slug: "cinema",
});
await user.click(screen.getByRole("button", { name: "Music" }));
await user.click(screen.getByRole("button", { name: "Delete" }));
await user.click(
within(screen.getByRole("alertdialog")).getByRole("button", {
name: "Delete category",
}),
);
await waitFor(() =>
expect(screen.queryByRole("button", { name: "Music" })).not
.toBeInTheDocument()
);
});
test("a refused category is reported, and Escape closes the editor", async () => {
route("GET /api/categories", () => []);
route("POST /api/categories", () => fail("Slug already taken", 409));
const admin = makeSession({ id: "ann", username: "ann", role: "admin" });
const { user } = open({
session: admin,
url: "/users/ann/~/manage",
user: { ...ann, role: "admin" },
});
await user.click(
await screen.findByRole("button", { name: "Add category" }),
);
await user.type(screen.getByRole("textbox", { name: "Name" }), "X");
await user.type(
screen.getByRole("textbox", { name: "URL slug" }),
"x{Enter}",
);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Slug already taken",
);
await user.type(
screen.getByRole("textbox", { name: "Name" }),
"{Escape}",
);
expect(screen.getByRole("button", { name: "Add category" }))
expect(await screen.findByText("This page does not exist."))
.toBeInTheDocument();
});
});