From 2e38af565ab945b3b558287ccb92aab42d9ff9ff Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Sun, 7 Jun 2026 11:32:17 +0200 Subject: [PATCH 1/2] =?UTF-8?q?feat(web):=20FlexibleFieldValue=20=E2=80=94?= =?UTF-8?q?=20resolve=20term/authority/localized=20field=20values=20(#45)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- web/src/i18n/en.json | 3 +- web/src/i18n/sv.json | 3 +- .../objects/flexible-field-value.stories.tsx | 62 +++++++++++ web/src/objects/flexible-field-value.test.tsx | 54 ++++++++++ web/src/objects/flexible-field-value.tsx | 102 ++++++++++++++++++ 5 files changed, 222 insertions(+), 2 deletions(-) create mode 100644 web/src/objects/flexible-field-value.stories.tsx create mode 100644 web/src/objects/flexible-field-value.test.tsx create mode 100644 web/src/objects/flexible-field-value.tsx diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 607e2da..3a03e1a 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -1,8 +1,9 @@ { "app": { "name": "Collection" }, + "common": { "yes": "Yes", "no": "No" }, "nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" }, "auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" }, - "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" } }, + "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" }, "unknownRef": "(unknown)" }, "fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" }, "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", "fieldRejected": "The field \"{{field}}\" was rejected — check its value", "flexibleHeading": "Catalogue fields" }, diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index f309267..6c6e143 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -1,8 +1,9 @@ { "app": { "name": "Samling" }, + "common": { "yes": "Ja", "no": "Nej" }, "nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "collapseSidebar": "Fäll ihop sidofältet", "expandSidebar": "Fäll ut sidofältet" }, "auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" }, - "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" } }, + "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" }, "unknownRef": "(okänd)" }, "fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" }, "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", "fieldRejected": "Fältet \"{{field}}\" avvisades — kontrollera värdet", "flexibleHeading": "Katalogfält" }, diff --git a/web/src/objects/flexible-field-value.stories.tsx b/web/src/objects/flexible-field-value.stories.tsx new file mode 100644 index 0000000..7454b3b --- /dev/null +++ b/web/src/objects/flexible-field-value.stories.tsx @@ -0,0 +1,62 @@ +import type { Meta, StoryObj } from '@storybook/react-vite' +import { expect } from 'storybook/test' + +import { FlexibleFieldValue } from './flexible-field-value' +import { fieldDefinitions } from '../test/fixtures' + +const def = (key: string) => fieldDefinitions.find((d) => d.key === key)! + +const meta = { + component: FlexibleFieldValue, + tags: ['ai-generated'], +} satisfies Meta + +export default meta +type Story = StoryObj + +export const Term: Story = { + args: { def: def('material'), value: 't-bronze', lang: 'en' }, + play: async ({ canvas }) => { + await expect(await canvas.findByText('Bronze')).toBeVisible() + }, +} + +export const Authority: Story = { + args: { def: def('maker'), value: 'a-ada', lang: 'en' }, + play: async ({ canvas }) => { + await expect(await canvas.findByText('Ada Lovelace')).toBeVisible() + }, +} + +export const LocalizedText: Story = { + args: { + def: def('title_ml'), + value: { sv: 'Brons-amfora', en: 'Bronze amphora' }, + lang: 'sv', + }, + play: async ({ canvas }) => { + await expect(canvas.getByText('Brons-amfora')).toBeVisible() + }, +} + +export const Date: Story = { + args: { def: def('made_on'), value: '2024-01-05', lang: 'en' }, + play: async ({ canvas }) => { + await expect(canvas.queryByText('2024-01-05')).not.toBeInTheDocument() + await expect(canvas.getByText(/Jan.*5.*2024/)).toBeVisible() + }, +} + +export const Boolean: Story = { + args: { def: def('is_fragment'), value: true, lang: 'en' }, + play: async ({ canvas }) => { + await expect(canvas.getByText('Yes')).toBeVisible() + }, +} + +export const UnknownRef: Story = { + args: { def: def('material'), value: 't-missing', lang: 'en' }, + play: async ({ canvas }) => { + await expect(await canvas.findByText(/t-missing\s*\(unknown\)/)).toBeVisible() + }, +} diff --git a/web/src/objects/flexible-field-value.test.tsx b/web/src/objects/flexible-field-value.test.tsx new file mode 100644 index 0000000..3a1ff98 --- /dev/null +++ b/web/src/objects/flexible-field-value.test.tsx @@ -0,0 +1,54 @@ +import { expect, test } from "vitest"; +import { screen } from "@testing-library/react"; + +import { renderApp } from "../test/render"; +import { FlexibleFieldValue } from "./flexible-field-value"; +import { fieldDefinitions } from "../test/fixtures"; + +function def(key: string) { + return fieldDefinitions.find((d) => d.key === key)!; +} + +test("term id resolves to its label", async () => { + renderApp(); + + expect(await screen.findByText("Bronze")).toBeInTheDocument(); +}); + +test("authority id resolves to its label", async () => { + renderApp(); + + expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument(); +}); + +test("unknown term id renders (unknown)", async () => { + renderApp(); + + expect(await screen.findByText(/t-missing\s*\(unknown\)/)).toBeInTheDocument(); +}); + +test("localized_text picks the active language string", () => { + renderApp( + , + ); + + expect(screen.getByText("Brons-amfora")).toBeInTheDocument(); + expect(screen.queryByText("Bronze amphora")).not.toBeInTheDocument(); +}); + +test("date is formatted, not the raw ISO string", () => { + renderApp(); + + expect(screen.queryByText("2024-01-05")).not.toBeInTheDocument(); + expect(screen.getByText(/Jan.*5.*2024/)).toBeInTheDocument(); +}); + +test("boolean true renders Yes", () => { + renderApp(); + + expect(screen.getByText("Yes")).toBeInTheDocument(); +}); diff --git a/web/src/objects/flexible-field-value.tsx b/web/src/objects/flexible-field-value.tsx new file mode 100644 index 0000000..823e0d4 --- /dev/null +++ b/web/src/objects/flexible-field-value.tsx @@ -0,0 +1,102 @@ +import { useTranslation } from "react-i18next"; + +import type { components } from "../api/schema"; +import { useTerms, useAuthorities } from "../api/queries"; +import { labelText } from "../lib/labels"; + +type FieldDefinitionView = components["schemas"]["FieldDefinitionView"]; + +/** Renders one flexible field value as human-readable text, resolving term/authority ids + * to labels and localized_text to the active language. */ +export function FlexibleFieldValue({ + def, + value, + lang, +}: { + def: FieldDefinitionView; + value: unknown; + lang: string; +}) { + switch (def.data_type) { + case "term": + return ; + case "authority": + return ; + case "localized_text": + return <>{pickLocalized(value, lang)}; + case "date": + return <>{formatDate(value, lang)}; + case "boolean": + return ; + default: + return <>{value == null ? "—" : String(value)}; + } +} + +function TermValue({ + vocabularyId, + value, + lang, +}: { + vocabularyId: string | null; + value: unknown; + lang: string; +}) { + const { t } = useTranslation(); + const { data: terms, isLoading } = useTerms(vocabularyId ?? undefined); + + if (typeof value !== "string") return <>—; + const term = terms?.find((x) => x.id === value); + if (term) return <>{labelText(term.labels, lang)}; + if (isLoading) return ; + return ( + + {value} {t("objects.unknownRef")} + + ); +} + +function AuthorityValue({ + kind, + value, + lang, +}: { + kind: string | null; + value: unknown; + lang: string; +}) { + const { t } = useTranslation(); + const { data: authorities, isLoading } = useAuthorities(kind ?? undefined); + + if (typeof value !== "string") return <>—; + const authority = authorities?.find((x) => x.id === value); + if (authority) return <>{labelText(authority.labels, lang)}; + if (isLoading) return ; + return ( + + {value} {t("objects.unknownRef")} + + ); +} + +function BooleanValue({ value }: { value: unknown }) { + const { t } = useTranslation(); + return <>{value ? t("common.yes") : t("common.no")}; +} + +function pickLocalized(value: unknown, lang: string): string { + if (value && typeof value === "object" && !Array.isArray(value)) { + const map = value as Record; + return map[lang] ?? map.en ?? Object.values(map)[0] ?? "—"; + } + 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); +} From 03d5b59b48c8116ed2ad5ad1c7e4e7d82753c7f0 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Sun, 7 Jun 2026 11:38:41 +0200 Subject: [PATCH 2/2] feat(web): readable, grouped object detail (labels, placeholders, actions toolbar) (#45) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- web/src/i18n/en.json | 2 +- web/src/i18n/sv.json | 2 +- web/src/lib/format-date.ts | 8 ++ web/src/objects/flexible-field-value.tsx | 10 +-- web/src/objects/object-detail.test.tsx | 93 ++++++++++++++++------ web/src/objects/object-detail.tsx | 98 ++++++++++++++++-------- 6 files changed, 148 insertions(+), 65 deletions(-) create mode 100644 web/src/lib/format-date.ts diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 3a03e1a..6ff7ab3 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -4,7 +4,7 @@ "nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" }, "auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" }, "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" }, "unknownRef": "(unknown)" }, - "fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" }, + "fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility" }, "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", "fieldRejected": "The field \"{{field}}\" was rejected — check its value", "flexibleHeading": "Catalogue fields" }, "actions": { "edit": "Edit", "delete": "Delete", "rename": "Rename", "save": "Save", "closeDetail": "Close detail", "confirmDelete": "Delete this object? This cannot be undone.", "confirmDeleteTerm": "Delete this term? This cannot be undone.", "confirmDeleteAuthority": "Delete this authority? This cannot be undone.", "confirmDeleteField": "Delete this field definition? This cannot be undone.", "confirmDeleteVocabulary": "Delete this vocabulary? This cannot be undone.", "inUse": "Can't delete — used by {{count}} object(s). Clear those fields first." }, diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index 6c6e143..74670d7 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -4,7 +4,7 @@ "nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "collapseSidebar": "Fäll ihop sidofältet", "expandSidebar": "Fäll ut sidofältet" }, "auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" }, "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" }, "unknownRef": "(okänd)" }, - "fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" }, + "fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet" }, "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", "fieldRejected": "Fältet \"{{field}}\" avvisades — kontrollera värdet", "flexibleHeading": "Katalogfält" }, "actions": { "edit": "Redigera", "delete": "Ta bort", "rename": "Byt namn", "save": "Spara", "closeDetail": "Stäng detalj", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras.", "confirmDeleteTerm": "Ta bort denna term? Detta kan inte ångras.", "confirmDeleteAuthority": "Ta bort denna auktoritet? Detta kan inte ångras.", "confirmDeleteField": "Ta bort denna fältdefinition? Detta kan inte ångras.", "confirmDeleteVocabulary": "Ta bort denna vokabulär? Detta kan inte ångras.", "inUse": "Kan inte ta bort — används av {{count}} föremål. Rensa de fälten först." }, diff --git a/web/src/lib/format-date.ts b/web/src/lib/format-date.ts new file mode 100644 index 0000000..f6551b5 --- /dev/null +++ b/web/src/lib/format-date.ts @@ -0,0 +1,8 @@ +/** 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); +} diff --git a/web/src/objects/flexible-field-value.tsx b/web/src/objects/flexible-field-value.tsx index 823e0d4..afc6d7d 100644 --- a/web/src/objects/flexible-field-value.tsx +++ b/web/src/objects/flexible-field-value.tsx @@ -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); -} diff --git a/web/src/objects/object-detail.test.tsx b/web/src/objects/object-detail.test.tsx index 4e9631a..228ae36 100644 --- a/web/src/objects/object-detail.test.tsx +++ b/web/src/objects/object-detail.test.tsx @@ -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, 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" }); diff --git a/web/src/objects/object-detail.tsx b/web/src/objects/object-detail.tsx index 3d18fc8..179a18f 100644 --- a/web/src/objects/object-detail.tsx +++ b/web/src/objects/object-detail.tsx @@ -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 (
{label}
-
{value}
+
{empty ? "—" : value}
); } @@ -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 (

{object.object_name}

- - {t("actions.edit")} - - +
+ + {t("actions.edit")} + + +
@@ -70,27 +99,34 @@ export function ObjectDetail() { - - {flexible.length > 0 && ( -
-
- {t("fieldsLabels.flexible")} -
- {flexible.map(([key, value]) => ( + + {groups.map((g) => ( +
+
{g.group}
+ {g.defs.map((d) => ( } /> ))} + {g.group === other && + orphans.map(([key, value]) => ( + + {typeof value === "object" ? JSON.stringify(value) : String(value)} + + } + /> + ))}
- )} + ))}
);