feat(web): readable, grouped object detail (labels, placeholders, actions toolbar) (#45)

Refactor object-detail.tsx to resolve term/authority ids to labels via
FlexibleFieldValue, group flexible fields by def.group in definition order
(ungrouped → trailing "Other"), always show core fields with "—" placeholders,
and move Edit (button-styled Link) + Delete into a right-aligned toolbar.

Move formatDate into lib/format-date.ts so the component module no longer
co-exports a non-component (clears the react-refresh/only-export-components
warning); both flexible-field-value.tsx and object-detail.tsx import it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-07 11:38:41 +02:00
parent 2e38af565a
commit 03d5b59b48
6 changed files with 148 additions and 65 deletions
+1 -9
View File
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useTerms, useAuthorities } from "../api/queries";
import { labelText } from "../lib/labels";
import { formatDate } from "../lib/format-date";
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
@@ -91,12 +92,3 @@ function pickLocalized(value: unknown, lang: string): string {
}
return value == null ? "—" : String(value);
}
/** Formats a date-only ISO string (YYYY-MM-DD) for display in the active locale.
* Parses as local midnight so a date-only value isn't shifted a day by tz. */
export function formatDate(value: unknown, lang: string): string {
if (typeof value !== "string") return value == null ? "—" : String(value);
const date = new Date(`${value}T00:00:00`);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(lang, { dateStyle: "medium" }).format(date);
}
+70 -23
View File
@@ -1,9 +1,10 @@
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { screen, within } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { Routes, Route } from "react-router-dom";
import { server } from "../test/server";
import { renderApp } from "../test/render";
import { amphora } from "../test/fixtures";
import { ObjectDetail } from "./object-detail";
function tree() {
@@ -14,35 +15,81 @@ function tree() {
);
}
test("renders inventory-minimum fields, flexible values and visibility", async () => {
// override so the object carries a flexible field value (schema types fields as
// Record<string,never>, so return a plain object literal here)
server.use(
http.get("/api/admin/objects/:id", () =>
HttpResponse.json({
id: "11111111-1111-1111-1111-111111111111",
object_number: "LM-0042",
object_name: "Amphora",
number_of_objects: 1,
brief_description: "Storage jar",
current_location: "Vault 3",
current_owner: null,
recorder: null,
recording_date: null,
visibility: "public",
fields: { material: "Bronze" },
}),
),
);
renderApp(tree(), { route: "/objects/11111111-1111-1111-1111-111111111111" });
// An object seeded with a term, a localized_text and a date flexible value.
// `inscription` belongs to the "Description" group; the rest are ungrouped
// ("Other"). recording_date is null to exercise the empty-core placeholder.
const detailed = {
...amphora,
recording_date: null,
fields: {
inscription: "AVE",
material: "t-bronze",
title_ml: { sv: "Brons-amfora", en: "Bronze amphora" },
made_on: "2024-01-05",
// No matching field definition — its definition was removed after the value
// was set. Must still render (muted), keyed by its raw key.
legacy_note: "orphaned value",
},
};
function renderDetail() {
server.use(http.get("/api/admin/objects/:id", () => HttpResponse.json(detailed)));
return renderApp(tree(), { route: `/objects/${detailed.id}` });
}
test("renders inventory-minimum fields and visibility", async () => {
renderDetail();
expect(await screen.findByText("Amphora")).toBeInTheDocument();
expect(screen.getByText("Vault 3")).toBeInTheDocument();
expect(screen.getByText("Bronze")).toBeInTheDocument(); // flexible field value
// "Public" appears in both the VisibilityBadge and the PublishControl stepper;
// scope the assertion to the badge element to avoid ambiguity.
expect(document.querySelector("[data-slot='badge']")).toHaveTextContent("Public");
});
test("resolves a term id to its label, not the UUID", async () => {
renderDetail();
expect(await screen.findByText("Bronze")).toBeInTheDocument();
expect(screen.queryByText("t-bronze")).not.toBeInTheDocument();
});
test("renders a localized_text value as a string, not JSON", async () => {
renderDetail();
// i18n falls back to "en", so the en variant is picked, never the JSON object.
expect(await screen.findByText("Bronze amphora")).toBeInTheDocument();
expect(screen.queryByText(/\{.*"en".*\}/)).not.toBeInTheDocument();
});
test("groups flexible fields under subheadings in definition order", async () => {
renderDetail();
await screen.findByText("Bronze");
// "Description" (the inscription def's group) precedes the trailing "Other" group.
const description = screen.getByText("Description");
const other = screen.getByText("Other");
expect(description.compareDocumentPosition(other)).toBe(
Node.DOCUMENT_POSITION_FOLLOWING,
);
});
test("renders an orphaned field key (no definition) with its raw key and value", async () => {
renderDetail();
await screen.findByText("Bronze");
// The key itself is the label, since there is no definition to localize it.
expect(screen.getByText("legacy_note")).toBeInTheDocument();
expect(screen.getByText("orphaned value")).toBeInTheDocument();
});
test("an empty core field shows a placeholder dash", async () => {
renderDetail();
const recordingDate = (await screen.findByText("Recording date")).parentElement;
expect(within(recordingDate!).getByText("—")).toBeInTheDocument();
});
test("the Edit link points to the object's edit route", async () => {
renderDetail();
const edit = await screen.findByRole("link", { name: "Edit" });
expect(edit).toHaveAttribute("href", `/objects/${detailed.id}/edit`);
});
test("shows a not-found state for a missing object", async () => {
server.use(http.get("/api/admin/objects/:id", () => new HttpResponse(null, { status: 404 })));
renderApp(tree(), { route: "/objects/does-not-exist" });
+67 -31
View File
@@ -1,25 +1,26 @@
import type { ReactNode } from "react";
import { Link, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useObject, useFieldDefinitions } from "../api/queries";
import { formatDate } from "../lib/format-date";
import { DeleteObjectDialog } from "./delete-object-dialog";
import { FlexibleFieldValue } from "./flexible-field-value";
import { PublishControl } from "./publish-control";
import { VisibilityBadge } from "./visibility-badge";
import { buttonVariants } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
function Field({
label,
value,
}: {
label: string;
value: string | number | null | undefined;
}) {
if (value === null || value === undefined || value === "") return null;
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
function Field({ label, value }: { label: string; value: ReactNode }) {
const empty = value === null || value === undefined || value === "";
return (
<div className="border-b py-2">
<div className="text-xs uppercase tracking-wide text-neutral-400">{label}</div>
<div className="text-sm text-neutral-900">{value}</div>
<div className="text-sm text-neutral-900">{empty ? "—" : value}</div>
</div>
);
}
@@ -52,17 +53,45 @@ export function ObjectDetail() {
return byLang ?? byEnglish ?? key;
};
const flexible = Object.entries(object.fields);
// Iterate definitions (stable order) and keep only defs whose key has a
// non-null value on this object, grouped by def.group. Ungrouped defs fall
// into a trailing "Other" group.
const other = t("fields.other");
const present = (definitions ?? []).filter((d) => object.fields[d.key] != null);
const groups: { group: string; defs: FieldDefinitionView[] }[] = [];
for (const def of present) {
const isOther = !def.group?.trim();
const group = isOther ? other : def.group!;
let bucket = groups.find((x) => x.group === group);
if (!bucket) {
bucket = { group, defs: [] };
groups.push(bucket);
}
bucket.defs.push(def);
}
// Defensive: a key present in object.fields with no matching definition (e.g. a
// definition removed after the value was set). Render it muted under "Other"
// rather than silently dropping data; the raw key is the label.
const definedKeys = new Set((definitions ?? []).map((d) => d.key));
const orphans = Object.entries(object.fields).filter(
([key, value]) => !definedKeys.has(key) && value != null,
);
if (orphans.length > 0 && !groups.some((g) => g.group === other)) {
groups.push({ group: other, defs: [] });
}
groups.sort((a, b) => Number(a.group === other) - Number(b.group === other));
return (
<div className="overflow-auto p-4">
<div className="mb-4 flex items-center gap-3">
<h2 className="text-xl font-semibold">{object.object_name}</h2>
<VisibilityBadge visibility={object.visibility} />
<Link to={`/objects/${object.id}/edit`} className="text-sm font-medium text-indigo-600">
{t("actions.edit")}
</Link>
<DeleteObjectDialog id={object.id} />
<div className="ml-auto flex items-center gap-2">
<Link to={`/objects/${object.id}/edit`} className={buttonVariants({ size: "sm" })}>
{t("actions.edit")}
</Link>
<DeleteObjectDialog id={object.id} />
</div>
</div>
<Field label={t("fieldsLabels.objectNumber")} value={object.object_number} />
<Field label={t("fieldsLabels.count")} value={object.number_of_objects} />
@@ -70,27 +99,34 @@ export function ObjectDetail() {
<Field label={t("fieldsLabels.currentLocation")} value={object.current_location} />
<Field label={t("fieldsLabels.currentOwner")} value={object.current_owner} />
<Field label={t("fieldsLabels.recorder")} value={object.recorder} />
<Field label={t("fieldsLabels.recordingDate")} value={object.recording_date} />
{flexible.length > 0 && (
<div className="mt-4">
<div className="mb-1 text-xs font-medium uppercase text-neutral-500">
{t("fieldsLabels.flexible")}
</div>
{flexible.map(([key, value]) => (
<Field
label={t("fieldsLabels.recordingDate")}
value={object.recording_date ? formatDate(object.recording_date, lang) : null}
/>
{groups.map((g) => (
<div key={g.group} className="mt-4">
<div className="mb-1 text-xs font-medium uppercase text-neutral-500">{g.group}</div>
{g.defs.map((d) => (
<Field
key={key}
label={labelFor(key)}
value={
value == null
? null
: typeof value === "object"
? JSON.stringify(value)
: String(value)
}
key={d.key}
label={labelFor(d.key)}
value={<FlexibleFieldValue def={d} value={object.fields[d.key]} lang={lang} />}
/>
))}
{g.group === other &&
orphans.map(([key, value]) => (
<Field
key={key}
label={key}
value={
<span className="text-neutral-400">
{typeof value === "object" ? JSON.stringify(value) : String(value)}
</span>
}
/>
))}
</div>
)}
))}
<PublishControl object={object} />
</div>
);