From d6dc1c9b57f436ce2608460b60035e129a86f4c8 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Fri, 5 Jun 2026 15:32:48 +0200 Subject: [PATCH 1/5] feat(api): field-level set_fields 422 body (#28); enum-type SearchHitView.visibility (#38) Co-Authored-By: Claude Sonnet 4.6 --- crates/api/src/admin_objects.rs | 68 +++++++++++++++++++++++-------- crates/api/src/admin_search.rs | 1 + crates/api/src/openapi.rs | 1 + crates/api/tests/admin_objects.rs | 46 +++++++++++++++++++++ web/src/api/schema.d.ts | 15 +++++-- web/src/test/fixtures.ts | 2 +- 6 files changed, 111 insertions(+), 22 deletions(-) diff --git a/crates/api/src/admin_objects.rs b/crates/api/src/admin_objects.rs index 72ea003..c053d85 100644 --- a/crates/api/src/admin_objects.rs +++ b/crates/api/src/admin_objects.rs @@ -510,6 +510,15 @@ pub(crate) async fn create_field_definition( } } +/// Field-level rejection detail for `set_fields`, so the UI can highlight the field. +#[derive(Serialize, ToSchema)] +pub(crate) struct FieldErrorView { + /// The flexible-field key that was rejected. + pub field: String, + /// Machine code: "unknown" | "type_mismatch" | "unresolved". + pub code: String, +} + /// Replace an object's flexible-field values (validated against the registry). /// /// **Replace semantics:** the body is the *complete* desired field set. Omitting a key @@ -525,7 +534,7 @@ pub(crate) async fn create_field_definition( (status = 401), (status = 403), (status = 404, description = "Object not found"), - (status = 422, description = "Unknown field, type mismatch, or unresolved reference") + (status = 422, body = FieldErrorView, description = "A field was rejected") ) )] pub(crate) async fn set_fields( @@ -533,34 +542,57 @@ pub(crate) async fn set_fields( State(state): State, Path(id): Path, Json(values): Json>, -) -> Result { - let object_id = id.parse::().map_err(|_| StatusCode::NOT_FOUND)?; +) -> axum::response::Response { + use axum::response::IntoResponse; - let mut tx = state - .db - .pool() - .begin() - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let Ok(object_id) = id.parse::() else { + return StatusCode::NOT_FOUND.into_response(); + }; + + let mut tx = match state.db.pool().begin().await { + Ok(tx) => tx, + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; let result = db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await; match result { Ok(()) => { - tx.commit() - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if tx.commit().await.is_err() { + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } reindex(&state, object_id).await; - Ok(StatusCode::NO_CONTENT) + StatusCode::NO_CONTENT.into_response() } - Err(db::catalog::FieldError::ObjectNotFound) => Err(StatusCode::NOT_FOUND), - Err(db::catalog::FieldError::Db(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR), - Err(db::catalog::FieldError::UnknownField(_)) => Err(StatusCode::UNPROCESSABLE_ENTITY), - Err(db::catalog::FieldError::TypeMismatch { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY), - Err(db::catalog::FieldError::Unresolved { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY), + Err(db::catalog::FieldError::ObjectNotFound) => StatusCode::NOT_FOUND.into_response(), + Err(db::catalog::FieldError::Db(_)) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + Err(db::catalog::FieldError::UnknownField(field)) => ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(FieldErrorView { + field, + code: "unknown".to_owned(), + }), + ) + .into_response(), + Err(db::catalog::FieldError::TypeMismatch { field, .. }) => ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(FieldErrorView { + field, + code: "type_mismatch".to_owned(), + }), + ) + .into_response(), + Err(db::catalog::FieldError::Unresolved { field, .. }) => ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(FieldErrorView { + field, + code: "unresolved".to_owned(), + }), + ) + .into_response(), } } diff --git a/crates/api/src/admin_search.rs b/crates/api/src/admin_search.rs index 2245f9c..fc03aa0 100644 --- a/crates/api/src/admin_search.rs +++ b/crates/api/src/admin_search.rs @@ -28,6 +28,7 @@ pub(crate) struct SearchHitView { pub object_number: String, pub object_name: String, pub brief_description: Option, + #[schema(value_type = domain::Visibility)] pub visibility: String, pub snippet: Option, } diff --git a/crates/api/src/openapi.rs b/crates/api/src/openapi.rs index c176145..b625cba 100644 --- a/crates/api/src/openapi.rs +++ b/crates/api/src/openapi.rs @@ -53,6 +53,7 @@ use crate::{ admin_objects::FieldDefinitionView, admin_objects::NewFieldDefinitionRequest, admin_objects::CreatedField, + admin_objects::FieldErrorView, admin_vocab::VocabularyView, admin_vocab::NewVocabularyRequest, admin_vocab::NewTermRequest, diff --git a/crates/api/tests/admin_objects.rs b/crates/api/tests/admin_objects.rs index fe6a677..aa098f5 100644 --- a/crates/api/tests/admin_objects.rs +++ b/crates/api/tests/admin_objects.rs @@ -434,6 +434,52 @@ async fn set_fields_and_list_field_definitions(pool: PgPool) { assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY); } +#[sqlx::test(migrations = "../db/migrations")] +async fn set_fields_unknown_field_returns_field_detail(pool: PgPool) { + migrate_sessions(&db::Db::from_pool(pool.clone())) + .await + .unwrap(); + + seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await; + + let db = db::Db::from_pool(pool.clone()); + let mut tx = db.pool().begin().await.unwrap(); + + let id = catalog::create_object( + &mut tx, + AuditActor::System, + &obj("A-1", "amphora", Visibility::Draft), + ) + .await + .unwrap(); + + tx.commit().await.unwrap(); + + let app = build_app(state(pool)); + let cookie = login(&app, "ed@example.com", "pw-editor-123").await; + + let resp = app + .oneshot( + Request::builder() + .method("PUT") + .uri(format!("/api/admin/objects/{id}/fields")) + .header(header::COOKIE, &cookie) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"definitely_not_a_field":"x"}"#)) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY); + + let body: serde_json::Value = + serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap(); + + assert_eq!(body["field"], "definitely_not_a_field"); + assert_eq!(body["code"], "unknown"); +} + #[sqlx::test(migrations = "../db/migrations")] async fn create_requires_auth(pool: PgPool) { migrate_sessions(&db::Db::from_pool(pool.clone())) diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 3fc7b8e..4e49a0d 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -408,6 +408,13 @@ export interface components { required: boolean; vocabulary_id?: string | null; }; + /** @description Field-level rejection detail for `set_fields`, so the UI can highlight the field. */ + FieldErrorView: { + /** @description Machine code: "unknown" | "type_mismatch" | "unresolved". */ + code: string; + /** @description The flexible-field key that was rejected. */ + field: string; + }; LabelInput: { label: string; lang: string; @@ -513,7 +520,7 @@ export interface components { object_name: string; object_number: string; snippet?: string | null; - visibility: string; + visibility: components["schemas"]["Visibility"]; }; SearchResultsView: { /** @description Meilisearch's estimate of the total number of matches. */ @@ -1038,12 +1045,14 @@ export interface operations { }; content?: never; }; - /** @description Unknown field, type mismatch, or unresolved reference */ + /** @description A field was rejected */ 422: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["FieldErrorView"]; + }; }; }; }; diff --git a/web/src/test/fixtures.ts b/web/src/test/fixtures.ts index 1fcd269..3c34bc7 100644 --- a/web/src/test/fixtures.ts +++ b/web/src/test/fixtures.ts @@ -79,7 +79,7 @@ export const searchHits: SearchHitView[] = [ object_number: `N-${i + 2}`, object_name: `Object ${i + 2}`, brief_description: null, - visibility: "internal", + visibility: "internal" as const, snippet: null, })), ]; From 0c9db7bcdb607ae11018d013e6df6c2889dd9207 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Fri, 5 Jun 2026 15:39:49 +0200 Subject: [PATCH 2/5] feat(web): highlight the offending field on a set_fields 422 (#28) Co-Authored-By: Claude Sonnet 4.6 --- web/src/api/queries.ts | 18 ++++++++++++++++-- web/src/i18n/en.json | 2 +- web/src/i18n/sv.json | 2 +- web/src/objects/object-edit-form.test.tsx | 20 ++++++++++++++++++++ web/src/objects/object-edit-form.tsx | 22 ++++++++++++++++++---- web/src/objects/object-form.tsx | 14 +++++++++++++- web/src/objects/object-new-page.tsx | 7 ++++--- 7 files changed, 73 insertions(+), 12 deletions(-) diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index d53d672..5741123 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -10,6 +10,13 @@ export class HttpError extends Error { } } +export class FieldRejection extends Error { + constructor(public readonly field: string, public readonly code: string) { + super(`field rejected: ${field}`); + this.name = "FieldRejection"; + } +} + type UserView = components["schemas"]["UserView"]; type LoginRequest = components["schemas"]["LoginRequest"]; @@ -179,12 +186,19 @@ export function useSetFields() { return useMutation({ mutationFn: async ({ id, fields }: { id: string; fields: Record }) => { - const { response } = await api.PUT("/api/admin/objects/{id}/fields", { + const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", { params: { path: { id } }, body: fields as Record, }); - if (response.status !== 204) throw new Error("set fields failed"); + if (response.status === 204) return; + + if (response.status === 422 && error && typeof error === "object" && "field" in error) { + const detail = error as { field: string; code: string }; + throw new FieldRejection(detail.field, detail.code); + } + + throw new Error("set fields failed"); }, onSuccess: (_d, { id }) => { void qc.invalidateQueries({ queryKey: ["object", id] }); diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index b07cfce..8f798b5 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -5,7 +5,7 @@ "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object" }, "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", "flexibleHeading": "Catalogue fields" }, + "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", "confirmDelete": "Delete this object? This cannot be undone." }, "labels": { "label": "Label", "externalUri": "External URI (optional)" }, "vocab": { diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index b6c7567..725ab38 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -5,7 +5,7 @@ "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål" }, "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", "flexibleHeading": "Katalogfält" }, + "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", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras." }, "labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)" }, "vocab": { diff --git a/web/src/objects/object-edit-form.test.tsx b/web/src/objects/object-edit-form.test.tsx index 590597d..f5cee74 100644 --- a/web/src/objects/object-edit-form.test.tsx +++ b/web/src/objects/object-edit-form.test.tsx @@ -17,6 +17,26 @@ function tree() { ); } +test("edit: fields PUT 422 with field body -> field error message shown and field marked invalid", async () => { + server.use( + http.get("/api/admin/objects/:id", () => + HttpResponse.json({ ...amphora, fields: { inscription: "old" } }), + ), + http.put("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })), + http.put("/api/admin/objects/:id/fields", () => + HttpResponse.json({ field: "inscription", code: "type_mismatch" }, { status: 422 }), + ), + ); + + renderApp(tree(), { route: `/objects/${amphora.id}/edit` }); + + await screen.findByDisplayValue("Amphora"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + + const alerts = await screen.findAllByText(/inscription.*rejected/i); + expect(alerts.length).toBeGreaterThanOrEqual(2); +}); + test("edit: prefilled, save -> PUT core + PUT fields -> back to detail", async () => { let putCore: unknown; let putFields: unknown; diff --git a/web/src/objects/object-edit-form.tsx b/web/src/objects/object-edit-form.tsx index 63bb105..901eebe 100644 --- a/web/src/objects/object-edit-form.tsx +++ b/web/src/objects/object-edit-form.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { useObject, useUpdateObject, useSetFields } from "../api/queries"; +import { useObject, useUpdateObject, useSetFields, FieldRejection } from "../api/queries"; import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form"; export function ObjectEditForm() { @@ -15,8 +15,14 @@ export function ObjectEditForm() { const update = useUpdateObject(); const setFields = useSetFields(); + const locationState = location.state as { fieldsError?: boolean; fieldErrorKey?: string } | null; + const [error, setError] = useState( - (location.state as { fieldsError?: boolean } | null)?.fieldsError ? t("form.rejected") : null, + locationState?.fieldsError ? t("form.rejected") : null, + ); + + const [fieldErrorKey, setFieldErrorKey] = useState( + locationState?.fieldErrorKey ?? null, ); if (isLoading) return
; @@ -38,12 +44,19 @@ export function ObjectEditForm() { const onSubmit = async (values: ObjectFormValues) => { setError(null); + setFieldErrorKey(null); try { await update.mutateAsync({ id: id!, body: values.core }); await setFields.mutateAsync({ id: id!, fields: values.fields }); - } catch { - setError(t("form.rejected")); + } catch (e) { + if (e instanceof FieldRejection) { + setFieldErrorKey(e.field); + setError(t("form.fieldRejected", { field: e.field })); + } else { + setError(t("form.rejected")); + } + return; } @@ -55,6 +68,7 @@ export function ObjectEditForm() { mode="edit" defaults={defaults} formError={error} + fieldErrorKey={fieldErrorKey} onSubmit={onSubmit} onCancel={() => navigate(`/objects/${id}`)} /> diff --git a/web/src/objects/object-form.tsx b/web/src/objects/object-form.tsx index b450502..de84807 100644 --- a/web/src/objects/object-form.tsx +++ b/web/src/objects/object-form.tsx @@ -1,3 +1,4 @@ +import { useEffect } from "react"; import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; @@ -47,12 +48,14 @@ export function ObjectForm({ onSubmit, onCancel, formError, + fieldErrorKey, }: { mode: "create" | "edit"; defaults?: { core: ObjectCore; fields: Record }; onSubmit: (values: ObjectFormValues) => void; onCancel: () => void; formError?: string | null; + fieldErrorKey?: string | null; }) { const { t } = useTranslation(); @@ -68,6 +71,15 @@ export function ObjectForm({ const { register, handleSubmit, formState: { errors } } = form; + useEffect(() => { + if (fieldErrorKey) { + form.setError(`fields.${fieldErrorKey}` as never, { + type: "server", + message: t("form.fieldRejected", { field: fieldErrorKey }), + }); + } + }, [fieldErrorKey, form, t]); + const submit = handleSubmit((data) => { const fields = pruneFields(data.fields); @@ -149,7 +161,7 @@ export function ObjectForm({ {errors.fields?.[def.key] && (

- {t("form.required")} + {errors.fields[def.key]?.message ?? t("form.required")}

)}
diff --git a/web/src/objects/object-new-page.tsx b/web/src/objects/object-new-page.tsx index d6010bc..6f69c3a 100644 --- a/web/src/objects/object-new-page.tsx +++ b/web/src/objects/object-new-page.tsx @@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { ObjectForm, type ObjectFormValues } from "./object-form"; -import { useCreateObject, useSetFields } from "../api/queries"; +import { useCreateObject, useSetFields, FieldRejection } from "../api/queries"; export function ObjectNewPage() { const { t } = useTranslation(); @@ -32,8 +32,9 @@ export function ObjectNewPage() { if (Object.keys(values.fields).length > 0) { try { await setFields.mutateAsync({ id, fields: values.fields }); - } catch { - navigate(`/objects/${id}/edit`, { state: { fieldsError: true } }); + } catch (e) { + const fieldErrorKey = e instanceof FieldRejection ? e.field : undefined; + navigate(`/objects/${id}/edit`, { state: { fieldsError: true, fieldErrorKey } }); return; } } From 0a29127f7e6cfa8be0867f5d243c4f776401a99e Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Fri, 5 Jun 2026 15:43:35 +0200 Subject: [PATCH 3/5] fix(web): name the field in the edit banner on create->fields-error redirect (#28) Co-Authored-By: Claude Sonnet 4.6 --- web/src/objects/object-edit-form.tsx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/web/src/objects/object-edit-form.tsx b/web/src/objects/object-edit-form.tsx index 901eebe..4829973 100644 --- a/web/src/objects/object-edit-form.tsx +++ b/web/src/objects/object-edit-form.tsx @@ -17,9 +17,11 @@ export function ObjectEditForm() { const locationState = location.state as { fieldsError?: boolean; fieldErrorKey?: string } | null; - const [error, setError] = useState( - locationState?.fieldsError ? t("form.rejected") : null, - ); + const [error, setError] = useState(() => { + if (locationState?.fieldErrorKey) return t("form.fieldRejected", { field: locationState.fieldErrorKey }); + if (locationState?.fieldsError) return t("form.rejected"); + return null; + }); const [fieldErrorKey, setFieldErrorKey] = useState( locationState?.fieldErrorKey ?? null, From b4d71b0f801781c5870b14d2b7cb642496806459 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Fri, 5 Jun 2026 15:46:48 +0200 Subject: [PATCH 4/5] fix(web): VisibilityBadge typed to the union (#38); normalize localized_text to default language on save (#41) Co-Authored-By: Claude Sonnet 4.6 --- web/src/objects/object-form.test.tsx | 38 ++++++++++++++++++++++++++++ web/src/objects/object-form.tsx | 32 ++++++----------------- web/src/objects/prune-fields.ts | 31 +++++++++++++++++++++++ web/src/objects/visibility-badge.tsx | 9 ++++--- 4 files changed, 83 insertions(+), 27 deletions(-) create mode 100644 web/src/objects/prune-fields.ts diff --git a/web/src/objects/object-form.test.tsx b/web/src/objects/object-form.test.tsx index a53c91c..476dbfb 100644 --- a/web/src/objects/object-form.test.tsx +++ b/web/src/objects/object-form.test.tsx @@ -3,6 +3,7 @@ import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { renderApp } from "../test/render"; import { ObjectForm } from "./object-form"; +import { pruneFields } from "./prune-fields"; test("create mode: shows visibility (draft/internal only) and submits assembled values", async () => { const onSubmit = vi.fn(); @@ -47,3 +48,40 @@ test("edit mode: no visibility control, save button, prefilled values", async () expect(screen.queryByLabelText(/visibility/i)).not.toBeInTheDocument(); expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument(); }); + +test("pruneFields: localized_text keeps only the default-language key, other object fields unaffected", () => { + const localizedTextKeys = new Set(["title_ml"]); + + const result = pruneFields( + { title_ml: { en: "Old", sv: "Ny" }, other: "x" }, + localizedTextKeys, + "sv", + ); + + expect(result).toEqual({ title_ml: { sv: "Ny" }, other: "x" }); + expect(Object.keys(result.title_ml as Record)).not.toContain("en"); +}); + +test("pruneFields: localized_text with only non-default lang produces empty object (key omitted)", () => { + const localizedTextKeys = new Set(["title_ml"]); + + const result = pruneFields( + { title_ml: { en: "English only" } }, + localizedTextKeys, + "sv", + ); + + expect(result).toEqual({}); +}); + +test("pruneFields: non-localized_text object fields are preserved as-is", () => { + const localizedTextKeys = new Set(["title_ml"]); + + const result = pruneFields( + { nested_obj: { a: "1", b: "2" } }, + localizedTextKeys, + "sv", + ); + + expect(result).toEqual({ nested_obj: { a: "1", b: "2" } }); +}); diff --git a/web/src/objects/object-form.tsx b/web/src/objects/object-form.tsx index de84807..ba16cd0 100644 --- a/web/src/objects/object-form.tsx +++ b/web/src/objects/object-form.tsx @@ -3,7 +3,9 @@ import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { useFieldDefinitions } from "../api/queries"; +import { useConfig } from "../config/config-context"; import { FieldInput } from "./field-input"; +import { pruneFields } from "./prune-fields"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -58,9 +60,14 @@ export function ObjectForm({ fieldErrorKey?: string | null; }) { const { t } = useTranslation(); + const { default_language } = useConfig(); const { data: definitions } = useFieldDefinitions(); + const localizedTextKeys = new Set( + (definitions ?? []).filter((d) => d.data_type === "localized_text").map((d) => d.key), + ); + const form = useForm({ defaultValues: { core: defaults?.core ?? EMPTY_CORE, @@ -81,7 +88,7 @@ export function ObjectForm({ }, [fieldErrorKey, form, t]); const submit = handleSubmit((data) => { - const fields = pruneFields(data.fields); + const fields = pruneFields(data.fields, localizedTextKeys, default_language); onSubmit( mode === "create" @@ -182,26 +189,3 @@ export function ObjectForm({ ); } -function pruneFields(fields: Record): Record { - const out: Record = {}; - - for (const [key, value] of Object.entries(fields)) { - if (value === undefined || value === null || value === "") continue; - - if (typeof value === "object" && !Array.isArray(value)) { - const inner = Object.fromEntries( - Object.entries(value as Record).filter( - ([, v]) => v !== undefined && v !== null && v !== "", - ), - ); - - if (Object.keys(inner).length > 0) out[key] = inner; - - continue; - } - - out[key] = value; - } - - return out; -} diff --git a/web/src/objects/prune-fields.ts b/web/src/objects/prune-fields.ts new file mode 100644 index 0000000..fe1f196 --- /dev/null +++ b/web/src/objects/prune-fields.ts @@ -0,0 +1,31 @@ +export function pruneFields( + fields: Record, + localizedTextKeys: Set, + defaultLang: string, +): Record { + const out: Record = {}; + + for (const [key, value] of Object.entries(fields)) { + if (value === undefined || value === null || value === "") continue; + + if (typeof value === "object" && !Array.isArray(value)) { + const map = value as Record; + // Single-language authoring: a localized_text value keeps only the default lang. + const entries = localizedTextKeys.has(key) + ? Object.entries(map).filter(([lang]) => lang === defaultLang) + : Object.entries(map); + + const inner = Object.fromEntries( + entries.filter(([, v]) => v !== undefined && v !== null && v !== ""), + ); + + if (Object.keys(inner).length > 0) out[key] = inner; + + continue; + } + + out[key] = value; + } + + return out; +} diff --git a/web/src/objects/visibility-badge.tsx b/web/src/objects/visibility-badge.tsx index dd9b6a9..40c398f 100644 --- a/web/src/objects/visibility-badge.tsx +++ b/web/src/objects/visibility-badge.tsx @@ -1,18 +1,21 @@ import { useTranslation } from "react-i18next"; +import type { components } from "../api/schema"; import { Badge } from "@/components/ui/badge"; -const STYLES: Record = { +type Visibility = components["schemas"]["Visibility"]; + +const STYLES: Record = { draft: "bg-neutral-100 text-neutral-600", internal: "bg-amber-100 text-amber-800", public: "bg-green-100 text-green-800", }; -export function VisibilityBadge({ visibility }: { visibility: string }) { +export function VisibilityBadge({ visibility }: { visibility: Visibility }) { const { t } = useTranslation(); return ( - + {t(`visibility.${visibility}`)} ); From e6fc3eaf2c829070043734ad2e2ad023b88ff808 Mon Sep 17 00:00:00 2001 From: Anders Olsson Date: Fri, 5 Jun 2026 15:50:40 +0200 Subject: [PATCH 5/5] build(web): pin pnpm via packageManager + align CI to pnpm 11 (#26) Co-Authored-By: Claude Sonnet 4.6 --- .gitea/workflows/ci.yaml | 2 +- web/package.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index ba217a4..6eed5d3 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -15,7 +15,7 @@ jobs: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 with: - version: 9 + version: 11 - uses: actions/setup-node@v4 with: node-version: 20 diff --git a/web/package.json b/web/package.json index a9dc0bb..e2be0ee 100644 --- a/web/package.json +++ b/web/package.json @@ -2,6 +2,7 @@ "name": "web", "private": true, "version": "0.0.0", + "packageManager": "pnpm@11.5.1", "type": "module", "scripts": { "dev": "vite",