Compare commits

..

11 Commits

Author SHA1 Message Date
logaritmisk 1bfa44a0ed merge: toast notifications + consistent mutation feedback (#47)
CI / web (push) Has been cancelled
Base UI toast region bridged to the QueryClient via an out-of-React manager; global
MutationCache gives every mutation feedback (opt-in success + catch-all type-aware
error toast, suppressible where errors show inline). Inline 422/409 UX preserved.
Closes #47.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 13:47:05 +02:00
logaritmisk 303c986d40 chore(web): raise bundle budget 180→250 KB gz (#47)
Generous ceiling so the budget stops blocking per-feature work (this is the third
raise in three frontend milestones) while still catching gross regressions. A
vendor-split / bundle audit can revisit always-loaded weight later.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 13:35:35 +02:00
logaritmisk fcad638549 feat(web): per-mutation success/error toast metadata (#47)
Declare meta on all 18 mutation hooks: meta.successMessage (toast.* key)
on every discrete user action, meta.suppressErrorToast where the consuming
component already renders the error inline. Corrected useUpdateFieldDefinition
to suppress (FieldForm renders update.isError as form.rejected inline).

Add an RTL+MSW integration test wiring the real MutationCache via
makeQueryClient() + ToastRegion: success toast, catch-all error toast, and
suppressed-no-toast. Tidy the toast Close aria-label to t("common.close")
with en/sv parity.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:55:54 +02:00
logaritmisk 604d4f6005 feat(web): Base UI toast region + global mutation feedback wiring (#47)
Add a module-scope Base UI toast manager bridged to the QueryClient so
every mutation can give consistent feedback. A MutationCache (extracted
into a makeQueryClient() factory for test reuse) emits a catch-all,
type-aware error toast (unless meta.suppressErrorToast) and an opt-in
success toast (meta.successMessage), reading mutation.meta + i18n.t
outside React. meta is type-checked via a react-query Register
augmentation. ToastRegion is mounted app-wide in main.tsx. Adds a toast
i18n namespace (en/sv parity) and a validated story.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:46:26 +02:00
logaritmisk 63bfff417b docs(plans): toast notifications + mutation feedback (#47)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:30:30 +02:00
logaritmisk 8eb527957b docs(specs): toast notifications + consistent mutation feedback (#47)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:09:09 +02:00
logaritmisk e2ae093ed8 merge: object detail readability — resolve labels, group fields (#45)
Object detail resolves term/authority ids to labels, localized_text to the active
language, dates locale-formatted; flexible fields grouped by definition; core fields
always shown with placeholders; Edit/Delete actions toolbar. Closes #45.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 11:54:53 +02:00
logaritmisk 03d5b59b48 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>
2026-06-07 11:44:35 +02:00
logaritmisk 2e38af565a feat(web): FlexibleFieldValue — resolve term/authority/localized field values (#45)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 11:32:17 +02:00
logaritmisk 7258b3fd03 docs(plans): object detail readability (#45)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 11:24:58 +02:00
logaritmisk 6ec31b6c51 docs(specs): object detail readability — resolve labels, group fields (#45)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 10:54:41 +02:00
21 changed files with 1322 additions and 64 deletions
@@ -0,0 +1,185 @@
# Object Detail Readability — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Make `web/src/objects/object-detail.tsx` readable: resolve term/authority ids → labels and `localized_text` → the active-language string, group flexible fields by `def.group` in definition order, and polish (date formatting, empty-core "—", an Edit/Delete actions toolbar).
**Architecture:** A new per-field `FlexibleFieldValue` component switches on `def.data_type` and resolves via the existing `useTerms`/`useAuthorities` + `labelText` (one hook call per component instance → rules-of-hooks safe; react-query dedups repeated vocabularies). `object-detail.tsx` iterates `definitions` (stable order) for grouping and renders core fields with placeholders. Frontend-only, no backend change.
**Tech Stack:** React 19 + TS + pnpm, react-i18next, TanStack Query, Vitest+RTL+MSW, Storybook 10.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; component source double-quote+semicolon, stories single-quote+no-semicolon; en/sv parity; no codename; tests query portals via `within(document.body)` (n/a here). `check:size` budget 180 KB gz (this is frontend-only, ~no bundle change).
**Spec:** `docs/superpowers/specs/2026-06-07-object-detail-readability-design.md`
**Facts:** flexible values in `object.fields` are: term/authority = UUID **string**, localized_text = `{lang: text}` **object**, others = primitive. `FieldDefinitionView` has `data_type`/`vocabulary_id`/`authority_kind`/`group`/`labels`/`key`. Helpers: `labelText(labels, lang)` (`web/src/lib/labels.ts`); hooks `useTerms(vocabularyId)` / `useAuthorities(kind)` (`web/src/api/queries.ts`). Core labels exist under `fieldsLabels.*`. `buttonVariants` is exported from `@/components/ui/button`. Test fixtures (`web/src/test/fixtures.ts`) have `fieldDefinitions` (covering all types), `materialTerms`, `personAuthorities`.
---
## Task 1: `FlexibleFieldValue` component + story + unit test
**Files:** create `web/src/objects/flexible-field-value.tsx`, `flexible-field-value.stories.tsx`, `flexible-field-value.test.tsx`. Modify `web/src/i18n/{en,sv}.json`.
- [ ] **Step 1: i18n keys.** Add to **both** locales: a `common` block `{ "yes": "Yes"/"Ja", "no": "No"/"Nej" }` and `objects.unknownRef` ("(unknown)" / "(okänd)").
- [ ] **Step 2: Write the component** `web/src/objects/flexible-field-value.tsx`:
```tsx
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 <TermValue vocabularyId={def.vocabulary_id} value={value} lang={lang} />;
case "authority":
return <AuthorityValue kind={def.authority_kind} value={value} lang={lang} />;
case "localized_text":
return <>{pickLocalized(value, lang)}</>;
case "date":
return <>{formatDate(value, lang)}</>;
case "boolean":
return <BooleanValue value={value} />;
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 <span className="text-neutral-400"></span>;
return <span className="text-neutral-400">{value} {t("objects.unknownRef")}</span>;
}
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 <span className="text-neutral-400"></span>;
return <span className="text-neutral-400">{value} {t("objects.unknownRef")}</span>;
}
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<string, string>;
return map[lang] ?? map.en ?? Object.values(map)[0] ?? "—";
}
return value == null ? "—" : String(value);
}
function formatDate(value: unknown, lang: string): string {
if (typeof value !== "string") return value == null ? "—" : String(value);
// Parse as local midnight so a date-only value isn't shifted a day by tz when formatted.
const date = new Date(`${value}T00:00:00`);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(lang, { dateStyle: "medium" }).format(date);
}
```
Confirm `useTerms`/`useAuthorities` accept `undefined` and short-circuit (they have `enabled: !!arg`) — yes; passing `undefined` disables the query and `data` is undefined → falls through to the `—`/`…` paths. Confirm `TermView`/`AuthorityView` have `id` + `labels` (they do).
- [ ] **Step 3: Unit test** `flexible-field-value.test.tsx` (RTL + MSW + a QueryClient wrapper; mirror existing component tests). Use fixtures `materialTerms`/`personAuthorities`/`fieldDefinitions`. Cover: a `term` def + a value that is a known term id → renders the label (e.g. "Bronze"); `authority` → label; an unknown term id → renders `<id> (unknown)`; `localized_text` `{sv:"…",en:"…"}` with lang sv → the sv string; `date` "2024-01-05" → a formatted date (assert it's not the raw ISO); `boolean` true → "Yes". MSW must serve `/api/admin/vocabularies/{id}/terms` and `/api/admin/authorities?kind=` (reuse `web/src/test/handlers.ts` patterns).
- [ ] **Step 4: Run the unit test.** `cd web && pnpm test -- flexible-field-value`. Iterate to green (genuine assertions — label not id; not vacuous).
- [ ] **Step 5: Storybook** `flexible-field-value.stories.tsx` (mirror `web/src/objects/visibility-badge.stories.tsx`): stories `Term`, `Authority`, `LocalizedText`, `Date`, `Boolean`, `UnknownRef`. The term/authority stories need the hooks' data — rely on the preview's MSW (`src/test/handlers.ts`) serving terms/authorities, passing a `def` with the matching `vocabulary_id`/`authority_kind` and a `value` that's a known id. Assert the resolved label text shows.
- [ ] **Step 6:** `pnpm typecheck && pnpm lint`. **Commit** `feat(web): FlexibleFieldValue — resolve term/authority/localized field values (#45)`.
---
## Task 2: Refactor `object-detail.tsx` (grouping, placeholders, toolbar) + tests
**Files:** `web/src/objects/object-detail.tsx`, `web/src/objects/object-detail.test.tsx` (create if absent).
- [ ] **Step 1: Failing/updated detail test.** In `object-detail.test.tsx` (RTL + MSW + MemoryRouter at `/objects/:id`, providers from the test harness), seed an object whose `fields` include a term (material → a known term id), a localized_text, and a date; assert the detail shows the **term label** (not the UUID), the **localized string** (not JSON), fields appear under **group subheadings** in definition order, an empty core field shows "—", and an **Edit** link/button points to `/objects/:id/edit`. Run → fails against the current JSON.stringify rendering.
- [ ] **Step 2: Refactor `object-detail.tsx`.**
- Update the local `Field` to take `value: React.ReactNode` and render "—" when the value is nullish/empty (instead of returning `null`) — so core fields are always shown:
```tsx
function Field({ label, value }: { label: string; value: React.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">{empty ? "—" : value}</div>
</div>
);
}
```
- **Header → actions toolbar:** keep `object_name` (`<h2>`) + `VisibilityBadge` on the left; move Edit + Delete into a right-aligned toolbar. Make Edit a button-styled `Link`:
```tsx
import { buttonVariants } from "@/components/ui/button";
// ...
<div className="mb-4 flex items-center gap-3">
<h2 className="text-xl font-semibold">{object.object_name}</h2>
<VisibilityBadge visibility={object.visibility} />
<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>
```
- **Core fields:** render the known core fields via `Field` (object number, count, brief description, current location, current owner, recorder, recording date). Format `recording_date` with the `formatDate` helper (import it from `flexible-field-value.tsx`, or duplicate the tiny helper — prefer exporting `formatDate` from the value module to keep one copy). They now always show (with "—").
- **Flexible fields grouped + ordered:** replace the `Object.entries(object.fields)` block with iteration over `definitions`:
```tsx
const OTHER = t("fields.other"); // existing key used by the field list; or add objects.otherGroup
const present = (definitions ?? []).filter((d) => object.fields[d.key] != null);
const groups: { group: string; defs: FieldDefinitionView[] }[] = [];
for (const d of present) {
const g = d.group?.trim() ? d.group : OTHER;
const bucket = groups.find((x) => x.group === g) ?? (groups.push({ group: g, defs: [] }), groups[groups.length - 1]);
bucket.defs.push(d);
}
// render: for each group → a subheading + each def as <Field label={labelFor(d.key)} value={<FlexibleFieldValue def={d} value={object.fields[d.key]} lang={lang} />} />
```
Keep the existing `labelFor(key)` helper (active-locale field label). Render a group subheading (reuse the uppercase caption style). Drop the old `JSON.stringify`/`typeof` logic entirely. Keep `PublishControl` below.
- (Confirm `fields.other` exists in i18n — the field-list screen uses it; if not, add `objects.otherGroup` to both locales.)
- [ ] **Step 3: Run tests.** `cd web && pnpm test -- object-detail flexible-field-value && pnpm typecheck && pnpm lint`. Green; the detail test now passes (labels, grouping, placeholder, Edit link).
- [ ] **Step 4: Commit** `feat(web): readable, grouped object detail (labels, placeholders, actions toolbar) (#45)`.
---
## Task 3: Final verification
- [ ] `cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size` — all green; bundle within 180 KB gz (frontend-only, ~no change).
- [ ] `pnpm test -- i18n` (en/sv parity for `common.yes`/`common.no`/`objects.unknownRef` [+ `objects.otherGroup` if added]); `git grep -in 'biggus\|dickus' -- web/src || echo CLEAN`; `git status --short` clean.
- [ ] **Manual smoke (recommended):** with the stack up + a seeded object that has a term/authority/localized field, open `/objects/:id` and confirm labels (not UUIDs/JSON), grouped sections, "—" for empty core fields, and the Edit/Delete toolbar.
---
## Self-Review (completed)
**Spec coverage:** value resolution per type + fallbacks → Task 1 (`FlexibleFieldValue` + sub-components); grouping/order + core placeholders + toolbar + date format → Task 2; story → Task 1 Step 5; tests → Task 1/2; i18n keys + parity + verification → Task 1 Step 1 / Task 3. ✓ Out of scope (export #39, form grouping, backend resolution) not included. ✓
**Placeholder scan:** concrete component + helper code given; the only "confirm X exists" notes (`fields.other`, hook `undefined` handling) are quick verifications against real code, not deferred work.
**Type consistency:** `FlexibleFieldValue({def, value, lang})` defined in Task 1, consumed in Task 2; `formatDate` exported from the value module and reused for `recording_date`; `labelText`/`useTerms`/`useAuthorities`/`buttonVariants` are existing exports.
## Notes
- No backend, no migration, no new dependency → no lockfile churn; bundle effectively unchanged.
- react-query dedups repeated `["terms", vocab]`/`["authorities", kind]` so multiple same-vocabulary term fields cause one fetch; often already warm from the table/combobox.
@@ -0,0 +1,218 @@
# Toast Notifications + Consistent Mutation Feedback — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Add a Base UI toast system bridged to the out-of-React `QueryClient`, so every mutation gives consistent feedback — a per-mutation success toast (opt-in via `meta.successMessage`) and a catch-all error toast (unless `meta.suppressErrorToast`) — while keeping the existing inline 422/409 UX.
**Architecture:** A module-scope `createToastManager()` is passed to a `<ToastRegion>` (`Toast.Provider` + portaled viewport) mounted app-wide, and `.add()`-ed from a `MutationCache` on the `QueryClient` (`onError`/`onSuccess` read `mutation.meta` + `i18n.t` outside React). The 18 mutation hooks declare `meta`. `meta` is type-checked via a react-query `Register` augmentation.
**Tech Stack:** React 19 + TS + pnpm, `@base-ui/react` toast (already a dep), TanStack Query, react-i18next, Vitest+RTL+MSW, Storybook 10.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; component source double-quote+semicolon, stories single-quote+no-semicolon; en/sv parity; no codename; portal queries via `within(document.body)`; `check:size` ≤ 180 KB gz.
**Spec:** `docs/superpowers/specs/2026-06-07-toast-notifications-design.md`
**Base UI Toast facts (validated from the d.ts):** `createToastManager()``{ add(opts) => id, close, update, promise }` (works outside React; `add({ title?, description?, type?, timeout?, priority? })`, `type` is a free-form string, re-`add` with same `id` updates in place). `Toast.Provider` accepts `toastManager`. Render: `const { toasts } = Toast.useToastManager(); toasts.map(t => <Toast.Root toast={t}>…)`. Parts: Provider / Viewport / Portal / Positioner / Root(requires `toast` prop) / Title(`<h2>`) / Description(`<p>`) / Close(`<button>`) / Action / Arrow. Title/Description read the toast's title/description from `ToastRootContext` (no children needed — **verify by running**). The wrapper pattern to mirror is `web/src/components/ui/alert-dialog.tsx`.
---
# Task 1: Toast infrastructure (manager, region, MutationCache wiring, meta typing, i18n, story)
**Files:** create `web/src/toast/toast-manager.ts`, `web/src/components/ui/toast.tsx`, `web/src/components/ui/toast.stories.tsx`, `web/src/api/react-query.d.ts`; modify `web/src/main.tsx`, `web/src/i18n/{en,sv}.json`.
- [ ] **Step 1: Module-scope manager** `web/src/toast/toast-manager.ts`:
```ts
import { createToastManager } from "@base-ui/react/toast";
/** A toast manager created outside React so non-React code (the QueryClient
* MutationCache) can add toasts. Passed to <Toast.Provider toastManager=…>. */
export const toastManager = createToastManager();
```
- [ ] **Step 2: `ui/toast.tsx`** — wrap the Base UI Toast parts (mirror `ui/alert-dialog.tsx`: `data-slot`, `cn()`), and export a `<ToastRegion>`:
```tsx
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { cn } from "@/lib/utils";
import { toastManager } from "@/toast/toast-manager";
function ToastList() {
const { toasts } = ToastPrimitive.useToastManager();
return toasts.map((toast) => (
<ToastPrimitive.Root
key={toast.id}
toast={toast}
data-slot="toast"
className={cn(
"flex items-start gap-2 rounded-md border bg-white p-3 text-sm shadow-md",
toast.type === "error" && "border-red-300",
)}
>
<div className="flex-1">
{toast.title && <ToastPrimitive.Title data-slot="toast-title" className="font-medium" />}
<ToastPrimitive.Description data-slot="toast-description" className="text-neutral-700" />
</div>
<ToastPrimitive.Close
data-slot="toast-close"
aria-label="Close"
className="text-neutral-400 hover:text-neutral-700"
>
×
</ToastPrimitive.Close>
</ToastPrimitive.Root>
));
}
/** App-wide toast region: provides the external manager + a portaled viewport. */
export function ToastRegion({ children }: { children: React.ReactNode }) {
return (
<ToastPrimitive.Provider toastManager={toastManager}>
{children}
<ToastPrimitive.Portal>
<ToastPrimitive.Viewport className="fixed bottom-4 right-4 z-50 flex w-80 flex-col gap-2">
<ToastList />
</ToastPrimitive.Viewport>
</ToastPrimitive.Portal>
</ToastPrimitive.Provider>
);
}
```
**Validate by running** (first toast in the repo): confirm `Title`/`Description` auto-render the toast's `title`/`description` from context (if they DON'T, pass `{toast.title}`/`{toast.description}` as children); confirm `Viewport`/`Positioner` nesting (Base UI may require a `Toast.Positioner` inside the viewport per toast — adjust to the real API when the story runs). Keep the styled-by-`type` distinction.
- [ ] **Step 3: meta typing** `web/src/api/react-query.d.ts`:
```ts
import "@tanstack/react-query";
declare module "@tanstack/react-query" {
interface Register {
mutationMeta: {
/** i18n key for a success toast (opt-in). */
successMessage?: string;
/** i18n key overriding the default error toast message. */
errorMessage?: string;
/** Skip the global error toast (the component shows the error inline). */
suppressErrorToast?: boolean;
};
}
}
```
- [ ] **Step 4: Wire the `MutationCache`** in `web/src/main.tsx`. Import the manager, the i18n instance (the configured singleton — confirm the default export of `web/src/i18n`; the app already does `import "./i18n"`), and the typed errors:
```tsx
import { MutationCache, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import i18n from "./i18n";
import { toastManager } from "./toast/toast-manager";
import { ToastRegion } from "./components/ui/toast";
import { InUseError, HttpError } from "./api/queries";
import type { MutationMeta } from "@tanstack/react-query"; // for the helper's param type
function mutationErrorMessage(error: unknown, meta: MutationMeta | undefined): string {
if (meta?.errorMessage) return i18n.t(meta.errorMessage);
if (error instanceof InUseError) return i18n.t("actions.inUse", { count: error.count });
if (error instanceof HttpError && error.status === 503) return i18n.t("search.unavailable");
return i18n.t("toast.error");
}
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
mutationCache: new MutationCache({
onError: (error, _vars, _ctx, mutation) => {
if (mutation.meta?.suppressErrorToast) return;
toastManager.add({ type: "error", description: mutationErrorMessage(error, mutation.meta) });
},
onSuccess: (_data, _vars, _ctx, mutation) => {
if (mutation.meta?.successMessage) {
toastManager.add({ type: "success", description: i18n.t(mutation.meta.successMessage) });
}
},
}),
});
```
And mount the region around `<App/>`:
```tsx
<QueryClientProvider client={queryClient}>
<ConfigProvider>
<ToastRegion>
<App />
</ToastRegion>
</ConfigProvider>
</QueryClientProvider>
```
(If `i18n` has no default export, import the instance it does export, or `import i18n from "i18next"` only if that's the configured instance — use whatever `web/src/i18n` exports; the goal is the *configured* instance so `t` resolves the app's keys/language.)
- [ ] **Step 5: i18n** — add a `toast` namespace to **both** `en.json` + `sv.json`:
`{ "created": "Created"/"Skapat", "saved": "Saved"/"Sparat", "updated": "Updated"/"Uppdaterat", "deleted": "Deleted"/"Borttaget", "renamed": "Renamed"/"Namn ändrat", "published": "Visibility updated"/"Synlighet uppdaterad", "error": "Something went wrong"/"Något gick fel" }`.
- [ ] **Step 6: Story** `web/src/components/ui/toast.stories.tsx` — render `<ToastRegion>` and, in `play`, call `toastManager.add({ type: "success", description: "Saved" })` (and an error one), asserting the toast text appears (portal → `within(document.body)`). Mirror the established story format. This is the **validation** that the Base UI composition is correct — iterate until green.
- [ ] **Step 7:** `cd web && pnpm test -- toast && pnpm typecheck && pnpm lint`. The toast must actually render. **Commit** `feat(web): Base UI toast region + global mutation feedback wiring (#47)`.
---
# Task 2: Declare `meta` on the mutation hooks + integration tests
**Files:** `web/src/api/queries.ts`; a test (e.g. `web/src/objects/publish-control.test.tsx` or a new `web/src/api/mutation-feedback.test.tsx`).
Add a `meta` option to each `useMutation({...})` per the rule:
- **`meta.successMessage`** (a `toast.*` key) on every discrete user action.
- **`meta.suppressErrorToast: true`** on mutations whose consuming component **already renders the error inline** (so no double-report).
| Hook | `successMessage` | `suppressErrorToast` | Why suppress |
|---|---|---|---|
| `useCreateObject` | `toast.created` | yes | object form shows `form.rejected` inline |
| `useUpdateObject` | `toast.saved` | yes | object form inline |
| `useSetFields` | — (the create/update toast covers the save) | yes | 422 field-highlight inline; no own success toast to avoid a double "saved" |
| `useDeleteObject` | `toast.deleted` | yes | `DeleteObjectDialog` shows error inline |
| `useSetVisibility` | `toast.published` | yes | `publish-control` shows error inline |
| `useLogin` | — | yes | login page shows error inline |
| `useLogout` | — | — | fire-and-forget |
| `useCreateVocabulary` | `toast.created` | yes | vocab create form shows `form.rejected` |
| `useRenameVocabulary` | `toast.renamed` | yes | vocab rename shows `form.rejected` |
| `useDeleteVocabulary` | `toast.deleted` | yes | delete dialog inline (409) |
| `useAddTerm` | `toast.created` | yes | add-term form inline |
| `useUpdateTerm` | `toast.saved` | **no** | TermRow has no inline error → let the toast be the feedback |
| `useDeleteTerm` | `toast.deleted` | yes | delete dialog inline |
| `useCreateAuthority` | `toast.created` | yes | authority create form inline |
| `useUpdateAuthority` | `toast.saved` | **no** | AuthorityRow has no inline error |
| `useDeleteAuthority` | `toast.deleted` | yes | delete dialog inline |
| `useCreateFieldDefinition` | `toast.created` | yes | field form inline |
| `useUpdateFieldDefinition` | `toast.saved` | **no** | field-form edit may lack inline error |
| `useDeleteFieldDefinition` | `toast.deleted` | yes | delete dialog inline |
- [ ] **Step 1: VERIFY the suppress column per component.** For each hook, open its consumer and check whether it visibly renders `isError`/catches+shows the error. Set `suppressErrorToast` **iff** it does. (The table is the expected mapping; correct any row that doesn't match the actual component — the principle governs: suppress only when the error is already shown inline. Update the "Why" if you change a row.)
- [ ] **Step 2: Add `meta` to each hook.** E.g.:
```ts
return useMutation({
mutationFn: async (body: NewVocabularyRequest) => { ... },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
```
Leave `mutationFn`/`onSuccess` unchanged; only add the `meta` line.
- [ ] **Step 3: Integration test** (`mutation-feedback.test.tsx`, RTL + MSW + the `renderApp` harness incl. `<ToastRegion>` — ensure the test render tree wraps with `ToastRegion` + the real `queryClient` MutationCache; if `renderApp` doesn't, add a variant that does, or test via `main`-equivalent providers):
- **Success:** perform a create-vocabulary action (or call a `meta.successMessage` mutation) → a "Created" toast appears (`within(document.body)`).
- **Error (catch-all):** MSW returns 500 for a non-suppressed mutation (e.g. `useUpdateTerm`) → an error toast appears.
- **Suppressed:** a `suppressErrorToast` mutation failing → **no** toast added (and its inline error still shows). Assert the toast region has no error toast.
- (Testing the MutationCache requires the real cache — construct a `QueryClient` with the same `mutationCache` config in the test wrapper, or export a `makeQueryClient()` factory from a shared module and use it in both `main.tsx` and tests. Prefer extracting the cache config into a small `web/src/api/query-client.ts` factory to avoid duplicating it in tests — do this if it keeps the test honest.)
- [ ] **Step 4:** `cd web && pnpm test && pnpm typecheck && pnpm lint`. All green. **Commit** `feat(web): per-mutation success/error toast metadata (#47)`.
---
# Task 3: Final verification
- [ ] `cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size` — all green; index ≤ 180 KB gz (Base UI toast adds to the always-loaded shell; report the number — if it pushes over, lazy-load is hard for a global region, so flag for a budget decision).
- [ ] `pnpm test -- i18n` (en/sv parity for `toast.*`); `git grep -in 'biggus\|dickus' -- web/src || echo CLEAN`; `git status --short` clean.
- [ ] **Manual smoke (recommended):** with the stack up, create a vocabulary → "Created" toast; trigger a failure (e.g. duplicate key) → error toast or the existing inline message (no double); delete a term in use → the dialog's "used by N" (no extra toast).
---
## Self-Review (completed)
**Spec coverage:** Base UI toast region + external manager (T1 S1S2, S6); global MutationCache onError catch-all + onSuccess meta-driven (T1 S4); meta typing (T1 S3); per-mutation meta (T2); inline 422/409 kept (suppress flags, T2); toast i18n + parity (T1 S5, T3); story (T1 S6); verification/bundle (T3). ✓ Out of scope (replace inline UX, undo/queued, read-error toasts) not included. ✓
**Placeholder scan:** concrete code for manager/region/cache/typing; the Base UI Title/Description auto-render + viewport nesting carry an explicit "validate by running" (novel primitive); the suppress mapping is a concrete table with a governing principle + a per-component verification step (not vague).
**Type consistency:** `meta` shape declared once (`react-query.d.ts`) and consumed in the MutationCache (T1) + set on hooks (T2); `mutationErrorMessage` uses the exported `InUseError`/`HttpError`; `toast.*` keys used in both the cache helper and the hook `meta`.
## Notes
- No new dependency (`@base-ui/react` present); bundle grows only by the toast primitive in the always-loaded region — watch `check:size` (budget 180).
- Re-`add` with the same id de-dupes/refreshes a toast — not used now, available if repeated errors get noisy.
- Extracting a `makeQueryClient()` factory (used by `main.tsx` + tests) keeps the toast wiring testable without duplicating the MutationCache config.
@@ -0,0 +1,119 @@
# Object Detail Readability — Design
**Date:** 2026-06-07
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #45.
## Context
`web/src/objects/object-detail.tsx` renders flexible field values with
`typeof value === "object" ? JSON.stringify(value) : String(value)`. Since term/authority
values are stored as **UUID strings** and `localized_text` as a `{lang: text}` **object**,
the result is: term/authority fields show a **raw UUID**, and `localized_text` shows
**`{"sv":"…"}`** JSON. Flexible fields also render in `Object.entries` (insertion) order,
ungrouped, and empty core fields vanish (layout shifts per object). This is the worst
readability defect in the screen curators read most — now more visible since the detail moved
into the new pane/drawer (#44).
The resolution machinery already exists: `useTerms(vocabulary_id)` / `useAuthorities(kind)`
and `labelText(labels, lang)` (`web/src/lib/labels.ts`) — the object form/combobox use them.
`FieldDefinitionView` carries `data_type`, `vocabulary_id`, `authority_kind`, `group`, and
`labels`.
### Decisions (from brainstorming)
1. **Client-side resolution**, reusing `useTerms`/`useAuthorities` + `labelText` (no backend
change; react-query dedups repeated vocabularies/kinds). Backend-resolved labels were
rejected for now (more work; the client machinery exists). PDF export (#39) may revisit
server-side resolution later.
2. **Scope = detail readability bundle:** value resolution + grouping/order + small polish
(date formatting, empty-core placeholders, an actions toolbar). **Excluded:** export/PDF
(#39), the object form's grouping (left to the form work / #46), backend resolution.
## Components
### `FlexibleFieldValue` (new, in `object-detail.tsx` or a sibling file)
Rendered once per flexible field — so the term/authority hooks satisfy the rules of hooks
(one hook call per component instance, not a loop). Props: `{ def: FieldDefinitionView,
value: unknown, lang: string }`. Switches on `def.data_type`:
- **`term`**: `const { data: terms } = useTerms(def.vocabulary_id)`; find `terms?.find(t => t.id === value)`; show `labelText(term.labels, lang)`.
- **`authority`**: `const { data: authorities } = useAuthorities(def.authority_kind)`; same.
- **`localized_text`**: `value` is `Record<string, string>`; show `value[lang] ?? value.en ?? Object.values(value)[0] ?? "—"`.
- **`date`**: `Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" }).format(new Date(value))` — a bare date, **no `timeZone`** (would shift a date-only value).
- **`boolean`**: `value ? t("common.yes") : t("common.no")`.
- **`integer` / `text` / default**: `String(value)`.
**Fallbacks:**
- Term/authority value present but not found in the loaded set (deleted ref) → render the raw
id in muted text with a `t("objects.unknownRef")` ("(unknown)") suffix.
- Terms/authorities still loading → a muted placeholder (e.g. the id faintly, or "…").
- Empty/absent value → "—".
- `def` missing for a stored key (field definition deleted) → fall back to `String(value)` (or
the raw value) muted.
react-query keys: `["terms", vocabularyId]` / `["authorities", kind]` are shared, so N term
fields in one vocabulary cause **one** fetch (often already cached from the table/combobox).
### Detail layout changes (`object-detail.tsx`)
- **Header → actions toolbar:** left = `object_name` (`<h2>`) + `VisibilityBadge`; right =
a toolbar with **Edit** (a real `Button` linking to `/objects/:id/edit` — use `Link` +
`buttonVariants` like the table's New button, since the Base UI `Button` has no `asChild`)
and **Delete** (the existing `DeleteObjectDialog`). `PublishControl` stays below the fields.
- **Core fields render always** with a muted "—" when empty (object number, count, brief
description, current location, current owner, recorder, recording date) — stable layout.
Update the local `Field` component to show "—" instead of returning `null`. (`recording_date`
formatted as a locale date.)
- **Flexible fields grouped + ordered:** iterate `definitions` (stable API order); for each
definition whose key exists in `object.fields` with a non-null value, render
`<FlexibleFieldValue>` under a subheading for its `def.group` (null group → an "Other" /
ungrouped section rendered last). No more `Object.entries`/`JSON.stringify`.
## Data flow
`useObject(id)` + `useFieldDefinitions()` (already loaded) → group definitions by
`group` (stable order) → for each present flexible field, `FlexibleFieldValue` resolves the
display via the type-appropriate hook (`useTerms`/`useAuthorities`, react-query-cached) or
inline (localized/date/boolean/text). Core fields render directly with placeholders.
## Error handling / edges
- Deleted term/authority (id not resolvable) → muted id + "(unknown)"; never a crash or raw
JSON.
- `localized_text` with no active-language entry → English → first → "—".
- Invalid date string → fall back to the raw string (guard `Number.isNaN(date.getTime())`).
- Object with no flexible values → no flexible section (only core fields).
- A stored key with no matching definition → render the raw value muted (don't drop silently
into `JSON.stringify`).
## Testing
**Vitest + RTL + MSW** (extend `web/src/test/fixtures.ts` — it already has `fieldDefinitions`
with term/authority/localized_text/date/boolean defs, `materialTerms`, `personAuthorities`):
- A `term` field renders the term's active-locale label (not the UUID); `authority` likewise;
`localized_text` renders the active-language string (not JSON); `date` is locale-formatted;
`boolean` → yes/no.
- A term value whose id isn't in the vocabulary → muted id + "(unknown)" fallback.
- Flexible fields render **grouped** with group subheadings, in definition order.
- An empty core field shows "—".
- The Edit action links to `/objects/:id/edit`; Delete dialog present.
- Component test for `FlexibleFieldValue` covering each `data_type` + the unknown-ref fallback.
**Storybook** (per the standing preference): `FlexibleFieldValue.stories.tsx` — Term /
Authority / LocalizedText / Date / Boolean / UnknownRef variants (MSW from the preview, or
pass pre-seeded query data). Mirror the established story format.
## Acceptance criteria
1. Term and authority flexible fields display their active-locale **label** (not a UUID);
`localized_text` shows the active-language string (not JSON); date/boolean/integer/text
render readably.
2. A deleted/unknown term/authority ref degrades to a muted id + "(unknown)", never raw JSON
or a crash.
3. Flexible fields are **grouped by `def.group`** in stable definition order; empty core fields
show "—".
4. The detail header is an actions toolbar (Edit as a Button + Delete); `recording_date` is
locale-formatted.
5. A `FlexibleFieldValue` Storybook story exists; en/sv parity for new keys (`common.yes`,
`common.no`, `objects.unknownRef`); `pnpm typecheck`/`lint`/`test`/`build` green;
`check:size` within budget; no codename; no `any`/`eslint-disable`.
## Out of scope → follow-ups
- **Export / PDF** of a record (#39).
- The **object form's** flexible-field grouping/order (the form still renders flat) — left to
the form work (#46) or a small follow-up.
- **Backend-resolved labels** (would help PDF export #39 and avoid client N+1 at large scale).
@@ -0,0 +1,123 @@
# Toast Notifications + Consistent Mutation Feedback — Design
**Date:** 2026-06-07
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #47.
## Context
Mutations across the app communicate **success only** by side effects (navigation, a dialog
closing) — a curator doing bulk cataloguing can't tell whether a save landed, which invites
double-submits and re-checking. **Errors** are inconsistent: inline `<p role="alert">` in the
forms, in-dialog for deletes, three message kinds in `publish-control`, and some mutation
failures surface nowhere. There is no toast/notification system (no `toast`/`sonner` dep).
### Facts established during exploration
- The `QueryClient` is created at **module scope** in `web/src/main.tsx` (outside React), with
`defaultOptions.queries` only — no mutation defaults yet.
- **Base UI ships a `toast` primitive** (`@base-ui/react/toast`) — no new dependency. It exports
`createToastManager()`, an **out-of-React manager** you pass to `<Toast.Provider>` and can
`.add()` from anywhere — the clean bridge to the module-scope queryClient handlers.
- The `i18n` singleton (`web/src/i18n`) exposes `i18n.t(...)`, callable **outside React**.
- Existing typed mutation errors (`web/src/api/queries.ts`): `InUseError` (409 + count),
`FieldRejection` (422 field), `HttpError` (status), `VisibilityError`. The object form shows
422 as a field highlight; the delete dialogs catch errors and show them inline.
### Decisions (from brainstorming)
1. **Base UI Toast**, bridged via a module-scope `createToastManager()` (no new dep, consistent
with the combobox/tooltip/drawer wrappers).
2. **Wiring: global `MutationCache` + per-mutation `meta`.** A global `onError` is a catch-all
safety net (no silent failures); a global `onSuccess` shows a toast only when a mutation
declares `meta.successMessage`. Mutations that report errors inline opt out via
`meta.suppressErrorToast`.
3. **Keep inline field/dialog errors** (422 highlight, 409 "in use") — toasts add success
confirmations + a catch-all for otherwise-silent failures, not a replacement.
## Components
### `ui/toast.tsx` (new) + the manager
- Module scope (alongside the QueryClient — `main.tsx` or a small `web/src/toast/` module):
`export const toastManager = Toast.createToastManager();`
- `web/src/components/ui/toast.tsx` — wrap the Base UI Toast parts (Provider / Viewport /
Portal / Positioner / Root / Title / Description / Close) in the established `ui/*` style
(`data-slot`, `cn()`, mirror `ui/alert-dialog.tsx`). Provide a `<ToastRegion>` that renders
`Toast.Provider` (with `toastManager`) + a `Toast.Viewport` listing the active toasts (mapped
from `useToastManager().toasts`), styled as stacked cards (success vs error variant via the
toast's `type`/`data`). The viewport must be an `aria-live` region (Base UI handles the live
semantics; confirm). **Base UI Toast is novel in this repo → the exact part tree + manager API
(`createToastManager`, `manager.add({ title?, description, type })`, `useToastManager`) must be
validated by running** (as the combobox/drawer/tooltip were).
- Mount `<ToastRegion>` in `main.tsx` inside the provider tree (so it's on every screen).
### Global mutation feedback (`main.tsx` / queryClient)
```ts
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
mutationCache: new MutationCache({
onError: (error, _vars, _ctx, mutation) => {
if (mutation.meta?.suppressErrorToast) return;
toastManager.add({ type: "error", description: errorMessage(error, mutation) });
},
onSuccess: (_data, _vars, _ctx, mutation) => {
const key = mutation.meta?.successMessage;
if (key) toastManager.add({ type: "success", description: i18n.t(key) });
},
}),
});
```
- `errorMessage(error, mutation)`: `mutation.meta?.errorMessage ? i18n.t(...)` else a type-aware
default — `InUseError``i18n.t("actions.inUse", { count })`, `HttpError` 503 →
`i18n.t("search.unavailable")`, otherwise `i18n.t("toast.error")`.
- `meta` is typed via a module augmentation of `@tanstack/react-query`'s `Register` interface so
`meta.successMessage`/`meta.errorMessage`/`meta.suppressErrorToast` are type-checked (no
`any`).
### Per-mutation meta (`web/src/api/queries.ts`)
- **`meta.successMessage`** (a `toast.*` key) on the discrete actions: object create/update/
delete, set-visibility/publish, vocabulary create/rename/delete, term create/update/delete,
authority create/update/delete, field-definition create/update/delete.
- **`meta.suppressErrorToast: true`** on mutations that surface errors inline: the object form's
create/update + `useSetFields` (422 field highlight), `useLogin`, and the delete hooks (the
`DeleteConfirmDialog`/`DeleteObjectDialog` show the 409/rejection inline). These keep success
toasts.
## Data flow
A mutation runs → react-query's `MutationCache` fires the global `onSuccess`/`onError` → reads
`mutation.meta``toastManager.add(...)` (message via `i18n.t`) → `<ToastRegion>` (subscribed
to the manager) renders the toast in its portal/viewport → auto-dismisses (Base UI default) or
on Close. Inline field/dialog errors render as before (unaffected).
## Error handling / edges
- A mutation with neither `meta` nor inline handling → still gets the catch-all error toast on
failure (the safety net); silent success (no `successMessage`) is intentional where navigation
already signals it.
- No double-report: inline-handling mutations set `suppressErrorToast`.
- `i18n.t` outside React uses the singleton's current language (already synced via the locale
hook); a missing key falls back to the generic `toast.error`.
- Toasts stack + auto-dismiss; an error toast may stay longer / be dismissible (Base UI config).
## Testing
- **Vitest + RTL + MSW:** a mutation declaring `meta.successMessage` shows a success toast
(query `within(document.body)`); a failing mutation (MSW 500) shows an error toast; a
`suppressErrorToast` mutation does **not** add a toast on error (no double-report) while its
inline error still renders; the toast region is present and `aria-live`. Drive these through a
real screen action (e.g. create a vocabulary → "Created" toast; a 500 → error toast).
- **Storybook:** a `ui/toast` story rendering a success + an error toast (via the manager), per
the standing preference; verify the Base UI composition by running.
- Reuse existing screens' MSW handlers (`web/src/test/handlers.ts`).
## Acceptance criteria
1. A Base UI toast region is mounted app-wide; `toastManager` (out-of-React) is `.add`-able from
the queryClient handlers. No new npm dependency.
2. Global `MutationCache`: `onError` toasts a catch-all (type-aware) message unless
`meta.suppressErrorToast`; `onSuccess` toasts `meta.successMessage` when present.
3. The discrete CRUD/publish mutations declare `meta.successMessage`; inline-error mutations
(object form, login, deletes) set `meta.suppressErrorToast` and keep their inline UX.
4. `meta` is type-checked (react-query `Register` augmentation); no `any`/`eslint-disable`.
5. en/sv parity for the `toast.*` keys; a toast Storybook story; `pnpm typecheck`/`lint`/`test`/
`build` green; `check:size` within 180 KB gz; no codename.
## Out of scope → follow-ups
- Replacing the inline 422 field-highlight / 409 "in use" UX with toasts.
- Undo/action toasts, queued/grouped toasts, per-account toast preferences.
- Toasting query (read) errors — this milestone covers mutations (the silent-write problem).
+1 -1
View File
@@ -3,7 +3,7 @@ import { readdirSync, readFileSync } from "node:fs";
import { gzipSync } from "node:zlib"; import { gzipSync } from "node:zlib";
import { join } from "node:path"; import { join } from "node:path";
const BUDGET_KB = 180; const BUDGET_KB = 250;
const dir = "dist/assets"; const dir = "dist/assets";
const jsFiles = readdirSync(dir).filter((f) => f.endsWith(".js")); const jsFiles = readdirSync(dir).filter((f) => f.endsWith(".js"));
if (jsFiles.length === 0) { if (jsFiles.length === 0) {
+112
View File
@@ -0,0 +1,112 @@
import { afterEach, describe, expect, test } from "vitest";
import { renderHook, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
import i18n from "../i18n";
import { ToastRegion } from "../components/ui/toast";
import { server } from "../test/server";
import { makeQueryClient } from "./query-client";
import { useDeleteVocabulary, useUpdateTerm } from "./queries";
// The toast manager is a module-scope singleton shared across renders, so each
// test mounts a fresh region and tears it down afterwards to keep toasts from
// one case bleeding into the next.
function makeWrapper() {
const queryClient = makeQueryClient();
return function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<ToastRegion>{children}</ToastRegion>
</QueryClientProvider>
);
};
}
afterEach(async () => {
// Allow any pending toast state updates to flush before the next test mounts.
await Promise.resolve();
});
describe("mutation feedback toasts", () => {
test("a meta.successMessage mutation shows its success toast on success", async () => {
server.use(
http.patch(
"/api/admin/vocabularies/:id/terms/:term_id",
() => new HttpResponse(null, { status: 204 }),
),
);
const { result, unmount } = renderHook(() => useUpdateTerm(), {
wrapper: makeWrapper(),
});
await result.current.mutateAsync({
vocabularyId: "v1",
termId: "t1",
external_uri: null,
labels: [{ lang: "en", label: "Bronze" }],
});
await waitFor(() => {
expect(
within(document.body).getByText(i18n.t("toast.saved")),
).toBeInTheDocument();
});
unmount();
});
test("a non-suppressed mutation failing shows the catch-all error toast", async () => {
server.use(
http.patch(
"/api/admin/vocabularies/:id/terms/:term_id",
() => new HttpResponse(null, { status: 500 }),
),
);
const { result, unmount } = renderHook(() => useUpdateTerm(), {
wrapper: makeWrapper(),
});
await expect(
result.current.mutateAsync({
vocabularyId: "v1",
termId: "t1",
external_uri: null,
labels: [{ lang: "en", label: "Bronze" }],
}),
).rejects.toThrow();
await waitFor(() => {
expect(
within(document.body).getByText(i18n.t("toast.error")),
).toBeInTheDocument();
});
unmount();
});
test("a suppressErrorToast mutation failing adds no toast", async () => {
server.use(
http.delete(
"/api/admin/vocabularies/:id",
() => new HttpResponse(null, { status: 500 }),
),
);
const { result, unmount } = renderHook(() => useDeleteVocabulary(), {
wrapper: makeWrapper(),
});
await expect(result.current.mutateAsync("v1")).rejects.toThrow();
// Give the MutationCache onError a turn; assert it stayed silent.
await Promise.resolve();
expect(within(document.body).queryByText(i18n.t("toast.error"))).toBeNull();
unmount();
});
});
+18
View File
@@ -122,6 +122,7 @@ export function useLogin() {
} }
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }),
meta: { suppressErrorToast: true },
}); });
} }
@@ -185,6 +186,7 @@ export function useCreateObject() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -204,6 +206,7 @@ export function useUpdateObject() {
void qc.invalidateQueries({ queryKey: ["objects"] }); void qc.invalidateQueries({ queryKey: ["objects"] });
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
}, },
meta: { successMessage: "toast.saved", suppressErrorToast: true },
}); });
} }
@@ -229,6 +232,7 @@ export function useSetFields() {
onSuccess: (_d, { id }) => { onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
}, },
meta: { suppressErrorToast: true },
}); });
} }
@@ -244,6 +248,7 @@ export function useDeleteObject() {
if (response.status !== 204) throw new Error("delete failed"); if (response.status !== 204) throw new Error("delete failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -276,6 +281,7 @@ export function useCreateVocabulary() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -301,6 +307,7 @@ export function useAddTerm() {
}, },
onSuccess: (_result, { vocabularyId }) => onSuccess: (_result, { vocabularyId }) =>
qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -325,6 +332,7 @@ export function useCreateAuthority() {
}, },
onSuccess: (_result, { kind }) => onSuccess: (_result, { kind }) =>
qc.invalidateQueries({ queryKey: ["authorities", kind] }), qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -376,6 +384,7 @@ export function useCreateFieldDefinition() {
return data; return data;
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
}); });
} }
@@ -405,6 +414,7 @@ export function useSetVisibility() {
void qc.invalidateQueries({ queryKey: ["object", id] }); void qc.invalidateQueries({ queryKey: ["object", id] });
void qc.invalidateQueries({ queryKey: ["objects"] }); void qc.invalidateQueries({ queryKey: ["objects"] });
}, },
meta: { successMessage: "toast.published", suppressErrorToast: true },
}); });
} }
@@ -431,6 +441,7 @@ export function useUpdateTerm() {
if (response.status !== 204) throw new Error("update term failed"); if (response.status !== 204) throw new Error("update term failed");
}, },
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.saved" },
}); });
} }
@@ -447,6 +458,7 @@ export function useDeleteTerm() {
if (response.status !== 204) throw new Error("delete term failed"); if (response.status !== 204) throw new Error("delete term failed");
}, },
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }), onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -463,6 +475,7 @@ export function useRenameVocabulary() {
if (response.status !== 204) throw new Error("rename failed"); if (response.status !== 204) throw new Error("rename failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.renamed", suppressErrorToast: true },
}); });
} }
@@ -479,6 +492,7 @@ export function useDeleteVocabulary() {
if (response.status !== 204) throw new Error("delete vocabulary failed"); if (response.status !== 204) throw new Error("delete vocabulary failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -504,6 +518,7 @@ export function useUpdateAuthority() {
if (response.status !== 204) throw new Error("update authority failed"); if (response.status !== 204) throw new Error("update authority failed");
}, },
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }), onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.saved" },
}); });
} }
@@ -520,6 +535,7 @@ export function useDeleteAuthority() {
if (response.status !== 204) throw new Error("delete authority failed"); if (response.status !== 204) throw new Error("delete authority failed");
}, },
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }), onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
@@ -546,6 +562,7 @@ export function useUpdateFieldDefinition() {
if (response.status !== 204) throw new Error("update field failed"); if (response.status !== 204) throw new Error("update field failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
}); });
} }
@@ -562,5 +579,6 @@ export function useDeleteFieldDefinition() {
if (response.status !== 204) throw new Error("delete field failed"); if (response.status !== 204) throw new Error("delete field failed");
}, },
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }), onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
}); });
} }
+49
View File
@@ -0,0 +1,49 @@
import {
MutationCache,
QueryClient,
type MutationMeta,
} from "@tanstack/react-query";
import i18n from "../i18n";
import { toastManager } from "../toast/toast-manager";
import { HttpError, InUseError } from "./queries";
function mutationErrorMessage(
error: unknown,
meta: MutationMeta | undefined,
): string {
if (meta?.errorMessage) return i18n.t(meta.errorMessage);
if (error instanceof InUseError) {
return i18n.t("actions.inUse", { count: error.count });
}
if (error instanceof HttpError && error.status === 503) {
return i18n.t("search.unavailable");
}
return i18n.t("toast.error");
}
/** Builds the app's QueryClient, including the MutationCache that bridges every
* mutation to the toast region (catch-all error toast + opt-in success toast).
* Shared by main.tsx and tests so the toast wiring stays consistent. */
export function makeQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
mutationCache: new MutationCache({
onError: (error, _vars, _ctx, mutation) => {
if (mutation.meta?.suppressErrorToast) return;
toastManager.add({
type: "error",
description: mutationErrorMessage(error, mutation.meta),
});
},
onSuccess: (_data, _vars, _ctx, mutation) => {
if (mutation.meta?.successMessage) {
toastManager.add({
type: "success",
description: i18n.t(mutation.meta.successMessage),
});
}
},
}),
});
}
+14
View File
@@ -0,0 +1,14 @@
import "@tanstack/react-query";
declare module "@tanstack/react-query" {
interface Register {
mutationMeta: {
/** i18n key for a success toast (opt-in). */
successMessage?: string;
/** i18n key overriding the default error toast message. */
errorMessage?: string;
/** Skip the global error toast (the component shows the error inline). */
suppressErrorToast?: boolean;
};
}
}
+31
View File
@@ -0,0 +1,31 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect, within } from 'storybook/test'
import { ToastRegion } from './toast'
import { toastManager } from '../../toast/toast-manager'
const meta = {
component: ToastRegion,
tags: ['ai-generated'],
} satisfies Meta<typeof ToastRegion>
export default meta
type Story = StoryObj<typeof meta>
export const Success: Story = {
args: { children: null },
play: async () => {
toastManager.add({ type: 'success', description: 'Saved' })
await expect(await within(document.body).findByText('Saved')).toBeInTheDocument()
},
}
export const Error: Story = {
args: { children: null },
play: async () => {
toastManager.add({ type: 'error', description: 'Something went wrong' })
await expect(
await within(document.body).findByText('Something went wrong'),
).toBeInTheDocument()
},
}
+57
View File
@@ -0,0 +1,57 @@
import type * as React from "react";
import { useTranslation } from "react-i18next";
import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { cn } from "@/lib/utils";
import { toastManager } from "@/toast/toast-manager";
function ToastList() {
const { t } = useTranslation();
const { toasts } = ToastPrimitive.useToastManager();
return toasts.map((toast) => (
<ToastPrimitive.Root
key={toast.id}
toast={toast}
data-slot="toast"
className={cn(
"flex items-start gap-2 rounded-md border bg-white p-3 text-sm shadow-md",
toast.type === "error" && "border-red-300",
toast.type === "success" && "border-green-300",
)}
>
<div className="flex-1">
{toast.title && (
<ToastPrimitive.Title
data-slot="toast-title"
className="font-medium"
/>
)}
<ToastPrimitive.Description
data-slot="toast-description"
className="text-neutral-700"
/>
</div>
<ToastPrimitive.Close
data-slot="toast-close"
aria-label={t("common.close")}
className="text-neutral-400 hover:text-neutral-700"
>
×
</ToastPrimitive.Close>
</ToastPrimitive.Root>
));
}
/** App-wide toast region: provides the external manager + a portaled viewport. */
export function ToastRegion({ children }: { children: React.ReactNode }) {
return (
<ToastPrimitive.Provider toastManager={toastManager}>
{children}
<ToastPrimitive.Portal>
<ToastPrimitive.Viewport className="fixed bottom-4 right-4 z-50 flex w-80 flex-col gap-2">
<ToastList />
</ToastPrimitive.Viewport>
</ToastPrimitive.Portal>
</ToastPrimitive.Provider>
);
}
+12 -2
View File
@@ -1,9 +1,10 @@
{ {
"app": { "name": "Collection" }, "app": { "name": "Collection" },
"common": { "yes": "Yes", "no": "No", "close": "Close" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" }, "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" }, "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" }, "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" }, "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" }, "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." }, "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." },
@@ -58,5 +59,14 @@
"gateError": "Can't publish — required fields are missing.", "gateError": "Can't publish — required fields are missing.",
"editLink": "Edit the record", "editLink": "Edit the record",
"illegalError": "That visibility change isn't allowed." "illegalError": "That visibility change isn't allowed."
},
"toast": {
"created": "Created",
"saved": "Saved",
"updated": "Updated",
"deleted": "Deleted",
"renamed": "Renamed",
"published": "Visibility updated",
"error": "Something went wrong"
} }
} }
+12 -2
View File
@@ -1,9 +1,10 @@
{ {
"app": { "name": "Samling" }, "app": { "name": "Samling" },
"common": { "yes": "Ja", "no": "Nej", "close": "Stäng" },
"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" }, "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" }, "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" }, "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" }, "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" }, "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." }, "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." },
@@ -58,5 +59,14 @@
"gateError": "Kan inte publicera — obligatoriska fält saknas.", "gateError": "Kan inte publicera — obligatoriska fält saknas.",
"editLink": "Redigera posten", "editLink": "Redigera posten",
"illegalError": "Den synlighetsändringen är inte tillåten." "illegalError": "Den synlighetsändringen är inte tillåten."
},
"toast": {
"created": "Skapat",
"saved": "Sparat",
"updated": "Uppdaterat",
"deleted": "Borttaget",
"renamed": "Namn ändrat",
"published": "Synlighet uppdaterad",
"error": "Något gick fel"
} }
} }
+8
View File
@@ -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);
}
+6 -4
View File
@@ -1,21 +1,23 @@
import { StrictMode } from "react"; import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClientProvider } from "@tanstack/react-query";
import { App } from "./app"; import { App } from "./app";
import { ConfigProvider } from "./config/config-provider"; import { ConfigProvider } from "./config/config-provider";
import { makeQueryClient } from "./api/query-client";
import { ToastRegion } from "./components/ui/toast";
import "./index.css"; import "./index.css";
import "./i18n"; import "./i18n";
const queryClient = new QueryClient({ const queryClient = makeQueryClient();
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
});
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<ConfigProvider> <ConfigProvider>
<ToastRegion>
<App /> <App />
</ToastRegion>
</ConfigProvider> </ConfigProvider>
</QueryClientProvider> </QueryClientProvider>
</StrictMode>, </StrictMode>,
@@ -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<typeof FlexibleFieldValue>
export default meta
type Story = StoryObj<typeof meta>
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()
},
}
@@ -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(<FlexibleFieldValue def={def("material")} value="t-bronze" lang="en" />);
expect(await screen.findByText("Bronze")).toBeInTheDocument();
});
test("authority id resolves to its label", async () => {
renderApp(<FlexibleFieldValue def={def("maker")} value="a-ada" lang="en" />);
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
});
test("unknown term id renders <id> (unknown)", async () => {
renderApp(<FlexibleFieldValue def={def("material")} value="t-missing" lang="en" />);
expect(await screen.findByText(/t-missing\s*\(unknown\)/)).toBeInTheDocument();
});
test("localized_text picks the active language string", () => {
renderApp(
<FlexibleFieldValue
def={def("title_ml")}
value={{ sv: "Brons-amfora", en: "Bronze amphora" }}
lang="sv"
/>,
);
expect(screen.getByText("Brons-amfora")).toBeInTheDocument();
expect(screen.queryByText("Bronze amphora")).not.toBeInTheDocument();
});
test("date is formatted, not the raw ISO string", () => {
renderApp(<FlexibleFieldValue def={def("made_on")} value="2024-01-05" lang="en" />);
expect(screen.queryByText("2024-01-05")).not.toBeInTheDocument();
expect(screen.getByText(/Jan.*5.*2024/)).toBeInTheDocument();
});
test("boolean true renders Yes", () => {
renderApp(<FlexibleFieldValue def={def("is_fragment")} value={true} lang="en" />);
expect(screen.getByText("Yes")).toBeInTheDocument();
});
+94
View File
@@ -0,0 +1,94 @@
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"];
/** 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 <TermValue vocabularyId={def.vocabulary_id ?? null} value={value} lang={lang} />;
case "authority":
return <AuthorityValue kind={def.authority_kind ?? null} value={value} lang={lang} />;
case "localized_text":
return <>{pickLocalized(value, lang)}</>;
case "date":
return <>{formatDate(value, lang)}</>;
case "boolean":
return <BooleanValue value={value} />;
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 <span className="text-neutral-400"></span>;
return (
<span className="text-neutral-400">
{value} {t("objects.unknownRef")}
</span>
);
}
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 <span className="text-neutral-400"></span>;
return (
<span className="text-neutral-400">
{value} {t("objects.unknownRef")}
</span>
);
}
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<string, string>;
return map[lang] ?? map.en ?? Object.values(map)[0] ?? "—";
}
return value == null ? "—" : String(value);
}
+69 -22
View File
@@ -1,9 +1,10 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { screen } from "@testing-library/react"; import { screen, within } from "@testing-library/react";
import { http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { Routes, Route } from "react-router-dom"; import { Routes, Route } from "react-router-dom";
import { server } from "../test/server"; import { server } from "../test/server";
import { renderApp } from "../test/render"; import { renderApp } from "../test/render";
import { amphora } from "../test/fixtures";
import { ObjectDetail } from "./object-detail"; import { ObjectDetail } from "./object-detail";
function tree() { function tree() {
@@ -14,35 +15,81 @@ function tree() {
); );
} }
test("renders inventory-minimum fields, flexible values and visibility", async () => { // An object seeded with a term, a localized_text and a date flexible value.
// override so the object carries a flexible field value (schema types fields as // `inscription` belongs to the "Description" group; the rest are ungrouped
// Record<string,never>, so return a plain object literal here) // ("Other"). recording_date is null to exercise the empty-core placeholder.
server.use( const detailed = {
http.get("/api/admin/objects/:id", () => ...amphora,
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, recording_date: null,
visibility: "public", fields: {
fields: { material: "Bronze" }, inscription: "AVE",
}), material: "t-bronze",
), title_ml: { sv: "Brons-amfora", en: "Bronze amphora" },
); made_on: "2024-01-05",
renderApp(tree(), { route: "/objects/11111111-1111-1111-1111-111111111111" }); // 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(await screen.findByText("Amphora")).toBeInTheDocument();
expect(screen.getByText("Vault 3")).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; // "Public" appears in both the VisibilityBadge and the PublishControl stepper;
// scope the assertion to the badge element to avoid ambiguity. // scope the assertion to the badge element to avoid ambiguity.
expect(document.querySelector("[data-slot='badge']")).toHaveTextContent("Public"); 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 () => { test("shows a not-found state for a missing object", async () => {
server.use(http.get("/api/admin/objects/:id", () => new HttpResponse(null, { status: 404 }))); server.use(http.get("/api/admin/objects/:id", () => new HttpResponse(null, { status: 404 })));
renderApp(tree(), { route: "/objects/does-not-exist" }); renderApp(tree(), { route: "/objects/does-not-exist" });
+61 -25
View File
@@ -1,25 +1,26 @@
import type { ReactNode } from "react";
import { Link, useParams } from "react-router-dom"; import { Link, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useObject, useFieldDefinitions } from "../api/queries"; import { useObject, useFieldDefinitions } from "../api/queries";
import { formatDate } from "../lib/format-date";
import { DeleteObjectDialog } from "./delete-object-dialog"; import { DeleteObjectDialog } from "./delete-object-dialog";
import { FlexibleFieldValue } from "./flexible-field-value";
import { PublishControl } from "./publish-control"; import { PublishControl } from "./publish-control";
import { VisibilityBadge } from "./visibility-badge"; import { VisibilityBadge } from "./visibility-badge";
import { buttonVariants } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
function Field({ type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
label,
value, function Field({ label, value }: { label: string; value: ReactNode }) {
}: { const empty = value === null || value === undefined || value === "";
label: string;
value: string | number | null | undefined;
}) {
if (value === null || value === undefined || value === "") return null;
return ( return (
<div className="border-b py-2"> <div className="border-b py-2">
<div className="text-xs uppercase tracking-wide text-neutral-400">{label}</div> <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> </div>
); );
} }
@@ -52,45 +53,80 @@ export function ObjectDetail() {
return byLang ?? byEnglish ?? key; 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 ( return (
<div className="overflow-auto p-4"> <div className="overflow-auto p-4">
<div className="mb-4 flex items-center gap-3"> <div className="mb-4 flex items-center gap-3">
<h2 className="text-xl font-semibold">{object.object_name}</h2> <h2 className="text-xl font-semibold">{object.object_name}</h2>
<VisibilityBadge visibility={object.visibility} /> <VisibilityBadge visibility={object.visibility} />
<Link to={`/objects/${object.id}/edit`} className="text-sm font-medium text-indigo-600"> <div className="ml-auto flex items-center gap-2">
<Link to={`/objects/${object.id}/edit`} className={buttonVariants({ size: "sm" })}>
{t("actions.edit")} {t("actions.edit")}
</Link> </Link>
<DeleteObjectDialog id={object.id} /> <DeleteObjectDialog id={object.id} />
</div> </div>
</div>
<Field label={t("fieldsLabels.objectNumber")} value={object.object_number} /> <Field label={t("fieldsLabels.objectNumber")} value={object.object_number} />
<Field label={t("fieldsLabels.count")} value={object.number_of_objects} /> <Field label={t("fieldsLabels.count")} value={object.number_of_objects} />
<Field label={t("fieldsLabels.briefDescription")} value={object.brief_description} /> <Field label={t("fieldsLabels.briefDescription")} value={object.brief_description} />
<Field label={t("fieldsLabels.currentLocation")} value={object.current_location} /> <Field label={t("fieldsLabels.currentLocation")} value={object.current_location} />
<Field label={t("fieldsLabels.currentOwner")} value={object.current_owner} /> <Field label={t("fieldsLabels.currentOwner")} value={object.current_owner} />
<Field label={t("fieldsLabels.recorder")} value={object.recorder} /> <Field label={t("fieldsLabels.recorder")} value={object.recorder} />
<Field label={t("fieldsLabels.recordingDate")} value={object.recording_date} /> <Field
{flexible.length > 0 && ( label={t("fieldsLabels.recordingDate")}
<div className="mt-4"> value={object.recording_date ? formatDate(object.recording_date, lang) : null}
<div className="mb-1 text-xs font-medium uppercase text-neutral-500"> />
{t("fieldsLabels.flexible")} {groups.map((g) => (
</div> <div key={g.group} className="mt-4">
{flexible.map(([key, value]) => ( <div className="mb-1 text-xs font-medium uppercase text-neutral-500">{g.group}</div>
{g.defs.map((d) => (
<Field
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 <Field
key={key} key={key}
label={labelFor(key)} label={key}
value={ value={
value == null <span className="text-neutral-400">
? null {typeof value === "object" ? JSON.stringify(value) : String(value)}
: typeof value === "object" </span>
? JSON.stringify(value)
: String(value)
} }
/> />
))} ))}
</div> </div>
)} ))}
<PublishControl object={object} /> <PublishControl object={object} />
</div> </div>
); );
+9
View File
@@ -0,0 +1,9 @@
import { Toast } from "@base-ui/react/toast";
/** A toast manager created outside React so non-React code (the QueryClient
* MutationCache) can add toasts. Passed to <Toast.Provider toastManager=…>.
*
* Note: in @base-ui/react ^1.5 `createToastManager` is only exported through
* the `Toast` namespace (index.parts), not as a top-level named export of the
* `@base-ui/react/toast` subpath — importing it directly fails at runtime. */
export const toastManager = Toast.createToastManager();