merge: frontend M4 — vocabulary & authority management (create+list)
Vocabularies two-pane screen (list/create + per-vocab terms/add), Authorities kind-tabbed screen (list/create), shared sv/en LabelEditor, 4 new query hooks, nav enabled for both surfaces. 57 tests, bundle 143.1 KB gz. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -200,6 +200,87 @@ export function useDeleteObject() {
|
||||
});
|
||||
}
|
||||
|
||||
type NewVocabularyRequest = components["schemas"]["NewVocabularyRequest"];
|
||||
type LabelInput = components["schemas"]["LabelInput"];
|
||||
|
||||
export function useVocabularies() {
|
||||
return useQuery({
|
||||
queryKey: ["vocabularies"],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await api.GET("/api/admin/vocabularies");
|
||||
|
||||
if (error || !data) throw new Error("failed to load vocabularies");
|
||||
|
||||
return data;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateVocabulary() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (body: NewVocabularyRequest) => {
|
||||
const { data, error } = await api.POST("/api/admin/vocabularies", { body });
|
||||
|
||||
if (error || !data) throw new Error("create vocabulary failed");
|
||||
|
||||
return data;
|
||||
},
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddTerm() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
vocabularyId,
|
||||
external_uri,
|
||||
labels,
|
||||
}: {
|
||||
vocabularyId: string;
|
||||
external_uri: string | null;
|
||||
labels: LabelInput[];
|
||||
}) => {
|
||||
const { response } = await api.POST("/api/admin/vocabularies/{id}/terms", {
|
||||
params: { path: { id: vocabularyId } },
|
||||
body: { external_uri, labels },
|
||||
});
|
||||
|
||||
if (response.status !== 201) throw new Error("add term failed");
|
||||
},
|
||||
onSuccess: (_result, { vocabularyId }) =>
|
||||
qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateAuthority() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
kind,
|
||||
external_uri,
|
||||
labels,
|
||||
}: {
|
||||
kind: string;
|
||||
external_uri: string | null;
|
||||
labels: LabelInput[];
|
||||
}) => {
|
||||
const { response } = await api.POST("/api/admin/authorities", {
|
||||
body: { kind, external_uri, labels },
|
||||
});
|
||||
|
||||
if (response.status !== 201) throw new Error("create authority failed");
|
||||
},
|
||||
onSuccess: (_result, { kind }) =>
|
||||
qc.invalidateQueries({ queryKey: ["authorities", kind] }),
|
||||
});
|
||||
}
|
||||
|
||||
type Visibility = "draft" | "internal" | "public";
|
||||
|
||||
/** Error carrying the HTTP status so callers can branch 422-gate vs 409-illegal. */
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import type { ReactNode } from "react";
|
||||
import { server } from "../test/server";
|
||||
import { useVocabularies, useCreateVocabulary, useAddTerm, useCreateAuthority } from "./queries";
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
describe("vocab/authority hooks", () => {
|
||||
test("useVocabularies lists vocabularies", async () => {
|
||||
const { result } = renderHook(() => useVocabularies(), { wrapper });
|
||||
await waitFor(() => expect(result.current.data?.length).toBe(2));
|
||||
expect(result.current.data?.[0].key).toBe("material");
|
||||
});
|
||||
test("useCreateVocabulary POSTs the key", async () => {
|
||||
let body: unknown;
|
||||
server.use(http.post("/api/admin/vocabularies", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ id: "v-x", key: "colour" }, { status: 201 });
|
||||
}));
|
||||
const { result } = renderHook(() => useCreateVocabulary(), { wrapper });
|
||||
await result.current.mutateAsync({ key: "colour" });
|
||||
expect((body as { key: string }).key).toBe("colour");
|
||||
});
|
||||
test("useAddTerm POSTs labels to the vocabulary", async () => {
|
||||
let body: unknown;
|
||||
server.use(http.post("/api/admin/vocabularies/:id/terms", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ id: "t-x" }, { status: 201 });
|
||||
}));
|
||||
const { result } = renderHook(() => useAddTerm(), { wrapper });
|
||||
await result.current.mutateAsync({ vocabularyId: "v-material", external_uri: null, labels: [{ lang: "en", label: "Red" }] });
|
||||
expect((body as { labels: { label: string }[] }).labels[0].label).toBe("Red");
|
||||
});
|
||||
test("useCreateAuthority POSTs kind + labels", async () => {
|
||||
let body: unknown;
|
||||
server.use(http.post("/api/admin/authorities", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ id: "a-x" }, { status: 201 });
|
||||
}));
|
||||
const { result } = renderHook(() => useCreateAuthority(), { wrapper });
|
||||
await result.current.mutateAsync({ kind: "person", external_uri: null, labels: [{ lang: "en", label: "Ada" }] });
|
||||
expect((body as { kind: string }).kind).toBe("person");
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,10 @@ import { AppShell } from "./shell/app-shell";
|
||||
import { ObjectsPage } from "./objects/objects-page";
|
||||
import { ObjectDetail } from "./objects/object-detail";
|
||||
import { SelectPrompt } from "./objects/select-prompt";
|
||||
import { VocabulariesPage } from "./vocab/vocabularies-page";
|
||||
import { VocabularyTerms } from "./vocab/vocabulary-terms";
|
||||
import { SelectVocabularyPrompt } from "./vocab/select-vocabulary-prompt";
|
||||
import { AuthoritiesPage } from "./authorities/authorities-page";
|
||||
|
||||
const ObjectNewPage = lazy(() =>
|
||||
import("./objects/object-new-page").then((m) => ({ default: m.ObjectNewPage })),
|
||||
@@ -47,6 +51,12 @@ export function App() {
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
<Route path="/vocabularies" element={<VocabulariesPage />}>
|
||||
<Route index element={<SelectVocabularyPrompt />} />
|
||||
<Route path=":id" element={<VocabularyTerms />} />
|
||||
</Route>
|
||||
<Route path="/authorities" element={<Navigate to="/authorities/person" replace />} />
|
||||
<Route path="/authorities/:kind" element={<AuthoritiesPage />} />
|
||||
<Route path="/" element={<Navigate to="/objects" replace />} />
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { NavLink, Navigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { useAuthorities, useCreateAuthority } from "../api/queries";
|
||||
import { LabelEditor } from "../components/label-editor";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelText } from "../lib/labels";
|
||||
|
||||
type LabelInput = components["schemas"]["LabelInput"];
|
||||
|
||||
const KINDS = ["person", "organisation", "place"] as const;
|
||||
|
||||
export function AuthoritiesPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { kind } = useParams();
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
|
||||
const isValidKind = (KINDS as readonly string[]).includes(kind ?? "");
|
||||
|
||||
const { data: authorities } = useAuthorities(isValidKind ? (kind as string) : "person");
|
||||
const create = useCreateAuthority();
|
||||
|
||||
const [labels, setLabels] = useState<LabelInput[]>([]);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
if (!isValidKind) return <Navigate to="/authorities/person" replace />;
|
||||
|
||||
const onCreate = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!labels.some((l) => l.lang === "en" && l.label)) {
|
||||
setError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(false);
|
||||
create.mutate(
|
||||
{ kind: kind as string, external_uri: null, labels },
|
||||
{ onSuccess: () => setLabels([]) },
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-auto p-4">
|
||||
<div className="mb-3 flex gap-2">
|
||||
{KINDS.map((k) => (
|
||||
<NavLink
|
||||
key={k}
|
||||
to={`/authorities/${k}`}
|
||||
className={({ isActive }) =>
|
||||
`rounded px-3 py-1 text-sm ${isActive ? "bg-neutral-800 text-white" : "border"}`
|
||||
}
|
||||
>
|
||||
{t(`authorities.${k}`)}
|
||||
</NavLink>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<ul className="mb-4">
|
||||
{authorities?.length === 0 && (
|
||||
<li className="text-sm text-neutral-500">{t("authorities.empty")}</li>
|
||||
)}
|
||||
{authorities?.map((a) => (
|
||||
<li key={a.id} className="border-b py-1 text-sm">
|
||||
{labelText(a.labels, lang)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<form onSubmit={onCreate} className="space-y-2 border-t pt-3">
|
||||
<div className="text-sm font-medium">
|
||||
{t("authorities.new")} · {t(`authorities.${kind}`)}
|
||||
</div>
|
||||
|
||||
<LabelEditor value={labels} onChange={setLabels} />
|
||||
|
||||
{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("authorities.create")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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 { Routes, Route } from "react-router-dom";
|
||||
import { server } from "../test/server";
|
||||
import { renderApp } from "../test/render";
|
||||
import { AuthoritiesPage } from "./authorities-page";
|
||||
|
||||
function tree() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/authorities/:kind" element={<AuthoritiesPage />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
test("lists authorities for the kind and creates one", async () => {
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.post("/api/admin/authorities", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ id: "a-c" }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
renderApp(tree(), { route: "/authorities/person" });
|
||||
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Carl von Linné");
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
await waitFor(() => expect((body as { kind: string })?.kind).toBe("person"));
|
||||
expect((body as { labels: { label: string }[] }).labels[0].label).toBe("Carl von Linné");
|
||||
});
|
||||
|
||||
test("kind tabs link to the other kinds", async () => {
|
||||
renderApp(tree(), { route: "/authorities/person" });
|
||||
expect(await screen.findByRole("link", { name: /place/i })).toHaveAttribute("href", "/authorities/place");
|
||||
});
|
||||
|
||||
test("create without EN label shows required alert and does not POST", async () => {
|
||||
let posted = false;
|
||||
server.use(
|
||||
http.post("/api/admin/authorities", () => {
|
||||
posted = true;
|
||||
return HttpResponse.json({ id: "a-x" }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
renderApp(tree(), { route: "/authorities/person" });
|
||||
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||
expect(posted).toBe(false);
|
||||
});
|
||||
|
||||
test("unknown kind redirects to person list", async () => {
|
||||
renderApp(tree(), { route: "/authorities/banana" });
|
||||
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState } from "react";
|
||||
import { expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { renderApp } from "../test/render";
|
||||
import { LabelEditor } from "./label-editor";
|
||||
import type { components } from "../api/schema";
|
||||
|
||||
type LabelInput = components["schemas"]["LabelInput"];
|
||||
|
||||
function Harness({ onChange }: { onChange: (v: LabelInput[]) => void }) {
|
||||
const [value, setValue] = useState<LabelInput[]>([]);
|
||||
return (
|
||||
<LabelEditor
|
||||
value={value}
|
||||
onChange={(v) => {
|
||||
setValue(v);
|
||||
onChange(v);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
test("typing EN and SV emits both labels; empty langs are omitted", async () => {
|
||||
const seen: LabelInput[][] = [];
|
||||
renderApp(<Harness onChange={(v) => seen.push(v)} />);
|
||||
await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Bronze");
|
||||
await userEvent.type(screen.getByLabelText(/label \(sv\)/i), "Brons");
|
||||
const last = seen[seen.length - 1]!;
|
||||
expect(last).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ lang: "en", label: "Bronze" },
|
||||
{ lang: "sv", label: "Brons" },
|
||||
]),
|
||||
);
|
||||
expect(seen.some((v) => v.length === 1 && v[0].lang === "en")).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
type LabelInput = components["schemas"]["LabelInput"];
|
||||
|
||||
/** Controlled sv/en label editor. Emits LabelInput[] with only the non-empty langs. */
|
||||
export function LabelEditor({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: LabelInput[];
|
||||
onChange: (labels: LabelInput[]) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const valueFor = (lang: string) => value.find((l) => l.lang === lang)?.label ?? "";
|
||||
|
||||
const set = (lang: string, label: string) => {
|
||||
const others = value.filter((l) => l.lang !== lang);
|
||||
|
||||
onChange(label.trim() ? [...others, { lang, label }] : others);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="label-en">{t("labels.en")}</Label>
|
||||
<Input
|
||||
id="label-en"
|
||||
value={valueFor("en")}
|
||||
onChange={(e) => set("en", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="label-sv">{t("labels.sv")}</Label>
|
||||
<Input
|
||||
id="label-sv"
|
||||
value={valueFor("sv")}
|
||||
onChange={(e) => set("sv", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,17 @@
|
||||
"visibility": { "draft": "Draft", "internal": "Internal", "public": "Public" },
|
||||
"form": { "selectPlaceholder": "— select —", "create": "Create object", "save": "Save", "cancel": "Cancel", "visibility": "Visibility", "draft": "Draft", "internal": "Internal", "required": "This field is required", "rejected": "The server rejected the changes — check required and referenced fields", "flexibleHeading": "Catalogue fields" },
|
||||
"actions": { "edit": "Edit", "delete": "Delete", "confirmDelete": "Delete this object? This cannot be undone." },
|
||||
"labels": { "en": "Label (EN)", "sv": "Label (SV)", "externalUri": "External URI (optional)" },
|
||||
"vocab": {
|
||||
"title": "Vocabularies", "newVocabulary": "New vocabulary", "key": "Key",
|
||||
"create": "Create", "selectPrompt": "Select a vocabulary to manage its terms",
|
||||
"terms": "Terms", "addTerm": "Add term", "empty": "No vocabularies yet",
|
||||
"noTerms": "No terms yet", "loadError": "Could not load"
|
||||
},
|
||||
"authorities": {
|
||||
"title": "Authorities", "person": "Person", "organisation": "Organisation", "place": "Place",
|
||||
"new": "New", "create": "Create", "empty": "No authorities yet", "loadError": "Could not load"
|
||||
},
|
||||
"publish": {
|
||||
"heading": "Visibility",
|
||||
"advanceInternal": "Advance to internal",
|
||||
|
||||
@@ -7,6 +7,17 @@
|
||||
"visibility": { "draft": "Utkast", "internal": "Intern", "public": "Publik" },
|
||||
"form": { "selectPlaceholder": "— välj —", "create": "Skapa föremål", "save": "Spara", "cancel": "Avbryt", "visibility": "Synlighet", "draft": "Utkast", "internal": "Intern", "required": "Fältet är obligatoriskt", "rejected": "Servern avvisade ändringarna — kontrollera obligatoriska och refererade fält", "flexibleHeading": "Katalogfält" },
|
||||
"actions": { "edit": "Redigera", "delete": "Ta bort", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras." },
|
||||
"labels": { "en": "Etikett (EN)", "sv": "Etikett (SV)", "externalUri": "Extern URI (valfritt)" },
|
||||
"vocab": {
|
||||
"title": "Vokabulär", "newVocabulary": "Ny vokabulär", "key": "Nyckel",
|
||||
"create": "Skapa", "selectPrompt": "Välj en vokabulär för att hantera dess termer",
|
||||
"terms": "Termer", "addTerm": "Lägg till term", "empty": "Inga vokabulärer ännu",
|
||||
"noTerms": "Inga termer ännu", "loadError": "Kunde inte ladda"
|
||||
},
|
||||
"authorities": {
|
||||
"title": "Auktoriteter", "person": "Person", "organisation": "Organisation", "place": "Plats",
|
||||
"new": "Ny", "create": "Skapa", "empty": "Inga auktoriteter ännu", "loadError": "Kunde inte ladda"
|
||||
},
|
||||
"publish": {
|
||||
"heading": "Synlighet",
|
||||
"advanceInternal": "Gör intern",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { components } from "../api/schema";
|
||||
|
||||
type LabelView = components["schemas"]["LabelView"];
|
||||
|
||||
export function labelText(labels: LabelView[], lang: string): string {
|
||||
return (
|
||||
labels.find((l) => l.lang === lang)?.label ??
|
||||
labels.find((l) => l.lang === "en")?.label ??
|
||||
labels[0]?.label ??
|
||||
""
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { useLogout } from "../api/queries";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LangSwitch } from "./lang-switch";
|
||||
|
||||
const FUTURE = ["vocabularies", "authorities", "fields", "search"] as const;
|
||||
const DISABLED_NAV = ["fields", "search"] as const;
|
||||
|
||||
export function AppShell() {
|
||||
const { t } = useTranslation();
|
||||
@@ -30,7 +30,23 @@ export function AppShell() {
|
||||
>
|
||||
{t("nav.objects")}
|
||||
</NavLink>
|
||||
{FUTURE.map((key) => (
|
||||
<NavLink
|
||||
to="/vocabularies"
|
||||
className={({ isActive }) =>
|
||||
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
|
||||
}
|
||||
>
|
||||
{t("nav.vocabularies")}
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/authorities"
|
||||
className={({ isActive }) =>
|
||||
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
|
||||
}
|
||||
>
|
||||
{t("nav.authorities")}
|
||||
</NavLink>
|
||||
{DISABLED_NAV.map((key) => (
|
||||
<button
|
||||
key={key}
|
||||
disabled
|
||||
|
||||
@@ -62,3 +62,10 @@ export const materialTerms: TermView[] = [
|
||||
export const personAuthorities: AuthorityView[] = [
|
||||
{ id: "a-ada", kind: "person", external_uri: null, labels: [{ lang: "en", label: "Ada Lovelace" }] },
|
||||
];
|
||||
|
||||
export type VocabularyView = components["schemas"]["VocabularyView"];
|
||||
|
||||
export const vocabularies: VocabularyView[] = [
|
||||
{ id: "v-material", key: "material" },
|
||||
{ id: "v-technique", key: "technique" },
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
|
||||
import { amphora, fibula, fieldDefinitions, materialTerms, objectsPage, personAuthorities } from "./fixtures";
|
||||
import { amphora, fibula, fieldDefinitions, materialTerms, objectsPage, personAuthorities, vocabularies } from "./fixtures";
|
||||
|
||||
export const handlers = [
|
||||
http.get("/api/admin/me", () =>
|
||||
@@ -17,6 +17,8 @@ export const handlers = [
|
||||
|
||||
http.get("/api/admin/field-definitions", () => HttpResponse.json(fieldDefinitions)),
|
||||
|
||||
http.get("/api/admin/vocabularies", () => HttpResponse.json(vocabularies)),
|
||||
|
||||
http.get("/api/admin/vocabularies/:id/terms", () => HttpResponse.json(materialTerms)),
|
||||
|
||||
http.get("/api/admin/authorities", ({ request }) => {
|
||||
@@ -25,6 +27,18 @@ export const handlers = [
|
||||
return HttpResponse.json(kind === "person" ? personAuthorities : []);
|
||||
}),
|
||||
|
||||
http.post("/api/admin/vocabularies", () =>
|
||||
HttpResponse.json({ id: "v-new", key: "new" }, { status: 201 }),
|
||||
),
|
||||
|
||||
http.post("/api/admin/vocabularies/:id/terms", () =>
|
||||
HttpResponse.json({ id: "t-new" }, { status: 201 }),
|
||||
),
|
||||
|
||||
http.post("/api/admin/authorities", () =>
|
||||
HttpResponse.json({ id: "a-new" }, { status: 201 }),
|
||||
),
|
||||
|
||||
http.post("/api/admin/objects", () =>
|
||||
HttpResponse.json({ id: "11111111-1111-1111-1111-111111111111" }, { status: 201 }),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export function SelectVocabularyPrompt() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-4 text-sm text-neutral-400">
|
||||
{t("vocab.selectPrompt")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Outlet } from "react-router-dom";
|
||||
|
||||
import { VocabularyList } from "./vocabulary-list";
|
||||
|
||||
export function VocabulariesPage() {
|
||||
return (
|
||||
<div className="grid h-full grid-cols-[20rem_1fr]">
|
||||
<div className="overflow-hidden border-r">
|
||||
<VocabularyList />
|
||||
</div>
|
||||
<div className="overflow-hidden">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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 { Routes, Route } from "react-router-dom";
|
||||
import { server } from "../test/server";
|
||||
import { renderApp } from "../test/render";
|
||||
import { VocabulariesPage } from "./vocabularies-page";
|
||||
import { VocabularyTerms } from "./vocabulary-terms";
|
||||
import { SelectVocabularyPrompt } from "./select-vocabulary-prompt";
|
||||
|
||||
function tree() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/vocabularies" element={<VocabulariesPage />}>
|
||||
<Route index element={<SelectVocabularyPrompt />} />
|
||||
<Route path=":id" element={<VocabularyTerms />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
test("lists vocabularies and creates one", async () => {
|
||||
let body: unknown;
|
||||
server.use(
|
||||
http.post("/api/admin/vocabularies", async ({ request }) => {
|
||||
body = await request.json();
|
||||
return HttpResponse.json({ id: "v-c", key: "colour" }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
renderApp(tree(), { route: "/vocabularies" });
|
||||
expect(await screen.findByText("material")).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText(/key/i), "colour");
|
||||
await userEvent.click(screen.getByRole("button", { name: /create/i }));
|
||||
await waitFor(() => expect((body as { key: string })?.key).toBe("colour"));
|
||||
});
|
||||
|
||||
test("selecting a vocabulary shows its terms and adds one", async () => {
|
||||
let termBody: unknown;
|
||||
server.use(
|
||||
http.post("/api/admin/vocabularies/:id/terms", async ({ request }) => {
|
||||
termBody = await request.json();
|
||||
return HttpResponse.json({ id: "t-c" }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
renderApp(tree(), { route: "/vocabularies/v-material" });
|
||||
expect(await screen.findByText("Bronze")).toBeInTheDocument();
|
||||
await userEvent.type(screen.getByLabelText(/label \(en\)/i), "Stone");
|
||||
await userEvent.click(screen.getByRole("button", { name: /add term/i }));
|
||||
await waitFor(() =>
|
||||
expect((termBody as { labels: { label: string }[] })?.labels[0].label).toBe("Stone"),
|
||||
);
|
||||
});
|
||||
|
||||
test("add term without EN label shows required alert and does not POST", async () => {
|
||||
let posted = false;
|
||||
server.use(
|
||||
http.post("/api/admin/vocabularies/:id/terms", () => {
|
||||
posted = true;
|
||||
return HttpResponse.json({ id: "t-x" }, { status: 201 });
|
||||
}),
|
||||
);
|
||||
renderApp(tree(), { route: "/vocabularies/v-material" });
|
||||
expect(await screen.findByText("Bronze")).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole("button", { name: /add term/i }));
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||
expect(posted).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useVocabularies, useCreateVocabulary } from "../api/queries";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
export function VocabularyList() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data, isLoading, isError } = useVocabularies();
|
||||
|
||||
const create = useCreateVocabulary();
|
||||
|
||||
const [key, setKey] = useState("");
|
||||
|
||||
const onCreate = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!key.trim()) return;
|
||||
|
||||
create.mutate({ key: key.trim() }, { onSuccess: () => setKey("") });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<form onSubmit={onCreate} className="space-y-1 border-b p-3">
|
||||
<div className="text-sm font-medium">{t("vocab.newVocabulary")}</div>
|
||||
<Label htmlFor="vocab-key">{t("vocab.key")}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="vocab-key"
|
||||
value={key}
|
||||
onChange={(e) => setKey(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" size="sm" disabled={create.isPending}>
|
||||
{t("vocab.create")}
|
||||
</Button>
|
||||
</div>
|
||||
{create.isError && (
|
||||
<p role="alert" className="text-xs text-red-600">
|
||||
{t("form.rejected")}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
<ul className="flex-1 overflow-auto">
|
||||
{isLoading && (
|
||||
<li className="p-3 text-sm text-neutral-400">…</li>
|
||||
)}
|
||||
{isError && (
|
||||
<li className="p-3 text-sm text-red-600">{t("vocab.loadError")}</li>
|
||||
)}
|
||||
{data?.length === 0 && (
|
||||
<li className="p-3 text-sm text-neutral-500">{t("vocab.empty")}</li>
|
||||
)}
|
||||
{data?.map((v) => (
|
||||
<li key={v.id}>
|
||||
<NavLink
|
||||
to={`/vocabularies/${v.id}`}
|
||||
className={({ isActive }) =>
|
||||
`block border-b px-3 py-2 text-sm ${isActive ? "bg-indigo-50" : "hover:bg-neutral-50"}`
|
||||
}
|
||||
>
|
||||
{v.key}
|
||||
</NavLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { useTerms, useAddTerm } 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 { labelText } from "../lib/labels";
|
||||
|
||||
type LabelInput = components["schemas"]["LabelInput"];
|
||||
|
||||
export function VocabularyTerms() {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const { id } = useParams();
|
||||
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
|
||||
const { data: terms } = useTerms(id);
|
||||
|
||||
const addTerm = useAddTerm();
|
||||
|
||||
const [labels, setLabels] = useState<LabelInput[]>([]);
|
||||
|
||||
const [uri, setUri] = useState("");
|
||||
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
if (!id) return null;
|
||||
|
||||
const onAdd = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!labels.some((l) => l.lang === "en" && l.label)) {
|
||||
setError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(false);
|
||||
|
||||
addTerm.mutate(
|
||||
{ vocabularyId: id, external_uri: uri.trim() || null, labels },
|
||||
{ onSuccess: () => { setLabels([]); setUri(""); } },
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-auto p-4">
|
||||
<h3 className="mb-2 text-sm font-medium uppercase text-neutral-500">
|
||||
{t("vocab.terms")}
|
||||
</h3>
|
||||
<ul className="mb-4">
|
||||
{terms?.length === 0 && (
|
||||
<li className="text-sm text-neutral-500">{t("vocab.noTerms")}</li>
|
||||
)}
|
||||
{terms?.map((term) => (
|
||||
<li key={term.id} className="border-b py-1 text-sm">
|
||||
{labelText(term.labels, lang)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<form onSubmit={onAdd} className="space-y-2 border-t pt-3">
|
||||
<div className="text-sm font-medium">{t("vocab.addTerm")}</div>
|
||||
<LabelEditor value={labels} onChange={setLabels} />
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="term-uri">{t("labels.externalUri")}</Label>
|
||||
<Input
|
||||
id="term-uri"
|
||||
value={uri}
|
||||
onChange={(e) => setUri(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="text-xs text-red-600">
|
||||
{t("form.required")}
|
||||
</p>
|
||||
)}
|
||||
{addTerm.isError && (
|
||||
<p role="alert" className="text-xs text-red-600">
|
||||
{t("form.rejected")}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" size="sm" disabled={addTerm.isPending}>
|
||||
{t("vocab.addTerm")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user