feat(web): /fields two-pane screen (grouped list + create form) + nav (no stubs left)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-04 14:22:57 +02:00
parent 6ad1304efd
commit 37c80121ed
9 changed files with 369 additions and 14 deletions
+12
View File
@@ -22,6 +22,10 @@ const ObjectEditForm = lazy(() =>
import("./objects/object-edit-form").then((m) => ({ default: m.ObjectEditForm })), import("./objects/object-edit-form").then((m) => ({ default: m.ObjectEditForm })),
); );
const FieldsPage = lazy(() =>
import("./fields/fields-page").then((m) => ({ default: m.FieldsPage })),
);
function FormFallback() { function FormFallback() {
return <div role="status" className="p-4 text-sm text-neutral-400">Loading</div>; return <div role="status" className="p-4 text-sm text-neutral-400">Loading</div>;
} }
@@ -63,6 +67,14 @@ export function App() {
</Route> </Route>
<Route path="/authorities" element={<Navigate to="/authorities/person" replace />} /> <Route path="/authorities" element={<Navigate to="/authorities/person" replace />} />
<Route path="/authorities/:kind" element={<AuthoritiesPage />} /> <Route path="/authorities/:kind" element={<AuthoritiesPage />} />
<Route
path="/fields"
element={
<Suspense fallback={<FormFallback />}>
<FieldsPage />
</Suspense>
}
/>
<Route path="/" element={<Navigate to="/objects" replace />} /> <Route path="/" element={<Navigate to="/objects" replace />} />
</Route> </Route>
</Route> </Route>
+158
View File
@@ -0,0 +1,158 @@
import { useState, type FormEvent } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useCreateFieldDefinition, useVocabularies } from "../api/queries";
import { LabelEditor } from "../components/label-editor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
type LabelInput = components["schemas"]["LabelInput"];
const TYPES = ["text", "localized_text", "integer", "date", "boolean", "term", "authority"] as const;
const KINDS = ["person", "organisation", "place"] as const;
export function FieldForm() {
const { t } = useTranslation();
const create = useCreateFieldDefinition();
const { data: vocabularies } = useVocabularies();
const [key, setKey] = useState("");
const [labels, setLabels] = useState<LabelInput[]>([]);
const [dataType, setDataType] = useState<string>("text");
const [vocabularyId, setVocabularyId] = useState("");
const [authorityKind, setAuthorityKind] = useState("");
const [group, setGroup] = useState("");
const [required, setRequired] = useState(false);
const [error, setError] = useState(false);
const reset = () => {
setKey("");
setLabels([]);
setDataType("text");
setVocabularyId("");
setAuthorityKind("");
setGroup("");
setRequired(false);
};
const onSubmit = (event: FormEvent) => {
event.preventDefault();
const hasEn = labels.some((l) => l.lang === "en" && l.label);
const termNeedsVocab = dataType === "term" && !vocabularyId;
if (!key.trim() || !hasEn || termNeedsVocab) {
setError(true);
return;
}
setError(false);
create.mutate(
{
key: key.trim(),
data_type: dataType,
vocabulary_id: dataType === "term" ? vocabularyId : null,
authority_kind: dataType === "authority" ? authorityKind || null : null,
required,
group: group.trim() || null,
labels,
},
{ onSuccess: reset },
);
};
return (
<form onSubmit={onSubmit} className="space-y-3 overflow-auto p-4">
<div className="text-sm font-medium">{t("fields.newField")}</div>
<div className="space-y-1">
<Label htmlFor="field-key">{t("fields.key")}</Label>
<Input id="field-key" value={key} onChange={(e) => setKey(e.target.value)} />
</div>
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor="field-type">{t("fields.type")}</Label>
<select
id="field-type"
value={dataType}
onChange={(e) => setDataType(e.target.value)}
className="w-full rounded border px-2 py-1 text-sm"
>
{TYPES.map((type) => (
<option key={type} value={type}>
{t(`fields.types.${type}`)}
</option>
))}
</select>
</div>
{dataType === "term" && (
<div className="space-y-1">
<Label htmlFor="field-vocab">{t("fields.vocabulary")}</Label>
<select
id="field-vocab"
value={vocabularyId}
onChange={(e) => setVocabularyId(e.target.value)}
className="w-full rounded border px-2 py-1 text-sm"
>
<option value="">{t("form.selectPlaceholder")}</option>
{vocabularies?.map((vocab) => (
<option key={vocab.id} value={vocab.id}>
{vocab.key}
</option>
))}
</select>
</div>
)}
{dataType === "authority" && (
<div className="space-y-1">
<Label htmlFor="field-kind">{t("fields.authorityKind")}</Label>
<select
id="field-kind"
value={authorityKind}
onChange={(e) => setAuthorityKind(e.target.value)}
className="w-full rounded border px-2 py-1 text-sm"
>
<option value="">{t("fields.anyKind")}</option>
{KINDS.map((kind) => (
<option key={kind} value={kind}>
{t(`authorities.${kind}`)}
</option>
))}
</select>
</div>
)}
<div className="space-y-1">
<Label htmlFor="field-group">{t("fields.group")}</Label>
<Input id="field-group" value={group} onChange={(e) => setGroup(e.target.value)} />
</div>
<label className="flex items-center gap-2 text-sm">
<Checkbox checked={required} onCheckedChange={(checked) => setRequired(checked === true)} />
{t("fields.required")}
</label>
{error && (
<p role="alert" className="text-xs text-red-600">
{t("form.required")}
</p>
)}
{create.isError && (
<p role="alert" className="text-xs text-red-600">
{t("form.rejected")}
</p>
)}
<Button type="submit" size="sm" disabled={create.isPending}>
{t("fields.create")}
</Button>
</form>
);
}
+70
View File
@@ -0,0 +1,70 @@
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useFieldDefinitions } from "../api/queries";
import { Skeleton } from "@/components/ui/skeleton";
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
function labelText(labels: FieldDefinitionView["labels"], lang: string): string {
return (
labels.find((l) => l.lang === lang)?.label ??
labels.find((l) => l.lang === "en")?.label ??
labels[0]?.label ??
""
);
}
export function FieldList() {
const { t, i18n } = useTranslation();
const { data, isLoading, isError } = useFieldDefinitions();
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
if (isLoading) {
return (
<div className="space-y-2 p-3">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-9 w-full" />
))}
</div>
);
}
if (isError) return <p className="p-4 text-sm text-red-600">{t("fields.loadError")}</p>;
if (!data || data.length === 0)
return <p className="p-4 text-sm text-neutral-500">{t("fields.empty")}</p>;
const groups = new Map<string, FieldDefinitionView[]>();
for (const def of data) {
const key = def.group?.trim() ? def.group : t("fields.other");
const bucket = groups.get(key) ?? [];
bucket.push(def);
groups.set(key, bucket);
}
return (
<ul className="overflow-auto">
{[...groups.entries()].map(([group, defs]) => (
<li key={group}>
<div className="border-b bg-neutral-50 px-3 py-1 text-xs font-medium uppercase tracking-wide text-neutral-500">
{group}
</div>
<ul>
{defs.map((def) => (
<li key={def.key} className="flex items-center gap-2 border-b px-3 py-2 text-sm">
<span className="font-medium">{labelText(def.labels, lang)}</span>
<span className="text-xs text-neutral-400">{def.key}</span>
<span className="rounded bg-neutral-100 px-1.5 py-0.5 text-xs text-neutral-600">
{t(`fields.types.${def.data_type}`)}
</span>
{def.required && <span className="text-xs text-red-600">*</span>}
</li>
))}
</ul>
</li>
))}
</ul>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { FieldList } from "./field-list";
import { FieldForm } from "./field-form";
export function FieldsPage() {
return (
<div className="grid h-full grid-cols-[20rem_1fr]">
<div className="overflow-hidden border-r">
<FieldList />
</div>
<div className="overflow-hidden">
<FieldForm />
</div>
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from "vitest";
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import { Route, Routes } from "react-router-dom";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { FieldsPage } from "./fields-page";
function tree() {
return (
<Routes>
<Route path="/fields" element={<FieldsPage />} />
</Routes>
);
}
test("lists field definitions grouped, with an Other heading for ungrouped", async () => {
renderApp(tree(), { route: "/fields" });
expect(await screen.findByText("Inscription")).toBeInTheDocument();
expect(screen.getByText(/^Description$/i)).toBeInTheDocument();
expect(screen.getByText(/^Other$/i)).toBeInTheDocument();
});
test("creates a text field — posts the body and clears the key input", async () => {
let body: { key: string; data_type: string } | undefined;
server.use(
http.post("/api/admin/field-definitions", async ({ request }) => {
body = (await request.json()) as { key: string; data_type: string };
return HttpResponse.json({ key: "notes" }, { status: 201 });
}),
);
renderApp(tree(), { route: "/fields" });
await userEvent.type(screen.getByLabelText(/^key$/i), "notes");
await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Notes");
await userEvent.click(screen.getByRole("button", { name: /create field/i }));
await waitFor(() => expect(body?.key).toBe("notes"));
expect(body?.data_type).toBe("text");
await waitFor(() => expect(screen.getByLabelText(/^key$/i)).toHaveValue(""));
});
test("selecting Term reveals the vocabulary picker and blocks submit until chosen", async () => {
let posted = false;
server.use(
http.post("/api/admin/field-definitions", () => {
posted = true;
return HttpResponse.json({ key: "x" }, { status: 201 });
}),
);
renderApp(tree(), { route: "/fields" });
await userEvent.type(screen.getByLabelText(/^key$/i), "material");
await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Material");
await userEvent.selectOptions(screen.getByLabelText(/^type$/i), "term");
const vocab = await screen.findByLabelText(/^vocabulary$/i);
expect(vocab).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: /create field/i }));
expect(await screen.findByRole("alert")).toBeInTheDocument();
expect(posted).toBe(false);
await userEvent.selectOptions(vocab, "v-material");
await userEvent.click(screen.getByRole("button", { name: /create field/i }));
await waitFor(() => expect(posted).toBe(true));
});
+16
View File
@@ -29,6 +29,22 @@
"resultCount_other": "{{count}} results", "resultCount_other": "{{count}} results",
"selectPrompt": "Select a result to see the full record" "selectPrompt": "Select a result to see the full record"
}, },
"fields": {
"title": "Fields",
"newField": "New field definition",
"key": "Key",
"type": "Type",
"vocabulary": "Vocabulary",
"authorityKind": "Authority kind",
"anyKind": "Any",
"group": "Group",
"required": "Required",
"create": "Create field",
"empty": "No field definitions yet",
"loadError": "Could not load",
"other": "Other",
"types": { "text": "Text", "localized_text": "Localized text", "integer": "Integer", "date": "Date", "boolean": "Boolean", "term": "Term", "authority": "Authority" }
},
"publish": { "publish": {
"heading": "Visibility", "heading": "Visibility",
"advanceInternal": "Advance to internal", "advanceInternal": "Advance to internal",
+16
View File
@@ -29,6 +29,22 @@
"resultCount_other": "{{count}} träffar", "resultCount_other": "{{count}} träffar",
"selectPrompt": "Välj en träff för att se hela posten" "selectPrompt": "Välj en träff för att se hela posten"
}, },
"fields": {
"title": "Fält",
"newField": "Nytt fältdefinition",
"key": "Nyckel",
"type": "Typ",
"vocabulary": "Vokabulär",
"authorityKind": "Auktoritetstyp",
"anyKind": "Alla",
"group": "Grupp",
"required": "Obligatoriskt",
"create": "Skapa fält",
"empty": "Inga fältdefinitioner ännu",
"loadError": "Kunde inte ladda",
"other": "Övrigt",
"types": { "text": "Text", "localized_text": "Lokaliserad text", "integer": "Heltal", "date": "Datum", "boolean": "Boolesk", "term": "Term", "authority": "Auktoritet" }
},
"publish": { "publish": {
"heading": "Synlighet", "heading": "Synlighet",
"advanceInternal": "Gör intern", "advanceInternal": "Gör intern",
+2 -2
View File
@@ -29,9 +29,9 @@ test("shows active and disabled nav and renders the outlet", async () => {
renderApp(tree(), { route: "/objects" }); renderApp(tree(), { route: "/objects" });
expect(await screen.findByText("objects outlet")).toBeInTheDocument(); expect(await screen.findByText("objects outlet")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /objects/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /objects/i })).toBeInTheDocument();
// fields is still disabled; search is now a link // fields and search are now links
expect(screen.getByRole("link", { name: /search/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /search/i })).toBeInTheDocument();
expect(screen.getByRole("button", { name: /fields/i })).toBeDisabled(); expect(screen.getByRole("link", { name: /fields/i })).toBeInTheDocument();
}); });
test("language switch toggles to Swedish", async () => { test("language switch toggles to Swedish", async () => {
+8 -12
View File
@@ -5,8 +5,6 @@ import { useLogout } from "../api/queries";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { LangSwitch } from "./lang-switch"; import { LangSwitch } from "./lang-switch";
const DISABLED_NAV = ["fields"] as const;
export function AppShell() { export function AppShell() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -54,16 +52,14 @@ export function AppShell() {
> >
{t("nav.search")} {t("nav.search")}
</NavLink> </NavLink>
{DISABLED_NAV.map((key) => ( <NavLink
<button to="/fields"
key={key} className={({ isActive }) =>
disabled `block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
title={t("nav.soon")} }
className="block w-full cursor-not-allowed rounded px-2 py-1 text-left text-neutral-400" >
> {t("nav.fields")}
{t(`nav.${key}`)} </NavLink>
</button>
))}
</nav> </nav>
</aside> </aside>
<div className="flex flex-1 flex-col"> <div className="flex flex-1 flex-col">