Files
gerbeur/src/components/category/CategoryManager.tsx
khannurien d392be7cb8
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s
v3: api/ gets one layout rule and keeps to it, and whatever crosses the wire is defined once, in shared/ — api/model/interfaces.ts and src/model.ts declared the same 40 types by hand and had drifted: the error envelope, email required on one side and optional on the other, Invitee/InviteTreeEntry and LinkPreview/UrlPreviewResponse for one shape each. The validation limits, the role permissions, the chat length cap, the @mention pattern and the Bandcamp and YouTube player responses were copied too, behind "keep in sync" comments. shared/ now holds them once, one file per domain (api, category, chat, comment, dump, follow, mention, notification, permissions, player, playlist, search, user, validation, ws), and imports nothing from either half. The server sends Dates; the client reads Wire<T>, the same type with every Date an ISO string, and turns it back with src/utils/shared/deserialize.ts. APIErrorCode becomes a const object, since the frontend's erasableSyntaxOnly rejects an enum. The shared types showed two real gaps: the avatar upload and GET /api/users/me return the full self user and the frontend read them as public users, and a stored session may predate media tokens, so the client keeps it as its own Session type. The backend rule: each folder holds one kind of module, each file is named after its domain. routes/ parse and answer; services/ hold the logic and every SQL query (lib/auth.ts's token check moves to user-service); remote/ is the only place that fetches from other sites — the guarded fetch and the HTML scraping out of rich-content-service, public-address, the Bandcamp and YouTube resolvers, the link providers, the image proxy (fetch, checks and cache, out of routes/preview.ts) and the Twemoji glyphs (out of lib/site-icons.ts). model/ holds per table a row type, its guard and its mappers; validators/ the request guards; db/connection.ts the handle and transaction(), db/startup.ts the purges and default admin that db.ts ran on import, called at the same moment. Tests mirror the source one file per module, test/<layer>/<module>.test.ts, with shared/'s under shared/test/ (deno task test runs both); the test that covered the bandcamp and soundcloud providers together is two now, and the backend can() has its own, so 202 tests. deno lint src/ is clean too: window.* becomes globalThis.*, and test bodies and act() callbacks that never awaited lose their async. The README states the rule. No behaviour changes; the catalogues only move their source references.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 20:19:48 +00:00

248 lines
7.1 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState } from "react";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../../config/api.ts";
import { VALIDATION } from "../../../shared/validation.ts";
import type {
Category,
CreateCategoryRequest,
UpdateCategoryRequest,
} from "../../../shared/category.ts";
import type { Wire } from "../../../shared/api.ts";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { useCategories } from "../../hooks/category/useCategories.ts";
import { ConfirmModal } from "../shared/ConfirmModal.tsx";
import { expectOk } from "../../utils/shared/api.ts";
import { FormError } from "../form/FormError.tsx";
import { FormProvider } from "react-hook-form";
import { SubmitButton } from "../form/SubmitButton.tsx";
import { useApiForm } from "../../hooks/form/useApiForm.ts";
interface CategoryFields {
name: string;
slug: string;
}
/** Sentinel for "the create chip is open" (vs. a category id being edited). */
const NEW = "new";
/**
* Admin UI to create, edit and delete categories. Rendered inside the "Manage"
* profile tab (gated by the `category:manage` permission).
*
* Categories show as chips; clicking one expands it into an inline editor. A
* trailing "+" chip opens the same editor in create mode. Only one editor is
* open at a time.
*/
export function CategoryManager() {
const { categories, isLoaded, refresh } = useCategories();
const [editing, setEditing] = useState<string | null>(null);
const close = () => setEditing(null);
const handleChanged = () => {
refresh();
close();
};
if (!isLoaded && categories.length === 0) {
return (
<p className="index-status">
<Trans>Loading…</Trans>
</p>
);
}
return (
<div className="category-chips">
{categories.map((category) =>
editing === category.id
? (
<CategoryEditor
key={category.id}
category={category}
onCancel={close}
onChanged={handleChanged}
/>
)
: (
<button
key={category.id}
type="button"
className="category-chip"
onClick={() => setEditing(category.id)}
disabled={editing !== null}
title={t`Edit ${category.name}`}
>
{category.name}
</button>
)
)}
{editing === NEW
? (
<CategoryEditor
onCancel={close}
onChanged={handleChanged}
/>
)
: (
<button
type="button"
className="category-chip category-chip--add"
onClick={() => setEditing(NEW)}
disabled={editing !== null}
aria-label={t`Add category`}
title={t`Add category`}
>
+
</button>
)}
</div>
);
}
interface CategoryEditorProps {
/** Omit to render the editor in "create" mode. */
category?: Category;
onCancel: () => void;
onChanged: () => void;
}
function CategoryEditor(
{ category, onCancel, onChanged }: CategoryEditorProps,
) {
const isNew = category === undefined;
const { authFetch } = useAuth();
const form = useApiForm<CategoryFields>({
defaultValues: { name: category?.name ?? "", slug: category?.slug ?? "" },
});
const name = form.watch("name");
const slug = form.watch("slug");
const { isDirty } = form.formState;
const [deleting, setDeleting] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const onSubmit = form.submit(async ({ name, slug }) => {
const body = { name: name.trim(), slug: slug.trim() };
await expectOk<Wire<Category>>(
isNew
? await authFetch(`${API_URL}/api/categories`, {
method: "POST",
body: JSON.stringify(body satisfies CreateCategoryRequest),
})
: await authFetch(`${API_URL}/api/categories/${category.id}`, {
method: "PUT",
body: JSON.stringify(body satisfies UpdateCategoryRequest),
}),
);
onChanged();
});
async function remove() {
if (isNew) return;
setConfirmOpen(false);
form.clearErrors("root");
setDeleting(true);
try {
await expectOk(
await authFetch(`${API_URL}/api/categories/${category.id}`, {
method: "DELETE",
}),
);
onChanged();
} catch (err) {
form.setError("root", {
message: err instanceof Error ? err.message : t`Failed to delete`,
});
setDeleting(false);
}
}
// Create needs both fields; edit needs an actual change too.
const canSave = !deleting && name.trim() !== "" && slug.trim() !== "" &&
(isNew || isDirty);
return (
<FormProvider {...form}>
<div className="category-editor-wrap">
<form
className="category-editor"
onSubmit={onSubmit}
onKeyDown={(e) => {
if (e.key === "Escape") onCancel();
}}
>
<input
className="category-editor-input category-editor-input--name"
type="text"
placeholder={t`Name`}
aria-label={t`Name`}
maxLength={VALIDATION.CATEGORY_NAME_MAX}
disabled={deleting}
autoFocus
{...form.register("name")}
/>
<span className="category-editor-sep" aria-hidden>
/
</span>
<input
className="category-editor-input category-editor-input--slug"
type="text"
placeholder={t`slug`}
aria-label={t`URL slug`}
maxLength={VALIDATION.CATEGORY_SLUG_MAX}
disabled={deleting}
{...form.register("slug")}
/>
<div className="category-editor-actions">
<SubmitButton
className="category-editor-btn category-editor-btn--save"
pendingLabel="…"
disabled={!canSave}
aria-label={t`Save`}
>
✓
</SubmitButton>
<button
type="button"
className="category-editor-btn"
onClick={onCancel}
disabled={deleting}
title={t`Cancel`}
aria-label={t`Cancel`}
>
✕
</button>
{!isNew && (
<button
type="button"
className="category-editor-btn category-editor-btn--delete"
onClick={() => setConfirmOpen(true)}
disabled={deleting}
title={t`Delete`}
aria-label={t`Delete`}
>
🗑
</button>
)}
</div>
</form>
<FormError
title={isNew
? t`Failed to create category`
: t`Failed to save category`}
/>
</div>
{confirmOpen && category && (
<ConfirmModal
message={t`Delete category "${category.name}"? This cannot be undone.`}
confirmLabel={t`Delete category`}
onConfirm={remove}
onCancel={() => setConfirmOpen(false)}
/>
)}
</FormProvider>
);
}