Compare commits

56 Commits

Author SHA1 Message Date
logaritmisk 97c63ac25b merge: UI polish bundle (#73)
CI / web (push) Successful in 6m4s
2026-06-10 13:47:28 +02:00
logaritmisk 62c569741f fix(web): UI polish — select placeholder, locked-field note, list overflow, sidebar toggle, heading wrap (#73)
Five small design/layout nits from the UI sweep:

- form.selectPlaceholder "— select —" → "Select…" / "Välj…", matching
  the affordance style of every other placeholder (Filter…, Search…).
- FieldForm in edit mode now explains its locked controls with a muted
  fields.lockedNote caption ("Key and type can't be changed after
  creation.") instead of leaving four silently disabled inputs.
- FieldList rows truncate long labels (min-w-0 on the row button +
  truncate on the label, shrink-0 on the badge and required marker)
  instead of overflowing the 20rem column.
- The sidebar collapse toggle is hidden on narrow viewports (hidden
  md:flex) instead of rendered permanently disabled/grayed — the rail
  is forced collapsed there anyway.
- PageTitle gains text-balance so long titles wrap evenly.

Closes #73

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:47:22 +02:00
logaritmisk 3ad0e56ecd merge: deep-linkable field selection (#72)
CI / web (push) Successful in 6m14s
2026-06-10 13:44:08 +02:00
logaritmisk ada5d06dad feat(web): deep-linkable field selection via /fields/:key (#72)
FieldsPage kept the selected field definition in component state, so
reload lost the selection, fields couldn't be linked/shared, and
back/forward didn't navigate selections — inconsistent with
/vocabularies/:id and /objects/:id.

Move selection into the URL: the route becomes /fields/:key?
(optional segment), FieldList selection navigates, cancel/done
navigates back to /fields, and the page derives the selected def from
the already-cached field-defs query. An unknown or stale key (e.g.
after deleting the selected field) falls back to the create form.

Tests: deep link opens the locked edit form, select→cancel round-trips
through the URL, unknown key falls back to create.

Closes #72

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:44:02 +02:00
logaritmisk 3a57c0a77c merge: reduced-motion support + overscroll containment (#71)
CI / web (push) Successful in 4m48s
2026-06-10 13:38:44 +02:00
logaritmisk 9a896bb5f6 fix(web): honor prefers-reduced-motion; contain overscroll in modal surfaces (#71)
Nothing in the app respected prefers-reduced-motion — the kit's
data-open/closed animations, the skeleton pulse, and the sidebar width
transition all ran unconditionally. Add a global base-layer rule that
collapses animation/transition durations to a single frame when the OS
asks for reduced motion; one rule covers current and future additions.

Add overscroll-y-contain to the scrollable modal/popup surfaces
(DrawerContent, SelectContent, ComboboxPopup) so flicking past the end
of their content no longer chain-scrolls the page beneath, and to
AlertDialogContent for when it gains scrollable content.

Verified in the built CSS: the media query and
overscroll-behavior-y:contain both compile into dist/assets.

Closes #71

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:38:37 +02:00
logaritmisk 78f5afad35 merge: pending-state feedback for delete confirms + login (#70)
CI / web (push) Successful in 4m37s
2026-06-10 13:35:34 +02:00
logaritmisk 27205c65ef fix(web): disable delete confirms while pending + Signing in… feedback (#70)
The delete dialogs (DeleteObjectDialog and the shared
DeleteConfirmDialog) left their confirm button enabled during the
in-flight request, so a double-click fired a second DELETE that 404'd
and surfaced a spurious error. Disable cancel + confirm while pending
and swap the confirm label to a new actions.deleting ("Deleting…" /
"Tar bort…").

The login button disabled itself during login.isPending but kept the
"Sign in" label; it now shows auth.signingIn ("Signing in…" /
"Loggar in…") so slow networks get visible feedback.

Each fix is covered by a gated-MSW (or gated-promise) test asserting
the pending label + disabled state before releasing the request.

Closes #70

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:35:27 +02:00
logaritmisk 091a1a651d merge: focus-visible rings + live search count (#69)
CI / web (push) Successful in 5m7s
2026-06-10 13:31:15 +02:00
logaritmisk ec11c9dc76 fix(web): focus-visible rings on remaining controls + live search count (#69)
Keyboard focus was invisible on the objects-table sort headers and
page-size select, breadcrumb links, the external-URI link, and the
combobox input/clear/trigger. Apply the shared focusRing helper in app
code and the kit's inline focus-visible classes (matching input.tsx)
in ui/combobox.

Make the search result count a role="status" live region so screen
readers announce updated counts while typing; the existing search test
now asserts the count through getByRole("status").

Closes #69

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:29:27 +02:00
logaritmisk 1d19ddfd96 merge: dark-mode tokens for popup primitives + theme-color/color-scheme sync (#68)
CI / web (push) Successful in 5m47s
2026-06-10 13:23:47 +02:00
logaritmisk 79a6567530 fix(web): dark-mode tokens for popup primitives + theme-color/color-scheme sync (#68)
Tooltip, toast, and combobox popups still hardcoded light colors
(bg-white, neutral-*, indigo-50) and rendered as white boxes in dark
mode; the objects-table page-size select did the same in app code.
Swap all of them to theme tokens (popover/accent/muted/destructive/
success) and replace the toast's literal "×" with the lucide X icon.

Wire browser chrome into the theme: color-scheme via CSS on
:root/.dark (follows the in-app toggle, not just the OS), a
theme-color meta kept in sync by the preload script and applyTheme(),
plus a unit test for the meta sync.

Extend check-no-raw-colors to also flag shadeless white/black
utilities outside components/ui/ so the objects-table case can't
recur.

Closes #68

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 09:42:57 +02:00
logaritmisk fe448034ac merge: instance-timezone timestamp formatter (#42)
CI / web (push) Successful in 5m29s
Add shared formatTimestamp(value, timeZone, locale) helper — date + short
time in the instance tz/locale, with a UTC fallback on an invalid IANA zone.
Route the objects-table 'Updated' column through it (was inline, date-only,
unguarded). Display-only; storage stays UTC.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 21:14:45 +02:00
logaritmisk 67c5da57bf feat(web): render objects 'Updated' as a tz-aware timestamp via formatTimestamp (#42) 2026-06-09 21:11:11 +02:00
logaritmisk 53405d7831 feat(web): formatTimestamp helper (instance tz + locale, UTC fallback) (#42) 2026-06-09 21:07:13 +02:00
logaritmisk e615260422 docs(plans): instance-timezone timestamp formatter — 2-task plan (#42) 2026-06-09 20:58:34 +02:00
logaritmisk 3b6441688f docs(specs): instance-timezone timestamp formatter (#42) 2026-06-09 15:34:02 +02:00
logaritmisk a0b7dcdc2d merge: responsive master/detail for vocabularies, search, fields (#58)
CI / web (push) Successful in 5m3s
2026-06-09 15:22:46 +02:00
logaritmisk 7f9cf9fe60 feat(web): responsive Fields page (stacks on narrow) (#58) 2026-06-09 15:18:39 +02:00
logaritmisk b83149e0bb feat(web): responsive Search master/detail (drawer on narrow) (#58) 2026-06-09 15:15:44 +02:00
logaritmisk 80c2aad298 feat(web): responsive Vocabularies master/detail (drawer on narrow) (#58) 2026-06-09 15:12:45 +02:00
logaritmisk b5756e16b5 refactor(web): shared DetailDrawer; objects-page uses it (#58) 2026-06-09 15:09:37 +02:00
logaritmisk b3f061ced7 docs(plans): responsive master/detail — 4-task plan (#58) 2026-06-09 15:06:42 +02:00
logaritmisk eec3a261b4 docs(specs): responsive master/detail for vocab/search/fields (#58) 2026-06-09 14:11:14 +02:00
logaritmisk 390f6897a8 merge: bundle vendor-split + test-gap fills (#67)
CI / web (push) Successful in 5m13s
2026-06-09 13:48:46 +02:00
logaritmisk 8b881f369b test(web): add a Storybook story for the combobox primitive (#67) 2026-06-09 12:32:06 +02:00
logaritmisk aef5000543 test(web): cover prune-fields, labels, format-date, delete-in-use dialog (#67) 2026-06-09 12:28:48 +02:00
logaritmisk 878db9a37b build(web): split framework deps into cache-stable vendor chunks (#67) 2026-06-09 12:24:47 +02:00
logaritmisk 0b44bc0855 docs(plans): bundle vendor-split + test gaps — 3-task plan (#67) 2026-06-09 12:16:23 +02:00
logaritmisk 79ee402b33 docs(specs): bundle vendor-split + test-gap fills (#67) 2026-06-09 12:09:02 +02:00
logaritmisk 64f35e5a57 merge: fix CI — Node 22, Playwright install, deterministic pending-state tests, testTimeout (#25)
CI / web (push) Successful in 7m32s
2026-06-09 11:57:32 +02:00
logaritmisk 3aff10557c ci: make the logout pending-state test deterministic (gate, not delay)
CI / web (push) Successful in 4m35s
Same timing-window race as object-new-page: the 50ms delay let the logout
resolve (menu unmounts on me=null) before findByText caught 'Signing out…'
on the slow CI runner. Hold the logout open with a promise released only
after the pending state is asserted.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 11:51:35 +02:00
logaritmisk e8fe24f755 ci: raise vitest testTimeout to 20s for the resource-constrained runner
CI / web (push) Failing after 3m50s
The 'narrow: detail renders inside a portaled drawer' test lazy-loads the
drawer chunk and exceeded the 5s default on the slow CI container (setup
alone took ~486s). Bump testTimeout on both vitest projects.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 11:44:30 +02:00
logaritmisk fc170ccf10 ci: install Playwright chromium for the storybook vitest project; deterministic in-flight test
CI / web (push) Failing after 4m5s
- CI runs the @vitest/browser-playwright (storybook) project, which needs the
  chromium browser downloaded — add 'playwright install --with-deps chromium'.
- object-new-page in-flight test held the create mutation open with a 50ms
  delay and raced the pending-state assertion (failed under CI timing); gate it
  on a promise released only after asserting 'saving…', so it's deterministic.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 11:37:20 +02:00
logaritmisk 3ae9d87e6e ci: bump Node 20 → 22 so pnpm 11 (needs Node ≥22.13) runs
CI / web (push) Failing after 2m25s
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 11:29:58 +02:00
logaritmisk 3dbede6bc2 and use correct container image
CI / web (push) Failing after 55s
2026-06-09 11:25:18 +02:00
logaritmisk ba238ca962 run ci on correct runner
CI / web (push) Failing after 4s
2026-06-09 11:24:08 +02:00
logaritmisk 7cabebc338 merge: design-kit consistency — useLang, class recipes, kit adoption (#66)
CI / web (push) Has been cancelled
2026-06-09 00:02:33 +02:00
logaritmisk 74cde67a54 refactor(web): kit consistency — focusRing, PageTitle, Badge, size-4, icon buttons (#66)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 23:49:35 +02:00
logaritmisk 900f85f8ac refactor(web): adopt useLang + segmentClass/rowStateClass across sites (#66) 2026-06-08 23:45:24 +02:00
logaritmisk 00a7ce772e feat(web): useLang + segmentClass/rowStateClass helpers; delete dead Card (#66) 2026-06-08 23:41:08 +02:00
logaritmisk 71dee23028 docs(plans): design-kit consistency — 3-task plan (#66) 2026-06-08 23:31:35 +02:00
logaritmisk 91716e628a docs(specs): design-kit consistency — useLang, class recipes, kit adoption (#66) 2026-06-08 22:32:34 +02:00
logaritmisk 002af9d1f8 merge: split queries.ts — errors + key factory + domain modules; invalidate search on object writes (#65)
CI / web (push) Has been cancelled
2026-06-08 22:26:41 +02:00
logaritmisk d8d8035850 refactor(web): split queries.ts into api/queries/ domain modules behind a barrel (#65) 2026-06-08 21:35:02 +02:00
logaritmisk 704b159d48 refactor(web): central query-key factory + invalidate search on object writes (#65)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 21:30:57 +02:00
logaritmisk c1bddb47c4 refactor(web): extract API error classes to api/errors.ts (#65) 2026-06-08 21:27:21 +02:00
logaritmisk a21ab85576 docs(plans): split queries.ts — 3-task plan (#65) 2026-06-08 20:46:29 +02:00
logaritmisk 7ddf6967ce docs(specs): split queries.ts — errors + key factory + domain modules (#65) 2026-06-08 20:37:11 +02:00
logaritmisk 404cf67f35 merge: unify vocabulary + authority CRUD into shared components (#64)
CI / web (push) Has been cancelled
2026-06-08 20:22:36 +02:00
logaritmisk 50d2512123 refactor(web): term/authority rows + pages adopt shared CRUD components (#64) 2026-06-08 20:16:17 +02:00
logaritmisk c689b8c0e9 feat(web): shared FilteredRecordList component (#64) 2026-06-08 20:11:29 +02:00
logaritmisk acdaf8d07f feat(web): shared LabelledRecordCreateForm component (#64) 2026-06-08 20:08:10 +02:00
logaritmisk 77c56f7a9d feat(web): shared LabelledRecordRow component (#64) 2026-06-08 20:05:05 +02:00
logaritmisk 030472c2da docs(plans): unify vocab + authority CRUD — 4-task plan (#64) 2026-06-08 19:56:42 +02:00
logaritmisk f1eb6a9ba5 docs(specs): unify vocabulary + authority CRUD (#64) 2026-06-08 19:52:35 +02:00
97 changed files with 5006 additions and 1192 deletions
+5 -2
View File
@@ -7,7 +7,9 @@ on:
jobs: jobs:
web: web:
runs-on: ubuntu-latest runs-on: aceofba-cluster
container:
image: ghcr.io/catthehacker/ubuntu:act-22.04
defaults: defaults:
run: run:
working-directory: web working-directory: web
@@ -18,12 +20,13 @@ jobs:
version: 11 version: 11
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 22
cache: pnpm cache: pnpm
cache-dependency-path: web/pnpm-lock.yaml cache-dependency-path: web/pnpm-lock.yaml
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm typecheck - run: pnpm typecheck
- run: pnpm lint - run: pnpm lint
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm test - run: pnpm test
- run: pnpm build - run: pnpm build
- run: pnpm check:size - run: pnpm check:size
@@ -0,0 +1,211 @@
# Design-Kit Consistency — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add three shared helpers (`useLang`, `segmentClass`, `rowStateClass`), adopt them across the duplicated sites, and apply behavior-preserving kit one-offs (delete dead Card, sidebar focusRing, login PageTitle, field-list Badge, size-4, icon dismiss buttons).
**Architecture:** Task 1 creates the helpers + deletes Card (additive/safe). Task 2 adopts the 3 helpers across 6 + 3 + 4 sites. Task 3 applies the one-off cleanups + full gate. Behavior-preserving throughout; `check:colors`/`check:size`/existing component tests are the guards.
**Tech Stack:** React 19 + TS + pnpm, Tailwind v4 (token classes + `cn`), react-i18next, Base UI, Vitest 4 + RTL.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; double-quote+semicolon; token classes only (`check:colors`). `tsconfig` has `noUnusedLocals`, so remove any destructure that becomes unused.
**Spec:** `docs/superpowers/specs/2026-06-08-design-kit-consistency-design.md`
**Key facts (verified current):**
- `lib/focus-ring.ts` exports `focusRing = "outline-none focus-visible:ring-3 focus-visible:ring-ring/50"`. `cn` is `@/lib/utils`.
- `Button` (`@/components/ui/button`) has sizes incl. `icon-sm`. `Badge` (`@/components/ui/badge`) has a `secondary` variant. `PageTitle` (`@/components/ui/page-title`) is an `<h1>` styled `text-2xl font-semibold tracking-tight`.
- `components/ui/card.tsx` has ZERO importers and no `card.stories`.
- `useLang` sites (each currently `const lang = i18n.language.startsWith("sv") ? "sv" : "en";`): `objects/object-detail.tsx:59`, `objects/field-input.tsx:32`, `vocab/vocabulary-terms.tsx:13`, `vocab/vocabulary-list.tsx:17`, `fields/field-list.tsx:27`, `authorities/authorities-page.tsx:19`.
- `segmentClass` sites: `objects/objects-table.tsx:174` (`` className={`${focusRing} rounded-md px-2 py-1 ${active ? "bg-primary text-primary-foreground" : "border"}`} ``), `search/search-panel.tsx:76` (`className={cn("rounded-md px-2 py-0.5", focusRing, active ? "bg-primary text-primary-foreground" : "border")}`), `authorities/authorities-page.tsx:41` (`cn("rounded-md px-3 py-1 text-sm", focusRing, isActive ? "bg-primary text-primary-foreground" : "border")`).
- `rowStateClass` sites: `objects/objects-table.tsx:252` (`selected ? "bg-primary/10" : "hover:bg-muted"`), `vocab/vocabulary-list.tsx:113` (`isActive ? "bg-primary/10" : "hover:bg-muted"`), `search/search-result-row.tsx:15` (`isActive ? "bg-primary/10" : "hover:bg-muted"`), `fields/field-list.tsx:86` (`def.key === selectedKey ? "bg-primary/10" : ""` — note the missing idle hover).
---
# Task 1: Create helpers + delete dead Card
**Files:** Create `web/src/lib/use-lang.ts`, `web/src/lib/class-recipes.ts`, `web/src/lib/class-recipes.test.ts`; Delete `web/src/components/ui/card.tsx`.
- [ ] **Step 1: `web/src/lib/use-lang.ts`:**
```ts
import { useTranslation } from "react-i18next";
/** The instance's active UI language, narrowed to the two supported locales. */
export function useLang(): "sv" | "en" {
const { i18n } = useTranslation();
return i18n.language.startsWith("sv") ? "sv" : "en";
}
```
- [ ] **Step 2: `web/src/lib/class-recipes.ts`:**
```ts
import { cn } from "@/lib/utils";
import { focusRing } from "./focus-ring";
/** Segmented-control / filter-pill item. Unifies the active/inactive token recipe +
* focus ring; callers pass their contextual padding/size via `className`. */
export function segmentClass(active: boolean, className?: string): string {
return cn("rounded-md", focusRing, active ? "bg-primary text-primary-foreground" : "border", className);
}
/** Selected vs idle row background for master-detail / list rows. */
export function rowStateClass(active: boolean): string {
return active ? "bg-primary/10" : "hover:bg-muted";
}
```
- [ ] **Step 3: `web/src/lib/class-recipes.test.ts`** (write + run):
```ts
import { expect, test } from "vitest";
import { rowStateClass, segmentClass } from "./class-recipes";
test("segmentClass active uses the primary tokens + focus ring", () => {
const cls = segmentClass(true, "px-2 py-1");
expect(cls).toContain("bg-primary");
expect(cls).toContain("text-primary-foreground");
expect(cls).toContain("focus-visible:ring-ring/50");
expect(cls).toContain("px-2");
});
test("segmentClass inactive uses border, not the primary fill", () => {
const cls = segmentClass(false);
expect(cls).toContain("border");
expect(cls).not.toContain("bg-primary");
});
test("rowStateClass toggles selected vs idle-hover", () => {
expect(rowStateClass(true)).toBe("bg-primary/10");
expect(rowStateClass(false)).toBe("hover:bg-muted");
});
```
Run: `cd web && pnpm vitest run src/lib/class-recipes.test.ts` → 3 passing.
- [ ] **Step 4: Delete the dead Card component:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git rm web/src/components/ui/card.tsx
```
(Confirm no references first: `git grep -n "components/ui/card\"" web/src` returns nothing.)
- [ ] **Step 5: Verify + lint:**
```bash
cd web && pnpm vitest run src/lib/class-recipes.test.ts && pnpm typecheck && pnpm lint
```
Expected: green (Card had no importers, so its deletion can't break typecheck/lint).
- [ ] **Step 6: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/lib/use-lang.ts web/src/lib/class-recipes.ts web/src/lib/class-recipes.test.ts
git rm -q web/src/components/ui/card.tsx 2>/dev/null; git add -A web/src/components/ui
git commit -m "feat(web): useLang + segmentClass/rowStateClass helpers; delete dead Card (#66)"
```
---
# Task 2: Adopt the helpers across the duplicated sites
**Files:** Modify `objects/object-detail.tsx`, `objects/field-input.tsx`, `vocab/vocabulary-terms.tsx`, `vocab/vocabulary-list.tsx`, `fields/field-list.tsx`, `authorities/authorities-page.tsx`, `objects/objects-table.tsx`, `search/search-panel.tsx`, `search/search-result-row.tsx`.
- [ ] **Step 1: Adopt `useLang()` in the 6 components.** In each of `objects/object-detail.tsx`, `objects/field-input.tsx`, `vocab/vocabulary-terms.tsx`, `vocab/vocabulary-list.tsx`, `fields/field-list.tsx`, `authorities/authorities-page.tsx`: add `import { useLang } from "../lib/use-lang";` and replace `const lang = i18n.language.startsWith("sv") ? "sv" : "en";` with `const lang = useLang();`. Then, if `i18n` is no longer referenced anywhere else in that component, change `const { t, i18n } = useTranslation();` to `const { t } = useTranslation();` (the `noUnusedLocals` typecheck will fail otherwise — so this removal is required wherever `i18n` becomes unused). Note `authorities/authorities-page.tsx` also imports `focusRing` and uses `cn` — leave those.
- [ ] **Step 2: Adopt `segmentClass` at the 3 segmented sites.**
- `objects/objects-table.tsx`: add `import { segmentClass } from "../lib/class-recipes";`; change the pill `className` (currently `` `${focusRing} rounded-md px-2 py-1 ${active ? "bg-primary text-primary-foreground" : "border"}` ``) to `className={segmentClass(active, "px-2 py-1")}`. If `focusRing` is now unused in this file, remove its import. (The object-number `<Link>` also uses `focusRing` — if so, KEEP the import.)
- `search/search-panel.tsx`: add the import; change `className={cn("rounded-md px-2 py-0.5", focusRing, active ? "bg-primary text-primary-foreground" : "border")}` to `className={segmentClass(active, "px-2 py-0.5")}`. Remove now-unused `focusRing`/`cn` imports if they're unused elsewhere in the file.
- `authorities/authorities-page.tsx`: add the import; change the NavLink className callback body `cn("rounded-md px-3 py-1 text-sm", focusRing, isActive ? "bg-primary text-primary-foreground" : "border")` to `segmentClass(isActive, "px-3 py-1 text-sm")`. Remove now-unused `focusRing`/`cn` imports if unused elsewhere.
- [ ] **Step 3: Adopt `rowStateClass` at the 4 selected-row sites.** Add `import { rowStateClass } from "…/lib/class-recipes";` (or extend the existing class-recipes import) to each:
- `objects/objects-table.tsx`: in the row `className`, change `${selected ? "bg-primary/10" : "hover:bg-muted"}` to `${rowStateClass(selected)}`.
- `vocab/vocabulary-list.tsx`: change `${isActive ? "bg-primary/10" : "hover:bg-muted"}` to `${rowStateClass(isActive)}`.
- `search/search-result-row.tsx`: change `${isActive ? "bg-primary/10" : "hover:bg-muted"}` to `${rowStateClass(isActive)}`.
- `fields/field-list.tsx`: change `${def.key === selectedKey ? "bg-primary/10" : ""}` to `${rowStateClass(def.key === selectedKey)}` (this ADDS the `hover:bg-muted` idle hover the others have — an intended consistency fix).
- [ ] **Step 4: Verify (vitest ONCE for the affected suites), typecheck, lint:**
```bash
cd web && pnpm vitest run src/objects src/vocab src/fields src/authorities src/search && pnpm typecheck && pnpm lint
```
Expected: green. These are class-string-equivalent changes (segmentClass/rowStateClass produce the same token sets; `cn` ordering is irrelevant to Tailwind), so the existing component tests pass unchanged. `field-list`'s row now also carries `hover:bg-muted` (additive). If a test asserted the exact old className string, update it to match the new equivalent (unlikely — tests query by role/text).
- [ ] **Step 5: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/objects/object-detail.tsx web/src/objects/field-input.tsx web/src/vocab/vocabulary-terms.tsx web/src/vocab/vocabulary-list.tsx web/src/fields/field-list.tsx web/src/authorities/authorities-page.tsx web/src/objects/objects-table.tsx web/src/search/search-panel.tsx web/src/search/search-result-row.tsx
git commit -m "refactor(web): adopt useLang + segmentClass/rowStateClass across sites (#66)"
```
---
# Task 3: One-off kit cleanups + full gate
**Files:** Modify `shell/sidebar.tsx`, `auth/login-page.tsx`, `fields/field-list.tsx`, `shell/theme-switch.tsx`, `shell/user-menu.tsx`, `shell/header-search.tsx`, `objects/objects-page.tsx`, `objects/object-detail-drawer.tsx`.
- [ ] **Step 1: `shell/sidebar.tsx`** — use the `focusRing` constant. Add `import { focusRing } from "../lib/focus-ring";` (if not already imported). At the two `cn(...)` sites (lines ~46 and ~88) replace the literal `"focus-visible:ring-3 focus-visible:ring-ring/50"` entry with `focusRing`. (Both are inside `cn(...)` lists, so just swap the string for the constant.)
- [ ] **Step 2: `auth/login-page.tsx`** — use `PageTitle`. Add `import { PageTitle } from "@/components/ui/page-title";` and change `<h1 className="text-2xl font-semibold">{app_name}</h1>` to `<PageTitle>{app_name}</PageTitle>`.
- [ ] **Step 3: `fields/field-list.tsx`** — type-tag → `Badge`. Add `import { Badge } from "@/components/ui/badge";` and change the type-tag `<span className="rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">{…}</span>` (line ~97) to `<Badge variant="secondary">{…}</Badge>` (keep the inner expression/children unchanged).
- [ ] **Step 4: Icon sizing → `size-4`** in the 3 app-source sites: `shell/theme-switch.tsx:39` (`<Icon className="h-4 w-4" …>``className="size-4"`), `shell/user-menu.tsx:27` (`<CircleUser className="h-4 w-4" …>``size-4`), `shell/header-search.tsx:23` (the search icon's `… h-4 w-4 …` → replace `h-4 w-4` with `size-4`, keeping the other classes). Do NOT touch `components/ui/select.tsx`.
- [ ] **Step 5: Icon dismiss buttons → kit Button.**
- `objects/objects-page.tsx:54`: add `import { Button } from "@/components/ui/button";` (if absent) and change the `<button type="button" onClick={closeDetail} aria-label={t("actions.closeDetail")} className="rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground"><X className="size-4" aria-hidden="true" /></button>` to:
```tsx
<Button
variant="ghost"
size="icon-sm"
onClick={closeDetail}
aria-label={t("actions.closeDetail")}
>
<X className="size-4" aria-hidden="true" />
</Button>
```
- `objects/object-detail-drawer.tsx:31-36`: add `import { Button } from "@/components/ui/button";` and render the `DrawerClose` AS the kit Button via the render prop:
```tsx
<DrawerClose
aria-label={t("actions.closeDetail")}
render={<Button variant="ghost" size="icon-sm" />}
>
<X className="size-4" aria-hidden="true" />
</DrawerClose>
```
(This mirrors the `AlertDialogTrigger render={<Button … />}` pattern in `components/delete-confirm-dialog.tsx`; the `DrawerClose` keeps its close-on-click behaviour and the `aria-label`.)
- [ ] **Step 6: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. Report test totals, largest chunk (gz) from check:size (should be ≤ the prior ~216.5 KB — the Card delete only removes dead code), and the `check:colors` line. The existing `user-menu`, `objects-table`, `object-detail`/drawer, `login-page`, sidebar, `field-list`, search tests must pass unchanged (the icon buttons keep their `aria-label`s; the drawer still closes; login still renders an `<h1>` via PageTitle).
- [ ] **Step 7: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`).
- [ ] **Step 8: Manual smoke (recommended).** `pnpm dev`: the visibility pills / authority tabs / search facets look unchanged and keep their focus rings; the selected list rows (objects, vocab, search, fields) highlight identically and field rows now have a hover; the object-detail close buttons (wide pane + drawer) work; the login title and field-list type tag look right.
- [ ] **Step 9: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/shell/sidebar.tsx web/src/auth/login-page.tsx web/src/fields/field-list.tsx web/src/shell/theme-switch.tsx web/src/shell/user-menu.tsx web/src/shell/header-search.tsx web/src/objects/objects-page.tsx web/src/objects/object-detail-drawer.tsx
git commit -m "refactor(web): kit consistency — focusRing, PageTitle, Badge, size-4, icon buttons (#66)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 `useLang` + 6 sites (T1 S1, T2 S1); AC2 `segmentClass`/`rowStateClass` + adoption + field-list hover fix (T1 S2-S3, T2 S2-S3); AC3 Card deleted (T1 S4); AC4 one-offs — sidebar focusRing, login PageTitle, field-list Badge, size-4, icon buttons (T3 S1-S5); AC5 gate/check:size/codename (T3 S6-S7). ✓
**Placeholder scan:** every edit gives the exact before string + after code; helper bodies are complete; the test has concrete assertions. The "remove `i18n` if unused" instructions are concrete (driven by `noUnusedLocals`). No TBD. ✓
**Type/consistency:** `useLang()` (T1) returns `"sv" | "en"` consumed as `const lang` (T2 S1); `segmentClass(active, className?)` / `rowStateClass(active)` (T1) called with the exact args in T2 S2-S3; `Button size="icon-sm"`, `Badge variant="secondary"`, `PageTitle` all confirmed to exist. ✓
## Notes
- No new dependency, no new i18n keys. `check:colors` stays green — `segmentClass`/`rowStateClass` and all edits use tokens (`bg-primary`, `border`, `ring-ring`, `bg-muted`). Card deletion only removes dead code.
- `cn()` (tailwind-merge) makes class ordering irrelevant, so the helper outputs are visually identical to the prior inline strings (except field-list's intended added hover).
- The `<SegmentedControl>` component and the form-spacing scale are deferred (out of scope).
@@ -0,0 +1,344 @@
# Split queries.ts — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Extract the 4 error classes to `api/errors.ts`, add a `keys` query-key factory in `api/query-keys.ts` (and invalidate `["search"]` on object writes), then split `queries.ts` into `api/queries/{auth,objects,field-defs,vocab,authorities,search}.ts` behind a stable `api/queries/index.ts` barrel — behavior-preserving except the search invalidation.
**Architecture:** Three ordered, individually-green tasks. Task 1 extracts errors (queries.ts re-exports them). Task 2 adds the key factory + search invalidation (still monolithic). Task 3 moves the now-final hook bodies into domain modules behind a barrel that keeps `../api/queries` stable for all ~30 consumers.
**Tech Stack:** React 19 + TS + pnpm, TanStack Query v5, openapi-fetch, Vitest 4 (jsdom) + RTL + MSW.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; double-quote+semicolon. Run a single test pass per task. Behavior-preserving except the one search-invalidation change.
**Spec:** `docs/superpowers/specs/2026-06-08-split-queries-design.md`
**Key facts:**
- `web/src/api/queries.ts` (584 lines) currently defines 4 error classes (`HttpError` :6, `FieldRejection` :13, `InUseError` :20, `VisibilityError` :394) + `type ObjectListParams` (:46) + all hooks.
- Error-class importers (non-test): `api/error-message.ts` (`HttpError, InUseError`), `objects/object-edit-form.tsx` + `objects/object-new-page.tsx` (`FieldRejection`), `objects/publish-control.tsx` (`VisibilityError`), `search/search-panel.tsx` (`HttpError`) — all via `../api/queries`. Tests: `mutation-error.test.tsx`, `labelled-record-row.test.tsx`, `error-message.test.ts` import error classes from `../api/queries`.
- ~30 files import hooks from `../api/queries`. Query-layer test suites: `queries.test.ts`, `queries.authoring.test.tsx`, `queries.fields.test.tsx`, `queries.search.test.tsx`, `queries.visibility.test.tsx`, `queries.vocab.test.tsx`, `mutation-feedback.test.tsx`.
- Key literals: `["me"]`, `["config"]` (in `config/config-provider.tsx:10`), `["objects", params]`, `["objects"]`, `["object", id]`, `["field-definitions"]`, `["terms", vocabularyId]`, `["authorities", kind]`, `["vocabularies"]`, `["search", term, visibility]`.
- `useTerms`/`useAuthorities` key on a `string | null | undefined` arg (enabled-gated), so `keys.terms`/`keys.authorities` must accept that union.
---
# Task 1: Extract error classes → `api/errors.ts`
**Files:** Create `web/src/api/errors.ts`; Modify `web/src/api/queries.ts`, `web/src/api/error-message.ts`.
- [ ] **Step 1: Create `web/src/api/errors.ts`** (move the 4 classes verbatim):
```ts
export class HttpError extends Error {
constructor(public readonly status: number) {
super(`HTTP ${status}`);
this.name = "HttpError";
}
}
export class FieldRejection extends Error {
constructor(public readonly field: string, public readonly code: string) {
super(`field rejected: ${field}`);
this.name = "FieldRejection";
}
}
export class InUseError extends Error {
constructor(public readonly count: number) {
super(`in use: ${count}`);
this.name = "InUseError";
}
}
/** Error carrying the HTTP status so callers can branch 422-gate vs 409-illegal. */
export class VisibilityError extends Error {
constructor(public status: number) {
super(`visibility change failed (${status})`);
this.name = "VisibilityError";
}
}
```
- [ ] **Step 2: Update `web/src/api/queries.ts`.** DELETE the 4 class definitions (lines ~6-25 `HttpError`/`FieldRejection`/`InUseError`, and ~393-399 `VisibilityError`). At the top of the file (after the existing `import` lines), add an import for use + a re-export for compatibility:
```ts
import { HttpError, FieldRejection, InUseError, VisibilityError } from "./errors";
export { HttpError, FieldRejection, InUseError, VisibilityError } from "./errors";
```
(The `import` binds them for the throw sites in this file; the `export … from` re-exports them so every consumer importing from `../api/queries` keeps working. Everything else in `queries.ts` is unchanged.)
- [ ] **Step 3: Repoint `web/src/api/error-message.ts`.** Change `import { HttpError, InUseError } from "./queries";` to `import { HttpError, InUseError } from "./errors";`. (This is the decoupling: the toast path no longer transitively loads the hook module.)
- [ ] **Step 4: Verify (vitest ONCE for the affected suites), typecheck, lint:**
```bash
cd web && pnpm vitest run src/api/error-message.test.ts src/api/mutation-feedback.test.tsx src/api/queries.test.ts src/components/mutation-error.test.tsx src/components/labelled-record-row.test.tsx && pnpm typecheck && pnpm lint
```
Expected: green. The error classes are now sourced from `errors.ts` but re-exported, so all importers resolve. If typecheck flags an unused import in `queries.ts`, ensure each of the 4 classes is actually thrown somewhere in the file (they are: `HttpError` many sites, `FieldRejection` in `useSetFields`, `InUseError` in the delete mutations, `VisibilityError` in `useSetVisibility`) — keep all four in the import.
- [ ] **Step 5: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/api/errors.ts web/src/api/queries.ts web/src/api/error-message.ts
git commit -m "refactor(web): extract API error classes to api/errors.ts (#65)"
```
---
# Task 2: Query-key factory + search invalidation
**Files:** Create `web/src/api/query-keys.ts`, `web/src/api/query-keys.test.ts`, `web/src/api/search-invalidation.test.tsx`; Modify `web/src/api/queries.ts`, `web/src/config/config-provider.tsx`.
- [ ] **Step 1: Create `web/src/api/query-keys.ts`:**
```ts
export type ObjectListParams = {
limit: number;
offset: number;
sort?: string;
order?: "asc" | "desc";
visibility?: string;
q?: string;
};
/** Central query-key factory — the single source of truth for cache keys, so
* query/invalidate/setQueryData sites can't drift. */
export const keys = {
me: () => ["me"] as const,
config: () => ["config"] as const,
objects: () => ["objects"] as const,
objectsPage: (params: ObjectListParams) => ["objects", params] as const,
object: (id: string) => ["object", id] as const,
fieldDefinitions: () => ["field-definitions"] as const,
vocabularies: () => ["vocabularies"] as const,
terms: (vocabularyId: string | null | undefined) => ["terms", vocabularyId] as const,
authorities: (kind: string | null | undefined) => ["authorities", kind] as const,
search: () => ["search"] as const,
searchResults: (term: string, visibility: string | null) => ["search", term, visibility] as const,
};
```
- [ ] **Step 2: Create `web/src/api/query-keys.test.ts`** (write + run):
```ts
import { expect, test } from "vitest";
import { keys } from "./query-keys";
test("the key factory produces the expected arrays", () => {
expect(keys.me()).toEqual(["me"]);
expect(keys.config()).toEqual(["config"]);
expect(keys.objects()).toEqual(["objects"]);
const p = { limit: 50, offset: 0 };
expect(keys.objectsPage(p)).toEqual(["objects", p]);
expect(keys.object("x")).toEqual(["object", "x"]);
expect(keys.fieldDefinitions()).toEqual(["field-definitions"]);
expect(keys.vocabularies()).toEqual(["vocabularies"]);
expect(keys.terms("v1")).toEqual(["terms", "v1"]);
expect(keys.authorities("person")).toEqual(["authorities", "person"]);
expect(keys.search()).toEqual(["search"]);
expect(keys.searchResults("q", null)).toEqual(["search", "q", null]);
});
test("objects() is a prefix of objectsPage() so invalidation matches", () => {
const prefix = keys.objects();
const full = keys.objectsPage({ limit: 50, offset: 0 });
expect(full.slice(0, prefix.length)).toEqual(prefix);
});
```
Run: `cd web && pnpm vitest run src/api/query-keys.test.ts`.
- [ ] **Step 3: Replace every key literal in `web/src/api/queries.ts` with `keys.*`.** Add `import { keys, type ObjectListParams } from "./query-keys";` and DELETE the local `export type ObjectListParams = {…};` block (now imported). Substitutions (every occurrence):
- `queryKey: ["me"]``queryKey: keys.me()`; `qc.invalidateQueries({ queryKey: ["me"] })``keys.me()`; `qc.setQueryData(["me"], null)``qc.setQueryData(keys.me(), null)`
- `queryKey: ["objects", params]``keys.objectsPage(params)`
- `["objects"]` (invalidations) → `keys.objects()`
- `["object", id]``keys.object(id)`
- `["field-definitions"]``keys.fieldDefinitions()`
- `["terms", vocabularyId]``keys.terms(vocabularyId)`
- `["authorities", kind]``keys.authorities(kind)`
- `["vocabularies"]``keys.vocabularies()`
- `queryKey: ["search", term, visibility]``keys.searchResults(term, visibility)`
Re-export the type so consumers importing `ObjectListParams` from `../api/queries` keep working: add `export type { ObjectListParams } from "./query-keys";` near the top.
- [ ] **Step 4: Add search invalidation (`web/src/api/queries.ts`).** In each of these `onSuccess` handlers add `void qc.invalidateQueries({ queryKey: keys.search() });`:
- `useUpdateObject` onSuccess (after the `objects`/`object` invalidations)
- `useDeleteObject` onSuccess (alongside the `objects` invalidation — convert it to a block: `onSuccess: () => { void qc.invalidateQueries({ queryKey: keys.objects() }); void qc.invalidateQueries({ queryKey: keys.search() }); }`)
- `useSetVisibility` onSuccess (after the `object`/`objects` invalidations)
- [ ] **Step 5: Update `web/src/config/config-provider.tsx`.** Add `import { keys } from "../api/query-keys";` and change `queryKey: ["config"]``queryKey: keys.config()`.
- [ ] **Step 6: Create `web/src/api/search-invalidation.test.tsx`** (write + run) — proves the new behavior:
```tsx
import { expect, test } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
import { server } from "../test/server";
import { useSetVisibility } from "./queries";
import { keys } from "./query-keys";
test("changing an object's visibility invalidates the active search query", async () => {
server.use(
http.post("/api/admin/objects/:id/visibility", () => new HttpResponse(null, { status: 204 })),
);
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(keys.searchResults("amphora", null), { pages: [], pageParams: [] });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>{children}</QueryClientProvider>
);
const { result } = renderHook(() => useSetVisibility(), { wrapper });
await result.current.mutateAsync({ id: "o1", visibility: "public" });
await waitFor(() =>
expect(qc.getQueryState(keys.searchResults("amphora", null))?.isInvalidated).toBe(true),
);
});
```
Run: `cd web && pnpm vitest run src/api/search-invalidation.test.tsx`. (If `isInvalidated` is flaky, assert `qc.getQueryState(keys.searchResults("amphora", null))` exists and was marked stale via `isInvalidated`; the mutation's `onSuccess` runs the invalidation synchronously after the 204.)
- [ ] **Step 7: Verify (vitest ONCE for the query suites), typecheck, lint:**
```bash
cd web && pnpm vitest run src/api/query-keys.test.ts src/api/search-invalidation.test.tsx src/api/queries.test.ts src/api/queries.authoring.test.tsx src/api/queries.fields.test.tsx src/api/queries.search.test.tsx src/api/queries.visibility.test.tsx src/api/queries.vocab.test.tsx src/config && pnpm typecheck && pnpm lint
```
Expected: green. The key arrays are identical to before, so all existing query tests pass unchanged.
- [ ] **Step 8: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/api/query-keys.ts web/src/api/query-keys.test.ts web/src/api/search-invalidation.test.tsx web/src/api/queries.ts web/src/config/config-provider.tsx
git commit -m "refactor(web): central query-key factory + invalidate search on object writes (#65)"
```
---
# Task 3: Split queries.ts into `api/queries/` domain modules
**Files:** Create `web/src/api/queries/{index,auth,objects,field-defs,vocab,authorities,search}.ts`; Delete `web/src/api/queries.ts`.
**Approach:** Move each hook (and its local `type X = components[...]` aliases) VERBATIM from the current `queries.ts` into its domain module — the bodies already use `keys.*` and the `errors.ts` classes after Tasks 1-2. Only the relative import paths change (`./client``../client`, `./schema``../schema`, `./errors`, `./query-keys`). Then add the barrel and delete `queries.ts`.
- [ ] **Step 1: `web/src/api/queries/auth.ts`** — header + move `useMe`, `useLogin`, `useLogout`:
```ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { keys } from "../query-keys";
type UserView = components["schemas"]["UserView"];
type LoginRequest = components["schemas"]["LoginRequest"];
```
(These three throw only plain `Error` — no `errors.ts` import needed here.)
- [ ] **Step 2: `web/src/api/queries/objects.ts`** — header + move `useObjectsPage`, `useObject`, `useCreateObject`, `useUpdateObject`, `useSetFields`, `useDeleteObject`, `useSetVisibility`:
```ts
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, FieldRejection, VisibilityError } from "../errors";
import { keys, type ObjectListParams } from "../query-keys";
type ObjectCreateRequest = components["schemas"]["ObjectCreateRequest"];
type ObjectUpdateRequest = components["schemas"]["ObjectUpdateRequest"];
type Visibility = "draft" | "internal" | "public";
```
(`ObjectListParams` now comes from `query-keys`. `useObjectsPage`/`useObject` query fns throw plain `Error`; the mutations use the imported error classes.)
- [ ] **Step 3: `web/src/api/queries/field-defs.ts`** — header + move `useFieldDefinitions`, `useCreateFieldDefinition`, `useUpdateFieldDefinition`, `useDeleteFieldDefinition`:
```ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type NewFieldDefinitionRequest = components["schemas"]["NewFieldDefinitionRequest"];
type LabelInput = components["schemas"]["LabelInput"];
```
- [ ] **Step 4: `web/src/api/queries/vocab.ts`** — header + move `useVocabularies`, `useCreateVocabulary`, `useRenameVocabulary`, `useDeleteVocabulary`, `useTerms`, `useAddTerm`, `useUpdateTerm`, `useDeleteTerm`:
```ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type NewVocabularyRequest = components["schemas"]["NewVocabularyRequest"];
type LabelInput = components["schemas"]["LabelInput"];
```
- [ ] **Step 5: `web/src/api/queries/authorities.ts`** — header + move `useAuthorities`, `useCreateAuthority`, `useUpdateAuthority`, `useDeleteAuthority`:
```ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type LabelInput = components["schemas"]["LabelInput"];
```
- [ ] **Step 6: `web/src/api/queries/search.ts`** — header + move the `SEARCH_PAGE` const and `useSearch`:
```ts
import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";
import { api } from "../client";
import { HttpError } from "../errors";
import { keys } from "../query-keys";
const SEARCH_PAGE = 20;
```
- [ ] **Step 7: `web/src/api/queries/index.ts`** (barrel):
```ts
export * from "./auth";
export * from "./objects";
export * from "./field-defs";
export * from "./vocab";
export * from "./authorities";
export * from "./search";
export * from "../errors";
export type { ObjectListParams } from "../query-keys";
```
- [ ] **Step 8: Delete the old monolith:** `git rm web/src/api/queries.ts` (every hook has been moved; the barrel + modules now provide the same exports). Confirm no hook/type was dropped: each of the 24 hooks + `ObjectListParams` + the 4 error classes is exported via the barrel.
- [ ] **Step 9: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. The `../api/queries` import path now resolves to `api/queries/index.ts`, so all ~30 consumers + the query-layer test suites resolve unchanged. If typecheck reports a missing export, a hook landed in the wrong module or an import path is off — fix the module, do NOT edit consumers/tests. Report test totals, largest chunk (gz), and the `check:colors` line.
- [ ] **Step 10: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`); `web/src/api/queries.ts` shows as deleted, the 7 new files added.
- [ ] **Step 11: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/api/queries/ && git rm -q web/src/api/queries.ts 2>/dev/null; git add -A web/src/api
git commit -m "refactor(web): split queries.ts into api/queries/ domain modules behind a barrel (#65)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 errors extracted + error-message repointed + barrel re-export (T1, T3 S7); AC2 directory split + queries.ts deleted + stable path (T3); AC3 key factory used everywhere incl. config-provider (T2 S3/S5); AC4 search invalidation on the 3 object mutations (T2 S4); AC5 existing tests unchanged + gate (T1 S4, T2 S7, T3 S9). ✓
**Placeholder scan:** every new file shown in full or as a precise header + verbatim-move instruction; the move tasks name the exact hook list per module; tests have concrete assertions. No TBD. ✓
**Type/consistency:** `keys` (T2) is the same object consumed in T3's modules; `ObjectListParams` defined in `query-keys.ts` (T2), imported by `objects.ts` (T3 S2) and re-exported by the barrel (T3 S7); error classes from `errors.ts` (T1) imported by `objects/field-defs/vocab/authorities/search` modules (T3) and re-exported by the barrel; `keys.terms`/`keys.authorities` accept `string | null | undefined` to match the enabled-gated query usage. ✓
## Notes
- No new dependency, no new i18n keys, `components/ui/*` untouched. `check:size` should be unchanged (pure reorg + one invalidate call). Barrel keeps `../api/queries` stable → zero consumer churn.
- The error classes are intentionally importable from both `../api/errors` (canonical) and `../api/queries` (compat re-export). Repointing the 4 component importers to `../api/errors` is a deferred cosmetic follow-up.
- `auth.ts` needs no `errors.ts` import (its throws are plain `Error`); every other module imports the error classes it throws.
@@ -0,0 +1,726 @@
# Unify Vocabulary + Authority CRUD — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Collapse the duplicated Vocabulary-terms + Authorities CRUD (~280 lines across 4 files) into three shared components, with the rows and pages reduced to thin adapters — behavior-preserving.
**Architecture:** Build `LabelledRecordRow`, `LabelledRecordCreateForm`, and `FilteredRecordList<T>` in `src/components/` (Tasks 1-3, additive — existing app untouched, all existing tests stay green). Then rewire `term-row`/`authority-row` and `authorities-page`/`vocabulary-terms` onto them (Task 4) and run the full gate. Variance (mutation hooks, arg shapes, i18n keys, page chrome) lives entirely in the adapters.
**Tech Stack:** React 19 + TS + pnpm, TanStack Query v5, react-i18next, Base UI, Vitest 4 (jsdom) + RTL.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; double-quote+semicolon; token classes only; `components/ui/*` untouched. Run a single test pass per task.
**Spec:** `docs/superpowers/specs/2026-06-08-unify-record-crud-design.md`
**Key facts:**
- Types: `type LabelView = components["schemas"]["LabelView"]`, `type LabelInput = components["schemas"]["LabelInput"]`. `labelText(labels: LabelView[], lang)` (`lib/labels`), `byLabel(lang)` returns a comparator over `{ labels: LabelView[] }` (`lib/sort`).
- Shared building blocks (in `src/components/`): `label-editor` (`LabelEditor`, uses `useId` since #62, needs `useConfig` which defaults to `DEFAULTS` — works under `renderApp`), `delete-confirm-dialog` (`DeleteConfirmDialog` — props `description`, `onConfirm: () => Promise<void>`), `mutation-error` (`MutationError` — prop `error: unknown`), `external-uri-link` (`ExternalUriLink` — prop `uri`).
- UI kit: `Button`, `Input`, `Label` from `@/components/ui/*`; `ListSkeleton` from `@/components/ui/skeletons` (props `className`, `rows`).
- Test harness: `renderApp(ui, { route })` from `../test/render` (wraps QueryClient + memory router + i18n; NO ConfigProvider, but `useConfig` falls back to defaults). `HttpError` is exported from `../api/queries`.
- Existing tests that MUST stay green unchanged: `vocab/term-row.test.tsx`, `authorities/authorities.test.tsx`, `vocab/vocabularies.test.tsx`.
- Current `term-row.tsx`/`authority-row.tsx` are twins; `authorities-page.tsx` has a kind `<nav>` + `PageTitle` + `Navigate` guard + breadcrumb; `vocabulary-terms.tsx` has a `vocab.terms` caption + breadcrumb. Both pages render the filter input ALWAYS, then `isLoading ? <ListSkeleton/> : <ul>…</ul>`.
---
# Task 1: `LabelledRecordRow`
**Files:** Create `web/src/components/labelled-record-row.tsx`, `web/src/components/labelled-record-row.test.tsx`.
- [ ] **Step 1: Create `web/src/components/labelled-record-row.tsx`:**
```tsx
import { useId, useState } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { MutationError } from "./mutation-error";
import { ExternalUriLink } from "./external-uri-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";
type LabelView = components["schemas"]["LabelView"];
type LabelInput = components["schemas"]["LabelInput"];
export type RecordLike = { id: string; labels: LabelView[]; external_uri: string | null };
/** One labelled record (term/authority): a display row with edit + delete, or an
* inline editor. All variance (mutation hooks, arg shapes, delete-confirm key) is
* supplied by the caller via callbacks/state — see term-row.tsx / authority-row.tsx. */
export function LabelledRecordRow({
record,
lang,
deleteConfirmKey,
savePending,
saveError,
onEditOpen,
onSave,
onDelete,
}: {
record: RecordLike;
lang: string;
deleteConfirmKey: string;
savePending: boolean;
saveError: unknown;
onEditOpen: () => void;
onSave: (labels: LabelInput[], uri: string | null, done: () => void) => void;
onDelete: () => Promise<void>;
}) {
const { t } = useTranslation();
const uriId = useId();
const [editing, setEditing] = useState(false);
const [labels, setLabels] = useState<LabelInput[]>(record.labels as LabelInput[]);
const [uri, setUri] = useState(record.external_uri ?? "");
if (editing) {
return (
<li className="space-y-2 border-b py-2">
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={uriId}>{t("labels.externalUri")}</Label>
<Input
id={uriId}
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/>
</div>
<div className="flex gap-2">
<Button
type="button"
size="sm"
disabled={savePending}
onClick={() => onSave(labels, uri.trim() || null, () => setEditing(false))}
>
{t("actions.save")}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
{t("form.cancel")}
</Button>
</div>
<MutationError error={saveError} />
</li>
);
}
return (
<li className="flex items-center gap-2 border-b py-1 text-sm">
<div className="flex-1">
<div>{labelText(record.labels, lang)}</div>
{record.external_uri && <ExternalUriLink uri={record.external_uri} />}
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
onEditOpen();
setLabels(record.labels as LabelInput[]);
setUri(record.external_uri ?? "");
setEditing(true);
}}
>
{t("actions.edit")}
</Button>
<DeleteConfirmDialog description={t(deleteConfirmKey)} onConfirm={onDelete} />
</li>
);
}
```
- [ ] **Step 2: Create `web/src/components/labelled-record-row.test.tsx`** (write + run). Type the test record as `RecordLike` (import it) — no `any`/`never`:
```tsx
import { expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { LabelledRecordRow, type RecordLike } from "./labelled-record-row";
import { HttpError } from "../api/queries";
const record: RecordLike = { id: "r1", external_uri: null, labels: [{ lang: "en", label: "Bronze" }] };
test("edit → save calls onSave and closes via done()", async () => {
const onSave = vi.fn((_labels: unknown, _uri: unknown, done: () => void) => done());
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={null}
onEditOpen={() => {}}
onSave={onSave}
onDelete={async () => {}}
/>
</ul>,
);
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(onSave).toHaveBeenCalled();
expect(screen.queryByRole("button", { name: /save/i })).toBeNull();
});
test("a save error renders inline and the row stays editable", async () => {
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={new HttpError(403)}
onEditOpen={() => {}}
onSave={() => {}}
onDelete={async () => {}}
/>
</ul>,
);
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(screen.getByRole("alert")).toHaveTextContent(/permission/i);
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
});
test("confirming delete invokes onDelete", async () => {
const onDelete = vi.fn(async () => {});
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={null}
onEditOpen={() => {}}
onSave={() => {}}
onDelete={onDelete}
/>
</ul>,
);
// open the confirm dialog (trigger button is labelled "Delete")
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
// the dialog renders in a portal on document.body with a confirm "Delete" action
const dialog = within(document.body);
const confirmButtons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(confirmButtons[confirmButtons.length - 1]);
expect(onDelete).toHaveBeenCalled();
});
```
Run: `cd web && pnpm vitest run src/components/labelled-record-row.test.tsx`. (If the delete-dialog DOM differs, mirror the portal/confirm pattern used in `web/src/shell/user-menu.test.tsx` / the delete-confirm-dialog story — the key assertion is that confirming calls `onDelete`. Don't weaken the save/error assertions.)
- [ ] **Step 3: Verify + lint:** `cd web && pnpm vitest run src/components/labelled-record-row.test.tsx && pnpm typecheck && pnpm lint` — all green.
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/components/labelled-record-row.tsx web/src/components/labelled-record-row.test.tsx
git commit -m "feat(web): shared LabelledRecordRow component (#64)"
```
---
# Task 2: `LabelledRecordCreateForm`
**Files:** Create `web/src/components/labelled-record-create-form.tsx`, `web/src/components/labelled-record-create-form.test.tsx`.
- [ ] **Step 1: Create `web/src/components/labelled-record-create-form.tsx`:**
```tsx
import { useId, useState, type FormEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { MutationError } from "./mutation-error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
type LabelInput = components["schemas"]["LabelInput"];
/** Create form for a labelled record (term/authority): single-language label +
* optional external URI, with required-label validation and a status-aware error.
* `onCreate` performs the mutation and is handed a `reset` to clear the inputs on success. */
export function LabelledRecordCreateForm({
heading,
submitLabel,
pending,
error,
onCreate,
}: {
heading: ReactNode;
submitLabel: string;
pending: boolean;
error: unknown;
onCreate: (labels: LabelInput[], uri: string | null, reset: () => void) => void;
}) {
const { t } = useTranslation();
const uriId = useId();
const [labels, setLabels] = useState<LabelInput[]>([]);
const [uri, setUri] = useState("");
const [requiredError, setRequiredError] = useState(false);
const onSubmit = (event: FormEvent) => {
event.preventDefault();
if (!labels.some((l) => l.label)) {
setRequiredError(true);
return;
}
setRequiredError(false);
onCreate(labels, uri.trim() || null, () => {
setLabels([]);
setUri("");
});
};
return (
<form onSubmit={onSubmit} className="space-y-2 border-t pt-3">
<div className="text-sm font-medium">{heading}</div>
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={uriId}>{t("labels.externalUri")}</Label>
<Input
id={uriId}
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/>
</div>
{requiredError && (
<p role="alert" className="text-xs text-destructive">
{t("form.required")}
</p>
)}
<MutationError error={error} />
<Button type="submit" size="sm" disabled={pending}>
{submitLabel}
</Button>
</form>
);
}
```
- [ ] **Step 2: Create `web/src/components/labelled-record-create-form.test.tsx`** (write + run):
```tsx
import { expect, test, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { LabelledRecordCreateForm } from "./labelled-record-create-form";
test("submitting with empty labels shows the required error and does not call onCreate", async () => {
const onCreate = vi.fn();
renderApp(
<LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
);
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(screen.getByRole("alert")).toBeInTheDocument(); // form.required (MutationError is null → no alert)
expect(onCreate).not.toHaveBeenCalled();
});
test("a valid submit calls onCreate and the reset clears the inputs", async () => {
const onCreate = vi.fn((_labels: unknown, _uri: unknown, reset: () => void) => reset());
renderApp(
<LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
);
const labelInput = screen.getByLabelText(/^label$/i) as HTMLInputElement;
await userEvent.type(labelInput, "Bronze");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(onCreate).toHaveBeenCalled();
expect((screen.getByLabelText(/^label$/i) as HTMLInputElement).value).toBe("");
});
```
Run: `cd web && pnpm vitest run src/components/labelled-record-create-form.test.tsx`. (The required-error `<p role="alert">` is the only alert when `error={null}`; `LabelEditor`'s label is "Label".)
- [ ] **Step 3: Verify + lint:** `cd web && pnpm vitest run src/components/labelled-record-create-form.test.tsx && pnpm typecheck && pnpm lint`.
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/components/labelled-record-create-form.tsx web/src/components/labelled-record-create-form.test.tsx
git commit -m "feat(web): shared LabelledRecordCreateForm component (#64)"
```
---
# Task 3: `FilteredRecordList<T>`
**Files:** Create `web/src/components/filtered-record-list.tsx`, `web/src/components/filtered-record-list.test.tsx`.
- [ ] **Step 1: Create `web/src/components/filtered-record-list.tsx`:**
```tsx
import { Fragment, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { byLabel } from "../lib/sort";
import { labelText } from "../lib/labels";
import { Input } from "@/components/ui/input";
import { ListSkeleton } from "@/components/ui/skeletons";
type LabelView = components["schemas"]["LabelView"];
/** Filterable, alphabetically-sorted list of labelled records with the standard
* loading / error / empty / no-matches states. The filter input stays visible
* during load (matching the prior page behaviour). */
export function FilteredRecordList<T extends { id: string; labels: LabelView[] }>({
records,
lang,
isLoading,
isError,
loadErrorText,
emptyText,
renderRow,
}: {
records: T[] | undefined;
lang: string;
isLoading: boolean;
isError: boolean;
loadErrorText: string;
emptyText: string;
renderRow: (record: T) => ReactNode;
}) {
const { t } = useTranslation();
const [filter, setFilter] = useState("");
const q = filter.trim().toLowerCase();
const rows = [...(records ?? [])]
.filter((r) => !q || labelText(r.labels, lang).toLowerCase().includes(q))
.sort(byLabel(lang));
return (
<>
<div className="mb-3">
<Input
aria-label={t("common.filter")}
placeholder={t("common.filter")}
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
</div>
{isLoading ? (
<ListSkeleton className="mb-4" rows={5} />
) : (
<ul className="mb-4">
{isError && <li className="text-sm text-destructive">{loadErrorText}</li>}
{!isError && records?.length === 0 && (
<li className="text-sm text-muted-foreground">{emptyText}</li>
)}
{!isError && records && records.length > 0 && rows.length === 0 && (
<li className="text-sm text-muted-foreground">{t("common.noMatches")}</li>
)}
{rows.map((r) => (
<Fragment key={r.id}>{renderRow(r)}</Fragment>
))}
</ul>
)}
</>
);
}
```
- [ ] **Step 2: Create `web/src/components/filtered-record-list.test.tsx`** (write + run):
```tsx
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { FilteredRecordList } from "./filtered-record-list";
import { labelText } from "../lib/labels";
type Rec = { id: string; labels: { lang: string; label: string }[] };
const recs: Rec[] = [
{ id: "a", labels: [{ lang: "en", label: "Alpha" }] },
{ id: "b", labels: [{ lang: "en", label: "Beta" }] },
];
const row = (r: Rec) => <li>{labelText(r.labels, "en")}</li>;
test("filtering narrows the rendered rows", async () => {
renderApp(
<FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("Alpha")).toBeInTheDocument();
expect(screen.getByText("Beta")).toBeInTheDocument();
await userEvent.type(screen.getByLabelText(/filter/i), "alph");
expect(screen.getByText("Alpha")).toBeInTheDocument();
expect(screen.queryByText("Beta")).toBeNull();
});
test("empty records show the empty text", () => {
renderApp(
<FilteredRecordList records={[]} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("EmptyMsg")).toBeInTheDocument();
});
test("non-empty records with a non-matching filter show no-matches", async () => {
renderApp(
<FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
await userEvent.type(screen.getByLabelText(/filter/i), "zzz");
expect(screen.getByText(/no matches/i)).toBeInTheDocument();
});
test("an error shows the load-error text", () => {
renderApp(
<FilteredRecordList records={undefined} lang="en" isLoading={false} isError={true}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("LoadErr")).toBeInTheDocument();
});
```
Run: `cd web && pnpm vitest run src/components/filtered-record-list.test.tsx`.
- [ ] **Step 3: Verify + lint:** `cd web && pnpm vitest run src/components/filtered-record-list.test.tsx && pnpm typecheck && pnpm lint`.
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/components/filtered-record-list.tsx web/src/components/filtered-record-list.test.tsx
git commit -m "feat(web): shared FilteredRecordList component (#64)"
```
---
# Task 4: Wire the adapters + pages, then full gate
**Files:** Modify `web/src/vocab/term-row.tsx`, `web/src/authorities/authority-row.tsx`, `web/src/authorities/authorities-page.tsx`, `web/src/vocab/vocabulary-terms.tsx`.
- [ ] **Step 1: Rewrite `web/src/vocab/term-row.tsx`** (keep the `<TermRow vocabularyId term lang />` API):
```tsx
import type { components } from "../api/schema";
import { useUpdateTerm, useDeleteTerm } from "../api/queries";
import { LabelledRecordRow } from "../components/labelled-record-row";
type TermView = components["schemas"]["TermView"];
export function TermRow({ vocabularyId, term, lang }: { vocabularyId: string; term: TermView; lang: string }) {
const update = useUpdateTerm();
const del = useDeleteTerm();
return (
<LabelledRecordRow
record={term}
lang={lang}
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={update.isPending}
saveError={update.error}
onEditOpen={() => update.reset()}
onSave={(labels, uri, done) =>
update.mutate({ vocabularyId, termId: term.id, external_uri: uri, labels }, { onSuccess: done })}
onDelete={() => del.mutateAsync({ vocabularyId, termId: term.id })}
/>
);
}
```
- [ ] **Step 2: Rewrite `web/src/authorities/authority-row.tsx`** (keep `<AuthorityRow authority kind lang />`):
```tsx
import type { components } from "../api/schema";
import { useUpdateAuthority, useDeleteAuthority } from "../api/queries";
import { LabelledRecordRow } from "../components/labelled-record-row";
type AuthorityView = components["schemas"]["AuthorityView"];
export function AuthorityRow({ authority, kind, lang }: { authority: AuthorityView; kind: string; lang: string }) {
const update = useUpdateAuthority();
const del = useDeleteAuthority();
return (
<LabelledRecordRow
record={authority}
lang={lang}
deleteConfirmKey="actions.confirmDeleteAuthority"
savePending={update.isPending}
saveError={update.error}
onEditOpen={() => update.reset()}
onSave={(labels, uri, done) =>
update.mutate({ id: authority.id, kind, external_uri: uri, labels }, { onSuccess: done })}
onDelete={() => del.mutateAsync({ id: authority.id, kind })}
/>
);
}
```
- [ ] **Step 3: Rewrite `web/src/authorities/authorities-page.tsx`** to use the shared list + form. Keep the `PageTitle`, kind `<nav>`, `Navigate` guard, `useDocumentTitle`, `useBreadcrumb`. Remove the local `labels`/`uri`/`error`/`filter` state, the `onCreate` handler, and now-unused imports (`useState`, `FormEvent`, `LabelEditor`, `MutationError`, `Input`, `Label`, `ListSkeleton`, `byLabel`, `labelText`). New file:
```tsx
import { NavLink, Navigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useAuthorities, useCreateAuthority } from "../api/queries";
import { FilteredRecordList } from "../components/filtered-record-list";
import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { PageTitle } from "@/components/ui/page-title";
import { AuthorityRow } from "./authority-row";
import { focusRing } from "../lib/focus-ring";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { cn } from "@/lib/utils";
const KINDS = ["person", "organisation", "place"] as const;
export function AuthoritiesPage() {
const { t, i18n } = useTranslation();
const { kind } = useParams();
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
const isValidKind = (KINDS as readonly string[]).includes(kind ?? "");
const currentKind = isValidKind ? (kind as string) : "person";
const { data: authorities, isLoading, isError } = useAuthorities(currentKind);
const create = useCreateAuthority();
useDocumentTitle(t("nav.authorities"));
useBreadcrumb([{ label: t("nav.authorities") }]);
if (!isValidKind) return <Navigate to="/authorities/person" replace />;
return (
<div className="overflow-auto p-4">
<PageTitle className="mb-3">{t("nav.authorities")}</PageTitle>
<nav aria-label={t("nav.authorities")} className="mb-3 flex gap-2">
{KINDS.map((k) => (
<NavLink
key={k}
to={`/authorities/${k}`}
className={({ isActive }) =>
cn("rounded-md px-3 py-1 text-sm", focusRing, isActive ? "bg-primary text-primary-foreground" : "border")
}
>
{t(`authorities.${k}`)}
</NavLink>
))}
</nav>
<FilteredRecordList
records={authorities}
lang={lang}
isLoading={isLoading}
isError={isError}
loadErrorText={t("authorities.loadError")}
emptyText={t("authorities.empty")}
renderRow={(a) => <AuthorityRow authority={a} kind={currentKind} lang={lang} />}
/>
<LabelledRecordCreateForm
heading={`${t("authorities.new")} · ${t(`authorities.${currentKind}`)}`}
submitLabel={t("authorities.create")}
pending={create.isPending}
error={create.error}
onCreate={(labels, uri, reset) =>
create.mutate({ kind: currentKind, external_uri: uri, labels }, { onSuccess: reset })}
/>
</div>
);
}
```
(Note: the original passed `kind: kind as string` to `create.mutate`; `currentKind` is equivalent here since the `isValidKind` guard already returned otherwise — use `currentKind`.)
- [ ] **Step 4: Rewrite `web/src/vocab/vocabulary-terms.tsx`** to use the shared list + form. Keep the `vocab.terms` caption + breadcrumb + the `useVocabularies` lookup. Remove the local form/list state + now-unused imports:
```tsx
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useTerms, useAddTerm, useVocabularies } from "../api/queries";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { FilteredRecordList } from "../components/filtered-record-list";
import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { TermRow } from "./term-row";
export function VocabularyTerms() {
const { t, i18n } = useTranslation();
const { id } = useParams();
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
const { data: terms, isLoading, isError } = useTerms(id);
const addTerm = useAddTerm();
const { data: vocabularies } = useVocabularies();
const vocabKey = vocabularies?.find((v) => v.id === id)?.key;
useBreadcrumb(
vocabKey
? [{ label: t("nav.vocabularies"), to: "/vocabularies" }, { label: vocabKey }]
: [{ label: t("nav.vocabularies"), to: "/vocabularies" }],
);
if (!id) return null;
return (
<div className="overflow-auto p-4">
<div className="mb-2 label-caption">{t("vocab.terms")}</div>
<FilteredRecordList
records={terms}
lang={lang}
isLoading={isLoading}
isError={isError}
loadErrorText={t("vocab.loadError")}
emptyText={t("vocab.noTerms")}
renderRow={(term) => <TermRow vocabularyId={id} term={term} lang={lang} />}
/>
<LabelledRecordCreateForm
heading={t("vocab.addTerm")}
submitLabel={t("vocab.addTerm")}
pending={addTerm.isPending}
error={addTerm.error}
onCreate={(labels, uri, reset) =>
addTerm.mutate({ vocabularyId: id, external_uri: uri, labels }, { onSuccess: reset })}
/>
</div>
);
}
```
(Note: `useTerms(id)` and `if (!id) return null``id` is `string | undefined`; the hooks accept it, and the `!id` guard runs after the hooks, matching the original order. `renderRow`/`onCreate` use the narrowed `id` inside JSX where `!id` already returned — but to satisfy TS, `id` is `string` after the guard since the guard is before the `return` JSX. Confirm typecheck is clean; if TS still widens, the original already used `id` directly in the same spot, so it resolves.)
- [ ] **Step 5: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. The existing `term-row.test.tsx`, `authorities.test.tsx`, `vocabularies.test.tsx` MUST pass unchanged (behavior-preserving). Report test totals, largest chunk (gz), and the `check:colors` line. If an existing test fails, the refactor changed behavior — fix the adapter/page to match, do NOT edit the test.
- [ ] **Step 6: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`).
- [ ] **Step 7: Manual smoke (recommended).** `pnpm dev`: on Authorities and Vocabulary-terms — filter narrows the list; create with an empty label shows the required error; create/edit/delete work; a failed save shows the inline message and keeps the row editable; the authorities kind-tabs + breadcrumbs are unchanged.
- [ ] **Step 8: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/vocab/term-row.tsx web/src/authorities/authority-row.tsx web/src/authorities/authorities-page.tsx web/src/vocab/vocabulary-terms.tsx
git commit -m "refactor(web): term/authority rows + pages adopt shared CRUD components (#64)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 three components with the prop shapes (T1-T3); AC2 rows + pages de-duplicated (T4 S1-S4); AC3 existing tests green + 3 new component tests (T1-T3 tests, T4 S5); AC4 behavior preserved — edit/save/delete/create/validation/filter/4-states/kind-nav/breadcrumb (T4 + the existing-test guard); AC5 gate/check:size/no-new-keys/codename (T4 S5-S6). ✓
**Placeholder scan:** every component + adapter shown in full; tests have concrete assertions; the two soft spots (delete-dialog portal DOM in T1; `id` narrowing in T4) name the exact mitigation/precedent. No TBD. ✓
**Type/consistency:** `RecordLike = { id; labels: LabelView[]; external_uri }` (T1) is the row's `record`; `TermView`/`AuthorityView` structurally satisfy it (both have those fields). `onSave(labels: LabelInput[], uri: string | null, done)` (T1) matches the adapters' `update.mutate({…, external_uri: uri, labels}, { onSuccess: done })` (T4). `LabelledRecordCreateForm.onCreate(labels, uri, reset)` (T2) matches `create.mutate({…}, { onSuccess: reset })` (T4). `FilteredRecordList<T extends { id; labels: LabelView[] }>` (T3) consumed with `authorities`/`terms` (T4). ✓
## Notes
- No new dependency, no new i18n keys, `components/ui/*` untouched. Net code reduction → `check:size` should not grow.
- `TermRow`/`AuthorityRow` keep their public props so `term-row.test.tsx` stays valid unchanged.
- `vocabulary-list.tsx` (key-based vocabularies) is deliberately NOT touched.
@@ -0,0 +1,338 @@
# Bundle Vendor-Split + Test-Gap Fills — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Split framework deps into cache-stable vendor chunks, and fill the audit's unit-test (prune-fields, delete-confirm-dialog in-use, labels, format-date) + combobox-story gaps.
**Architecture:** Task 1 adds `build.rollupOptions.output.manualChunks` to `vite.config.ts` (production build only). Task 2 adds 4 jsdom unit tests for pure/critical units. Task 3 adds a Storybook story for the combobox primitive and runs the full gate. All additive/behavior-preserving.
**Tech Stack:** Vite 6 (Rollup), React 19 + TS + pnpm, Vitest 4 (jsdom + storybook-browser projects), Storybook, RTL + MSW.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; app/test source double-quote+semicolon; **stories use single-quote + no-semicolon** (mirror existing `ui/*.stories.tsx`). Run a single test pass per task.
**Spec:** `docs/superpowers/specs/2026-06-09-bundle-and-tests-design.md`
**Key facts:**
- `scripts/check-bundle-size.mjs` fails if the **largest** `dist/assets/*.js` gzip exceeds 250 KB; today ~216.5 KB (one chunk).
- `vite.config.ts` exports `defineConfig({ plugins, resolve, server, test })` — no `build` block. Deps: `react`, `react-dom`, `react-router-dom` (v7, re-exports `react-router`), `@tanstack/react-query`, `@base-ui/react`, `i18next`, `react-i18next`.
- `objects/prune-fields.ts`: `pruneFields(fields: Record<string, unknown>, localizedTextKeys: Set<string>, defaultLang: string): Record<string, unknown>`.
- `lib/labels.ts`: `labelText(labels: LabelView[], lang: string): string` (lang match → `"en"` → first → `""`).
- `lib/format-date.ts`: `formatDate(value: unknown, lang: string): string` (non-string null→`"—"`, non-string→`String(value)`; invalid→returns value; valid `YYYY-MM-DD``Intl.DateTimeFormat(lang,{dateStyle:"medium"})`, parsed at local midnight).
- `components/delete-confirm-dialog.tsx`: `DeleteConfirmDialog({ description, onConfirm: () => Promise<void>, triggerLabel? })`. Trigger is a `Button` labelled `t("actions.delete")` ("Delete"); the confirm action is also labelled `t("actions.delete")`. On a thrown error it sets a message via `errorMessageKey(err)` and **returns without closing**; on success it closes. `actions.inUse` (en) = "Can't delete — used by {{count}} object(s). Clear those fields first." `InUseError` is exported from `../api/errors` (and re-exported by `../api/queries`).
- `components/ui/combobox.tsx` exports `ComboboxRoot<Value>`, `ComboboxInputGroup`, `ComboboxInput`, `ComboboxClear`, `ComboboxTrigger`, `ComboboxPopup`, `ComboboxList`, `ComboboxItem`, `ComboboxItemIndicator`, `ComboboxEmpty`. See `objects/options-combobox.tsx` for the composition (ComboboxRoot props: `items`, `value`, `onValueChange`, `itemToStringLabel`, `isItemEqualToValue`; ComboboxList takes a render-function child).
- Story format (from `components/ui/badge.stories.tsx`): `import type { Meta, StoryObj } from '@storybook/react-vite'`; `import { expect } from 'storybook/test'`; `const meta = { component, tags: ['ai-generated'] } satisfies Meta<typeof X>`; `export default meta`; `type Story = StoryObj<typeof meta>`; `export const Default: Story = { play: async ({ canvas }) => {...} }`.
---
# Task 1: Vendor split (`vite.config.ts`)
**Files:** Modify `web/vite.config.ts`.
- [ ] **Step 1: Add the `build` block.** In `web/vite.config.ts`, add a top-level `build` key to the `defineConfig({...})` object (sibling of `plugins`/`resolve`/`server`/`test`):
```ts
build: {
rollupOptions: {
output: {
manualChunks: {
react: ["react", "react-dom", "react-router", "react-router-dom"],
"base-ui": ["@base-ui/react"],
query: ["@tanstack/react-query"],
i18n: ["i18next", "react-i18next"],
},
},
},
},
```
- [ ] **Step 2: Build + verify chunk split + budget:**
```bash
cd web && pnpm build && pnpm check:size && ls -1 dist/assets/*.js
```
Expected: build succeeds; `check:size` prints `largest JS chunk: <name> = <kb> KB gz (budget 250 KB)` and passes; `dist/assets/` now contains separate `react-*.js`, `base-ui-*.js`, `query-*.js`, `i18n-*.js` chunks plus the app entry. Report the largest chunk size (should be a vendor chunk, well under 250). If the build warns about React being in multiple chunks or a chunk is oversized, confirm `react`+`react-dom`+`react-router`+`react-router-dom` are all in the one `react` group and adjust.
- [ ] **Step 3: typecheck + lint** (config change shouldn't affect them, but confirm):
```bash
cd web && pnpm typecheck && pnpm lint
```
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/vite.config.ts
git commit -m "build(web): split framework deps into cache-stable vendor chunks (#67)"
```
---
# Task 2: Unit-test gaps (prune-fields, labels, format-date, delete-confirm-dialog)
**Files:** Create `web/src/objects/prune-fields.test.ts`, `web/src/lib/labels.test.ts`, `web/src/lib/format-date.test.ts`, `web/src/components/delete-confirm-dialog.test.tsx`.
- [ ] **Step 1: `web/src/objects/prune-fields.test.ts`:**
```ts
import { expect, test } from "vitest";
import { pruneFields } from "./prune-fields";
test("drops empty/null/undefined scalars, keeps real scalars", () => {
const out = pruneFields(
{ a: "x", b: "", c: null, d: undefined, e: 0, f: false },
new Set(),
"en",
);
expect(out).toEqual({ a: "x", e: 0, f: false });
});
test("a localized_text key keeps only the default-language entry", () => {
const out = pruneFields(
{ title: { en: "Bowl", sv: "Skål" } },
new Set(["title"]),
"sv",
);
expect(out).toEqual({ title: { sv: "Skål" } });
});
test("a non-localized object value keeps all non-empty entries", () => {
const out = pruneFields(
{ dims: { w: "10", h: "", d: "5" } },
new Set(),
"en",
);
expect(out).toEqual({ dims: { w: "10", d: "5" } });
});
test("an object value left with no entries is dropped entirely", () => {
const out = pruneFields(
{ title: { en: "Bowl" }, empty: { en: "", sv: "" } },
new Set(["title", "empty"]),
"sv",
);
// title has no `sv` entry → empty after filtering → dropped; empty → dropped
expect(out).toEqual({});
});
```
Run: `cd web && pnpm vitest run src/objects/prune-fields.test.ts`. (If a case's expectation mismatches the real semantics, re-read `prune-fields.ts` and correct the EXPECTATION to the true behavior — do not change the source.)
- [ ] **Step 2: `web/src/lib/labels.test.ts`:**
```ts
import { expect, test } from "vitest";
import { labelText } from "./labels";
const labels = [
{ lang: "en", label: "Bowl" },
{ lang: "sv", label: "Skål" },
];
test("returns the exact-language label when present", () => {
expect(labelText(labels, "sv")).toBe("Skål");
});
test("falls back to the English label when the requested language is missing", () => {
expect(labelText(labels, "de")).toBe("Bowl");
});
test("falls back to the first label when neither the language nor English is present", () => {
expect(labelText([{ lang: "fr", label: "Bol" }], "de")).toBe("Bol");
});
test("returns an empty string for no labels", () => {
expect(labelText([], "en")).toBe("");
});
```
Run: `cd web && pnpm vitest run src/lib/labels.test.ts`.
- [ ] **Step 3: `web/src/lib/format-date.test.ts`:**
```ts
import { expect, test } from "vitest";
import { formatDate } from "./format-date";
test("formats a date-only string in the locale without a timezone day-shift", () => {
// local-midnight parse must keep the calendar day (3), not shift to the 2nd
expect(formatDate("1962-04-03", "en")).toBe("Apr 3, 1962");
});
test("returns the em-dash placeholder for null", () => {
expect(formatDate(null, "en")).toBe("—");
});
test("returns an unparseable string unchanged", () => {
expect(formatDate("not-a-date", "en")).toBe("not-a-date");
});
test("stringifies a non-string, non-null value", () => {
expect(formatDate(42, "en")).toBe("42");
});
```
Run: `cd web && pnpm vitest run src/lib/format-date.test.ts`. (The CI/runtime is full-ICU Node 22, so en `dateStyle:"medium"``"Apr 3, 1962"`. If your local ICU formats slightly differently, assert the equivalent string but keep the day as `3` — the day-shift guard is the point.)
- [ ] **Step 4: `web/src/components/delete-confirm-dialog.test.tsx`:**
```tsx
import { expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { InUseError } from "../api/errors";
test("delete-in-use shows the in-use count and keeps the dialog open", async () => {
const onConfirm = vi.fn<() => Promise<void>>().mockRejectedValue(new InUseError(3));
renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const buttons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(buttons[buttons.length - 1]); // the confirm action
expect(await dialog.findByText(/used by 3/i)).toBeInTheDocument();
// dialog stays open: its description is still shown
expect(dialog.getByText("Delete this term?")).toBeInTheDocument();
});
test("a clean confirm closes the dialog", async () => {
const onConfirm = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const buttons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(buttons[buttons.length - 1]);
await waitFor(() => expect(dialog.queryByText("Delete this term?")).toBeNull());
expect(onConfirm).toHaveBeenCalledTimes(1);
});
```
Run: `cd web && pnpm vitest run src/components/delete-confirm-dialog.test.tsx`. (Before opening, only the trigger "Delete" button exists. After opening, the portal adds the action "Delete"; `findAllByRole` returns both, click the last. `actions.inUse` en contains "used by 3". If `vi.fn<() => Promise<void>>()` generic syntax trips the TS/vitest version, use `vi.fn(() => Promise.reject(new InUseError(3)))` / `vi.fn(() => Promise.resolve())`.)
- [ ] **Step 5: Verify all four (vitest ONCE) + typecheck + lint:**
```bash
cd web && pnpm vitest run src/objects/prune-fields.test.ts src/lib/labels.test.ts src/lib/format-date.test.ts src/components/delete-confirm-dialog.test.tsx && pnpm typecheck && pnpm lint
```
All green.
- [ ] **Step 6: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/objects/prune-fields.test.ts web/src/lib/labels.test.ts web/src/lib/format-date.test.ts web/src/components/delete-confirm-dialog.test.tsx
git commit -m "test(web): cover prune-fields, labels, format-date, delete-in-use dialog (#67)"
```
---
# Task 3: Combobox story + full gate
**Files:** Create `web/src/components/ui/combobox.stories.tsx`.
- [ ] **Step 1: Read `web/src/objects/options-combobox.tsx`** to mirror the exact `ComboboxRoot` composition (generic, props, the `ComboboxList` render-function child), then create `web/src/components/ui/combobox.stories.tsx` (single-quote + no-semicolon, matching `badge.stories.tsx`):
```tsx
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { expect } from 'storybook/test'
import {
ComboboxRoot,
ComboboxInputGroup,
ComboboxInput,
ComboboxClear,
ComboboxTrigger,
ComboboxPopup,
ComboboxList,
ComboboxItem,
ComboboxItemIndicator,
ComboboxEmpty,
} from './combobox'
const fruits = ['Apple', 'Apricot', 'Banana', 'Cherry']
function ComboboxDemo() {
const [value, setValue] = useState<string | null>(null)
return (
<ComboboxRoot<string | null>
items={fruits}
value={value}
onValueChange={setValue}
itemToStringLabel={(item) => item ?? ''}
isItemEqualToValue={(a, b) => a === b}
>
<ComboboxInputGroup>
<ComboboxInput placeholder='Pick a fruit' />
<ComboboxClear aria-label='Clear' />
<ComboboxTrigger aria-label='Open' />
</ComboboxInputGroup>
<ComboboxPopup>
<ComboboxEmpty>No matches</ComboboxEmpty>
<ComboboxList>
{(item: string) => (
<ComboboxItem key={item} value={item}>
<ComboboxItemIndicator className='text-primary'></ComboboxItemIndicator>
{item}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxPopup>
</ComboboxRoot>
)
}
const meta = {
component: ComboboxDemo,
tags: ['ai-generated'],
} satisfies Meta<typeof ComboboxDemo>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
play: async ({ canvas }) => {
await expect(canvas.getByPlaceholderText('Pick a fruit')).toBeInTheDocument()
},
}
```
(Adjust the `ComboboxRoot` generic/props to match `options-combobox.tsx` exactly if they differ — the goal is a rendering `Default` story; keep the `play` minimal to stay stable in the browser project.)
- [ ] **Step 2: Run the storybook project for this story** (browser test):
```bash
cd web && pnpm vitest run src/components/ui/combobox.stories.tsx
```
Expected: the `Default` story passes (input renders). If the Base UI combobox API needs a different prop shape, fix the story (mirror `options-combobox.tsx`); do not weaken the assertion below a render check.
- [ ] **Step 3: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. Report total test count (should be prior 268 + 4 unit + 1 story ≈ 273), the largest chunk (gz) from check:size (a vendor chunk, < 250), and the check:colors line.
- [ ] **Step 4: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`).
- [ ] **Step 5: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/components/ui/combobox.stories.tsx
git commit -m "test(web): add a Storybook story for the combobox primitive (#67)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 vendor split + verify (T1); AC2 the 4 unit tests (T2 S1-S4); AC3 combobox story (T3 S1-S2); AC4 full gate + codename (T3 S3-S4). ✓
**Placeholder scan:** every test/story is complete code with concrete assertions; manualChunks is exact; the format-date ICU note and the vi.fn generic note give concrete fallbacks, not vague TODOs. ✓
**Type/consistency:** `pruneFields(fields, Set, lang)`, `labelText(labels, lang)`, `formatDate(value, lang)`, `DeleteConfirmDialog({description,onConfirm})`, `InUseError(count)` from `../api/errors` — all match the spec's documented signatures; the combobox story imports the exact exports from `./combobox`. ✓
## Notes
- No new dependency, no new i18n keys. `build.rollupOptions` only affects `pnpm build`; the test projects are unaffected.
- The combobox story is the one item with a (small) CI cost (a browser test on the slow runner); it's isolated in its own task/commit so it can be dropped cleanly if undesired.
- `check:size` should report a smaller largest chunk after the split (a vendor chunk, not the combined app+vendor chunk).
@@ -0,0 +1,425 @@
# Responsive Master/Detail (vocab/search/fields) — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Bring the Vocabularies, Search, and Fields master/detail screens to the responsive behavior the Objects screen already has — preserving wide side-by-side, collapsing to single-column + a slide-in Drawer (vocab/search) or a stack (fields) on narrow — via one shared `DetailDrawer`.
**Architecture:** Generalize the objects-specific drawer into a reusable `components/detail-drawer.tsx` and retrofit Objects onto it (Task 1). Make vocabularies + search responsive with `useMediaQuery("(min-width: 1024px)")` + `useMatch` + the shared drawer (Tasks 2-3). Make fields a pure-CSS responsive stack (Task 4) + full gate. Behavior-preserving on wide; only narrow changes.
**Tech Stack:** React 19 + TS + pnpm, React Router 7, Base UI Drawer, Tailwind v4, Vitest 4 (jsdom) + RTL + MSW.
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; double-quote+semicolon; token classes only. Breakpoint **1024px** (`useMediaQuery("(min-width: 1024px)")` / Tailwind `lg:`), matching Objects. Run a single test pass per task.
**Spec:** `docs/superpowers/specs/2026-06-09-responsive-master-detail-design.md`
**Key facts:**
- `lib/use-media-query.ts`: `useMediaQuery(query): boolean` (SSR-safe matchMedia).
- `objects/object-detail-drawer.tsx` (to be generalized + deleted) is: `<Drawer open onOpenChange={(n)=>{if(!n)onClose()}} swipeDirection="right"><DrawerContent aria-label={t("objects.detailTitle")}><div className="flex justify-end border-b p-2"><DrawerClose aria-label={t("actions.closeDetail")} render={<Button variant="ghost" size="icon-sm" />}><X className="size-4" aria-hidden="true" /></DrawerClose></div><div className="flex-1 overflow-auto"><Outlet/></div></DrawerContent></Drawer>`. `Drawer`/`DrawerClose`/`DrawerContent` from `@/components/ui/drawer`.
- `objects/objects-page.tsx` currently `lazy()`-loads `ObjectDetailDrawer` + wraps in `<Suspense fallback={null}>`; narrow branch renders `{open && <Suspense><ObjectDetailDrawer open={open} onClose={closeDetail} /></Suspense>}`. The WIDE pane has its own close `<Button … aria-label={t("actions.closeDetail")}><X/></Button>` — keep it (`X` import stays).
- Existing i18n (no new keys): `objects.detailTitle` ("Object detail"), `vocab.terms` ("Terms"), `actions.closeDetail` ("Close detail").
- `vocabularies-page.tsx`: `<div flex h-full flex-col><PageTitle>…</PageTitle><div grid grid-cols-[20rem_1fr]><div border-r><VocabularyList/></div><div><Outlet/></div></div></div>`. Routes: `/vocabularies` (index `SelectVocabularyPrompt`) + `/vocabularies/:id` (`VocabularyTerms`).
- `search-page.tsx`: same shape, `grid-cols-[24rem_1fr]`, `<SearchPanel/>`, routes `/search` (index `SelectSearchPrompt`) + `/search/:id` (`ObjectDetail`).
- `fields-page.tsx`: `useState`-driven; `<div grid grid-cols-[20rem_1fr]><div border-r><FieldList selectedKey onSelect/></div><div><FieldForm key editing onDone/></div></div>`. No routes.
- Test harness: `objects-page.test.tsx` has a `setViewport(wide: boolean)` helper that overrides `window.matchMedia` to match `(min-width: 1024px)` only when `wide`; default test setup is narrow (`matches:false`); `afterEach(() => vi.restoreAllMocks())`. Narrow-drawer assertion pattern: deep-link to `:id`, then `within(document.body).findByRole(...)` for the portaled drawer + assert the `/close detail/i` button. No `vocabularies-page`/`search-page`/`fields-page` test files exist yet.
---
# Task 1: Shared `DetailDrawer` + retrofit Objects
**Files:** Create `web/src/components/detail-drawer.tsx`, `web/src/components/detail-drawer.test.tsx`; Modify `web/src/objects/objects-page.tsx`; Delete `web/src/objects/object-detail-drawer.tsx`.
- [ ] **Step 1: Create `web/src/components/detail-drawer.tsx`:**
```tsx
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { X } from "lucide-react";
import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer";
import { Button } from "@/components/ui/button";
/** A right-sliding Base UI Drawer for a master/detail "detail" on narrow viewports.
* Provides the close affordance + an accessible dialog name; the caller supplies the content. */
export function DetailDrawer({
open,
onClose,
ariaLabel,
children,
}: {
open: boolean;
onClose: () => void;
ariaLabel: string;
children: ReactNode;
}) {
const { t } = useTranslation();
return (
<Drawer
open={open}
onOpenChange={(next) => {
if (!next) onClose();
}}
swipeDirection="right"
>
<DrawerContent aria-label={ariaLabel}>
<div className="flex justify-end border-b p-2">
<DrawerClose
aria-label={t("actions.closeDetail")}
render={<Button variant="ghost" size="icon-sm" />}
>
<X className="size-4" aria-hidden="true" />
</DrawerClose>
</div>
<div className="flex-1 overflow-auto">{children}</div>
</DrawerContent>
</Drawer>
);
}
```
- [ ] **Step 2: Create `web/src/components/detail-drawer.test.tsx`** (write + run):
```tsx
import { expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { DetailDrawer } from "./detail-drawer";
test("renders children in a named drawer and closes via the close button", async () => {
const onClose = vi.fn();
renderApp(
<DetailDrawer open onClose={onClose} ariaLabel="Object detail">
<p>detail body</p>
</DetailDrawer>,
);
const body = within(document.body);
expect(await body.findByText("detail body")).toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: /close detail/i }));
expect(onClose).toHaveBeenCalled();
});
```
Run: `cd web && pnpm vitest run src/components/detail-drawer.test.tsx`. (If Base UI requires `open` to mount the portal, it's set; the content is portaled to `document.body`.)
- [ ] **Step 3: Retrofit `web/src/objects/objects-page.tsx`.** Remove `import { lazy, Suspense } from "react";` and the `const ObjectDetailDrawer = lazy(...)` block; add `import { DetailDrawer } from "../components/detail-drawer";`. Replace the narrow `return` block's drawer with:
```tsx
return (
<div className="h-full">
{table}
{open && (
<DetailDrawer open={open} onClose={closeDetail} ariaLabel={t("objects.detailTitle")}>
<Outlet />
</DetailDrawer>
)}
</div>
);
```
(Keep everything else — the wide grid branch with its own close `<Button><X/></Button>` is unchanged, so the `X` and `Button` imports stay.)
- [ ] **Step 4: Delete the old drawer:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git rm web/src/objects/object-detail-drawer.tsx
```
(Confirm no other importer: `git grep -n object-detail-drawer web/src` → only objects-page, now changed.)
- [ ] **Step 5: Verify (vitest ONCE) + typecheck + lint:**
```bash
cd web && pnpm vitest run src/components/detail-drawer.test.tsx src/objects/objects-page.test.tsx && pnpm typecheck && pnpm lint
```
Expected: green. The objects-page narrow + wide tests must pass unchanged (the shared `DetailDrawer` renders the same drawer + `/close detail/i` button).
- [ ] **Step 6: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/components/detail-drawer.tsx web/src/components/detail-drawer.test.tsx web/src/objects/objects-page.tsx
git rm -q web/src/objects/object-detail-drawer.tsx 2>/dev/null; git add -A web/src/objects
git commit -m "refactor(web): shared DetailDrawer; objects-page uses it (#58)"
```
---
# Task 2: Responsive Vocabularies page
**Files:** Modify `web/src/vocab/vocabularies-page.tsx`; Create `web/src/vocab/vocabularies-page.test.tsx`.
- [ ] **Step 1: Rewrite `web/src/vocab/vocabularies-page.tsx`:**
```tsx
import { Outlet, useMatch, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { VocabularyList } from "./vocabulary-list";
import { DetailDrawer } from "../components/detail-drawer";
import { useMediaQuery } from "../lib/use-media-query";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title";
export function VocabulariesPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const detailMatch = useMatch("/vocabularies/:id");
const open = Boolean(detailMatch);
const isWide = useMediaQuery("(min-width: 1024px)");
useDocumentTitle(t("nav.vocabularies"));
useBreadcrumb([{ label: t("nav.vocabularies") }]);
const close = () => navigate("/vocabularies");
return (
<div className="flex h-full flex-col">
<PageTitle className="px-4 pt-4 pb-2">{t("nav.vocabularies")}</PageTitle>
{isWide ? (
<div className="grid flex-1 grid-cols-[20rem_1fr] overflow-hidden">
<div className="overflow-hidden border-r">
<VocabularyList />
</div>
<div className="overflow-hidden">
<Outlet />
</div>
</div>
) : (
<div className="flex-1 overflow-hidden">
<VocabularyList />
</div>
)}
{!isWide && open && (
<DetailDrawer open={open} onClose={close} ariaLabel={t("vocab.terms")}>
<Outlet />
</DetailDrawer>
)}
</div>
);
}
```
(The `<Outlet/>` is rendered in exactly one place: the wide grid, OR the narrow drawer when `open`. On narrow with no `:id`, neither renders the Outlet — just the list.)
- [ ] **Step 2: Create `web/src/vocab/vocabularies-page.test.tsx`.** Read `web/src/test/fixtures.ts` + `web/src/test/handlers.ts` for the vocabularies list + terms handlers and a real vocabulary id. Mirror the `objects-page.test.tsx` `setViewport` harness:
```tsx
import { afterEach, expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import { Route, Routes } from "react-router-dom";
import { renderApp } from "../test/render";
import { VocabulariesPage } from "./vocabularies-page";
import { VocabularyTerms } from "./vocabulary-terms";
import { SelectVocabularyPrompt } from "./select-vocabulary-prompt";
function setViewport(wide: boolean) {
Object.defineProperty(window, "matchMedia", {
value: (query: string): MediaQueryList =>
({
matches: wide && query === "(min-width: 1024px)",
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as MediaQueryList,
writable: true,
});
}
afterEach(() => vi.restoreAllMocks());
function tree() {
return (
<Routes>
<Route path="/vocabularies" element={<VocabulariesPage />}>
<Route index element={<SelectVocabularyPrompt />} />
<Route path=":id" element={<VocabularyTerms />} />
</Route>
</Routes>
);
}
test("narrow: a selected vocabulary's detail renders in a portaled drawer", async () => {
setViewport(false);
renderApp(tree(), { route: `/vocabularies/<VOCAB_ID>` });
const body = within(document.body);
expect(
await body.findByRole("button", { name: /close detail/i }, { timeout: 5000 }),
).toBeInTheDocument();
});
test("wide: a selected vocabulary renders inline (no detail drawer)", async () => {
setViewport(true);
renderApp(tree(), { route: `/vocabularies/<VOCAB_ID>` });
// the list (master) is present and there is NO close-detail button (inline pane, not a drawer)
expect(await screen.findByRole("button", { name: /close detail/i }).catch(() => null)).toBeNull();
});
```
Replace `<VOCAB_ID>` with a real id from `fixtures.ts`. The narrow test asserts the drawer is present (the `/close detail/i` button only exists inside `DetailDrawer`). For the wide test, prefer a positive assertion that the master + inline detail both render (e.g. `await screen.findByText(<a stable vocab list item or the vocab.terms caption>)`) AND `screen.queryByRole("button", { name: /close detail/i })` is null. Adjust the queries to the fixtures' actual rendered text; the load-bearing checks are: **narrow → close-detail button present (drawer); wide → close-detail button absent (inline)**. Reuse the default MSW handlers (don't add new ones unless a handler is missing).
- [ ] **Step 3: Verify (vitest ONCE) + typecheck + lint:**
```bash
cd web && pnpm vitest run src/vocab/vocabularies-page.test.tsx src/vocab && pnpm typecheck && pnpm lint
```
Green. (Existing vocab tests stay green.)
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/vocab/vocabularies-page.tsx web/src/vocab/vocabularies-page.test.tsx
git commit -m "feat(web): responsive Vocabularies master/detail (drawer on narrow) (#58)"
```
---
# Task 3: Responsive Search page
**Files:** Modify `web/src/search/search-page.tsx`; Create `web/src/search/search-page.test.tsx`.
- [ ] **Step 1: Rewrite `web/src/search/search-page.tsx`** (same pattern as vocab; `24rem` master, `SearchPanel`, route `"/search/:id"`, close `"/search"`, drawer ariaLabel `t("objects.detailTitle")` since the search detail is an object):
```tsx
import { Outlet, useMatch, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { SearchPanel } from "./search-panel";
import { DetailDrawer } from "../components/detail-drawer";
import { useMediaQuery } from "../lib/use-media-query";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title";
export function SearchPage() {
const { t } = useTranslation();
const navigate = useNavigate();
const detailMatch = useMatch("/search/:id");
const open = Boolean(detailMatch);
const isWide = useMediaQuery("(min-width: 1024px)");
useDocumentTitle(t("nav.search"));
useBreadcrumb([{ label: t("nav.search") }]);
const close = () => navigate("/search");
return (
<div className="flex h-full flex-col">
<PageTitle className="px-4 pt-4 pb-2">{t("nav.search")}</PageTitle>
{isWide ? (
<div className="grid flex-1 grid-cols-[24rem_1fr] overflow-hidden">
<div className="overflow-hidden border-r">
<SearchPanel />
</div>
<div className="overflow-hidden">
<Outlet />
</div>
</div>
) : (
<div className="flex-1 overflow-hidden">
<SearchPanel />
</div>
)}
{!isWide && open && (
<DetailDrawer open={open} onClose={close} ariaLabel={t("objects.detailTitle")}>
<Outlet />
</DetailDrawer>
)}
</div>
);
}
```
- [ ] **Step 2: Create `web/src/search/search-page.test.tsx`** mirroring the vocab test (the `setViewport` helper, the same narrow→close-detail-present / wide→absent discriminator). Tree: `<Route path="/search" element={<SearchPage/>}><Route index element={<SelectSearchPrompt/>}/><Route path=":id" element={<ObjectDetail/>}/></Route>`. Deep-link `/search/<OBJECT_ID>` (use a real object id from `fixtures.ts`; the search detail loads the object via the same `/api/admin/objects/{id}` handler the objects tests use). Narrow → `within(document.body).findByRole("button", { name: /close detail/i })` present; wide → absent + the object detail renders inline. Reuse the default MSW handlers.
- [ ] **Step 3: Verify (vitest ONCE) + typecheck + lint:**
```bash
cd web && pnpm vitest run src/search/search-page.test.tsx src/search && pnpm typecheck && pnpm lint
```
Green.
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/search/search-page.tsx web/src/search/search-page.test.tsx
git commit -m "feat(web): responsive Search master/detail (drawer on narrow) (#58)"
```
---
# Task 4: Responsive Fields page (CSS stack) + full gate
**Files:** Modify `web/src/fields/fields-page.tsx`; Create `web/src/fields/fields-page.test.tsx`.
- [ ] **Step 1: Make `fields-page.tsx` a responsive stack.** Change the grid container + the list pane's border so it stacks on narrow and is side-by-side on `lg`:
```tsx
<div className="grid flex-1 grid-cols-1 overflow-auto lg:grid-cols-[20rem_1fr] lg:overflow-hidden">
<div className="overflow-hidden border-b lg:border-r lg:border-b-0">
<FieldList selectedKey={selected?.key ?? null} onSelect={setSelected} />
</div>
<div className="overflow-hidden">
<FieldForm
key={selected?.key ?? "create"}
editing={selected}
onDone={() => setSelected(null)}
/>
</div>
</div>
```
(On narrow: single column — list then form, the grid container scrolls (`overflow-auto`), the list gets a bottom divider. On `lg`: the two-column grid with the list's right border, clipped overflow as before. If the stacked panes still clip awkwardly in a manual smoke, adjust the narrow pane `overflow` — keep `lg:` behavior identical to today.)
- [ ] **Step 2: Create `web/src/fields/fields-page.test.tsx`:**
```tsx
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { renderApp } from "../test/render";
import { FieldsPage } from "./fields-page";
test("renders the field list and the field form, in a responsive grid", async () => {
const { container } = renderApp(<FieldsPage />);
// both panes present (master + detail)
expect(await screen.findByText(/fields/i)).toBeInTheDocument();
// the responsive grid: single-column by default, two-column at lg
const grid = container.querySelector("div.grid");
expect(grid?.className).toContain("grid-cols-1");
expect(grid?.className).toContain("lg:grid-cols-[20rem_1fr]");
});
```
Run: `cd web && pnpm vitest run src/fields/fields-page.test.tsx`. (Adjust the `findByText` to a stable rendered string — the `fields.title` PageTitle, the field-list, or the field-form's "Key" label. jsdom can't measure layout, so the class assertion is the responsive guard.)
- [ ] **Step 3: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. Report total test count, largest chunk (gz), the check:colors line. (`check:size` should be unchanged-or-smaller — the objects drawer's separate lazy chunk folds into `base-ui`.)
- [ ] **Step 4: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`).
- [ ] **Step 5: Manual smoke (recommended).** `pnpm dev`, narrow the window (<1024px): the sidebar is an icon rail; Vocabularies/Search show the list/panel full-width and selecting an item slides in the detail Drawer (close returns to the index); Fields stacks the list above the form (both scrollable). Widen (≥1024): all three return to side-by-side; Objects unchanged.
- [ ] **Step 6: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/fields/fields-page.tsx web/src/fields/fields-page.test.tsx
git commit -m "feat(web): responsive Fields page (stacks on narrow) (#58)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 `DetailDrawer` + objects retrofit + delete old (T1); AC2 vocab + search responsive drawer (T2-T3); AC3 fields responsive grid (T4 S1); AC4 new tests for drawer/vocab/search/fields + existing green (T1-T4 tests); AC5 gate/codename/no-new-keys (T4 S3-S4). ✓
**Placeholder scan:** full code for `DetailDrawer` + all three pages; tests give the exact `setViewport` harness + the narrow/wide discriminator; the `<VOCAB_ID>`/`<OBJECT_ID>` and `findByText` adjustments are explicit "read fixtures" instructions with a stated load-bearing assertion, not vague TODOs. ✓
**Type/consistency:** `DetailDrawer({ open, onClose, ariaLabel, children })` (T1) is consumed with those exact props in objects/vocab/search (T1-T3); `useMediaQuery("(min-width: 1024px)")` + `useMatch("/<x>/:id")` + `navigate("/<x>")` consistent across vocab/search; ariaLabels use existing keys (`objects.detailTitle`, `vocab.terms`). ✓
## Notes
- No new dependency; no new i18n keys (`objects.detailTitle`, `vocab.terms`, `actions.closeDetail` all exist). `components/ui/*` untouched (drawer/button wrappers unchanged; only a new app-level `components/detail-drawer.tsx`).
- The `<Outlet/>` per page is rendered in exactly one place per `isWide` branch — no double-mount.
- Fields stays `useState`-driven + stacked (no routing change, no "New field" trigger needed); the resizable splitter is deferred.
- Breakpoint 1024px is consistent with the existing Objects screen.
@@ -0,0 +1,154 @@
# Instance-Timezone Timestamp Formatter — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add a shared `formatTimestamp(value, timeZone, locale)` helper (date+time in the instance timezone, with an invalid-IANA → UTC fallback) and route the objects-table "Updated" column through it.
**Architecture:** Task 1 adds `lib/format-timestamp.ts` (mirrors `lib/format-date.ts`) + its unit test. Task 2 swaps objects-table's inline `dateFmt`/`formatUpdated` for the helper and runs the full gate. Display-only; UTC stays in storage/transmission.
**Tech Stack:** React 19 + TS + pnpm, `Intl.DateTimeFormat`, Vitest 4 (jsdom).
**Conventions:** pnpm; **no `any`/`eslint-disable`/`@ts-ignore`**; no codename; double-quote+semicolon. No new dependency, no new i18n keys, no backend change.
**Spec:** `docs/superpowers/specs/2026-06-09-timestamp-tz-design.md`
**Key facts:**
- `lib/format-date.ts` is the sibling pattern (date-only, no tz): `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);`.
- `objects/objects-table.tsx`: `const { t, i18n } = useTranslation();` (line ~31), `const { default_timezone } = useConfig();` (~32). Lines ~123-131 are the inline `const dateFmt = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeZone: default_timezone });` + `const formatUpdated = (iso: string) => { const parsed = new Date(iso); return Number.isNaN(parsed.getTime()) ? iso : dateFmt.format(parsed); };`. The Updated cell (~line 270): `<td className="px-3 py-2 text-muted-foreground">{formatUpdated(object.updated_at)}</td>`.
- After removing `dateFmt`/`formatUpdated`, both `i18n` and `default_timezone` remain used (passed to `formatTimestamp`), and `t` is used elsewhere — no unused-locals.
- `objects-table.test.tsx` does NOT assert the rendered Updated value → no test edit needed there. Fixture `amphora.updated_at = "2026-01-05T14:30:00Z"`.
---
# Task 1: `lib/format-timestamp.ts` + test
**Files:** Create `web/src/lib/format-timestamp.ts`, `web/src/lib/format-timestamp.test.ts`.
- [ ] **Step 1: Create `web/src/lib/format-timestamp.ts`:**
```ts
/** Formats a UTC ISO timestamp for display in the instance timezone + active locale.
* Storage/transmission stay UTC — this is display-only. Falls back to UTC formatting on an
* invalid IANA zone (a misconfigured instance) rather than throwing. */
export function formatTimestamp(value: unknown, timeZone: string, locale: string): string {
if (typeof value !== "string") return value == null ? "—" : String(value);
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const opts = { dateStyle: "medium", timeStyle: "short" } as const;
try {
return new Intl.DateTimeFormat(locale, { ...opts, timeZone }).format(date);
} catch {
// Invalid IANA timeZone (misconfigured instance) — fall back to UTC rather than crash.
return new Intl.DateTimeFormat(locale, { ...opts, timeZone: "UTC" }).format(date);
}
}
```
- [ ] **Step 2: Create `web/src/lib/format-timestamp.test.ts`** (write + run):
```ts
import { expect, test } from "vitest";
import { formatTimestamp } from "./format-timestamp";
test("formats a UTC timestamp with date and time in the given locale", () => {
const out = formatTimestamp("2026-06-08T12:30:00Z", "UTC", "en");
expect(out).toContain("2026");
expect(out).toContain("12:30");
});
test("applies the timezone — a near-midnight UTC instant shifts the calendar day", () => {
// 02:00 UTC on Jun 8 is 22:00 on Jun 7 in New York (EDT, UTC-4)
const ny = formatTimestamp("2026-06-08T02:00:00Z", "America/New_York", "en");
const utc = formatTimestamp("2026-06-08T02:00:00Z", "UTC", "en");
expect(ny).toContain("Jun 7");
expect(utc).toContain("Jun 8");
});
test("an invalid IANA zone does not throw and falls back to UTC", () => {
const out = formatTimestamp("2026-06-08T12:30:00Z", "Not/AZone", "en");
expect(out).toContain("2026");
});
test("null renders the em-dash placeholder; an unparseable string is returned unchanged", () => {
expect(formatTimestamp(null, "UTC", "en")).toBe("—");
expect(formatTimestamp("not-a-date", "UTC", "en")).toBe("not-a-date");
});
```
Run: `cd web && pnpm vitest run src/lib/format-timestamp.test.ts` → 4 passing. (Full-ICU Node renders en medium+short as e.g. `"Jun 8, 2026, 12:30 PM"`; the assertions check substrings — `2026`, `12:30`, `Jun 7`/`Jun 8` — to stay robust across ICU punctuation. If the local ICU renders the time without a leading-zero/`12:30`, assert the day-shift `Jun 7` vs `Jun 8` which is the load-bearing tz check.)
- [ ] **Step 3: Verify + lint:**
```bash
cd web && pnpm vitest run src/lib/format-timestamp.test.ts && pnpm typecheck && pnpm lint
```
All green.
- [ ] **Step 4: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/lib/format-timestamp.ts web/src/lib/format-timestamp.test.ts
git commit -m "feat(web): formatTimestamp helper (instance tz + locale, UTC fallback) (#42)"
```
---
# Task 2: Route objects-table "Updated" through `formatTimestamp` + full gate
**Files:** Modify `web/src/objects/objects-table.tsx`.
- [ ] **Step 1: Add the import** to `web/src/objects/objects-table.tsx` (alongside the other `../lib/*` imports):
```ts
import { formatTimestamp } from "../lib/format-timestamp";
```
- [ ] **Step 2: Remove the inline formatter.** Delete the `const dateFmt = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeZone: default_timezone });` block AND the `const formatUpdated = (iso: string) => { … };` function (the ~9 lines, currently around lines 123-131). (`i18n` and `default_timezone` stay declared — they're now passed to `formatTimestamp` at the call site; `t` remains used elsewhere.)
- [ ] **Step 3: Update the Updated cell.** Change:
```tsx
<td className="px-3 py-2 text-muted-foreground">{formatUpdated(object.updated_at)}</td>
```
to:
```tsx
<td className="px-3 py-2 text-muted-foreground">
{formatTimestamp(object.updated_at, default_timezone, i18n.language)}
</td>
```
- [ ] **Step 4: FULL FRONTEND GATE (run tests EXACTLY ONCE):**
```bash
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size && pnpm check:colors
```
All green. The objects-table tests stay green (they don't assert the Updated cell's text). Report total test count, largest chunk (gz), the check:colors line. If typecheck flags `i18n`/`default_timezone` as unused, the call site in Step 3 must reference them (it does) — re-check the edit.
- [ ] **Step 5: Codename + status:**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git grep -in 'biggus\|dickus' -- web/src; echo "codename-exit=$?"
git status --short
```
Expected: no matches (`codename-exit=1`).
- [ ] **Step 6: Manual smoke (recommended).** `pnpm dev`: the objects list "Updated" column now shows date + time in the instance timezone (e.g. for an instance in `Europe/Stockholm`, a `…T14:30:00Z` value renders ~`Jan 5, 2026, 3:30 PM`); switching the UI language reformats it.
- [ ] **Step 7: Commit**
```bash
cd /Users/olsson/Laboratory/biggus-dickus
git add web/src/objects/objects-table.tsx
git commit -m "feat(web): render objects 'Updated' as a tz-aware timestamp via formatTimestamp (#42)"
```
---
## Self-Review (completed)
**Spec coverage:** AC1 `formatTimestamp` helper + unit tests incl. day-shift + invalid-zone (T1); AC2 objects-table adoption, inline formatter removed, date+time (T2 S1-S3); AC3 gate/codename/no-new-dep-or-keys (T2 S4-S5). ✓
**Placeholder scan:** full helper + test code; the ICU-substring note gives a concrete robustness fallback (assert `Jun 7`/`Jun 8`); exact lines/strings for the objects-table edit. No TBD. ✓
**Type/consistency:** `formatTimestamp(value: unknown, timeZone: string, locale: string)` (T1) called as `formatTimestamp(object.updated_at, default_timezone, i18n.language)` (T2) — `updated_at: string`, `default_timezone: string` (useConfig), `i18n.language: string`. ✓
## Notes
- No new dependency, no new i18n keys, no backend change. `format-date.ts` (plain DATE) is untouched.
- The helper constructs an `Intl.DateTimeFormat` per call (vs the prior once-per-render memo); negligible for the ≤200-row page.
- Only the one timestamp display exists today; future displays (object-detail created/updated, audit history) route through the same helper when they land.
@@ -0,0 +1,122 @@
# Design-Kit Consistency — Design
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #66 (dead Card, duplicated segmented-control + selected-row recipes, `useLang`/`focusRing` drift, misc kit one-offs).
## Context
A frontend deep audit found subtler design-system inconsistencies the `check:colors` guard doesn't catch
(the app is already hex-free + token-based + dark-mode-clean). These are duplicated class recipes and
non-adoption of the `ui/*` kit. All fixes are behavior-preserving; `check:colors`/`check:size`/the existing
component tests are the guards. State re-verified against the current code (post #62/#64).
## Components
### New shared helpers
**`lib/use-lang.ts`** — `useLang(): "sv" | "en"`
```ts
import { useTranslation } from "react-i18next";
/** The instance's active UI language, narrowed to the two supported locales. */
export function useLang(): "sv" | "en" {
const { i18n } = useTranslation();
return i18n.language.startsWith("sv") ? "sv" : "en";
}
```
Replaces the inline `const lang = i18n.language.startsWith("sv") ? "sv" : "en";` in **6** components:
`objects/object-detail.tsx`, `objects/field-input.tsx`, `vocab/vocabulary-terms.tsx`,
`vocab/vocabulary-list.tsx`, `fields/field-list.tsx`, `authorities/authorities-page.tsx`. Each switches to
`const lang = useLang();` and drops the now-unused `i18n` from its `useTranslation()` destructure where
`i18n` is otherwise unused. (Left untouched: `shell/lang-switch.tsx` — derives from a different `locale`
var; `i18n/index.ts` — the infra `languageChanged` handler.)
**`lib/class-recipes.ts`** — two shared class helpers
```ts
import { cn } from "@/lib/utils";
import { focusRing } from "./focus-ring";
/** Segmented-control / filter-pill item. Unifies the active/inactive token recipe +
* focus ring; callers pass their contextual padding/size via `className`. */
export function segmentClass(active: boolean, className?: string): string {
return cn("rounded-md", focusRing, active ? "bg-primary text-primary-foreground" : "border", className);
}
/** Selected vs idle row background for master-detail / list rows. */
export function rowStateClass(active: boolean): string {
return active ? "bg-primary/10" : "hover:bg-muted";
}
```
- **`segmentClass`** is adopted at the 3 segmented sites, each keeping its contextual padding:
- `objects/objects-table.tsx:174``segmentClass(active, "px-2 py-1")`
- `search/search-panel.tsx:76``segmentClass(active, "px-2 py-0.5")`
- `authorities/authorities-page.tsx:41` (NavLink) → `segmentClass(isActive, "px-3 py-1 text-sm")`
This DRYs the bug-prone recipe (the active/inactive token pair + `focusRing` — the part that drifted and
caused the #62 missing-ring bug); contextual sizing is intentionally preserved per site.
- **`rowStateClass`** is adopted at the 4 selected-row sites:
- `objects/objects-table.tsx:252``rowStateClass(selected)`
- `vocab/vocabulary-list.tsx:113``rowStateClass(isActive)`
- `search/search-result-row.tsx:15``rowStateClass(isActive)`
- `fields/field-list.tsx:86``rowStateClass(def.key === selectedKey)`**fixes** this site, which
currently uses `… ? "bg-primary/10" : ""` (dropping the `hover:bg-muted` idle hover the others have).
### One-off cleanups
- **Delete `components/ui/card.tsx`** — zero importers (no app/test/story references; no `card.stories`).
- **`shell/sidebar.tsx:46,88`** — replace the raw `focus-visible:ring-3 focus-visible:ring-ring/50`
string (inside the existing `cn(...)`) with the imported `focusRing` constant (adds `outline-none`,
matching every other call site).
- **`auth/login-page.tsx:49`** — `<h1 className="text-2xl font-semibold">{app_name}</h1>`
`<PageTitle>{app_name}</PageTitle>` (`PageTitle` is `text-2xl font-semibold tracking-tight`, restoring
the missing `tracking-tight`). Import `PageTitle` from `@/components/ui/page-title`.
- **`fields/field-list.tsx:97`** — the hand-rolled type-tag `<span className="rounded-md bg-muted px-1.5
py-0.5 text-xs text-muted-foreground">` → `<Badge variant="secondary">` (from `@/components/ui/badge`).
- **Icon sizing** — `h-4 w-4` → `size-4` in the 3 **app-source** sites: `shell/theme-switch.tsx:39`,
`shell/user-menu.tsx:27`, `shell/header-search.tsx:23`. (Leave `components/ui/select.tsx` — kit-internal.)
- **Icon dismiss buttons** → kit `Button variant="ghost" size="icon-sm"`:
- `objects/objects-page.tsx:54` (plain `<button onClick={closeDetail} aria-label={…}>`) → `<Button
variant="ghost" size="icon-sm" onClick={closeDetail} aria-label={t("actions.closeDetail")}><X
className="size-4" aria-hidden="true" /></Button>` (import `Button`).
- `objects/object-detail-drawer.tsx:33` (Base UI `<DrawerClose>`) → keep `DrawerClose` for its
close-on-click semantics, render it AS the kit Button via the render prop:
`<DrawerClose aria-label={t("actions.closeDetail")} render={<Button variant="ghost" size="icon-sm" />}><X
className="size-4" aria-hidden="true" /></DrawerClose>` (mirrors the `AlertDialogTrigger render={<Button/>}`
pattern in `delete-confirm-dialog.tsx`; import `Button`).
## Error handling / edges
- `segmentClass`/`rowStateClass` are pure string builders — no runtime concerns. `cn()` (tailwind-merge)
resolves any padding/utility overlap predictably.
- `<Badge variant="secondary">` shifts the type-tag from `bg-muted`/`text-muted-foreground` to the
`secondary` token pair — a deliberate, minor visual adoption of the kit; still token-based (check:colors
clean).
- The drawer `DrawerClose render={<Button/>}` keeps Base UI's close behaviour (Base UI merges its props
onto the rendered Button); the `aria-label` stays on `DrawerClose`.
- `useLang` returns the same `"sv" | "en"` the inline code produced — no behaviour change.
## Testing
- **`lib/class-recipes.test.ts`** (new): `segmentClass(true)` contains `bg-primary` + `text-primary-foreground`
and the focus-ring utility; `segmentClass(false)` contains `border` (not `bg-primary`); both contain a
passed `className`; `rowStateClass(true)` === `"bg-primary/10"`, `rowStateClass(false)` === `"hover:bg-muted"`.
- **Behavior guard:** the existing component tests must stay green unchanged — `objects-table.test.tsx`,
`authorities.test.tsx`, `vocabularies.test.tsx`, `field-list` / `search` tests, `login-page.test.tsx`,
`breadcrumb`/sidebar, `object-detail`/drawer, `user-menu.test.tsx`. (The login `PageTitle` still renders an
`<h1>`; the icon buttons keep their `aria-label`s; the drawer close still closes.)
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; no new dependency; no new
i18n keys; no codename. `check:size` unchanged-or-smaller (Card deletion removes dead code).
## Acceptance criteria
1. `useLang()` exists and replaces the inline lang derivation in the 6 listed components; `lang-switch` and
`i18n/index.ts` are untouched.
2. `segmentClass`/`rowStateClass` exist (unit-tested) and are adopted at the 3 segmented + 4 selected-row
sites; `field-list`'s selected row gains the `hover:bg-muted` idle hover.
3. `components/ui/card.tsx` is deleted (no remaining references).
4. The one-offs are applied: sidebar uses `focusRing`; login uses `PageTitle`; field-list type-tag uses
`Badge`; the 3 app-source icons use `size-4`; both icon dismiss buttons use `Button variant="ghost"
size="icon-sm"`.
5. All existing tests pass unchanged; `typecheck`/`lint`/`build`/`check:colors` green; `check:size`
unchanged-or-smaller; no new dependency; no new i18n keys; no codename.
## Out of scope → follow-ups
- A full `<SegmentedControl>`/`<ToggleGroup>` component (the button-vs-NavLink interaction split makes a
class helper the better fit); the form `space-y-*` scale (too subjective — churn risk).
- Standardizing icon sizing inside `components/ui/*` (kit-internal style, separate from app-source).
@@ -0,0 +1,146 @@
# Split queries.ts: Errors + Query-Key Factory + Domain Modules — Design
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #65 (split the 584-line `queries.ts`, extract the error classes, add a query-key factory, decide the search-invalidation gap).
## Context
`web/src/api/queries.ts` is 584 lines spanning 8 domains (error classes, auth, objects, fields-on-object,
field-definitions, vocab, terms, authorities, search). No hook crosses a domain boundary, so a split is
low-risk. Three concrete problems:
- **Toast path drags in the hook module.** After #63, `query-client.ts` imports `errorMessageKey` from
`error-message.ts`, which imports `{ HttpError, InUseError }` from `./queries` — so the toast wiring
transitively loads all the hooks. Extracting the error classes breaks that chain.
- **No query-key factory.** ~20 key literals (`["objects", params]`, `["object", id]`,
`["terms", vocabularyId]`, …) plus `config-provider.tsx`'s `["config"]` are hand-written and
typo-prone.
- **Object writes don't invalidate `["search"]`.** `useUpdateObject`/`useDeleteObject`/`useSetVisibility`
invalidate `["objects"]`/`["object", id]` but never the search index, so the search panel keeps stale
hits until the user re-searches. **Decision (brainstorming): invalidate** — conventional
eventually-consistent behaviour; the query is `enabled` only with a term, so it's a no-op when not
searching.
**Constraint:** ~30 files import from `../api/queries`. The public import path must stay stable (a
barrel), so the refactor touches the data layer only — feature files don't change.
## Components
### `api/errors.ts` (new) — canonical home for the 4 error classes
Move `HttpError`, `FieldRejection`, `InUseError`, `VisibilityError` here verbatim (no behaviour change).
`error-message.ts` changes its import from `./queries` to `./errors` — this is the decoupling: the toast
path (`query-client → error-message → errors`) no longer loads the hook module. The barrel (below)
**re-exports** the error classes (`export * from "../errors"`), so the existing importers that pull them
from `../api/queries``object-edit-form.tsx`, `object-new-page.tsx`, `publish-control.tsx`,
`search-panel.tsx`, and the tests `mutation-error.test.tsx` / `labelled-record-row.test.tsx` /
`error-message.test.ts` — keep working unchanged.
### `api/query-keys.ts` (new) — one key factory
```ts
export type ObjectListParams = {
limit: number;
offset: number;
sort?: string;
order?: "asc" | "desc";
visibility?: string;
q?: string;
};
export const keys = {
me: () => ["me"] as const,
config: () => ["config"] as const,
objects: () => ["objects"] as const, // family prefix (invalidation)
objectsPage: (p: ObjectListParams) => ["objects", p] as const,
object: (id: string) => ["object", id] as const,
fieldDefinitions: () => ["field-definitions"] as const,
vocabularies: () => ["vocabularies"] as const,
terms: (vocabularyId: string) => ["terms", vocabularyId] as const,
authorities: (kind: string) => ["authorities", kind] as const,
search: () => ["search"] as const, // family prefix (invalidation)
searchResults: (term: string, visibility: string | null) => ["search", term, visibility] as const,
};
```
- Every `queryKey:` / `invalidateQueries` / `setQueryData` site in the query modules **and**
`config-provider.tsx`'s `["config"]` routes through `keys.*` — producing the identical arrays, so
cache behaviour is unchanged. (`keys.objects()` prefix-matches `keys.objectsPage(p)` exactly as
`["objects"]` matches `["objects", params]` today.)
- `ObjectListParams` lives here (it *is* part of the key); `objects.ts` imports it from here — one
direction, no import cycle. (It moves out of `queries.ts`'s objects section.)
### `api/queries/` (new directory) — split by domain + barrel
```
api/
client.ts (unchanged)
errors.ts (new)
query-keys.ts (new)
query-client.ts (unchanged — already imports only error-message)
error-message.ts (one-line change: import errors from ./errors)
queries/
index.ts barrel: `export * from "./auth"; … ; export * from "../errors";`
auth.ts useMe, useLogin, useLogout
objects.ts useObjectsPage, useObject, useCreateObject, useUpdateObject, useSetFields, useDeleteObject, useSetVisibility
field-defs.ts useFieldDefinitions, useCreateFieldDefinition, useUpdateFieldDefinition, useDeleteFieldDefinition
vocab.ts useVocabularies, useCreateVocabulary, useRenameVocabulary, useDeleteVocabulary, useTerms, useAddTerm, useUpdateTerm, useDeleteTerm
authorities.ts useAuthorities, useCreateAuthority, useUpdateAuthority, useDeleteAuthority
search.ts useSearch, SEARCH_PAGE
```
`api/queries.ts` is deleted; `import { … } from "../api/queries"` resolves to `api/queries/index.ts`.
Each module imports `api` from `../client`, types from `../schema`, error classes from `../errors`, and
`keys` from `../query-keys`. The hook bodies are moved verbatim (only their key literals → `keys.*`).
### `api/query-client.ts`
No change needed — after #63 it imports only `errorMessageKey`. (Once `error-message.ts` points at
`./errors`, the `query-client → error-message → queries` hook dependency is gone.)
### Search invalidation (`objects.ts`)
`useUpdateObject`, `useDeleteObject`, `useSetVisibility` add
`void qc.invalidateQueries({ queryKey: keys.search() })` alongside their existing object invalidations.
## Data flow / behaviour
Identical to today except: after an object update/delete/visibility-change, an active search query
refetches (eventually-consistent with the Meilisearch reindex). All keys, hooks, error classes, and
endpoints are otherwise unchanged.
## Error handling / edges
- The barrel re-exporting errors means the classes are importable from both `../api/errors` (canonical)
and `../api/queries` (compat) — intentional, to avoid churning ~6 importers + tests.
- `as const` keys are readonly tuples; TanStack Query accepts readonly arrays as keys — no type issue.
- No import cycle: `query-keys.ts` exports `ObjectListParams` + `keys` and imports nothing from
`queries/`; `objects.ts` imports both from `query-keys.ts`.
- The search query stays `enabled: term.length > 0`, so invalidating `["search"]` is a no-op when no
search is active.
## Testing
- **Behavior guard (must pass unchanged):** `queries.test.ts`, `queries.authoring.test.tsx`,
`queries.fields.test.tsx`, `queries.search.test.tsx`, `queries.visibility.test.tsx`,
`queries.vocab.test.tsx`, `mutation-feedback.test.tsx`, `error-message.test.ts`,
`mutation-error.test.tsx`, `labelled-record-row.test.tsx` — all import from `../api/queries` (the
barrel) and from the re-exported error classes; they must not need edits. The full app suite is the
integration guard.
- **New `query-keys.test.ts`:** assert the factory arrays — e.g. `keys.objects()``["objects"]`,
`keys.objectsPage(p)``["objects", p]`, `keys.object("x")``["object", "x"]`,
`keys.searchResults("q", null)``["search", "q", null]`.
- **Search-invalidation assertion:** extend `queries.visibility.test.tsx` (or `.authoring`) to seed an
active `["search", …]` query in the cache, run an object update/delete/set-visibility, and assert the
search query is invalidated (e.g. its `isInvalidated`/refetch fires).
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; no new dependency; no new
i18n keys; no codename; `check:size` unchanged (pure reorg + one invalidate call).
## Acceptance criteria
1. `api/errors.ts` holds the 4 error classes; `error-message.ts` imports them from `./errors`; the barrel
re-exports them so every existing importer (components + tests) still resolves.
2. `queries.ts` is split into `api/queries/{auth,objects,field-defs,vocab,authorities,search}.ts` +
`index.ts`; `api/queries.ts` is deleted; the `../api/queries` import path is unchanged for all ~30
consumers.
3. A `keys` factory in `api/query-keys.ts` is used by every `queryKey`/invalidate/setQueryData site,
including `config-provider.tsx`.
4. `useUpdateObject`/`useDeleteObject`/`useSetVisibility` invalidate `keys.search()`.
5. All existing tests pass unchanged; `typecheck`/`lint`/`build`/`check:colors` green; `check:size`
unchanged; no new dependency; no new i18n keys; no codename.
## Out of scope → follow-ups
- No hook signature/behaviour changes beyond the search invalidation; no endpoint changes.
- `staleTime` / `keepPreviousData` choices stay as-is (intentional per #63's note).
- Repointing the 4 component error-importers from the barrel to `../api/errors` (the re-export keeps them
working; a later cosmetic cleanup could do it).
@@ -0,0 +1,182 @@
# Unify Vocabulary + Authority CRUD — Design
**Date:** 2026-06-08
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #64 (the duplicated Vocabulary-terms + Authorities CRUD surfaces).
## Context
The Vocabulary-terms and Authorities admin surfaces are two copies of one feature ("a labelled record
with an optional external URI: filterable list + inline-edit rows + create form"). The duplication spans
four files and ~280 lines:
- `vocab/term-row.tsx` and `authorities/authority-row.tsx` are byte-for-byte twins except: the mutation
hooks (`useUpdateTerm`/`useDeleteTerm` vs `useUpdateAuthority`/`useDeleteAuthority`), the record type
(`TermView` vs `AuthorityView`), the URI-input id prefix (`term-uri-` / `auth-uri-`), the mutate-arg
shape (`{ vocabularyId, termId, … }` vs `{ id, kind, … }`), and the delete-confirm i18n key.
- `authorities/authorities-page.tsx` and `vocab/vocabulary-terms.tsx` share the filter input, the
4-state list (loading→skeleton / error / empty / no-matches / rows), and the create form
(`LabelEditor` + URI input + `labels.some()` validation + `MutationError` + submit). They differ in the
i18n keys, the create-form heading, and (authorities only) the kind-tabs `<nav>` + `PageTitle` +
`Navigate` guard.
A fix to inline-edit behaviour must currently be made in two places and silently drifts. (These files
already share `LabelEditor`, `ExternalUriLink`, `DeleteConfirmDialog`, and `MutationError`.)
`vocabulary-list.tsx` (vocabularies are `key`-based, not labelled records) and the `objects` RHF surface
are intentionally **not** unified — different shapes.
### Decisions (from brainstorming)
Full unification — three shared components in `src/components/`, with `TermRow`/`AuthorityRow` and the
two pages reduced to thin adapters. All variance is pushed into props; no generics on the row (the adapter
owns the mutate-arg shape). Behavior-preserving — existing tests are the guard.
## Components
### `components/labelled-record-row.tsx` (new) — `LabelledRecordRow`
Owns `editing` / `labels` / `uri` state. Renders the display row (`labelText` + `ExternalUriLink` + Edit
button + `DeleteConfirmDialog`) or the edit view (`LabelEditor` + URI `<Input>` + Save/Cancel +
`MutationError`).
```ts
type RecordLike = { id: string; labels: LabelView[]; external_uri: string | null };
function LabelledRecordRow(props: {
record: RecordLike;
lang: string;
deleteConfirmKey: string; // i18n key for the confirm prompt
savePending: boolean; // update.isPending
saveError: unknown; // update.error
onEditOpen: () => void; // adapter calls update.reset()
onSave: (labels: LabelInput[], uri: string | null, done: () => void) => void;
onDelete: () => Promise<void>;
}): JSX.Element;
```
- Edit button onClick: `onEditOpen(); setLabels(record.labels as LabelInput[]); setUri(record.external_uri ?? ""); setEditing(true);` (preserves the #63 reset-on-edit-open behaviour).
- Save: `onSave(labels, uri.trim() || null, () => setEditing(false))`; Save disabled while `savePending`;
`<MutationError error={saveError} />` below the buttons.
- The URI input id uses `useId()` (replaces the `term-uri-${id}` / `auth-uri-${id}` scheme).
- `record.labels` is `LabelView[]`; cast to `LabelInput[]` for `LabelEditor` (same cast the current rows do).
### `components/labelled-record-create-form.tsx` (new) — `LabelledRecordCreateForm`
Owns its own `labels` / `uri` / `requiredError` state. Renders `heading` + `LabelEditor` + URI `<Input>`
(id via `useId()`) + the `form.required` validation alert + `<MutationError error={error} />` + submit.
```ts
function LabelledRecordCreateForm(props: {
heading: ReactNode;
submitLabel: string;
pending: boolean; // create.isPending
error: unknown; // create.error
onCreate: (labels: LabelInput[], uri: string | null, reset: () => void) => void;
}): JSX.Element;
```
- Submit: `if (!labels.some((l) => l.label)) { setRequiredError(true); return; } setRequiredError(false);
onCreate(labels, uri.trim() || null, () => { setLabels([]); setUri(""); });`
- Submit button disabled while `pending`.
### `components/filtered-record-list.tsx` (new) — `FilteredRecordList<T>`
Owns the `filter` state. Renders the filter `<Input>` **always**, then (loading → `<ListSkeleton>` else the
`<ul>`), so the filter stays visible during load (matches current behaviour).
```ts
function FilteredRecordList<T extends { id: string; labels: LabelView[] }>(props: {
records: T[] | undefined;
lang: string;
isLoading: boolean;
isError: boolean;
loadErrorText: string;
emptyText: string;
renderRow: (record: T) => ReactNode;
}): JSX.Element;
```
- `const q = filter.trim().toLowerCase(); const rows = [...(records ?? [])].filter((r) => !q ||
labelText(r.labels, lang).toLowerCase().includes(q)).sort(byLabel(lang));`
- List states (preserving the current logic exactly): `isError` → `loadErrorText`; `!isError &&
records?.length === 0` → `emptyText`; `!isError && records && records.length > 0 && rows.length === 0`
→ `t("common.noMatches")`; else `rows.map(renderRow)`.
- Filter input uses `aria-label={t("common.filter")}` + `placeholder={t("common.filter")}` (unchanged).
### Adapters
**`vocab/term-row.tsx`** keeps its public API `<TermRow vocabularyId term lang />` (its #63 test stays
valid). Body:
```tsx
const update = useUpdateTerm();
const del = useDeleteTerm();
return (
<LabelledRecordRow
record={term}
lang={lang}
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={update.isPending}
saveError={update.error}
onEditOpen={() => update.reset()}
onSave={(labels, uri, done) =>
update.mutate({ vocabularyId, termId: term.id, external_uri: uri, labels }, { onSuccess: done })}
onDelete={() => del.mutateAsync({ vocabularyId, termId: term.id })}
/>
);
```
**`authorities/authority-row.tsx`** keeps `<AuthorityRow authority kind lang />`; analogous with
`useUpdateAuthority`/`useDeleteAuthority`, `deleteConfirmKey="actions.confirmDeleteAuthority"`, save arg
`{ id: authority.id, kind, external_uri: uri, labels }`, delete `{ id: authority.id, kind }`.
**`authorities/authorities-page.tsx`** keeps the `PageTitle`, kind `<nav>`, `Navigate` guard, breadcrumb,
and `useDocumentTitle`. Replaces the inline filter/list with `<FilteredRecordList records={authorities}
lang={lang} isLoading={isLoading} isError={isError} loadErrorText={t("authorities.loadError")}
emptyText={t("authorities.empty")} renderRow={(a) => <AuthorityRow authority={a} kind={currentKind}
lang={lang} />} />`, and the inline form with `<LabelledRecordCreateForm heading={`${t("authorities.new")} ·
${t(\`authorities.${currentKind}\`)}`} submitLabel={t("authorities.create")} pending={create.isPending}
error={create.error} onCreate={(labels, uri, reset) => create.mutate({ kind, external_uri: uri, labels },
{ onSuccess: reset })} />`. (Drops the now-unused local `labels`/`uri`/`error`/`filter` state and the
`onCreate` handler.)
**`vocab/vocabulary-terms.tsx`** keeps its `vocab.terms` caption + breadcrumb. Uses `<FilteredRecordList
records={terms} … loadErrorText={t("vocab.loadError")} emptyText={t("vocab.noTerms")} renderRow={(term) =>
<TermRow vocabularyId={id} term={term} lang={lang} />} />` and `<LabelledRecordCreateForm
heading={t("vocab.addTerm")} submitLabel={t("vocab.addTerm")} pending={addTerm.isPending}
error={addTerm.error} onCreate={(labels, uri, reset) => addTerm.mutate({ vocabularyId: id, external_uri:
uri, labels }, { onSuccess: reset })} />`.
## Data flow
No change to the query/mutation layer. Each page owns its data hooks + the page-specific chrome (nav,
headings, breadcrumb) and hands records + render callbacks to the shared list, mutate callbacks to the
shared create form, and per-row mutate callbacks (via the row adapters) to the shared row.
## Error handling / edges
- Inline save errors and create errors still render via `<MutationError>` (status-aware, from #63),
unchanged.
- The `form.required` validation (empty labels) stays in the create form.
- Reset-on-edit-open (`update.reset()`) preserved so a stale save error doesn't linger.
- The empty-vs-no-matches distinction is computed from the **raw** `records` length (empty) vs the
**filtered** `rows` length (no matches), exactly as today.
- `useId()` keeps URI-input ids unique across simultaneously-mounted rows/forms.
## Testing
- **Behavior guard:** existing tests stay green unchanged — `vocab/term-row.test.tsx`,
`authorities/authorities.test.tsx` (page filter/create/list), `vocab/vocabularies.test.tsx`
(out-of-scope list, must not break). Same public component APIs + DOM.
- **New focused tests** for the three components:
- `labelled-record-row.test.tsx`: display → click Edit → Save calls `onSave` and closes on `done`; a
failed save (passing `saveError`) shows the inline error and the row stays editable; Delete invokes
`onDelete`.
- `labelled-record-create-form.test.tsx`: submit with empty labels shows `form.required` and does NOT
call `onCreate`; a valid submit calls `onCreate` and the `reset` clears the inputs.
- `filtered-record-list.test.tsx`: typing in the filter narrows the rendered rows; `records=[]`
`emptyText`; non-empty records + non-matching filter → `common.noMatches`; `isError``loadErrorText`;
`isLoading` → skeleton.
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; no new i18n keys; en/sv
parity unaffected; no codename; no new dependency. `check:size` should not grow (net code reduction).
## Acceptance criteria
1. `LabelledRecordRow`, `LabelledRecordCreateForm`, `FilteredRecordList<T>` exist in `src/components/` with
the prop shapes above; `TermRow`/`AuthorityRow` and the two pages are adapters over them.
2. `term-row.tsx` + `authority-row.tsx` no longer duplicate the row body; `authorities-page.tsx` +
`vocabulary-terms.tsx` no longer duplicate the filter/list/create-form body.
3. All existing tests pass unchanged; the three new components have focused tests.
4. No behavior change: inline edit/save/delete, create + validation, filtering, the 4 list states, the
authorities kind-nav, and breadcrumbs all work as before.
5. `typecheck`/`lint`/`test`/`build`/`check:colors` green; `check:size` reported (not increased); no new
i18n keys; no codename; no new dependency.
## Out of scope → follow-ups
- `vocabulary-list.tsx` (key-based vocabularies) and the `objects` table/detail/RHF surface.
- A field-definition "position"/ordering concept; server-side filtering for large vocabularies (#43).
@@ -0,0 +1,111 @@
# Bundle Vendor-Split + Test-Gap Fills — Design
**Date:** 2026-06-09
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #67 (vendor-split the bundle for cache stability/headroom; fill the audit's unit-test + story gaps).
## Context
The production build emits a single ~216 KB-gz entry chunk (the largest, measured by
`scripts/check-bundle-size.mjs`, budget 250 KB) that bundles the framework deps (react-dom, react-router 7,
@tanstack/react-query, @base-ui/react, i18next) together with app code — so every app edit invalidates the
whole chunk's cache. `vite.config.ts` has no `build.rollupOptions`. Separately, four well-isolated units
have no direct tests, and the composed combobox primitive has no story.
All changes are additive/low-risk; `check:size`/`check:colors`/the existing tests are the guards.
## Components
### 1. Vendor split — `vite.config.ts`
Add a top-level `build` block (sibling of `plugins`/`resolve`/`server`/`test`) with `manualChunks`:
```ts
build: {
rollupOptions: {
output: {
manualChunks: {
react: ["react", "react-dom", "react-router", "react-router-dom"],
"base-ui": ["@base-ui/react"],
query: ["@tanstack/react-query"],
i18n: ["i18next", "react-i18next"],
},
},
},
},
```
- The app entry chunk then carries only app code; the listed deps land in cache-stable vendor chunks
(`react-*.js`, `base-ui-*.js`, `query-*.js`, `i18n-*.js`). `react-router` **and** `react-router-dom` are
both listed so router code (v7 re-exports `react-router` internally) stays in one chunk and React isn't
duplicated.
- Only affects `pnpm build` (production); the Storybook/vitest browser builder is independent, so the
test suite is unaffected.
- `check:size` measures the largest emitted chunk; after the split the largest is a vendor chunk well under
the 250 KB budget (verified in implementation by running `pnpm build` + `pnpm check:size` and reporting
the chunk sizes). If a chunk is unexpectedly oversized or React duplicates, adjust the groups.
### 2. Test-gap fills (4 unit tests)
**`objects/prune-fields.test.ts`** (new) — `pruneFields(fields, localizedTextKeys: Set<string>, defaultLang)`:
- scalars pass through; `undefined`/`null`/`""` top-level values are dropped.
- a non-array object value whose key is in `localizedTextKeys` keeps **only** the `defaultLang` entry;
other-language entries are dropped.
- a non-array object value whose key is **not** in `localizedTextKeys` keeps all (non-empty) language
entries.
- empty inner entries (`""`/`null`/`undefined`) are filtered, and a map left with zero entries is dropped
entirely.
**`components/delete-confirm-dialog.test.tsx`** (new) — the delete-in-use flow:
- render `<DeleteConfirmDialog description=… onConfirm=… />`, open it (click the trigger), click the
confirm action.
- when `onConfirm` rejects with `InUseError(3)`, the dialog shows the `actions.inUse` message (containing
the count `3`) and **stays open** (the confirm action is still present / the dialog isn't dismissed).
- when `onConfirm` resolves, the dialog closes.
(`DeleteConfirmDialog` routes its catch through `errorMessageKey`, which maps `InUseError`
`actions.inUse` with the count — so this also exercises the shared error mapping.)
**`lib/labels.test.ts`** (new) — `labelText(labels, lang)`:
- exact `lang` match wins; else falls back to the `"en"` label; else the first label; else `""` for an
empty array.
**`lib/format-date.test.ts`** (new) — `formatDate(value, lang)`:
- a valid `"YYYY-MM-DD"` formats via `Intl.DateTimeFormat(lang, { dateStyle: "medium" })` and is **not**
shifted off its calendar day (assert the rendered string contains the expected day number for a fixed
date + a fixed `lang` like `"en"`).
- `null``"—"`; a non-date string (e.g. `"not-a-date"`) is returned unchanged; a non-string non-null
(e.g. a number) is `String()`-ified.
### 3. Combobox story — `components/ui/combobox.stories.tsx` (new)
A visual/interactive story for the composed combobox primitive, mirroring the existing `ui/*` story format
(`@storybook/react-vite` `Meta`/`StoryObj`, single-quote + no-semicolon, `tags: ['ai-generated']`, a `play`
using `canvas` + `storybook/test`). A small controlled wrapper renders `ComboboxRoot` with a handful of
string options (`ComboboxInput`/`ComboboxClear`/`ComboboxTrigger`/`ComboboxPopup`/`ComboboxList`/
`ComboboxItem`/`ComboboxEmpty`), matching how `OptionsCombobox` composes them. A `Default` story; the
`play` asserts the input renders and (optionally) typing filters the list. (Runs as a browser test in the
Storybook vitest project — a few seconds in CI.)
## Error handling / edges
- `manualChunks`: Rollup orders chunks by the import graph, so vendor chunks load before the app chunk that
imports them — no load-order/duplicate-React risk when react+react-dom+router share one named chunk.
- `formatDate` parses `\`${value}T00:00:00\`` (local midnight) to avoid a UTC day-shift; the test pins a
fixed `lang` to keep `Intl` output deterministic (assert a substring like the day number, not the full
locale string, to stay robust across ICU versions).
- `delete-confirm-dialog` test drives the Base UI AlertDialog in its portal (`within(document.body)` for the
confirm action), mirroring existing portal-aware tests.
## Testing
- The 4 unit tests run in the jsdom project; the story adds one Storybook browser test.
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; `check:size` reports the
new largest (vendor) chunk under budget; no new dependency; no new i18n keys; no codename. en/sv parity
unaffected.
## Acceptance criteria
1. `vite.config.ts` has `build.rollupOptions.output.manualChunks` splitting react/base-ui/query/i18n into
their own chunks; `pnpm build` succeeds and `check:size` passes (largest chunk reported, < 250 KB gz, no
React duplication).
2. New tests exist and pass: `prune-fields.test.ts`, `delete-confirm-dialog.test.tsx` (InUseError →
`actions.inUse`, stays open), `labels.test.ts`, `format-date.test.ts`.
3. `components/ui/combobox.stories.tsx` exists with a working `Default` story (browser-test green).
4. Full gate green; no new dependency; no new i18n keys; no codename; existing tests unchanged.
## Out of scope → follow-ups
- The buildkit/Dockerfile CI migration (the robust fix for the slow native runner; overlaps #25).
- Deeper treeshaking/bundle analysis; route-level code-split changes beyond the existing `lazy()` boundaries.
@@ -0,0 +1,137 @@
# Responsive Master/Detail for Vocabularies, Search, Fields — Design
**Date:** 2026-06-09
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #58 (master/detail + sidebar layout has no responsive/small-screen handling — remaining half).
## Context
#58 is partially done (commit `0a88a86`, #44): the sidebar collapses to an icon rail, the **Objects** master/detail
is responsive (wide right-pane / narrow Base UI `Drawer`), and a reusable `lib/use-media-query.ts` exists. The
**remaining** master/detail screens still use fixed `grid-cols-[20rem_1fr]` / `[24rem_1fr]` with no breakpoints —
`vocabularies-page.tsx`, `search-page.tsx`, `fields-page.tsx` — so on a small laptop / tablet / split window the
fixed list + sidebar leave a cramped detail pane, and below ~640px the panes can't coexist.
**Decision (brainstorming): keep the wide side-by-side layout (it's useful for curators); fix only narrow.** Reuse
one shared drawer + the existing `useMediaQuery` hook. Breakpoint **1024px (`lg`)**, matching Objects. Authorities
is single-pane → no change. The "resizable splitter" the issue *suggests considering* is out of scope.
The three pages differ: vocabularies + search are **route-driven** (`<Outlet/>`, an index-prompt route + `:id`);
fields is **`useState`-driven** (FieldList → FieldForm, with the form always present for "create").
## Components
### 1. `components/detail-drawer.tsx` (new) — generalize the Objects drawer
Today `objects/object-detail-drawer.tsx` is objects-specific (Base UI `Drawer` + close button + a hardcoded
`<Outlet/>`). Generalize to a reusable component taking `children` + `ariaLabel`:
```tsx
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { X } from "lucide-react";
import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer";
import { Button } from "@/components/ui/button";
/** A right-sliding Base UI Drawer for a master/detail "detail" on narrow viewports. */
export function DetailDrawer({
open,
onClose,
ariaLabel,
children,
}: {
open: boolean;
onClose: () => void;
ariaLabel: string;
children: ReactNode;
}) {
const { t } = useTranslation();
return (
<Drawer open={open} onOpenChange={(next) => { if (!next) onClose(); }} swipeDirection="right">
<DrawerContent aria-label={ariaLabel}>
<div className="flex justify-end border-b p-2">
<DrawerClose aria-label={t("actions.closeDetail")} render={<Button variant="ghost" size="icon-sm" />}>
<X className="size-4" aria-hidden="true" />
</DrawerClose>
</div>
<div className="flex-1 overflow-auto">{children}</div>
</DrawerContent>
</Drawer>
);
}
```
- Delete `objects/object-detail-drawer.tsx`.
- **Drop the `lazy()`/`Suspense`** that objects-page used to wrap the drawer: it kept Base UI's drawer code out of
the entry chunk, but #67 already split `@base-ui/react` into its own `base-ui` vendor chunk (loaded app-wide via
the menu/select/etc.), so the lazy boundary no longer saves anything. `DetailDrawer` is a normal import.
- The close-button label keeps the existing generic `actions.closeDetail` key.
### 2. `vocab/vocabularies-page.tsx` + `search/search-page.tsx` — `useMediaQuery` + route drawer
Mirror the Objects pattern. Add `useMediaQuery("(min-width: 1024px)")` (`isWide`) and a `useMatch` for the detail
route (`"/vocabularies/:id"` / `"/search/:id"`), `open = Boolean(match)`, `close = () => navigate("/vocabularies")`
(resp. `"/search"`).
- **Wide:** the current side-by-side grid with `<Outlet/>` inline (prompt when no `:id`, detail when selected) —
unchanged.
- **Narrow:** the master full-width (`VocabularyList` / `SearchPanel` under the existing `PageTitle`), plus
`{open && <DetailDrawer open={open} onClose={close} ariaLabel={…}><Outlet/></DetailDrawer>}`. With no `:id`, just
the master (the index-prompt is a wide-only affordance).
- Drawer `ariaLabel`: vocabularies → `t("vocab.terms")` ("Terms"); search → `t("objects.detailTitle")` ("Object
detail", since a search result's detail IS an object). **No new i18n keys.**
- The `<Outlet/>` is rendered in exactly one place per branch (the `isWide` ternary), so no double-mount.
### 3. `fields/fields-page.tsx` — pure-CSS responsive stack
`fields-page` is `useState`-driven and its right pane is *always* a form (create when nothing selected), so a
drawer would need a new "New field" trigger. Instead make it a responsive **stack** (the issue comment explicitly
allows "or stack"): change the grid container from `grid grid-cols-[20rem_1fr]` to
`grid grid-cols-1 lg:grid-cols-[20rem_1fr]`, and give the form pane a top border that only shows when stacked
(`border-t lg:border-t-0`) while the list keeps its `border-r` (which reads as a bottom divider when stacked — or
add `border-b lg:border-b-0 lg:border-r` for a clean stacked divider). No JS, no drawer, no new trigger, no
element duplication — the same `FieldForm` reflows from below the list (narrow) to beside it (wide).
### 4. `objects/objects-page.tsx` — retrofit onto `DetailDrawer`
Replace the `lazy(ObjectDetailDrawer)` import + `<Suspense>` with a direct `DetailDrawer` import; in the narrow
branch render `{open && <DetailDrawer open={open} onClose={closeDetail} ariaLabel={t("objects.detailTitle")}><Outlet/></DetailDrawer>}`.
Behavior-preserving — its existing "narrow: detail renders inside a portaled drawer" test stays green.
## Data flow / behaviour
No data/routing changes. Each page picks layout via `useMediaQuery("(min-width:1024px)")` (vocab/search/objects) or
pure CSS (fields). The detail content is identical to today; only its container (inline pane vs Drawer) changes by
width. The detail route/state, breadcrumbs, and titles are unchanged.
## Error handling / edges
- `useMediaQuery` is SSR-safe (returns `false` server-side / pre-mount → narrow-first, then corrects on mount).
- Drawer `open` is derived from the route match (`:id`) / nothing on the index, so the Outlet only has content when
open; rendering `{open && <DetailDrawer …>}` mounts it only when active (matches the current objects behaviour).
- Fields stack: `FieldList` is `overflow-hidden` in a `grid-cols-1` row — ensure the stacked list has a sensible
height (it's in a flex/grid row that can scroll); the form below scrolls in its own pane. Keep each pane's
`overflow` as today.
- Drawer accessible name comes from `ariaLabel` (required prop) so every detail drawer is a named dialog (the #62
a11y fix, preserved + generalized).
## Testing
- **`components/detail-drawer.test.tsx`** (new): with `open`, the children render inside a dialog whose accessible
name is the `ariaLabel`; clicking the close button (labelled `actions.closeDetail`) calls `onClose`.
- **`vocab/vocabularies-page` + `search/search-page` tests** (new or extended): reuse the `setViewport(wide)`
matchMedia mock from `objects-page.test.tsx`. Narrow + a `:id` route → the detail renders in a portaled drawer
(`getByRole("dialog", { name })` within `document.body`); wide + `:id` → the detail is the inline pane (no
dialog). Closing the drawer navigates back to the index route.
- **`fields/fields-page` test**: the grid container carries the responsive classes (`grid-cols-1` +
`lg:grid-cols-[20rem_1fr]`); both the list and the form render (jsdom can't measure layout, so assert structure).
- **`objects/objects-page` tests**: stay green unchanged (the drawer is now the shared `DetailDrawer`).
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; no new dependency; no new i18n
keys; no codename; en/sv parity unaffected. `check:size` unchanged-or-smaller (dropping the objects drawer's
separate lazy chunk folds it into base-ui).
## Acceptance criteria
1. `components/detail-drawer.tsx` exists (Base UI drawer + close button + `children`/`ariaLabel`); `object-detail-drawer.tsx`
is deleted; Objects uses the shared `DetailDrawer` (no `lazy`/`Suspense`); its tests stay green.
2. Vocabularies + Search: wide = current side-by-side (unchanged); narrow (<1024) = master full-width + the detail
in a `DetailDrawer` when a `:id` is active; close returns to the index route.
3. Fields: responsive grid (`grid-cols-1 lg:grid-cols-[20rem_1fr]`) — stacked on narrow, side-by-side on wide.
4. New tests for `DetailDrawer`, vocabularies-page, search-page (narrow drawer + wide pane), fields-page (responsive
structure); all existing tests pass unchanged.
5. `typecheck`/`lint`/`build`/`check:colors` green; `check:size` reported (unchanged-or-smaller); no new
dependency; no new i18n keys; no codename.
## Out of scope → follow-ups
- A resizable master/detail splitter (issue "consider"); a per-user pane-width preference.
- Converting `fields` to a route-driven master/detail (it stays `useState`-driven + stacked).
@@ -0,0 +1,104 @@
# Instance-Timezone Timestamp Formatter — Design
**Date:** 2026-06-09
**Status:** Approved (brainstorming) — ready for implementation planning.
**Issue:** #42 (render UTC timestamps in the instance timezone via Intl — now that a display exists).
## Context
#42 was filed conditionally ("wire up the `default_timezone` formatter when the first timestamp display
lands"). That condition is now met: the objects-table **"Updated" column** (`updated_at`, a UTC timestamp)
is rendered — and it's already timezone+locale-aware, but via an **inline** `Intl.DateTimeFormat` in
`objects-table.tsx` (`dateStyle: "medium"`, `timeZone: default_timezone`) that:
- is **not** the shared `formatTimestamp` helper the issue asks for,
- shows **date only** (no time-of-day), and
- has **no invalid-IANA guard** — a misconfigured `default_timezone` would make `Intl.DateTimeFormat`
throw a `RangeError` and crash the table.
`recording_date` (object-detail) is a plain `DATE` formatted by `lib/format-date.ts` (no timezone) — correct
and out of scope. There are no other UTC-timestamp displays. `default_timezone` is exposed via
`useConfig().default_timezone` (IANA name; default `"Europe/Stockholm"`).
This is a display-only change: storage/transmission stay UTC. No backend change, no new dependency, no new
i18n keys.
## Components
### `lib/format-timestamp.ts` (new)
Mirrors `lib/format-date.ts`'s shape (same null/invalid-string edge handling), for UTC **timestamps**:
```ts
/** Formats a UTC ISO timestamp for display in the instance timezone + active locale.
* Storage/transmission stay UTC — this is display-only. Falls back to UTC formatting on an
* invalid IANA zone (a misconfigured instance) rather than throwing. */
export function formatTimestamp(value: unknown, timeZone: string, locale: string): string {
if (typeof value !== "string") return value == null ? "—" : String(value);
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const opts = { dateStyle: "medium", timeStyle: "short" } as const;
try {
return new Intl.DateTimeFormat(locale, { ...opts, timeZone }).format(date);
} catch {
return new Intl.DateTimeFormat(locale, { ...opts, timeZone: "UTC" }).format(date);
}
}
```
- **date + short time** (the chosen display) in `timeZone` + `locale`.
- **Invalid-IANA guard:** `new Intl.DateTimeFormat(locale, { timeZone })` throws `RangeError` for a bad
zone → the `catch` re-formats with `timeZone: "UTC"` (no crash).
- Edge handling matches `format-date.ts`: non-string `null``"—"`; other non-strings → `String(value)`;
an unparseable string → returned unchanged.
### `objects/objects-table.tsx` (modify)
Remove the inline `const dateFmt = new Intl.DateTimeFormat(...)` + `formatUpdated` helper. Add
`import { formatTimestamp } from "../lib/format-timestamp";`. Keep `default_timezone` (from `useConfig()`)
and `i18n.language`. Render the Updated cell as:
```tsx
<td className="px-3 py-2 text-muted-foreground">
{formatTimestamp(object.updated_at, default_timezone, i18n.language)}
</td>
```
The column changes from date-only to **date + short time**. (The helper constructs an `Intl.DateTimeFormat`
per cell rather than once-per-render; negligible for the ≤200-row page — kept simple over re-memoizing.)
## Data flow / behaviour
`updated_at` (UTC ISO from the API) → `formatTimestamp(value, default_timezone, i18n.language)` → a
locale-formatted date+time in the instance zone. Identical data; only the display string changes (now
includes the time and is crash-guarded).
## Error handling / edges
- Invalid `default_timezone` → UTC-formatted output (guarded), never a thrown render.
- `null`/non-string `updated_at``"—"`/`String(value)` (defensive; in practice `updated_at` is always a
string).
- Unparseable date string → returned verbatim (matches `format-date.ts`).
- Locale comes from `i18n.language` (full-ICU Node in CI / browsers) — deterministic per locale.
## Testing
- **`lib/format-timestamp.test.ts`** (new):
- valid: `formatTimestamp("2026-06-08T12:30:00Z", "UTC", "en")` contains `"2026"` and `"12:30"` (date +
time rendered).
- **timezone applied (day-shift):** `formatTimestamp("2026-06-08T02:00:00Z", "America/New_York", "en")`
shows `Jun 7` (02:00 UTC = 22:00 prev-day EDT), distinct from the same instant in `"UTC"` (`Jun 8`) —
proves the zone is honored.
- **invalid IANA:** `formatTimestamp("2026-06-08T12:30:00Z", "Not/AZone", "en")` does **not** throw and
returns a non-empty string containing `"2026"` (UTC fallback).
- `null``"—"`; `"not-a-date"``"not-a-date"`.
- **`objects-table.test.tsx`:** the suite does not assert the rendered Updated value, so it stays green;
if any assertion is added/affected, assert the new date+time output loosely (don't pin the exact locale
string).
- **Gate:** `typecheck`/`lint`/`test`/`build`/`check:size`/`check:colors` green; no new dependency; no new
i18n keys; no codename; en/sv parity unaffected.
## Acceptance criteria
1. `lib/format-timestamp.ts` exports `formatTimestamp(value, timeZone, locale)` — date+time in the given
zone/locale, with a UTC fallback on an invalid IANA zone and the null/invalid edge handling; unit-tested
(incl. the day-shift + invalid-zone cases).
2. `objects-table.tsx` renders `updated_at` via `formatTimestamp(object.updated_at, default_timezone,
i18n.language)`; the inline `dateFmt`/`formatUpdated` are removed; the column shows date + short time.
3. All existing tests pass (objects-table green); `typecheck`/`lint`/`build`/`check:colors` green;
`check:size` reported; no new dependency; no new i18n keys; no codename.
## Out of scope → follow-ups
- Additional timestamp displays (object-detail `created_at`/`updated_at`, an audit-history view) — none
exist yet; route them through `formatTimestamp` when they land.
- Server-side timestamp formatting for the PDF export (#39) — needs a Rust tz library, separate.
- `recording_date` / `format-date.ts` (plain DATE, no timezone) — unchanged.
+5
View File
@@ -3,6 +3,8 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<meta name="theme-color" content="#ffffff" />
<title>Collection</title> <title>Collection</title>
<script> <script>
try { try {
@@ -12,6 +14,9 @@
(t === "system" && (t === "system" &&
window.matchMedia("(prefers-color-scheme: dark)").matches); window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark); document.documentElement.classList.toggle("dark", dark);
// Keep in sync with THEME_COLORS in src/theme/theme.ts.
var meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute("content", dark ? "#0a0a0a" : "#ffffff");
} catch (e) {} } catch (e) {}
</script> </script>
</head> </head>
+1 -1
View File
@@ -5,7 +5,7 @@ import { join, relative } from "node:path";
const root = "src"; const root = "src";
const excludeDir = join("src", "components", "ui"); const excludeDir = join("src", "components", "ui");
const RAW_COLOR = const RAW_COLOR =
/(?:text|bg|border|ring|fill|stroke|from|to|via|decoration|outline|divide|placeholder)-(?:neutral|gray|slate|zinc|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950)\b/; /(?:text|bg|border|ring|fill|stroke|from|to|via|decoration|outline|divide|placeholder)-(?:(?:neutral|gray|slate|zinc|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950)|white|black)\b/;
function walk(dir) { function walk(dir) {
const files = []; const files = [];
+1 -1
View File
@@ -1,4 +1,4 @@
import { HttpError, InUseError } from "./queries"; import { HttpError, InUseError } from "./errors";
/** Maps a caught mutation error to an i18n key (+ interpolation opts). The single /** Maps a caught mutation error to an i18n key (+ interpolation opts). The single
* source of truth shared by the global toast fallback and every inline display. */ * source of truth shared by the global toast fallback and every inline display. */
+28
View File
@@ -0,0 +1,28 @@
export class HttpError extends Error {
constructor(public readonly status: number) {
super(`HTTP ${status}`);
this.name = "HttpError";
}
}
export class FieldRejection extends Error {
constructor(public readonly field: string, public readonly code: string) {
super(`field rejected: ${field}`);
this.name = "FieldRejection";
}
}
export class InUseError extends Error {
constructor(public readonly count: number) {
super(`in use: ${count}`);
this.name = "InUseError";
}
}
/** Error carrying the HTTP status so callers can branch 422-gate vs 409-illegal. */
export class VisibilityError extends Error {
constructor(public status: number) {
super(`visibility change failed (${status})`);
this.name = "VisibilityError";
}
}
-584
View File
@@ -1,584 +0,0 @@
import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./client";
import type { components } from "./schema";
export class HttpError extends Error {
constructor(public readonly status: number) {
super(`HTTP ${status}`);
this.name = "HttpError";
}
}
export class FieldRejection extends Error {
constructor(public readonly field: string, public readonly code: string) {
super(`field rejected: ${field}`);
this.name = "FieldRejection";
}
}
export class InUseError extends Error {
constructor(public readonly count: number) {
super(`in use: ${count}`);
this.name = "InUseError";
}
}
type UserView = components["schemas"]["UserView"];
type LoginRequest = components["schemas"]["LoginRequest"];
export function useMe() {
return useQuery({
queryKey: ["me"],
queryFn: async (): Promise<UserView | null> => {
const { data, response } = await api.GET("/api/admin/me");
if (response.status === 401) return null;
if (!data) throw new Error("failed to load session");
return data;
},
retry: false,
});
}
export type ObjectListParams = {
limit: number;
offset: number;
sort?: string;
order?: "asc" | "desc";
visibility?: string;
q?: string;
};
export function useObjectsPage(params: ObjectListParams) {
return useQuery({
queryKey: ["objects", params],
placeholderData: keepPreviousData,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/objects", {
params: {
query: {
limit: params.limit,
offset: params.offset,
sort: params.sort,
order: params.order,
visibility: params.visibility,
q: params.q,
},
},
});
if (error || !data) throw new Error("failed to load objects");
return data;
},
});
}
export function useObject(id: string) {
return useQuery({
queryKey: ["object", id],
queryFn: async () => {
const { data, response } = await api.GET("/api/admin/objects/{id}", {
params: { path: { id } },
});
if (response.status === 404) return null;
if (!data) throw new Error("failed to load object");
return data;
},
// A 404 resolves to null rather than erroring, so don't retry it.
retry: false,
});
}
export function useFieldDefinitions() {
return useQuery({
queryKey: ["field-definitions"],
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/field-definitions");
if (error || !data) throw new Error("failed to load field definitions");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useLogin() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: LoginRequest) => {
const { response } = await api.POST("/api/admin/login", { body });
if (response.status !== 204) {
throw new Error(response.status === 401 ? "invalid" : "network");
}
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["me"] }),
meta: { suppressErrorToast: true },
});
}
export function useLogout() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => {
await api.POST("/api/admin/logout");
},
onSuccess: () => qc.setQueryData(["me"], null),
});
}
type ObjectCreateRequest = components["schemas"]["ObjectCreateRequest"];
type ObjectUpdateRequest = components["schemas"]["ObjectUpdateRequest"];
export function useTerms(vocabularyId: string | null | undefined) {
return useQuery({
queryKey: ["terms", vocabularyId],
enabled: !!vocabularyId,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/vocabularies/{id}/terms", {
params: { path: { id: vocabularyId! } },
});
if (error || !data) throw new Error("failed to load terms");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useAuthorities(kind: string | null | undefined) {
return useQuery({
queryKey: ["authorities", kind],
enabled: !!kind,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/authorities", {
params: { query: { kind: kind! } },
});
if (error || !data) throw new Error("failed to load authorities");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useCreateObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: ObjectCreateRequest) => {
const { data, error, response } = await api.POST("/api/admin/objects", { body });
if (error || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useUpdateObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, body }: { id: string; body: ObjectUpdateRequest }) => {
const { response } = await api.PUT("/api/admin/objects/{id}", {
params: { path: { id } },
body,
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: ["objects"] });
void qc.invalidateQueries({ queryKey: ["object", id] });
},
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useSetFields() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, fields }: { id: string; fields: Record<string, unknown> }) => {
const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", {
params: { path: { id } },
body: fields as Record<string, never>,
});
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 HttpError(response.status);
},
onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: ["object", id] });
},
meta: { suppressErrorToast: true },
});
}
export function useDeleteObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { response } = await api.DELETE("/api/admin/objects/{id}", {
params: { path: { id } },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["objects"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
type NewVocabularyRequest = components["schemas"]["NewVocabularyRequest"];
type LabelInput = components["schemas"]["LabelInput"];
export function useVocabularies() {
return useQuery({
queryKey: ["vocabularies"],
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/vocabularies");
if (error || !data) throw new Error("failed to load vocabularies");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useCreateVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: NewVocabularyRequest) => {
const { data, error, response } = await api.POST("/api/admin/vocabularies", { body });
if (error || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useAddTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
vocabularyId,
external_uri,
labels,
}: {
vocabularyId: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.POST("/api/admin/vocabularies/{id}/terms", {
params: { path: { id: vocabularyId } },
body: { external_uri, labels },
});
if (response.status !== 201) throw new HttpError(response.status);
},
onSuccess: (_result, { vocabularyId }) =>
qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useCreateAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
kind,
external_uri,
labels,
}: {
kind: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.POST("/api/admin/authorities", {
body: { kind, external_uri, labels },
});
if (response.status !== 201) throw new HttpError(response.status);
},
onSuccess: (_result, { kind }) =>
qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
const SEARCH_PAGE = 20;
export function useSearch(q: string, visibility: string | null) {
const term = q.trim();
return useInfiniteQuery({
queryKey: ["search", term, visibility],
enabled: term.length > 0,
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
const { data, error, response } = await api.GET("/api/admin/search", {
params: {
query: {
q: term,
...(visibility ? { visibility } : {}),
offset: pageParam,
limit: SEARCH_PAGE,
},
},
});
if (error || !data) throw new HttpError(response.status);
return data;
},
placeholderData: keepPreviousData,
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce((n, page) => n + page.hits.length, 0);
return loaded < lastPage.estimated_total ? loaded : undefined;
},
});
}
type NewFieldDefinitionRequest = components["schemas"]["NewFieldDefinitionRequest"];
export function useCreateFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: NewFieldDefinitionRequest) => {
const { data, response } = await api.POST("/api/admin/field-definitions", { body });
if (response.status !== 201 || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
type Visibility = "draft" | "internal" | "public";
/** Error carrying the HTTP status so callers can branch 422-gate vs 409-illegal. */
export class VisibilityError extends Error {
constructor(public status: number) {
super(`visibility change failed (${status})`);
this.name = "VisibilityError";
}
}
export function useSetVisibility() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, visibility }: { id: string; visibility: Visibility }) => {
const { response } = await api.POST("/api/admin/objects/{id}/visibility", {
params: { path: { id } },
body: { visibility },
});
if (response.status !== 204) throw new VisibilityError(response.status);
},
onSuccess: (_result, { id }) => {
void qc.invalidateQueries({ queryKey: ["object", id] });
void qc.invalidateQueries({ queryKey: ["objects"] });
},
meta: { successMessage: "toast.published", suppressErrorToast: true },
});
}
export function useUpdateTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
vocabularyId,
termId,
external_uri,
labels,
}: {
vocabularyId: string;
termId: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/vocabularies/{id}/terms/{term_id}", {
params: { path: { id: vocabularyId, term_id: termId } },
body: { external_uri, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ vocabularyId, termId }: { vocabularyId: string; termId: string }) => {
const { error, response } = await api.DELETE("/api/admin/vocabularies/{id}/terms/{term_id}", {
params: { path: { id: vocabularyId, term_id: termId } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: ["terms", vocabularyId] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
export function useRenameVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, key }: { id: string; key: string }) => {
const { response } = await api.PATCH("/api/admin/vocabularies/{id}", {
params: { path: { id } },
body: { key },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.renamed", suppressErrorToast: true },
});
}
export function useDeleteVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error, response } = await api.DELETE("/api/admin/vocabularies/{id}", {
params: { path: { id } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["vocabularies"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
export function useUpdateAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
id,
external_uri,
labels,
}: {
id: string;
kind: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/authorities/{id}", {
params: { path: { id } },
body: { external_uri, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id }: { id: string; kind: string }) => {
const { error, response } = await api.DELETE("/api/admin/authorities/{id}", {
params: { path: { id } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: ["authorities", kind] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
export function useUpdateFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
key,
required,
group,
labels,
}: {
key: string;
required: boolean;
group: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/field-definitions/{key}", {
params: { path: { key } },
body: { required, group, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (key: string) => {
const { error, response } = await api.DELETE("/api/admin/field-definitions/{key}", {
params: { path: { key } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["field-definitions"] }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
+51
View File
@@ -0,0 +1,51 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { keys } from "../query-keys";
type UserView = components["schemas"]["UserView"];
type LoginRequest = components["schemas"]["LoginRequest"];
export function useMe() {
return useQuery({
queryKey: keys.me(),
queryFn: async (): Promise<UserView | null> => {
const { data, response } = await api.GET("/api/admin/me");
if (response.status === 401) return null;
if (!data) throw new Error("failed to load session");
return data;
},
retry: false,
});
}
export function useLogin() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: LoginRequest) => {
const { response } = await api.POST("/api/admin/login", { body });
if (response.status !== 204) {
throw new Error(response.status === 401 ? "invalid" : "network");
}
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.me() }),
meta: { suppressErrorToast: true },
});
}
export function useLogout() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => {
await api.POST("/api/admin/logout");
},
onSuccess: () => qc.setQueryData(keys.me(), null),
});
}
+93
View File
@@ -0,0 +1,93 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type LabelInput = components["schemas"]["LabelInput"];
export function useAuthorities(kind: string | null | undefined) {
return useQuery({
queryKey: keys.authorities(kind),
enabled: !!kind,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/authorities", {
params: { query: { kind: kind! } },
});
if (error || !data) throw new Error("failed to load authorities");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useCreateAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
kind,
external_uri,
labels,
}: {
kind: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.POST("/api/admin/authorities", {
body: { kind, external_uri, labels },
});
if (response.status !== 201) throw new HttpError(response.status);
},
onSuccess: (_result, { kind }) =>
qc.invalidateQueries({ queryKey: keys.authorities(kind) }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useUpdateAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
id,
external_uri,
labels,
}: {
id: string;
kind: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/authorities/{id}", {
params: { path: { id } },
body: { external_uri, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: keys.authorities(kind) }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteAuthority() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id }: { id: string; kind: string }) => {
const { error, response } = await api.DELETE("/api/admin/authorities/{id}", {
params: { path: { id } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { kind }) => qc.invalidateQueries({ queryKey: keys.authorities(kind) }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
+83
View File
@@ -0,0 +1,83 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type NewFieldDefinitionRequest = components["schemas"]["NewFieldDefinitionRequest"];
type LabelInput = components["schemas"]["LabelInput"];
export function useFieldDefinitions() {
return useQuery({
queryKey: keys.fieldDefinitions(),
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/field-definitions");
if (error || !data) throw new Error("failed to load field definitions");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useCreateFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: NewFieldDefinitionRequest) => {
const { data, response } = await api.POST("/api/admin/field-definitions", { body });
if (response.status !== 201 || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.fieldDefinitions() }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useUpdateFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
key,
required,
group,
labels,
}: {
key: string;
required: boolean;
group: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/field-definitions/{key}", {
params: { path: { key } },
body: { required, group, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.fieldDefinitions() }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteFieldDefinition() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (key: string) => {
const { error, response } = await api.DELETE("/api/admin/field-definitions/{key}", {
params: { path: { key } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.fieldDefinitions() }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
+8
View File
@@ -0,0 +1,8 @@
export * from "./auth";
export * from "./objects";
export * from "./field-defs";
export * from "./vocab";
export * from "./authorities";
export * from "./search";
export * from "../errors";
export type { ObjectListParams } from "../query-keys";
+157
View File
@@ -0,0 +1,157 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, FieldRejection, VisibilityError } from "../errors";
import { keys, type ObjectListParams } from "../query-keys";
type ObjectCreateRequest = components["schemas"]["ObjectCreateRequest"];
type ObjectUpdateRequest = components["schemas"]["ObjectUpdateRequest"];
type Visibility = "draft" | "internal" | "public";
export function useObjectsPage(params: ObjectListParams) {
return useQuery({
queryKey: keys.objectsPage(params),
placeholderData: keepPreviousData,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/objects", {
params: {
query: {
limit: params.limit,
offset: params.offset,
sort: params.sort,
order: params.order,
visibility: params.visibility,
q: params.q,
},
},
});
if (error || !data) throw new Error("failed to load objects");
return data;
},
});
}
export function useObject(id: string) {
return useQuery({
queryKey: keys.object(id),
queryFn: async () => {
const { data, response } = await api.GET("/api/admin/objects/{id}", {
params: { path: { id } },
});
if (response.status === 404) return null;
if (!data) throw new Error("failed to load object");
return data;
},
// A 404 resolves to null rather than erroring, so don't retry it.
retry: false,
});
}
export function useCreateObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: ObjectCreateRequest) => {
const { data, error, response } = await api.POST("/api/admin/objects", { body });
if (error || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.objects() }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useUpdateObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, body }: { id: string; body: ObjectUpdateRequest }) => {
const { response } = await api.PUT("/api/admin/objects/{id}", {
params: { path: { id } },
body,
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: keys.objects() });
void qc.invalidateQueries({ queryKey: keys.object(id) });
void qc.invalidateQueries({ queryKey: keys.search() });
},
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useSetFields() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, fields }: { id: string; fields: Record<string, unknown> }) => {
const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", {
params: { path: { id } },
body: fields as Record<string, never>,
});
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 HttpError(response.status);
},
onSuccess: (_d, { id }) => {
void qc.invalidateQueries({ queryKey: keys.object(id) });
},
meta: { suppressErrorToast: true },
});
}
export function useDeleteObject() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { response } = await api.DELETE("/api/admin/objects/{id}", {
params: { path: { id } },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => {
void qc.invalidateQueries({ queryKey: keys.objects() });
void qc.invalidateQueries({ queryKey: keys.search() });
},
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
export function useSetVisibility() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, visibility }: { id: string; visibility: Visibility }) => {
const { response } = await api.POST("/api/admin/objects/{id}/visibility", {
params: { path: { id } },
body: { visibility },
});
if (response.status !== 204) throw new VisibilityError(response.status);
},
onSuccess: (_result, { id }) => {
void qc.invalidateQueries({ queryKey: keys.object(id) });
void qc.invalidateQueries({ queryKey: keys.objects() });
void qc.invalidateQueries({ queryKey: keys.search() });
},
meta: { successMessage: "toast.published", suppressErrorToast: true },
});
}
+39
View File
@@ -0,0 +1,39 @@
import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";
import { api } from "../client";
import { HttpError } from "../errors";
import { keys } from "../query-keys";
const SEARCH_PAGE = 20;
export function useSearch(q: string, visibility: string | null) {
const term = q.trim();
return useInfiniteQuery({
queryKey: keys.searchResults(term, visibility),
enabled: term.length > 0,
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
const { data, error, response } = await api.GET("/api/admin/search", {
params: {
query: {
q: term,
...(visibility ? { visibility } : {}),
offset: pageParam,
limit: SEARCH_PAGE,
},
},
});
if (error || !data) throw new HttpError(response.status);
return data;
},
placeholderData: keepPreviousData,
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce((n, page) => n + page.hits.length, 0);
return loaded < lastPage.estimated_total ? loaded : undefined;
},
});
}
+160
View File
@@ -0,0 +1,160 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "../client";
import type { components } from "../schema";
import { HttpError, InUseError } from "../errors";
import { keys } from "../query-keys";
type NewVocabularyRequest = components["schemas"]["NewVocabularyRequest"];
type LabelInput = components["schemas"]["LabelInput"];
export function useVocabularies() {
return useQuery({
queryKey: keys.vocabularies(),
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/vocabularies");
if (error || !data) throw new Error("failed to load vocabularies");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useCreateVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body: NewVocabularyRequest) => {
const { data, error, response } = await api.POST("/api/admin/vocabularies", { body });
if (error || !data) throw new HttpError(response.status);
return data;
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.vocabularies() }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useRenameVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, key }: { id: string; key: string }) => {
const { response } = await api.PATCH("/api/admin/vocabularies/{id}", {
params: { path: { id } },
body: { key },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.vocabularies() }),
meta: { successMessage: "toast.renamed", suppressErrorToast: true },
});
}
export function useDeleteVocabulary() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error, response } = await api.DELETE("/api/admin/vocabularies/{id}", {
params: { path: { id } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: () => qc.invalidateQueries({ queryKey: keys.vocabularies() }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
export function useTerms(vocabularyId: string | null | undefined) {
return useQuery({
queryKey: keys.terms(vocabularyId),
enabled: !!vocabularyId,
queryFn: async () => {
const { data, error } = await api.GET("/api/admin/vocabularies/{id}/terms", {
params: { path: { id: vocabularyId! } },
});
if (error || !data) throw new Error("failed to load terms");
return data;
},
staleTime: 5 * 60 * 1000,
});
}
export function useAddTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
vocabularyId,
external_uri,
labels,
}: {
vocabularyId: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.POST("/api/admin/vocabularies/{id}/terms", {
params: { path: { id: vocabularyId } },
body: { external_uri, labels },
});
if (response.status !== 201) throw new HttpError(response.status);
},
onSuccess: (_result, { vocabularyId }) =>
qc.invalidateQueries({ queryKey: keys.terms(vocabularyId) }),
meta: { successMessage: "toast.created", suppressErrorToast: true },
});
}
export function useUpdateTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
vocabularyId,
termId,
external_uri,
labels,
}: {
vocabularyId: string;
termId: string;
external_uri: string | null;
labels: LabelInput[];
}) => {
const { response } = await api.PATCH("/api/admin/vocabularies/{id}/terms/{term_id}", {
params: { path: { id: vocabularyId, term_id: termId } },
body: { external_uri, labels },
});
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: keys.terms(vocabularyId) }),
meta: { successMessage: "toast.saved", suppressErrorToast: true },
});
}
export function useDeleteTerm() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ vocabularyId, termId }: { vocabularyId: string; termId: string }) => {
const { error, response } = await api.DELETE("/api/admin/vocabularies/{id}/terms/{term_id}", {
params: { path: { id: vocabularyId, term_id: termId } },
});
if (response.status === 409) throw new InUseError((error as { count?: number })?.count ?? 0);
if (response.status !== 204) throw new HttpError(response.status);
},
onSuccess: (_d, { vocabularyId }) => qc.invalidateQueries({ queryKey: keys.terms(vocabularyId) }),
meta: { successMessage: "toast.deleted", suppressErrorToast: true },
});
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, test } from "vitest";
import { keys } from "./query-keys";
test("the key factory produces the expected arrays", () => {
expect(keys.me()).toEqual(["me"]);
expect(keys.config()).toEqual(["config"]);
expect(keys.objects()).toEqual(["objects"]);
const p = { limit: 50, offset: 0 };
expect(keys.objectsPage(p)).toEqual(["objects", p]);
expect(keys.object("x")).toEqual(["object", "x"]);
expect(keys.fieldDefinitions()).toEqual(["field-definitions"]);
expect(keys.vocabularies()).toEqual(["vocabularies"]);
expect(keys.terms("v1")).toEqual(["terms", "v1"]);
expect(keys.authorities("person")).toEqual(["authorities", "person"]);
expect(keys.search()).toEqual(["search"]);
expect(keys.searchResults("q", null)).toEqual(["search", "q", null]);
});
test("objects() is a prefix of objectsPage() so invalidation matches", () => {
const prefix = keys.objects();
const full = keys.objectsPage({ limit: 50, offset: 0 });
expect(full.slice(0, prefix.length)).toEqual(prefix);
});
+24
View File
@@ -0,0 +1,24 @@
export type ObjectListParams = {
limit: number;
offset: number;
sort?: string;
order?: "asc" | "desc";
visibility?: string;
q?: string;
};
/** Central query-key factory — the single source of truth for cache keys, so
* query/invalidate/setQueryData sites can't drift. */
export const keys = {
me: () => ["me"] as const,
config: () => ["config"] as const,
objects: () => ["objects"] as const,
objectsPage: (params: ObjectListParams) => ["objects", params] as const,
object: (id: string) => ["object", id] as const,
fieldDefinitions: () => ["field-definitions"] as const,
vocabularies: () => ["vocabularies"] as const,
terms: (vocabularyId: string | null | undefined) => ["terms", vocabularyId] as const,
authorities: (kind: string | null | undefined) => ["authorities", kind] as const,
search: () => ["search"] as const,
searchResults: (term: string, visibility: string | null) => ["search", term, visibility] as const,
};
+28
View File
@@ -0,0 +1,28 @@
import { expect, test } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
import { server } from "../test/server";
import { useSetVisibility } from "./queries";
import { keys } from "./query-keys";
test("changing an object's visibility invalidates the active search query", async () => {
server.use(
http.post("/api/admin/objects/:id/visibility", () => new HttpResponse(null, { status: 204 })),
);
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(keys.searchResults("amphora", null), { pages: [], pageParams: [] });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>{children}</QueryClientProvider>
);
const { result } = renderHook(() => useSetVisibility(), { wrapper });
await result.current.mutateAsync({ id: "o1", visibility: "public" });
await waitFor(() =>
expect(qc.getQueryState(keys.searchResults("amphora", null))?.isInvalidated).toBe(true),
);
});
+1 -1
View File
@@ -72,7 +72,7 @@ const router = createBrowserRouter(
<Route path="/authorities" element={<Navigate to="/authorities/person" replace />} /> <Route path="/authorities" element={<Navigate to="/authorities/person" replace />} />
<Route path="/authorities/:kind" element={<AuthoritiesPage />} /> <Route path="/authorities/:kind" element={<AuthoritiesPage />} />
<Route <Route
path="/fields" path="/fields/:key?"
element={ element={
<Suspense fallback={<ListSkeleton />}> <Suspense fallback={<ListSkeleton />}>
<FieldsPage /> <FieldsPage />
+25
View File
@@ -57,6 +57,31 @@ test("rejects an off-site from and falls back to /objects", async () => {
expect(await screen.findByText("objects landing")).toBeInTheDocument(); expect(await screen.findByText("objects landing")).toBeInTheDocument();
}); });
test("shows Signing in… and disables the button while pending", async () => {
let release!: () => void;
const gate = new Promise<void>((r) => {
release = r;
});
server.use(
http.post("/api/admin/login", async () => {
await gate;
return new HttpResponse(null, { status: 204 });
}),
);
renderApp(tree(), { route: "/login" });
await userEvent.type(screen.getByLabelText(/email/i), "editor@example.com");
await userEvent.type(screen.getByLabelText(/password/i), "pw-editor-123");
await userEvent.click(screen.getByRole("button", { name: /sign in/i }));
const pending = await screen.findByRole("button", { name: /signing in/i });
expect(pending).toBeDisabled();
release();
expect(await screen.findByText("objects landing")).toBeInTheDocument();
});
test("disables submit until both fields are filled", async () => { test("disables submit until both fields are filled", async () => {
renderApp(tree(), { route: "/login" }); renderApp(tree(), { route: "/login" });
const button = screen.getByRole("button", { name: /sign in/i }); const button = screen.getByRole("button", { name: /sign in/i });
+3 -2
View File
@@ -7,6 +7,7 @@ import { useConfig } from "../config/config-context";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { PageTitle } from "@/components/ui/page-title";
/** Accept only a single-leading-slash local path; reject protocol-relative /** Accept only a single-leading-slash local path; reject protocol-relative
* ("//host") and absolute URLs to avoid an open redirect. */ * ("//host") and absolute URLs to avoid an open redirect. */
@@ -46,7 +47,7 @@ export function LoginPage() {
return ( return (
<div className="flex min-h-screen items-center justify-center p-4"> <div className="flex min-h-screen items-center justify-center p-4">
<form onSubmit={onSubmit} className="w-full max-w-sm space-y-4"> <form onSubmit={onSubmit} className="w-full max-w-sm space-y-4">
<h1 className="text-2xl font-semibold">{app_name}</h1> <PageTitle>{app_name}</PageTitle>
{sessionExpired && ( {sessionExpired && (
<p className="text-sm text-muted-foreground">{t("auth.sessionExpired")}</p> <p className="text-sm text-muted-foreground">{t("auth.sessionExpired")}</p>
)} )}
@@ -76,7 +77,7 @@ export function LoginPage() {
</p> </p>
)} )}
<Button type="submit" className="w-full" disabled={login.isPending || !email.trim() || !password}> <Button type="submit" className="w-full" disabled={login.isPending || !email.trim() || !password}>
{t("auth.signIn")} {login.isPending ? t("auth.signingIn") : t("auth.signIn")}
</Button> </Button>
</form> </form>
</div> </div>
+22 -108
View File
@@ -1,32 +1,22 @@
import { useState, type FormEvent } from "react";
import { NavLink, Navigate, useParams } from "react-router-dom"; import { NavLink, Navigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useAuthorities, useCreateAuthority } from "../api/queries"; import { useAuthorities, useCreateAuthority } from "../api/queries";
import { LabelEditor } from "../components/label-editor"; import { FilteredRecordList } from "../components/filtered-record-list";
import { MutationError } from "../components/mutation-error"; import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PageTitle } from "@/components/ui/page-title"; import { PageTitle } from "@/components/ui/page-title";
import { ListSkeleton } from "@/components/ui/skeletons";
import { AuthorityRow } from "./authority-row"; import { AuthorityRow } from "./authority-row";
import { byLabel } from "../lib/sort"; import { useLang } from "../lib/use-lang";
import { labelText } from "../lib/labels"; import { segmentClass } from "../lib/class-recipes";
import { focusRing } from "../lib/focus-ring";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { cn } from "@/lib/utils";
type LabelInput = components["schemas"]["LabelInput"];
const KINDS = ["person", "organisation", "place"] as const; const KINDS = ["person", "organisation", "place"] as const;
export function AuthoritiesPage() { export function AuthoritiesPage() {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const { kind } = useParams(); const { kind } = useParams();
const lang = i18n.language.startsWith("sv") ? "sv" : "en"; const lang = useLang();
const isValidKind = (KINDS as readonly string[]).includes(kind ?? ""); const isValidKind = (KINDS as readonly string[]).includes(kind ?? "");
const currentKind = isValidKind ? (kind as string) : "person"; const currentKind = isValidKind ? (kind as string) : "person";
@@ -34,36 +24,11 @@ export function AuthoritiesPage() {
const { data: authorities, isLoading, isError } = useAuthorities(currentKind); const { data: authorities, isLoading, isError } = useAuthorities(currentKind);
const create = useCreateAuthority(); const create = useCreateAuthority();
const [labels, setLabels] = useState<LabelInput[]>([]);
const [error, setError] = useState(false);
const [filter, setFilter] = useState("");
const [uri, setUri] = useState("");
useDocumentTitle(t("nav.authorities")); useDocumentTitle(t("nav.authorities"));
useBreadcrumb([{ label: t("nav.authorities") }]); useBreadcrumb([{ label: t("nav.authorities") }]);
if (!isValidKind) return <Navigate to="/authorities/person" replace />; if (!isValidKind) return <Navigate to="/authorities/person" replace />;
const onCreate = (event: FormEvent) => {
event.preventDefault();
if (!labels.some((l) => l.label)) {
setError(true);
return;
}
setError(false);
create.mutate(
{ kind: kind as string, external_uri: uri.trim() || null, labels },
{
onSuccess: () => {
setLabels([]);
setUri("");
},
},
);
};
return ( return (
<div className="overflow-auto p-4"> <div className="overflow-auto p-4">
<PageTitle className="mb-3">{t("nav.authorities")}</PageTitle> <PageTitle className="mb-3">{t("nav.authorities")}</PageTitle>
@@ -72,82 +37,31 @@ export function AuthoritiesPage() {
<NavLink <NavLink
key={k} key={k}
to={`/authorities/${k}`} to={`/authorities/${k}`}
className={({ isActive }) => className={({ isActive }) => segmentClass(isActive, "px-3 py-1 text-sm")}
cn("rounded-md px-3 py-1 text-sm", focusRing, isActive ? "bg-primary text-primary-foreground" : "border")
}
> >
{t(`authorities.${k}`)} {t(`authorities.${k}`)}
</NavLink> </NavLink>
))} ))}
</nav> </nav>
<div className="mb-3"> <FilteredRecordList
<Input records={authorities}
aria-label={t("common.filter")} lang={lang}
placeholder={t("common.filter")} isLoading={isLoading}
value={filter} isError={isError}
onChange={(e) => setFilter(e.target.value)} loadErrorText={t("authorities.loadError")}
emptyText={t("authorities.empty")}
renderRow={(a) => <AuthorityRow authority={a} kind={currentKind} lang={lang} />}
/> />
</div>
{isLoading ? ( <LabelledRecordCreateForm
<ListSkeleton className="mb-4" rows={5} /> heading={`${t("authorities.new")} · ${t(`authorities.${currentKind}`)}`}
) : ( submitLabel={t("authorities.create")}
(() => { pending={create.isPending}
const q = filter.trim().toLowerCase(); error={create.error}
const rows = [...(authorities ?? [])] onCreate={(labels, uri, reset) =>
.filter((a) => !q || labelText(a.labels, lang).toLowerCase().includes(q)) create.mutate({ kind: currentKind, external_uri: uri, labels }, { onSuccess: reset })}
.sort(byLabel(lang));
return (
<ul className="mb-4">
{isError && (
<li className="text-sm text-destructive">{t("authorities.loadError")}</li>
)}
{!isError && authorities?.length === 0 && (
<li className="text-sm text-muted-foreground">{t("authorities.empty")}</li>
)}
{!isError && authorities && authorities.length > 0 && rows.length === 0 && (
<li className="text-sm text-muted-foreground">{t("common.noMatches")}</li>
)}
{rows.map((a) => (
<AuthorityRow key={a.id} authority={a} kind={currentKind} lang={lang} />
))}
</ul>
);
})()
)}
<form onSubmit={onCreate} className="space-y-2 border-t pt-3">
<div className="text-sm font-medium">
{t("authorities.new")} · {t(`authorities.${currentKind}`)}
</div>
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor="auth-create-uri">{t("labels.externalUri")}</Label>
<Input
id="auth-create-uri"
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/> />
</div> </div>
{error && (
<p role="alert" className="text-xs text-destructive">
{t("form.required")}
</p>
)}
<MutationError error={create.error} />
<Button type="submit" size="sm" disabled={create.isPending}>
{t("authorities.create")}
</Button>
</form>
</div>
); );
} }
+13 -79
View File
@@ -1,90 +1,24 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { useUpdateAuthority, useDeleteAuthority } from "../api/queries"; import { useUpdateAuthority, useDeleteAuthority } from "../api/queries";
import { LabelEditor } from "../components/label-editor"; import { LabelledRecordRow } from "../components/labelled-record-row";
import { DeleteConfirmDialog } from "../components/delete-confirm-dialog";
import { MutationError } from "../components/mutation-error";
import { ExternalUriLink } from "../components/external-uri-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";
type AuthorityView = components["schemas"]["AuthorityView"]; type AuthorityView = components["schemas"]["AuthorityView"];
type LabelInput = components["schemas"]["LabelInput"];
export function AuthorityRow({ authority, kind, lang }: { authority: AuthorityView; kind: string; lang: string }) { export function AuthorityRow({ authority, kind, lang }: { authority: AuthorityView; kind: string; lang: string }) {
const { t } = useTranslation(); const update = useUpdateAuthority();
const del = useDeleteAuthority();
const updateAuthority = useUpdateAuthority();
const deleteAuthority = useDeleteAuthority();
const [editing, setEditing] = useState(false);
const [labels, setLabels] = useState<LabelInput[]>(authority.labels as LabelInput[]);
const [uri, setUri] = useState(authority.external_uri ?? "");
if (editing) {
return (
<li className="space-y-2 border-b py-2">
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={`auth-uri-${authority.id}`}>{t("labels.externalUri")}</Label>
<Input
id={`auth-uri-${authority.id}`}
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/>
</div>
<div className="flex gap-2">
<Button
type="button"
size="sm"
disabled={updateAuthority.isPending}
onClick={() =>
updateAuthority.mutate(
{ id: authority.id, kind, external_uri: uri.trim() || null, labels },
{ onSuccess: () => setEditing(false) },
)
}
>
{t("actions.save")}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
{t("form.cancel")}
</Button>
</div>
<MutationError error={updateAuthority.error} />
</li>
);
}
return ( return (
<li className="flex items-center gap-2 border-b py-1 text-sm"> <LabelledRecordRow
<div className="flex-1"> record={{ ...authority, external_uri: authority.external_uri ?? null }}
<div>{labelText(authority.labels, lang)}</div> lang={lang}
{authority.external_uri && <ExternalUriLink uri={authority.external_uri} />} deleteConfirmKey="actions.confirmDeleteAuthority"
</div> savePending={update.isPending}
<Button saveError={update.error}
type="button" onEditOpen={() => update.reset()}
variant="ghost" onSave={(labels, uri, done) =>
size="sm" update.mutate({ id: authority.id, kind, external_uri: uri, labels }, { onSuccess: done })}
onClick={() => { onDelete={() => del.mutateAsync({ id: authority.id, kind })}
updateAuthority.reset();
setLabels(authority.labels as LabelInput[]);
setUri(authority.external_uri ?? "");
setEditing(true);
}}
>
{t("actions.edit")}
</Button>
<DeleteConfirmDialog
description={t("actions.confirmDeleteAuthority")}
onConfirm={() => deleteAuthority.mutateAsync({ id: authority.id, kind })}
/> />
</li>
); );
} }
@@ -0,0 +1,60 @@
import { expect, test, vi } from "vitest";
import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { InUseError } from "../api/errors";
test("delete-in-use shows the in-use count and keeps the dialog open", async () => {
const onConfirm = vi.fn(() => Promise.reject(new InUseError(3)));
renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const buttons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(buttons[buttons.length - 1]);
expect(await dialog.findByText(/used by 3/i)).toBeInTheDocument();
expect(dialog.getByText("Delete this term?")).toBeInTheDocument();
});
test("confirm is disabled and labelled Deleting… while pending", async () => {
let resolve!: () => void;
const onConfirm = vi.fn(
() =>
new Promise<void>((r) => {
resolve = r;
}),
);
renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const buttons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(buttons[buttons.length - 1]);
const pending = await dialog.findByRole("button", { name: /deleting/i });
expect(pending).toBeDisabled();
expect(dialog.getByRole("button", { name: /cancel/i })).toBeDisabled();
expect(onConfirm).toHaveBeenCalledTimes(1);
resolve();
await waitFor(() => expect(dialog.queryByText("Delete this term?")).toBeNull());
});
test("a clean confirm closes the dialog", async () => {
const onConfirm = vi.fn(() => Promise.resolve());
renderApp(<DeleteConfirmDialog description="Delete this term?" onConfirm={onConfirm} />);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const buttons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(buttons[buttons.length - 1]);
await waitFor(() => expect(dialog.queryByText("Delete this term?")).toBeNull());
expect(onConfirm).toHaveBeenCalledTimes(1);
});
+8 -2
View File
@@ -28,10 +28,12 @@ export function DeleteConfirmDialog({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
const confirm = async () => { const confirm = async () => {
setMessage(null); setMessage(null);
setPending(true);
try { try {
await onConfirm(); await onConfirm();
} catch (err) { } catch (err) {
@@ -40,6 +42,8 @@ export function DeleteConfirmDialog({
const { key, opts } = errorMessageKey(err); const { key, opts } = errorMessageKey(err);
setMessage(t(key, opts)); setMessage(t(key, opts));
return; return;
} finally {
setPending(false);
} }
setOpen(false); setOpen(false);
}; };
@@ -62,8 +66,10 @@ export function DeleteConfirmDialog({
</p> </p>
)} )}
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t("form.cancel")}</AlertDialogCancel> <AlertDialogCancel disabled={pending}>{t("form.cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={confirm}>{t("actions.delete")}</AlertDialogAction> <AlertDialogAction disabled={pending} onClick={confirm}>
{pending ? t("actions.deleting") : t("actions.delete")}
</AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
+20
View File
@@ -0,0 +1,20 @@
import { expect, test, vi } from "vitest";
import { within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { DetailDrawer } from "./detail-drawer";
test("renders children in a named drawer and closes via the close button", async () => {
const onClose = vi.fn();
renderApp(
<DetailDrawer open onClose={onClose} ariaLabel="Object detail">
<p>detail body</p>
</DetailDrawer>,
);
const body = within(document.body);
expect(await body.findByText("detail body")).toBeInTheDocument();
await userEvent.click(body.getByRole("button", { name: /close detail/i }));
expect(onClose).toHaveBeenCalled();
});
@@ -1,20 +1,22 @@
import { Outlet } from "react-router-dom"; import type { ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer"; import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer";
import { Button } from "@/components/ui/button";
/** /** A right-sliding Base UI Drawer for a master/detail "detail" on narrow viewports.
* Narrow-viewport object detail: the nested <Outlet/> inside a Base UI Drawer that * Provides the close affordance + an accessible dialog name; the caller supplies the content. */
* slides from the right. Lazy-loaded so Base UI's drawer code (swipe/snap machinery) export function DetailDrawer({
* splits out of the main entry chunk the wide pane path never pays for it.
*/
export function ObjectDetailDrawer({
open, open,
onClose, onClose,
ariaLabel,
children,
}: { }: {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
ariaLabel: string;
children: ReactNode;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -26,18 +28,16 @@ export function ObjectDetailDrawer({
}} }}
swipeDirection="right" swipeDirection="right"
> >
<DrawerContent aria-label={t("objects.detailTitle")}> <DrawerContent aria-label={ariaLabel}>
<div className="flex justify-end border-b p-2"> <div className="flex justify-end border-b p-2">
<DrawerClose <DrawerClose
aria-label={t("actions.closeDetail")} aria-label={t("actions.closeDetail")}
className="rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground" render={<Button variant="ghost" size="icon-sm" />}
> >
<X className="size-4" aria-hidden="true" /> <X className="size-4" aria-hidden="true" />
</DrawerClose> </DrawerClose>
</div> </div>
<div className="flex-1 overflow-auto"> <div className="flex-1 overflow-auto">{children}</div>
<Outlet />
</div>
</DrawerContent> </DrawerContent>
</Drawer> </Drawer>
); );
+3 -1
View File
@@ -1,10 +1,12 @@
import { focusRing } from "../lib/focus-ring";
export function ExternalUriLink({ uri }: { uri: string }) { export function ExternalUriLink({ uri }: { uri: string }) {
return ( return (
<a <a
href={uri} href={uri}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="block truncate text-xs text-muted-foreground hover:text-foreground" className={`block truncate rounded-sm text-xs text-muted-foreground hover:text-foreground ${focusRing}`}
> >
{uri} {uri}
</a> </a>
@@ -0,0 +1,51 @@
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { FilteredRecordList } from "./filtered-record-list";
import { labelText } from "../lib/labels";
type Rec = { id: string; labels: { lang: string; label: string }[] };
const recs: Rec[] = [
{ id: "a", labels: [{ lang: "en", label: "Alpha" }] },
{ id: "b", labels: [{ lang: "en", label: "Beta" }] },
];
const row = (r: Rec) => <li>{labelText(r.labels, "en")}</li>;
test("filtering narrows the rendered rows", async () => {
renderApp(
<FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("Alpha")).toBeInTheDocument();
expect(screen.getByText("Beta")).toBeInTheDocument();
await userEvent.type(screen.getByLabelText(/filter/i), "alph");
expect(screen.getByText("Alpha")).toBeInTheDocument();
expect(screen.queryByText("Beta")).toBeNull();
});
test("empty records show the empty text", () => {
renderApp(
<FilteredRecordList records={[]} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("EmptyMsg")).toBeInTheDocument();
});
test("non-empty records with a non-matching filter show no-matches", async () => {
renderApp(
<FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
await userEvent.type(screen.getByLabelText(/filter/i), "zzz");
expect(screen.getByText(/no matches/i)).toBeInTheDocument();
});
test("an error shows the load-error text", () => {
renderApp(
<FilteredRecordList records={undefined} lang="en" isLoading={false} isError={true}
loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
);
expect(screen.getByText("LoadErr")).toBeInTheDocument();
});
@@ -0,0 +1,68 @@
import { Fragment, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { byLabel } from "../lib/sort";
import { labelText } from "../lib/labels";
import { Input } from "@/components/ui/input";
import { ListSkeleton } from "@/components/ui/skeletons";
type LabelView = components["schemas"]["LabelView"];
/** Filterable, alphabetically-sorted list of labelled records with the standard
* loading / error / empty / no-matches states. The filter input stays visible
* during load (matching the prior page behaviour). */
export function FilteredRecordList<T extends { id: string; labels: LabelView[] }>({
records,
lang,
isLoading,
isError,
loadErrorText,
emptyText,
renderRow,
}: {
records: T[] | undefined;
lang: string;
isLoading: boolean;
isError: boolean;
loadErrorText: string;
emptyText: string;
renderRow: (record: T) => ReactNode;
}) {
const { t } = useTranslation();
const [filter, setFilter] = useState("");
const q = filter.trim().toLowerCase();
const rows = [...(records ?? [])]
.filter((r) => !q || labelText(r.labels, lang).toLowerCase().includes(q))
.sort(byLabel(lang));
return (
<>
<div className="mb-3">
<Input
aria-label={t("common.filter")}
placeholder={t("common.filter")}
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
</div>
{isLoading ? (
<ListSkeleton className="mb-4" rows={5} />
) : (
<ul className="mb-4">
{isError && <li className="text-sm text-destructive">{loadErrorText}</li>}
{!isError && records?.length === 0 && (
<li className="text-sm text-muted-foreground">{emptyText}</li>
)}
{!isError && records && records.length > 0 && rows.length === 0 && (
<li className="text-sm text-muted-foreground">{t("common.noMatches")}</li>
)}
{rows.map((r) => (
<Fragment key={r.id}>{renderRow(r)}</Fragment>
))}
</ul>
)}
</>
);
}
@@ -0,0 +1,28 @@
import { expect, test, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { LabelledRecordCreateForm } from "./labelled-record-create-form";
test("submitting with empty labels shows the required error and does not call onCreate", async () => {
const onCreate = vi.fn();
renderApp(
<LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
);
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(screen.getByRole("alert")).toBeInTheDocument();
expect(onCreate).not.toHaveBeenCalled();
});
test("a valid submit calls onCreate and the reset clears the inputs", async () => {
const onCreate = vi.fn((_labels: unknown, _uri: unknown, reset: () => void) => reset());
renderApp(
<LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
);
const labelInput = screen.getByLabelText(/^label$/i) as HTMLInputElement;
await userEvent.type(labelInput, "Bronze");
await userEvent.click(screen.getByRole("button", { name: /create/i }));
expect(onCreate).toHaveBeenCalled();
expect((screen.getByLabelText(/^label$/i) as HTMLInputElement).value).toBe("");
});
@@ -0,0 +1,76 @@
import { useId, useState, type FormEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { MutationError } from "./mutation-error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
type LabelInput = components["schemas"]["LabelInput"];
/** Create form for a labelled record (term/authority): single-language label +
* optional external URI, with required-label validation and a status-aware error.
* `onCreate` performs the mutation and is handed a `reset` to clear the inputs on success. */
export function LabelledRecordCreateForm({
heading,
submitLabel,
pending,
error,
onCreate,
}: {
heading: ReactNode;
submitLabel: string;
pending: boolean;
error: unknown;
onCreate: (labels: LabelInput[], uri: string | null, reset: () => void) => void;
}) {
const { t } = useTranslation();
const uriId = useId();
const [labels, setLabels] = useState<LabelInput[]>([]);
const [uri, setUri] = useState("");
const [requiredError, setRequiredError] = useState(false);
const onSubmit = (event: FormEvent) => {
event.preventDefault();
if (!labels.some((l) => l.label)) {
setRequiredError(true);
return;
}
setRequiredError(false);
onCreate(labels, uri.trim() || null, () => {
setLabels([]);
setUri("");
});
};
return (
<form onSubmit={onSubmit} className="space-y-2 border-t pt-3">
<div className="text-sm font-medium">{heading}</div>
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={uriId}>{t("labels.externalUri")}</Label>
<Input
id={uriId}
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/>
</div>
{requiredError && (
<p role="alert" className="text-xs text-destructive">
{t("form.required")}
</p>
)}
<MutationError error={error} />
<Button type="submit" size="sm" disabled={pending}>
{submitLabel}
</Button>
</form>
);
}
@@ -0,0 +1,74 @@
import { expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderApp } from "../test/render";
import { LabelledRecordRow, type RecordLike } from "./labelled-record-row";
import { HttpError } from "../api/queries";
const record: RecordLike = { id: "r1", external_uri: null, labels: [{ lang: "en", label: "Bronze" }] };
test("edit → save calls onSave and closes via done()", async () => {
const onSave = vi.fn((_labels: unknown, _uri: unknown, done: () => void) => done());
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={null}
onEditOpen={() => {}}
onSave={onSave}
onDelete={async () => {}}
/>
</ul>,
);
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(onSave).toHaveBeenCalled();
expect(screen.queryByRole("button", { name: /save/i })).toBeNull();
});
test("a save error renders inline and the row stays editable", async () => {
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={new HttpError(403)}
onEditOpen={() => {}}
onSave={() => {}}
onDelete={async () => {}}
/>
</ul>,
);
await userEvent.click(screen.getByRole("button", { name: /edit/i }));
expect(screen.getByRole("alert")).toHaveTextContent(/permission/i);
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
});
test("confirming delete invokes onDelete", async () => {
const onDelete = vi.fn(async () => {});
renderApp(
<ul>
<LabelledRecordRow
record={record}
lang="en"
deleteConfirmKey="actions.confirmDeleteTerm"
savePending={false}
saveError={null}
onEditOpen={() => {}}
onSave={() => {}}
onDelete={onDelete}
/>
</ul>,
);
await userEvent.click(screen.getByRole("button", { name: /delete/i }));
const dialog = within(document.body);
const confirmButtons = await dialog.findAllByRole("button", { name: /delete/i });
await userEvent.click(confirmButtons[confirmButtons.length - 1]);
expect(onDelete).toHaveBeenCalled();
});
+102
View File
@@ -0,0 +1,102 @@
import { useId, useState } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { MutationError } from "./mutation-error";
import { ExternalUriLink } from "./external-uri-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";
type LabelView = components["schemas"]["LabelView"];
type LabelInput = components["schemas"]["LabelInput"];
export type RecordLike = { id: string; labels: LabelView[]; external_uri: string | null };
/** One labelled record (term/authority): a display row with edit + delete, or an
* inline editor. All variance (mutation hooks, arg shapes, delete-confirm key) is
* supplied by the caller via callbacks/state — see term-row.tsx / authority-row.tsx. */
export function LabelledRecordRow({
record,
lang,
deleteConfirmKey,
savePending,
saveError,
onEditOpen,
onSave,
onDelete,
}: {
record: RecordLike;
lang: string;
deleteConfirmKey: string;
savePending: boolean;
saveError: unknown;
onEditOpen: () => void;
onSave: (labels: LabelInput[], uri: string | null, done: () => void) => void;
onDelete: () => Promise<void>;
}) {
const { t } = useTranslation();
const uriId = useId();
const [editing, setEditing] = useState(false);
const [labels, setLabels] = useState<LabelInput[]>(record.labels as LabelInput[]);
const [uri, setUri] = useState(record.external_uri ?? "");
if (editing) {
return (
<li className="space-y-2 border-b py-2">
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={uriId}>{t("labels.externalUri")}</Label>
<Input
id={uriId}
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/>
</div>
<div className="flex gap-2">
<Button
type="button"
size="sm"
disabled={savePending}
onClick={() => onSave(labels, uri.trim() || null, () => setEditing(false))}
>
{t("actions.save")}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
{t("form.cancel")}
</Button>
</div>
<MutationError error={saveError} />
</li>
);
}
return (
<li className="flex items-center gap-2 border-b py-1 text-sm">
<div className="flex-1">
<div>{labelText(record.labels, lang)}</div>
{record.external_uri && <ExternalUriLink uri={record.external_uri} />}
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
onEditOpen();
setLabels(record.labels as LabelInput[]);
setUri(record.external_uri ?? "");
setEditing(true);
}}
>
{t("actions.edit")}
</Button>
<DeleteConfirmDialog description={t(deleteConfirmKey)} onConfirm={onDelete} />
</li>
);
}
+1 -1
View File
@@ -50,7 +50,7 @@ function AlertDialogContent({
data-slot="alert-dialog-content" data-slot="alert-dialog-content"
data-size={size} data-size={size}
className={cn( className={cn(
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 overscroll-y-contain rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className className
)} )}
{...props} {...props}
-103
View File
@@ -1,103 +0,0 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
@@ -0,0 +1,63 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { expect } from 'storybook/test'
import {
ComboboxRoot,
ComboboxInputGroup,
ComboboxInput,
ComboboxClear,
ComboboxTrigger,
ComboboxPopup,
ComboboxList,
ComboboxItem,
ComboboxItemIndicator,
ComboboxEmpty,
} from './combobox'
const fruits = ['Apple', 'Apricot', 'Banana', 'Cherry']
function ComboboxDemo() {
const [value, setValue] = useState<string | null>(null)
return (
<ComboboxRoot<string | null>
items={fruits}
value={value}
onValueChange={setValue}
itemToStringLabel={(item) => item ?? ''}
isItemEqualToValue={(a, b) => a === b}
>
<ComboboxInputGroup>
<ComboboxInput placeholder='Pick a fruit' />
<ComboboxClear aria-label='Clear' />
<ComboboxTrigger aria-label='Open' />
</ComboboxInputGroup>
<ComboboxPopup>
<ComboboxEmpty>No matches</ComboboxEmpty>
<ComboboxList>
{(item: string) => (
<ComboboxItem key={item} value={item}>
<ComboboxItemIndicator className='text-primary'></ComboboxItemIndicator>
{item}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxPopup>
</ComboboxRoot>
)
}
const meta = {
component: ComboboxDemo,
tags: ['ai-generated'],
} satisfies Meta<typeof ComboboxDemo>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
play: async ({ canvas }) => {
await expect(canvas.getByPlaceholderText('Pick a fruit')).toBeInTheDocument()
},
}
+12 -6
View File
@@ -20,7 +20,10 @@ function ComboboxInput({ className, ...props }: ComboboxPrimitive.Input.Props) {
return ( return (
<ComboboxPrimitive.Input <ComboboxPrimitive.Input
data-slot="combobox-input" data-slot="combobox-input"
className={cn("w-full rounded border px-2 py-1 pr-12 text-sm", className)} className={cn(
"w-full rounded border px-2 py-1 pr-12 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
className,
)}
{...props} {...props}
/> />
); );
@@ -31,7 +34,7 @@ function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
<ComboboxPrimitive.Clear <ComboboxPrimitive.Clear
data-slot="combobox-clear" data-slot="combobox-clear"
className={cn( className={cn(
"absolute right-6 text-neutral-400 hover:text-neutral-700", "absolute right-6 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50",
className, className,
)} )}
{...props} {...props}
@@ -43,7 +46,10 @@ function ComboboxTrigger({ className, ...props }: ComboboxPrimitive.Trigger.Prop
return ( return (
<ComboboxPrimitive.Trigger <ComboboxPrimitive.Trigger
data-slot="combobox-trigger" data-slot="combobox-trigger"
className={cn("absolute right-1 text-neutral-500", className)} className={cn(
"absolute right-1 rounded-sm text-muted-foreground outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
className,
)}
{...props} {...props}
/> />
); );
@@ -56,7 +62,7 @@ function ComboboxPopup({ className, ...props }: ComboboxPrimitive.Popup.Props) {
<ComboboxPrimitive.Popup <ComboboxPrimitive.Popup
data-slot="combobox-popup" data-slot="combobox-popup"
className={cn( className={cn(
"max-h-64 min-w-48 overflow-auto rounded border bg-white p-1 text-sm shadow-md", "max-h-64 min-w-48 overflow-auto overscroll-y-contain rounded border bg-popover p-1 text-sm text-popover-foreground shadow-md",
className, className,
)} )}
{...props} {...props}
@@ -81,7 +87,7 @@ function ComboboxItem({ className, ...props }: ComboboxPrimitive.Item.Props) {
<ComboboxPrimitive.Item <ComboboxPrimitive.Item
data-slot="combobox-item" data-slot="combobox-item"
className={cn( className={cn(
"flex cursor-default items-center gap-2 rounded px-2 py-1 data-[highlighted]:bg-indigo-50", "flex cursor-default items-center gap-2 rounded px-2 py-1 data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",
className, className,
)} )}
{...props} {...props}
@@ -103,7 +109,7 @@ function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
return ( return (
<ComboboxPrimitive.Empty <ComboboxPrimitive.Empty
data-slot="combobox-empty" data-slot="combobox-empty"
className={cn("px-2 py-1 text-neutral-500", className)} className={cn("px-2 py-1 text-muted-foreground", className)}
{...props} {...props}
/> />
); );
+1 -1
View File
@@ -35,7 +35,7 @@ function DrawerContent({ className, children, ...props }: DrawerPrimitive.Popup.
<DrawerPrimitive.Popup <DrawerPrimitive.Popup
data-slot="drawer-content" data-slot="drawer-content"
className={cn( className={cn(
"fixed inset-y-0 right-0 flex w-full max-w-md flex-col overflow-y-auto bg-background shadow-xl outline-none duration-200 data-open:animate-in data-open:slide-in-from-right data-closed:animate-out data-closed:slide-out-to-right", "fixed inset-y-0 right-0 flex w-full max-w-md flex-col overflow-y-auto overscroll-y-contain bg-background shadow-xl outline-none duration-200 data-open:animate-in data-open:slide-in-from-right data-closed:animate-out data-closed:slide-out-to-right",
className, className,
)} )}
{...props} {...props}
+1 -1
View File
@@ -6,7 +6,7 @@ export function PageTitle({ className, ...props }: ComponentProps<"h1">) {
return ( return (
<h1 <h1
data-slot="page-title" data-slot="page-title"
className={cn("text-2xl font-semibold tracking-tight", className)} className={cn("text-2xl font-semibold tracking-tight text-balance", className)}
{...props} {...props}
/> />
) )
+1 -1
View File
@@ -99,7 +99,7 @@ function SelectContent({
<SelectPrimitive.Popup <SelectPrimitive.Popup
data-slot="select-content" data-slot="select-content"
className={cn( className={cn(
"max-h-[min(24rem,var(--available-height))] min-w-[var(--anchor-width)] overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md outline-none", "max-h-[min(24rem,var(--available-height))] min-w-[var(--anchor-width)] overflow-y-auto overscroll-y-contain rounded-md border bg-popover p-1 text-popover-foreground shadow-md outline-none",
"data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0", "data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className className
)} )}
+7 -6
View File
@@ -1,6 +1,7 @@
import type * as React from "react"; import type * as React from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Toast as ToastPrimitive } from "@base-ui/react/toast"; import { Toast as ToastPrimitive } from "@base-ui/react/toast";
import { X } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { toastManager } from "@/toast/toast-manager"; import { toastManager } from "@/toast/toast-manager";
@@ -14,9 +15,9 @@ function ToastList() {
toast={toast} toast={toast}
data-slot="toast" data-slot="toast"
className={cn( className={cn(
"flex items-start gap-2 rounded-md border bg-white p-3 text-sm shadow-md", "flex items-start gap-2 rounded-md border bg-popover p-3 text-sm text-popover-foreground shadow-md",
toast.type === "error" && "border-red-300", toast.type === "error" && "border-destructive",
toast.type === "success" && "border-green-300", toast.type === "success" && "border-success",
)} )}
> >
<div className="flex-1"> <div className="flex-1">
@@ -28,15 +29,15 @@ function ToastList() {
)} )}
<ToastPrimitive.Description <ToastPrimitive.Description
data-slot="toast-description" data-slot="toast-description"
className="text-neutral-700" className="text-muted-foreground"
/> />
</div> </div>
<ToastPrimitive.Close <ToastPrimitive.Close
data-slot="toast-close" data-slot="toast-close"
aria-label={t("common.close")} aria-label={t("common.close")}
className="text-neutral-400 hover:text-neutral-700" className="text-muted-foreground hover:text-foreground"
> >
× <X className="size-4" aria-hidden="true" />
</ToastPrimitive.Close> </ToastPrimitive.Close>
</ToastPrimitive.Root> </ToastPrimitive.Root>
)); ));
+1 -1
View File
@@ -22,7 +22,7 @@ function TooltipPopup({ className, ...props }: TooltipPrimitive.Popup.Props) {
<TooltipPrimitive.Popup <TooltipPrimitive.Popup
data-slot="tooltip-popup" data-slot="tooltip-popup"
className={cn( className={cn(
"rounded border bg-white px-2 py-1 text-sm shadow-md", "rounded border bg-popover px-2 py-1 text-sm text-popover-foreground shadow-md",
className, className,
)} )}
{...props} {...props}
+2 -1
View File
@@ -2,12 +2,13 @@ import { useEffect, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { api } from "../api/client"; import { api } from "../api/client";
import { keys } from "../api/query-keys";
import i18n, { LOCALE_KEY } from "../i18n"; import i18n, { LOCALE_KEY } from "../i18n";
import { ConfigContext, DEFAULTS, type ConfigView } from "./config-context"; import { ConfigContext, DEFAULTS, type ConfigView } from "./config-context";
export function ConfigProvider({ children }: { children: ReactNode }) { export function ConfigProvider({ children }: { children: ReactNode }) {
const { data } = useQuery({ const { data } = useQuery({
queryKey: ["config"], queryKey: keys.config(),
queryFn: async (): Promise<ConfigView> => { queryFn: async (): Promise<ConfigView> => {
const { data, error } = await api.GET("/api/config"); const { data, error } = await api.GET("/api/config");
+2
View File
@@ -110,6 +110,8 @@ export function FieldForm({
)} )}
</div> </div>
{isEdit && <p className="text-xs text-muted-foreground">{t("fields.lockedNote")}</p>}
<div className="space-y-1"> <div className="space-y-1">
<Label htmlFor="field-key">{t("fields.key")}</Label> <Label htmlFor="field-key">{t("fields.key")}</Label>
<Input <Input
+18 -11
View File
@@ -3,6 +3,8 @@ import { useTranslation } from "react-i18next";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { useFieldDefinitions, useDeleteFieldDefinition } from "../api/queries"; import { useFieldDefinitions, useDeleteFieldDefinition } from "../api/queries";
import { useLang } from "../lib/use-lang";
import { rowStateClass } from "../lib/class-recipes";
import { labelText } from "../lib/labels"; import { labelText } from "../lib/labels";
import { byLabel, compareStrings } from "../lib/sort"; import { byLabel, compareStrings } from "../lib/sort";
import { focusRing } from "../lib/focus-ring"; import { focusRing } from "../lib/focus-ring";
@@ -21,10 +23,10 @@ export function FieldList({
selectedKey: string | null; selectedKey: string | null;
onSelect: (def: FieldDefinitionView) => void; onSelect: (def: FieldDefinitionView) => void;
}) { }) {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const { data, isLoading, isError } = useFieldDefinitions(); const { data, isLoading, isError } = useFieldDefinitions();
const deleteField = useDeleteFieldDefinition(); const deleteField = useDeleteFieldDefinition();
const lang = i18n.language.startsWith("sv") ? "sv" : "en"; const lang = useLang();
const [filter, setFilter] = useState(""); const [filter, setFilter] = useState("");
if (isLoading) return <ListSkeleton rows={6} />; if (isLoading) return <ListSkeleton rows={6} />;
@@ -82,24 +84,29 @@ export function FieldList({
{[...defs].sort(byLabel(lang)).map((def) => ( {[...defs].sort(byLabel(lang)).map((def) => (
<li <li
key={def.key} key={def.key}
className={`flex items-center gap-2 border-b px-3 py-2 text-sm ${ className={`flex items-center gap-2 border-b px-3 py-2 text-sm ${rowStateClass(
def.key === selectedKey ? "bg-primary/10" : "" def.key === selectedKey,
}`} )}`}
> >
<button <button
type="button" type="button"
className={cn("flex flex-1 items-center gap-2 rounded-sm text-left", focusRing)} className={cn(
"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left",
focusRing,
)}
aria-pressed={def.key === selectedKey} aria-pressed={def.key === selectedKey}
onClick={() => onSelect(def)} onClick={() => onSelect(def)}
> >
<span className="font-medium">{labelText(def.labels, lang)}</span> <span className="min-w-0 truncate font-medium">
<span className="text-xs text-muted-foreground">{def.key}</span> {labelText(def.labels, lang)}
<span className="rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
{t(`fields.types.${def.data_type}`)}
</span> </span>
<span className="text-xs text-muted-foreground">{def.key}</span>
<Badge variant="secondary" className="shrink-0">
{t(`fields.types.${def.data_type}`)}
</Badge>
{def.required && ( {def.required && (
<span <span
className="text-xs text-destructive" className="shrink-0 text-xs text-destructive"
title={t("fields.required")} title={t("fields.required")}
aria-label={t("fields.required")} aria-label={t("fields.required")}
> >
+17
View File
@@ -0,0 +1,17 @@
import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import { renderApp } from "../test/render";
import { FieldsPage } from "./fields-page";
test("renders the field list and form in a responsive grid", async () => {
const { container } = renderApp(<FieldsPage />);
// both panes are present (master list + detail form)
expect(await screen.findByText(/fields/i)).toBeInTheDocument();
// responsive: single-column by default, two-column at lg
const grid = container.querySelector("div.grid");
expect(grid?.className).toContain("grid-cols-1");
expect(grid?.className).toContain("lg:grid-cols-[20rem_1fr]");
});
+17 -9
View File
@@ -1,18 +1,23 @@
import { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import type { components } from "../api/schema"; import { useFieldDefinitions } from "../api/queries";
import { FieldList } from "./field-list"; import { FieldList } from "./field-list";
import { FieldForm } from "./field-form"; import { FieldForm } from "./field-form";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title"; import { PageTitle } from "@/components/ui/page-title";
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];
export function FieldsPage() { export function FieldsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const [selected, setSelected] = useState<FieldDefinitionView | null>(null); const navigate = useNavigate();
const { key } = useParams();
const { data } = useFieldDefinitions();
// Selection lives in the URL (/fields/:key) so it survives reload and can be
// shared, matching /vocabularies/:id. An unknown or absent key falls back to
// the create form. Same cached query as FieldList, so no extra fetch.
const selected = (key && data?.find((def) => def.key === key)) || null;
useDocumentTitle(t("fields.title")); useDocumentTitle(t("fields.title"));
useBreadcrumb([{ label: t("nav.fields") }]); useBreadcrumb([{ label: t("nav.fields") }]);
@@ -20,15 +25,18 @@ export function FieldsPage() {
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageTitle className="px-4 pt-4 pb-2">{t("fields.title")}</PageTitle> <PageTitle className="px-4 pt-4 pb-2">{t("fields.title")}</PageTitle>
<div className="grid flex-1 grid-cols-[20rem_1fr] overflow-hidden"> <div className="grid flex-1 grid-cols-1 overflow-auto lg:grid-cols-[20rem_1fr] lg:overflow-hidden">
<div className="overflow-hidden border-r"> <div className="overflow-hidden border-b lg:border-r lg:border-b-0">
<FieldList selectedKey={selected?.key ?? null} onSelect={setSelected} /> <FieldList
selectedKey={selected?.key ?? null}
onSelect={(def) => navigate(`/fields/${encodeURIComponent(def.key)}`)}
/>
</div> </div>
<div className="overflow-hidden"> <div className="overflow-hidden">
<FieldForm <FieldForm
key={selected?.key ?? "create"} key={selected?.key ?? "create"}
editing={selected} editing={selected}
onDone={() => setSelected(null)} onDone={() => navigate("/fields")}
/> />
</div> </div>
</div> </div>
+35 -1
View File
@@ -11,7 +11,7 @@ import { FieldsPage } from "./fields-page";
function tree() { function tree() {
return ( return (
<Routes> <Routes>
<Route path="/fields" element={<FieldsPage />} /> <Route path="/fields/:key?" element={<FieldsPage />} />
</Routes> </Routes>
); );
} }
@@ -87,6 +87,40 @@ test("filter narrows the visible fields", async () => {
expect(await screen.findByText(/no matches/i)).toBeInTheDocument(); expect(await screen.findByText(/no matches/i)).toBeInTheDocument();
}); });
test("deep link /fields/:key opens the edit form for that field", async () => {
renderApp(tree(), { route: "/fields/inscription" });
// edit mode: the key input is locked and prefilled from the URL. The form
// remounts when the defs query resolves, so re-query inside waitFor.
await waitFor(() => expect(screen.getByLabelText(/^key$/i)).toHaveValue("inscription"));
expect(screen.getByLabelText(/^key$/i)).toBeDisabled();
expect(screen.getByRole("button", { name: /cancel/i })).toBeInTheDocument();
});
test("selecting a field switches to its edit form; cancel returns to create", async () => {
renderApp(tree(), { route: "/fields" });
await userEvent.click(await screen.findByRole("button", { name: /inscription/i }));
await waitFor(() => expect(screen.getByLabelText(/^key$/i)).toHaveValue("inscription"));
expect(screen.getByLabelText(/^key$/i)).toBeDisabled();
await userEvent.click(screen.getByRole("button", { name: /cancel/i }));
await waitFor(() => expect(screen.getByLabelText(/^key$/i)).toHaveValue(""));
expect(screen.getByLabelText(/^key$/i)).toBeEnabled();
});
test("an unknown key falls back to the create form", async () => {
renderApp(tree(), { route: "/fields/zzz-does-not-exist" });
await screen.findByText("Inscription");
const key = screen.getByLabelText(/^key$/i);
expect(key).toHaveValue("");
expect(key).toBeEnabled();
});
test("creates a text field — posts the body and clears the key input", async () => { test("creates a text field — posts the body and clears the key input", async () => {
let body: { key: string; data_type: string } | undefined; let body: { key: string; data_type: string } | undefined;
+4 -3
View File
@@ -1,12 +1,12 @@
{ {
"common": { "yes": "Yes", "no": "No", "close": "Close", "loading": "Loading", "filter": "Filter…", "noMatches": "No matches", "language": "Language", "skipToContent": "Skip to content", "clear": "Clear", "open": "Open" }, "common": { "yes": "Yes", "no": "No", "close": "Close", "loading": "Loading", "filter": "Filter…", "noMatches": "No matches", "language": "Language", "skipToContent": "Skip to content", "clear": "Clear", "open": "Open" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar", "breadcrumb": "Breadcrumb" }, "nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar", "breadcrumb": "Breadcrumb" },
"auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server", "sessionExpired": "Your session expired — please sign in again.", "signingOut": "Signing out…" }, "auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signingIn": "Signing in…", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server", "sessionExpired": "Your session expired — please sign in again.", "signingOut": "Signing out…" },
"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)", "detailTitle": "Object detail", "tableLabel": "Objects" }, "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)", "detailTitle": "Object detail", "tableLabel": "Objects" },
"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" }, "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", "createdButFieldRejected": "Object created, but a field was rejected — fix it below.", "flexibleHeading": "Catalogue fields", "saving": "Saving…", "createAnother": "Save & create another", "minCount": "Must be at least 1", "fieldError": { "type_mismatch": "Wrong type for this field", "unresolved": "Referenced value not found", "unknown": "Unknown field" }, "unsaved": { "title": "Discard unsaved changes?", "body": "You have unsaved changes that will be lost.", "stay": "Keep editing", "leave": "Discard" } }, "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", "createdButFieldRejected": "Object created, but a field was rejected — fix it below.", "flexibleHeading": "Catalogue fields", "saving": "Saving…", "createAnother": "Save & create another", "minCount": "Must be at least 1", "fieldError": { "type_mismatch": "Wrong type for this field", "unresolved": "Referenced value not found", "unknown": "Unknown field" }, "unsaved": { "title": "Discard unsaved changes?", "body": "You have unsaved changes that will be lost.", "stay": "Keep editing", "leave": "Discard" } },
"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": { "deleting": "Deleting…", "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." },
"labels": { "label": "Label", "externalUri": "External URI (optional)", "otherLanguages": "This entry also has labels in other languages, which are kept.", "uriPlaceholder": "https://…" }, "labels": { "label": "Label", "externalUri": "External URI (optional)", "otherLanguages": "This entry also has labels in other languages, which are kept.", "uriPlaceholder": "https://…" },
"theme": { "light": "Light", "dark": "Dark", "system": "System" }, "theme": { "light": "Light", "dark": "Dark", "system": "System" },
"vocab": { "vocab": {
@@ -41,6 +41,7 @@
"authorityKind": "Authority kind", "authorityKind": "Authority kind",
"anyKind": "Any", "anyKind": "Any",
"group": "Group", "group": "Group",
"lockedNote": "Key and type can't be changed after creation.",
"required": "Required", "required": "Required",
"create": "Create field", "create": "Create field",
"empty": "No field definitions yet", "empty": "No field definitions yet",
+4 -3
View File
@@ -1,12 +1,12 @@
{ {
"common": { "yes": "Ja", "no": "Nej", "close": "Stäng", "loading": "Laddar", "filter": "Filtrera…", "noMatches": "Inga träffar", "language": "Språk", "skipToContent": "Hoppa till innehåll", "clear": "Rensa", "open": "Öppna" }, "common": { "yes": "Ja", "no": "Nej", "close": "Stäng", "loading": "Laddar", "filter": "Filtrera…", "noMatches": "Inga träffar", "language": "Språk", "skipToContent": "Hoppa till innehåll", "clear": "Rensa", "open": "Öppna" },
"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", "breadcrumb": "Brödsmulor" }, "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", "breadcrumb": "Brödsmulor" },
"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", "sessionExpired": "Din session har gått ut — logga in igen.", "signingOut": "Loggar ut…" }, "auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signingIn": "Loggar in…", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern", "sessionExpired": "Din session har gått ut — logga in igen.", "signingOut": "Loggar ut…" },
"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)", "detailTitle": "Objektdetalj", "tableLabel": "Objekt" }, "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)", "detailTitle": "Objektdetalj", "tableLabel": "Objekt" },
"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" }, "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", "createdButFieldRejected": "Föremålet skapades, men ett fält avvisades — åtgärda nedan.", "flexibleHeading": "Katalogfält", "saving": "Sparar…", "createAnother": "Spara & skapa ny", "minCount": "Måste vara minst 1", "fieldError": { "type_mismatch": "Fel typ för detta fält", "unresolved": "Refererat värde hittades inte", "unknown": "Okänt fält" }, "unsaved": { "title": "Kasta osparade ändringar?", "body": "Du har osparade ändringar som går förlorade.", "stay": "Fortsätt redigera", "leave": "Kasta" } }, "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", "createdButFieldRejected": "Föremålet skapades, men ett fält avvisades — åtgärda nedan.", "flexibleHeading": "Katalogfält", "saving": "Sparar…", "createAnother": "Spara & skapa ny", "minCount": "Måste vara minst 1", "fieldError": { "type_mismatch": "Fel typ för detta fält", "unresolved": "Refererat värde hittades inte", "unknown": "Okänt fält" }, "unsaved": { "title": "Kasta osparade ändringar?", "body": "Du har osparade ändringar som går förlorade.", "stay": "Fortsätt redigera", "leave": "Kasta" } },
"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": { "deleting": "Tar bort…", "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." },
"labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)", "otherLanguages": "Denna post har även etiketter på andra språk, som behålls.", "uriPlaceholder": "https://…" }, "labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)", "otherLanguages": "Denna post har även etiketter på andra språk, som behålls.", "uriPlaceholder": "https://…" },
"theme": { "light": "Ljust", "dark": "Mörkt", "system": "System" }, "theme": { "light": "Ljust", "dark": "Mörkt", "system": "System" },
"vocab": { "vocab": {
@@ -41,6 +41,7 @@
"authorityKind": "Auktoritetstyp", "authorityKind": "Auktoritetstyp",
"anyKind": "Alla", "anyKind": "Alla",
"group": "Grupp", "group": "Grupp",
"lockedNote": "Nyckel och typ kan inte ändras efter att fältet skapats.",
"required": "Obligatoriskt", "required": "Obligatoriskt",
"create": "Skapa fält", "create": "Skapa fält",
"empty": "Inga fältdefinitioner ännu", "empty": "Inga fältdefinitioner ännu",
+15
View File
@@ -35,6 +35,7 @@
} }
:root { :root {
color-scheme: light;
--background: oklch(1 0 0); --background: oklch(1 0 0);
--foreground: oklch(0.145 0 0); --foreground: oklch(0.145 0 0);
--card: oklch(1 0 0); --card: oklch(1 0 0);
@@ -63,6 +64,7 @@
} }
.dark { .dark {
color-scheme: dark;
--background: oklch(0.145 0 0); --background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0); --foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0); --card: oklch(0.205 0 0);
@@ -97,6 +99,19 @@
body { body {
@apply bg-background text-foreground font-sans; @apply bg-background text-foreground font-sans;
} }
/* Collapse all animation/transition to a single frame for users who ask the
OS for reduced motion. Covers the kit's data-open/closed animations, the
skeleton pulse, and the sidebar width transition in one place. */
@media (prefers-reduced-motion: reduce) {
*,
::before,
::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
} }
@layer components { @layer components {
+22
View File
@@ -0,0 +1,22 @@
import { expect, test } from "vitest";
import { rowStateClass, segmentClass } from "./class-recipes";
test("segmentClass active uses the primary tokens + focus ring", () => {
const cls = segmentClass(true, "px-2 py-1");
expect(cls).toContain("bg-primary");
expect(cls).toContain("text-primary-foreground");
expect(cls).toContain("focus-visible:ring-ring/50");
expect(cls).toContain("px-2");
});
test("segmentClass inactive uses border, not the primary fill", () => {
const cls = segmentClass(false);
expect(cls).toContain("border");
expect(cls).not.toContain("bg-primary");
});
test("rowStateClass toggles selected vs idle-hover", () => {
expect(rowStateClass(true)).toBe("bg-primary/10");
expect(rowStateClass(false)).toBe("hover:bg-muted");
});
+14
View File
@@ -0,0 +1,14 @@
import { cn } from "@/lib/utils";
import { focusRing } from "./focus-ring";
/** Segmented-control / filter-pill item. Unifies the active/inactive token recipe +
* focus ring; callers pass their contextual padding/size via `className`. */
export function segmentClass(active: boolean, className?: string): string {
return cn("rounded-md", focusRing, active ? "bg-primary text-primary-foreground" : "border", className);
}
/** Selected vs idle row background for master-detail / list rows. */
export function rowStateClass(active: boolean): string {
return active ? "bg-primary/10" : "hover:bg-muted";
}
+19
View File
@@ -0,0 +1,19 @@
import { expect, test } from "vitest";
import { formatDate } from "./format-date";
test("formats a date-only string in the locale without a timezone day-shift", () => {
expect(formatDate("1962-04-03", "en")).toBe("Apr 3, 1962");
});
test("returns the em-dash placeholder for null", () => {
expect(formatDate(null, "en")).toBe("—");
});
test("returns an unparseable string unchanged", () => {
expect(formatDate("not-a-date", "en")).toBe("not-a-date");
});
test("stringifies a non-string, non-null value", () => {
expect(formatDate(42, "en")).toBe("42");
});
+27
View File
@@ -0,0 +1,27 @@
import { expect, test } from "vitest";
import { formatTimestamp } from "./format-timestamp";
test("formats a UTC timestamp with date and time in the given locale", () => {
const out = formatTimestamp("2026-06-08T12:30:00Z", "UTC", "en");
expect(out).toContain("2026");
expect(out).toContain("12:30");
});
test("applies the timezone — a near-midnight UTC instant shifts the calendar day", () => {
// 02:00 UTC on Jun 8 is 22:00 on Jun 7 in New York (EDT, UTC-4)
const ny = formatTimestamp("2026-06-08T02:00:00Z", "America/New_York", "en");
const utc = formatTimestamp("2026-06-08T02:00:00Z", "UTC", "en");
expect(ny).toContain("Jun 7");
expect(utc).toContain("Jun 8");
});
test("an invalid IANA zone does not throw and falls back to UTC", () => {
const out = formatTimestamp("2026-06-08T12:30:00Z", "Not/AZone", "en");
expect(out).toContain("2026");
});
test("null renders the em-dash placeholder; an unparseable string is returned unchanged", () => {
expect(formatTimestamp(null, "UTC", "en")).toBe("—");
expect(formatTimestamp("not-a-date", "UTC", "en")).toBe("not-a-date");
});
+18
View File
@@ -0,0 +1,18 @@
/** Formats a UTC ISO timestamp for display in the instance timezone + active locale.
* Storage/transmission stay UTC — this is display-only. Falls back to UTC formatting on an
* invalid IANA zone (a misconfigured instance) rather than throwing. */
export function formatTimestamp(value: unknown, timeZone: string, locale: string): string {
if (typeof value !== "string") return value == null ? "—" : String(value);
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const opts = { dateStyle: "medium", timeStyle: "short" } as const;
try {
return new Intl.DateTimeFormat(locale, { ...opts, timeZone }).format(date);
} catch {
// Invalid IANA timeZone (misconfigured instance) — fall back to UTC rather than crash.
return new Intl.DateTimeFormat(locale, { ...opts, timeZone: "UTC" }).format(date);
}
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, test } from "vitest";
import { labelText } from "./labels";
const labels = [
{ lang: "en", label: "Bowl" },
{ lang: "sv", label: "Skål" },
];
test("returns the exact-language label when present", () => {
expect(labelText(labels, "sv")).toBe("Skål");
});
test("falls back to the English label when the requested language is missing", () => {
expect(labelText(labels, "de")).toBe("Bowl");
});
test("falls back to the first label when neither the language nor English is present", () => {
expect(labelText([{ lang: "fr", label: "Bol" }], "de")).toBe("Bol");
});
test("returns an empty string for no labels", () => {
expect(labelText([], "en")).toBe("");
});
+7
View File
@@ -0,0 +1,7 @@
import { useTranslation } from "react-i18next";
/** The instance's active UI language, narrowed to the two supported locales. */
export function useLang(): "sv" | "en" {
const { i18n } = useTranslation();
return i18n.language.startsWith("sv") ? "sv" : "en";
}
@@ -41,6 +41,35 @@ test("confirm delete: DELETE then navigate to the list", async () => {
expect(deleted).toBe(true); expect(deleted).toBe(true);
}); });
test("confirm is disabled and labelled Deleting… while the DELETE is in flight", async () => {
let release!: () => void;
const gate = new Promise<void>((r) => {
release = r;
});
server.use(
http.delete("/api/admin/objects/:id", async () => {
await gate;
return new HttpResponse(null, { status: 204 });
}),
);
renderApp(tree(), { route: "/objects/o-1" });
await userEvent.click(await screen.findByRole("button", { name: /delete/i }));
const dialog = await screen.findByRole("alertdialog");
await userEvent.click(within(dialog).getByRole("button", { name: /delete/i }));
const pending = await within(dialog).findByRole("button", { name: /deleting/i });
expect(pending).toBeDisabled();
expect(within(dialog).getByRole("button", { name: /cancel/i })).toBeDisabled();
release();
await waitFor(() => expect(screen.getByText("objects list")).toBeInTheDocument());
});
test("cancel does not delete", async () => { test("cancel does not delete", async () => {
let deleted = false; let deleted = false;
+3 -3
View File
@@ -54,9 +54,9 @@ export function DeleteObjectDialog({ id }: { id: string }) {
</p> </p>
)} )}
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>{t("form.cancel")}</AlertDialogCancel> <AlertDialogCancel disabled={del.isPending}>{t("form.cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={onConfirm}> <AlertDialogAction disabled={del.isPending} onClick={onConfirm}>
{t("actions.delete")} {del.isPending ? t("actions.deleting") : t("actions.delete")}
</AlertDialogAction> </AlertDialogAction>
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
+2 -2
View File
@@ -54,7 +54,7 @@ test("term field filters and selects from the vocabulary combobox", async () =>
renderApp(<FormHarness defKey="material" onSubmit={(v) => submitted.push(v)} />); renderApp(<FormHarness defKey="material" onSubmit={(v) => submitted.push(v)} />);
const input = await screen.findByPlaceholderText("— select"); const input = await screen.findByPlaceholderText("Select");
await user.click(input); await user.click(input);
await user.type(input, "bro"); await user.type(input, "bro");
@@ -73,7 +73,7 @@ test("authority field filters and selects from the authority combobox", async ()
renderApp(<FormHarness defKey="maker" onSubmit={(v) => submitted.push(v)} />); renderApp(<FormHarness defKey="maker" onSubmit={(v) => submitted.push(v)} />);
const input = await screen.findByPlaceholderText("— select"); const input = await screen.findByPlaceholderText("Select");
await user.click(input); await user.click(input);
await user.type(input, "ada"); await user.type(input, "ada");
+3 -2
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { useAuthorities, useTerms } from "../api/queries"; import { useAuthorities, useTerms } from "../api/queries";
import { useConfig } from "../config/config-context"; import { useConfig } from "../config/config-context";
import { useLang } from "../lib/use-lang";
import { labelText } from "../lib/labels"; import { labelText } from "../lib/labels";
import { OptionsCombobox } from "./options-combobox"; import { OptionsCombobox } from "./options-combobox";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
@@ -27,9 +28,9 @@ export function FieldInput<TValues extends { fields: Record<string, unknown> }>(
definition: FieldDefinitionView; definition: FieldDefinitionView;
form: FieldForm<TValues>; form: FieldForm<TValues>;
}) { }) {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const { default_language } = useConfig(); const { default_language } = useConfig();
const lang = i18n.language.startsWith("sv") ? "sv" : "en"; const lang = useLang();
const label = labelText(definition.labels, lang); const label = labelText(definition.labels, lang);
const name = fieldPath<TValues>(definition.key); const name = fieldPath<TValues>(definition.key);
const placeholder = t("form.selectPlaceholder"); const placeholder = t("form.selectPlaceholder");
+3 -2
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { useObject, useFieldDefinitions } from "../api/queries"; import { useObject, useFieldDefinitions } from "../api/queries";
import { useLang } from "../lib/use-lang";
import { groupDefinitions } from "../lib/group-fields"; import { groupDefinitions } from "../lib/group-fields";
import { formatDate } from "../lib/format-date"; import { formatDate } from "../lib/format-date";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
@@ -49,14 +50,14 @@ export function ObjectDetail() {
} }
function ObjectDetailLoaded({ object }: { object: AdminObjectView }) { function ObjectDetailLoaded({ object }: { object: AdminObjectView }) {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const { data: definitions } = useFieldDefinitions(); const { data: definitions } = useFieldDefinitions();
useDocumentTitle(object.object_number); useDocumentTitle(object.object_number);
useBreadcrumb([{ label: t("nav.objects"), to: "/objects" }, { label: object.object_number }]); useBreadcrumb([{ label: t("nav.objects"), to: "/objects" }, { label: object.object_number }]);
// Prefer the active locale's label, then English, then the raw key. // Prefer the active locale's label, then English, then the raw key.
const lang = i18n.language.startsWith("sv") ? "sv" : "en"; const lang = useLang();
const labelFor = (key: string) => { const labelFor = (key: string) => {
const labels = definitions?.find((d) => d.key === key)?.labels; const labels = definitions?.find((d) => d.key === key)?.labels;
const byLang = labels?.find((l) => l.lang === lang)?.label; const byLang = labels?.find((l) => l.lang === lang)?.label;
+11 -3
View File
@@ -1,7 +1,7 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { screen, waitFor } from "@testing-library/react"; import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { delay, 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";
@@ -72,11 +72,15 @@ test("partial create: fields PUT fails -> edit page shows the 'created' banner a
test("in-flight submit: button disabled + shows Saving…, create fires exactly once on double-click", async () => { test("in-flight submit: button disabled + shows Saving…, create fires exactly once on double-click", async () => {
let postCount = 0; let postCount = 0;
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
server.use( server.use(
http.post("/api/admin/objects", async () => { http.post("/api/admin/objects", async () => {
postCount += 1; postCount += 1;
await delay(50); await gate;
return HttpResponse.json({ id: "new-id-3" }, { status: 201 }); return HttpResponse.json({ id: "new-id-3" }, { status: 201 });
}), }),
); );
@@ -91,9 +95,13 @@ test("in-flight submit: button disabled + shows Saving…, create fires exactly
await userEvent.click(button); await userEvent.click(button);
await userEvent.click(button); await userEvent.click(button);
await waitFor(() => expect(screen.getByText(/saving…/i)).toBeInTheDocument()); // The mutation is held open by `gate`, so the pending state is observed
// deterministically (no reliance on a timing window).
expect(await screen.findByText(/saving…/i)).toBeInTheDocument();
expect(screen.getByRole("button", { name: /saving…/i })).toBeDisabled(); expect(screen.getByRole("button", { name: /saving…/i })).toBeDisabled();
release();
await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument()); await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument());
expect(postCount).toBe(1); expect(postCount).toBe(1);
}); });
+10 -14
View File
@@ -1,18 +1,15 @@
import { lazy, Suspense } from "react";
import { Outlet, useMatch, useNavigate, useSearchParams } from "react-router-dom"; import { Outlet, useMatch, useNavigate, useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { ObjectsTable } from "./objects-table"; import { ObjectsTable } from "./objects-table";
import { DetailDrawer } from "../components/detail-drawer";
import { useMediaQuery } from "../lib/use-media-query"; import { useMediaQuery } from "../lib/use-media-query";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { Button } from "@/components/ui/button";
import { PageTitle } from "@/components/ui/page-title"; import { PageTitle } from "@/components/ui/page-title";
const ObjectDetailDrawer = lazy(() =>
import("./object-detail-drawer").then((m) => ({ default: m.ObjectDetailDrawer })),
);
export function ObjectsPage() { export function ObjectsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -47,14 +44,14 @@ export function ObjectsPage() {
{open && ( {open && (
<div className="flex h-full flex-col overflow-hidden border-l"> <div className="flex h-full flex-col overflow-hidden border-l">
<div className="flex justify-end border-b p-2"> <div className="flex justify-end border-b p-2">
<button <Button
type="button" variant="ghost"
size="icon-sm"
onClick={closeDetail} onClick={closeDetail}
aria-label={t("actions.closeDetail")} aria-label={t("actions.closeDetail")}
className="rounded-md p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
> >
<X className="size-4" aria-hidden="true" /> <X className="size-4" aria-hidden="true" />
</button> </Button>
</div> </div>
<div className="flex-1 overflow-auto"> <div className="flex-1 overflow-auto">
<Outlet /> <Outlet />
@@ -65,15 +62,14 @@ export function ObjectsPage() {
); );
} }
// Narrow: the detail lives in a Drawer, lazy-loaded so Base UI's drawer code stays // Narrow: the detail lives in a Drawer sliding from the right.
// out of the main entry chunk.
return ( return (
<div className="h-full"> <div className="h-full">
{table} {table}
{open && ( {open && (
<Suspense fallback={null}> <DetailDrawer open={open} onClose={closeDetail} ariaLabel={t("objects.detailTitle")}>
<ObjectDetailDrawer open={open} onClose={closeDetail} /> <Outlet />
</Suspense> </DetailDrawer>
)} )}
</div> </div>
); );
+9 -17
View File
@@ -7,6 +7,8 @@ import type { components } from "../api/schema";
import { useObjectsPage } from "../api/queries"; import { useObjectsPage } from "../api/queries";
import { useDebouncedValue } from "../lib/use-debounced-value"; import { useDebouncedValue } from "../lib/use-debounced-value";
import { focusRing } from "../lib/focus-ring"; import { focusRing } from "../lib/focus-ring";
import { segmentClass, rowStateClass } from "../lib/class-recipes";
import { formatTimestamp } from "../lib/format-timestamp";
import { useConfig } from "../config/config-context"; import { useConfig } from "../config/config-context";
import { VisibilityBadge } from "./visibility-badge"; import { VisibilityBadge } from "./visibility-badge";
import { Button, buttonVariants } from "@/components/ui/button"; import { Button, buttonVariants } from "@/components/ui/button";
@@ -119,16 +121,6 @@ export function ObjectsTable() {
else next.set("offset", String(value)); else next.set("offset", String(value));
}); });
const dateFmt = new Intl.DateTimeFormat(i18n.language, {
dateStyle: "medium",
timeZone: default_timezone,
});
const formatUpdated = (iso: string) => {
const parsed = new Date(iso);
return Number.isNaN(parsed.getTime()) ? iso : dateFmt.format(parsed);
};
const headerCell = (col: SortColumn) => { const headerCell = (col: SortColumn) => {
const active = sort === col; const active = sort === col;
const ariaSort = active ? (order === "asc" ? "ascending" : "descending") : "none"; const ariaSort = active ? (order === "asc" ? "ascending" : "descending") : "none";
@@ -139,7 +131,7 @@ export function ObjectsTable() {
<button <button
type="button" type="button"
onClick={() => toggleSort(col)} onClick={() => toggleSort(col)}
className="flex items-center gap-1 hover:text-foreground" className={`flex items-center gap-1 rounded-sm hover:text-foreground ${focusRing}`}
> >
{t(COLUMN_KEYS[col])} {t(COLUMN_KEYS[col])}
<Icon className="size-3.5 text-muted-foreground" aria-hidden="true" /> <Icon className="size-3.5 text-muted-foreground" aria-hidden="true" />
@@ -171,7 +163,7 @@ export function ObjectsTable() {
type="button" type="button"
aria-pressed={active} aria-pressed={active}
onClick={() => setVisibility(value)} onClick={() => setVisibility(value)}
className={`${focusRing} rounded-md px-2 py-1 ${active ? "bg-primary text-primary-foreground" : "border"}`} className={segmentClass(active, "px-2 py-1")}
> >
{value === "all" ? t("search.all") : t(`visibility.${value}`)} {value === "all" ? t("search.all") : t(`visibility.${value}`)}
</button> </button>
@@ -248,9 +240,7 @@ export function ObjectsTable() {
<tr <tr
key={object.id} key={object.id}
onClick={() => navigate(`/objects/${object.id}?${params}`)} onClick={() => navigate(`/objects/${object.id}?${params}`)}
className={`cursor-pointer border-b text-sm ${ className={`cursor-pointer border-b text-sm ${rowStateClass(selected)}`}
selected ? "bg-primary/10" : "hover:bg-muted"
}`}
> >
<td className="px-3 py-2 text-muted-foreground"> <td className="px-3 py-2 text-muted-foreground">
<Link <Link
@@ -268,7 +258,9 @@ export function ObjectsTable() {
</td> </td>
<td className="px-3 py-2 text-muted-foreground">{object.current_location ?? "—"}</td> <td className="px-3 py-2 text-muted-foreground">{object.current_location ?? "—"}</td>
<td className="px-3 py-2 text-right tabular-nums">{object.number_of_objects}</td> <td className="px-3 py-2 text-right tabular-nums">{object.number_of_objects}</td>
<td className="px-3 py-2 text-muted-foreground">{formatUpdated(object.updated_at)}</td> <td className="px-3 py-2 text-muted-foreground">
{formatTimestamp(object.updated_at, default_timezone, i18n.language)}
</td>
</tr> </tr>
); );
})} })}
@@ -295,7 +287,7 @@ export function ObjectsTable() {
value={limit} value={limit}
onChange={(event) => setLimit(Number(event.target.value))} onChange={(event) => setLimit(Number(event.target.value))}
aria-label={t("objects.pageSize")} aria-label={t("objects.pageSize")}
className="rounded-md border bg-white px-1 py-0.5" className={`rounded-md border bg-background px-1 py-0.5 ${focusRing}`}
> >
{PAGE_SIZES.map((size) => ( {PAGE_SIZES.map((size) => (
<option key={size} value={size}> <option key={size} value={size}>
+39
View File
@@ -0,0 +1,39 @@
import { expect, test } from "vitest";
import { pruneFields } from "./prune-fields";
test("drops empty/null/undefined scalars, keeps real scalars", () => {
const out = pruneFields(
{ a: "x", b: "", c: null, d: undefined, e: 0, f: false },
new Set(),
"en",
);
expect(out).toEqual({ a: "x", e: 0, f: false });
});
test("a localized_text key keeps only the default-language entry", () => {
const out = pruneFields(
{ title: { en: "Bowl", sv: "Skål" } },
new Set(["title"]),
"sv",
);
expect(out).toEqual({ title: { sv: "Skål" } });
});
test("a non-localized object value keeps all non-empty entries", () => {
const out = pruneFields(
{ dims: { w: "10", h: "", d: "5" } },
new Set(),
"en",
);
expect(out).toEqual({ dims: { w: "10", d: "5" } });
});
test("an object value left with no entries is dropped entirely", () => {
const out = pruneFields(
{ title: { en: "Bowl" }, empty: { en: "", sv: "" } },
new Set(["title", "empty"]),
"sv",
);
expect(out).toEqual({});
});
+56
View File
@@ -0,0 +1,56 @@
import { afterEach, expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import { Route, Routes } from "react-router-dom";
import { renderApp } from "../test/render";
import { SearchPage } from "./search-page";
import { ObjectDetail } from "../objects/object-detail";
import { SelectSearchPrompt } from "./select-search-prompt";
function setViewport(wide: boolean) {
Object.defineProperty(window, "matchMedia", {
value: (query: string): MediaQueryList =>
({
matches: wide && query === "(min-width: 1024px)",
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as MediaQueryList,
writable: true,
});
}
afterEach(() => vi.restoreAllMocks());
function tree() {
return (
<Routes>
<Route path="/search" element={<SearchPage />}>
<Route index element={<SelectSearchPrompt />} />
<Route path=":id" element={<ObjectDetail />} />
</Route>
</Routes>
);
}
test("narrow: a selected result's detail renders in a portaled drawer", async () => {
setViewport(false);
renderApp(tree(), { route: "/search/11111111-1111-1111-1111-111111111111" });
const body = within(document.body);
expect(
await body.findByRole("button", { name: /close detail/i }, { timeout: 5000 }),
).toBeInTheDocument();
});
test("wide: a selected result renders inline, with no detail drawer", async () => {
setViewport(true);
renderApp(tree(), { route: "/search/11111111-1111-1111-1111-111111111111" });
expect(await screen.findByRole("heading", { name: "Amphora" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /close detail/i })).toBeNull();
});
+20 -1
View File
@@ -1,20 +1,29 @@
import { Outlet } from "react-router-dom"; import { Outlet, useMatch, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { SearchPanel } from "./search-panel"; import { SearchPanel } from "./search-panel";
import { DetailDrawer } from "../components/detail-drawer";
import { useMediaQuery } from "../lib/use-media-query";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title"; import { PageTitle } from "@/components/ui/page-title";
export function SearchPage() { export function SearchPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate();
const detailMatch = useMatch("/search/:id");
const open = Boolean(detailMatch);
const isWide = useMediaQuery("(min-width: 1024px)");
useDocumentTitle(t("nav.search")); useDocumentTitle(t("nav.search"));
useBreadcrumb([{ label: t("nav.search") }]); useBreadcrumb([{ label: t("nav.search") }]);
const close = () => navigate("/search");
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageTitle className="px-4 pt-4 pb-2">{t("nav.search")}</PageTitle> <PageTitle className="px-4 pt-4 pb-2">{t("nav.search")}</PageTitle>
{isWide ? (
<div className="grid flex-1 grid-cols-[24rem_1fr] overflow-hidden"> <div className="grid flex-1 grid-cols-[24rem_1fr] overflow-hidden">
<div className="overflow-hidden border-r"> <div className="overflow-hidden border-r">
<SearchPanel /> <SearchPanel />
@@ -23,6 +32,16 @@ export function SearchPage() {
<Outlet /> <Outlet />
</div> </div>
</div> </div>
) : (
<div className="flex-1 overflow-hidden">
<SearchPanel />
</div>
)}
{!isWide && open && (
<DetailDrawer open={open} onClose={close} ariaLabel={t("objects.detailTitle")}>
<Outlet />
</DetailDrawer>
)}
</div> </div>
); );
} }
+3 -4
View File
@@ -4,9 +4,8 @@ import { useTranslation } from "react-i18next";
import { useSearch, HttpError } from "../api/queries"; import { useSearch, HttpError } from "../api/queries";
import { useDebouncedValue } from "../lib/use-debounced-value"; import { useDebouncedValue } from "../lib/use-debounced-value";
import { focusRing } from "../lib/focus-ring"; import { segmentClass } from "../lib/class-recipes";
import { SearchResultRow } from "./search-result-row"; import { SearchResultRow } from "./search-result-row";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { ListSkeleton } from "@/components/ui/skeletons"; import { ListSkeleton } from "@/components/ui/skeletons";
@@ -73,7 +72,7 @@ export function SearchPanel() {
type="button" type="button"
aria-pressed={active} aria-pressed={active}
onClick={() => setVisibility(value)} onClick={() => setVisibility(value)}
className={cn("rounded-md px-2 py-0.5", focusRing, active ? "bg-primary text-primary-foreground" : "border")} className={segmentClass(active, "px-2 py-0.5")}
> >
{value === "all" ? t("search.all") : t(`visibility.${value}`)} {value === "all" ? t("search.all") : t(`visibility.${value}`)}
</button> </button>
@@ -103,7 +102,7 @@ export function SearchPanel() {
{hits.length > 0 && ( {hits.length > 0 && (
<> <>
<p className="px-3 pt-2 text-xs text-muted-foreground"> <p role="status" className="px-3 pt-2 text-xs text-muted-foreground">
{t("search.resultCount", { count: total })} {t("search.resultCount", { count: total })}
</p> </p>
<ul> <ul>
+2 -1
View File
@@ -2,6 +2,7 @@ import { NavLink } from "react-router-dom";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { VisibilityBadge } from "../objects/visibility-badge"; import { VisibilityBadge } from "../objects/visibility-badge";
import { rowStateClass } from "../lib/class-recipes";
import { Highlight } from "./highlight"; import { Highlight } from "./highlight";
type SearchHitView = components["schemas"]["SearchHitView"]; type SearchHitView = components["schemas"]["SearchHitView"];
@@ -12,7 +13,7 @@ export function SearchResultRow({ hit }: { hit: SearchHitView }) {
<NavLink <NavLink
to={`/search/${hit.id}`} to={`/search/${hit.id}`}
className={({ isActive }) => className={({ isActive }) =>
`block border-b px-3 py-2 ${isActive ? "bg-primary/10" : "hover:bg-muted"}` `block border-b px-3 py-2 ${rowStateClass(isActive)}`
} }
> >
<div className="text-sm font-semibold">{hit.object_name}</div> <div className="text-sm font-semibold">{hit.object_name}</div>
+2 -1
View File
@@ -60,7 +60,8 @@ test("typing searches and renders highlighted rich rows", async () => {
expect(await screen.findByText("Bronze figurine")).toBeInTheDocument(); expect(await screen.findByText("Bronze figurine")).toBeInTheDocument();
const mark = await screen.findByText("bronze"); const mark = await screen.findByText("bronze");
expect(mark.tagName).toBe("MARK"); expect(mark.tagName).toBe("MARK");
expect(screen.getByText(/~\s*25 results/i)).toBeInTheDocument(); // The estimated count lives in a status region so updates are announced.
expect(screen.getByRole("status")).toHaveTextContent(/~\s*25 results/i);
expect(screen.getByText(/1962-04-03/)).toBeInTheDocument(); expect(screen.getByText(/1962-04-03/)).toBeInTheDocument();
}); });
+5 -1
View File
@@ -2,6 +2,7 @@ import { Fragment } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { focusRing } from "../lib/focus-ring";
import { useBreadcrumbTrail } from "./breadcrumb-context"; import { useBreadcrumbTrail } from "./breadcrumb-context";
export function Breadcrumb() { export function Breadcrumb() {
@@ -16,7 +17,10 @@ export function Breadcrumb() {
<Fragment key={`${item.label}-${i}`}> <Fragment key={`${item.label}-${i}`}>
{i > 0 && <span className="text-muted-foreground">/</span>} {i > 0 && <span className="text-muted-foreground">/</span>}
{item.to && !last ? ( {item.to && !last ? (
<Link to={item.to} className="truncate text-muted-foreground hover:text-foreground"> <Link
to={item.to}
className={`truncate rounded-sm text-muted-foreground hover:text-foreground ${focusRing}`}
>
{item.label} {item.label}
</Link> </Link>
) : ( ) : (
+1 -1
View File
@@ -20,7 +20,7 @@ export function HeaderSearch() {
<form onSubmit={onSubmit} className="hidden sm:block"> <form onSubmit={onSubmit} className="hidden sm:block">
<div className="relative"> <div className="relative">
<Search <Search
className="pointer-events-none absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2 text-muted-foreground" className="pointer-events-none absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground"
aria-hidden aria-hidden
/> />
<Input <Input
+8 -5
View File
@@ -13,6 +13,7 @@ import {
import type { LucideIcon } from "lucide-react"; import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { focusRing } from "../lib/focus-ring";
import { Tooltip } from "@/components/ui/tooltip"; import { Tooltip } from "@/components/ui/tooltip";
import { useMediaQuery } from "@/lib/use-media-query"; import { useMediaQuery } from "@/lib/use-media-query";
import { useConfig } from "../config/config-context"; import { useConfig } from "../config/config-context";
@@ -43,7 +44,7 @@ function navLinkClass(collapsed: boolean) {
return ({ isActive }: { isActive: boolean }) => return ({ isActive }: { isActive: boolean }) =>
cn( cn(
"flex items-center gap-2 rounded-md px-2 py-1 outline-none", "flex items-center gap-2 rounded-md px-2 py-1 outline-none",
"focus-visible:ring-3 focus-visible:ring-ring/50", focusRing,
collapsed && "justify-center", collapsed && "justify-center",
isActive && "bg-accent font-medium", isActive && "bg-accent font-medium",
); );
@@ -79,14 +80,16 @@ export function Sidebar() {
<button <button
type="button" type="button"
onClick={toggle} onClick={toggle}
disabled={narrow}
aria-expanded={!collapsed} aria-expanded={!collapsed}
aria-label={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")} aria-label={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")}
title={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")} title={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")}
className={cn( className={cn(
"flex items-center justify-center rounded-md p-1 outline-none", // On narrow viewports the rail is forced collapsed, so the toggle
"hover:bg-accent focus-visible:ring-3 focus-visible:ring-ring/50", // is hidden rather than shown disabled (a grayed button reads as
"disabled:pointer-events-none disabled:opacity-50", // broken, not unavailable).
"hidden items-center justify-center rounded-md p-1 outline-none md:flex",
"hover:bg-accent",
focusRing,
)} )}
> >
{collapsed ? ( {collapsed ? (
+1 -1
View File
@@ -36,7 +36,7 @@ export function ThemeSwitch() {
: "text-muted-foreground hover:text-foreground", : "text-muted-foreground hover:text-foreground",
)} )}
> >
<Icon className="h-4 w-4" aria-hidden /> <Icon className="size-4" aria-hidden />
</button> </button>
); );
})} })}
+11 -2
View File
@@ -1,7 +1,7 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { screen, waitFor, within } from "@testing-library/react"; import { screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { delay, http, HttpResponse } from "msw"; import { http, HttpResponse } from "msw";
import { server } from "../test/server"; import { server } from "../test/server";
import { renderApp } from "../test/render"; import { renderApp } from "../test/render";
import { UserMenu } from "./user-menu"; import { UserMenu } from "./user-menu";
@@ -35,9 +35,13 @@ test("opens the menu showing email + role and signs out", async () => {
}); });
test("shows a pending state on Sign out while logging out", async () => { test("shows a pending state on Sign out while logging out", async () => {
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
server.use( server.use(
http.post("/api/admin/logout", async () => { http.post("/api/admin/logout", async () => {
await delay(50); await gate;
return new HttpResponse(null, { status: 204 }); return new HttpResponse(null, { status: 204 });
}), }),
); );
@@ -50,5 +54,10 @@ test("shows a pending state on Sign out while logging out", async () => {
const menu = within(document.body); const menu = within(document.body);
await userEvent.click(await menu.findByText("Sign out")); await userEvent.click(await menu.findByText("Sign out"));
// The logout is held open by `gate`, so the pending state is observed
// deterministically (no reliance on a timing window).
expect(await menu.findByText(/signing out/i)).toBeInTheDocument(); expect(await menu.findByText(/signing out/i)).toBeInTheDocument();
release();
await waitFor(() => expect(menu.queryByText(/signing out/i)).toBeNull());
}); });
+1 -1
View File
@@ -24,7 +24,7 @@ export function UserMenu() {
<MenuTrigger <MenuTrigger
render={ render={
<Button variant="ghost" size="sm" className="max-w-44"> <Button variant="ghost" size="sm" className="max-w-44">
<CircleUser className="h-4 w-4" aria-hidden /> <CircleUser className="size-4" aria-hidden />
<span className="truncate">{me.email}</span> <span className="truncate">{me.email}</span>
</Button> </Button>
} }
+15
View File
@@ -40,6 +40,21 @@ test("readTheme defaults to system when unset or invalid", () => {
expect(readTheme()).toBe("dark"); expect(readTheme()).toBe("dark");
}); });
test("applyTheme syncs the theme-color meta when present", () => {
const meta = document.createElement("meta");
meta.setAttribute("name", "theme-color");
document.head.appendChild(meta);
try {
mockMatchMedia(false);
applyTheme("dark");
expect(meta.getAttribute("content")).toBe("#0a0a0a");
applyTheme("light");
expect(meta.getAttribute("content")).toBe("#ffffff");
} finally {
meta.remove();
}
});
test("applyTheme toggles the dark class on documentElement", () => { test("applyTheme toggles the dark class on documentElement", () => {
mockMatchMedia(false); mockMatchMedia(false);
applyTheme("dark"); applyTheme("dark");
+9 -1
View File
@@ -26,8 +26,16 @@ export function readTheme(): Theme {
return THEMES.includes(stored as Theme) ? (stored as Theme) : "system"; return THEMES.includes(stored as Theme) ? (stored as Theme) : "system";
} }
/** Browser-chrome colors per resolved theme; must match `--background` in index.css. */
const THEME_COLORS = { light: "#ffffff", dark: "#0a0a0a" } as const;
export function applyTheme(theme: Theme): void { export function applyTheme(theme: Theme): void {
if (typeof document === "undefined") return; if (typeof document === "undefined") return;
document.documentElement.classList.toggle("dark", resolveTheme(theme) === "dark"); const resolved = resolveTheme(theme);
document.documentElement.classList.toggle("dark", resolved === "dark");
document
.querySelector('meta[name="theme-color"]')
?.setAttribute("content", THEME_COLORS[resolved]);
} }
+13 -73
View File
@@ -1,84 +1,24 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { components } from "../api/schema"; import type { components } from "../api/schema";
import { useUpdateTerm, useDeleteTerm } from "../api/queries"; import { useUpdateTerm, useDeleteTerm } from "../api/queries";
import { LabelEditor } from "../components/label-editor"; import { LabelledRecordRow } from "../components/labelled-record-row";
import { DeleteConfirmDialog } from "../components/delete-confirm-dialog";
import { MutationError } from "../components/mutation-error";
import { ExternalUriLink } from "../components/external-uri-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";
type TermView = components["schemas"]["TermView"]; type TermView = components["schemas"]["TermView"];
type LabelInput = components["schemas"]["LabelInput"];
export function TermRow({ vocabularyId, term, lang }: { vocabularyId: string; term: TermView; lang: string }) { export function TermRow({ vocabularyId, term, lang }: { vocabularyId: string; term: TermView; lang: string }) {
const { t } = useTranslation(); const update = useUpdateTerm();
const del = useDeleteTerm();
const updateTerm = useUpdateTerm();
const deleteTerm = useDeleteTerm();
const [editing, setEditing] = useState(false);
const [labels, setLabels] = useState<LabelInput[]>(term.labels as LabelInput[]);
const [uri, setUri] = useState(term.external_uri ?? "");
if (editing) {
return (
<li className="space-y-2 border-b py-2">
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor={`term-uri-${term.id}`}>{t("labels.externalUri")}</Label>
<Input id={`term-uri-${term.id}`} type="url" placeholder={t("labels.uriPlaceholder")} value={uri} onChange={(e) => setUri(e.target.value)} />
</div>
<div className="flex gap-2">
<Button
type="button"
size="sm"
disabled={updateTerm.isPending}
onClick={() =>
updateTerm.mutate(
{ vocabularyId, termId: term.id, external_uri: uri.trim() || null, labels },
{ onSuccess: () => setEditing(false) },
)
}
>
{t("actions.save")}
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
{t("form.cancel")}
</Button>
</div>
<MutationError error={updateTerm.error} />
</li>
);
}
return ( return (
<li className="flex items-center gap-2 border-b py-1 text-sm"> <LabelledRecordRow
<div className="flex-1"> record={{ ...term, external_uri: term.external_uri ?? null }}
<div>{labelText(term.labels, lang)}</div> lang={lang}
{term.external_uri && <ExternalUriLink uri={term.external_uri} />} deleteConfirmKey="actions.confirmDeleteTerm"
</div> savePending={update.isPending}
<Button saveError={update.error}
type="button" onEditOpen={() => update.reset()}
variant="ghost" onSave={(labels, uri, done) =>
size="sm" update.mutate({ vocabularyId, termId: term.id, external_uri: uri, labels }, { onSuccess: done })}
onClick={() => { onDelete={() => del.mutateAsync({ vocabularyId, termId: term.id })}
updateTerm.reset();
setLabels(term.labels as LabelInput[]);
setUri(term.external_uri ?? "");
setEditing(true);
}}
>
{t("actions.edit")}
</Button>
<DeleteConfirmDialog
description={t("actions.confirmDeleteTerm")}
onConfirm={() => deleteTerm.mutateAsync({ vocabularyId, termId: term.id })}
/> />
</li>
); );
} }
+57
View File
@@ -0,0 +1,57 @@
import { afterEach, expect, test, vi } from "vitest";
import { screen, within } from "@testing-library/react";
import { Route, Routes } from "react-router-dom";
import { renderApp } from "../test/render";
import { VocabulariesPage } from "./vocabularies-page";
import { VocabularyTerms } from "./vocabulary-terms";
import { SelectVocabularyPrompt } from "./select-vocabulary-prompt";
function setViewport(wide: boolean) {
Object.defineProperty(window, "matchMedia", {
value: (query: string): MediaQueryList =>
({
matches: wide && query === "(min-width: 1024px)",
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as MediaQueryList,
writable: true,
});
}
afterEach(() => vi.restoreAllMocks());
function tree() {
return (
<Routes>
<Route path="/vocabularies" element={<VocabulariesPage />}>
<Route index element={<SelectVocabularyPrompt />} />
<Route path=":id" element={<VocabularyTerms />} />
</Route>
</Routes>
);
}
test("narrow: a selected vocabulary's detail renders in a portaled drawer", async () => {
setViewport(false);
renderApp(tree(), { route: "/vocabularies/v-material" });
const body = within(document.body);
expect(
await body.findByRole("button", { name: /close detail/i }, { timeout: 5000 }),
).toBeInTheDocument();
});
test("wide: a selected vocabulary renders inline, with no detail drawer", async () => {
setViewport(true);
renderApp(tree(), { route: "/vocabularies/v-material" });
// VocabularyTerms renders its "Terms" caption inline in the right pane.
await screen.findByText(/terms/i);
expect(screen.queryByRole("button", { name: /close detail/i })).toBeNull();
});
+20 -1
View File
@@ -1,20 +1,29 @@
import { Outlet } from "react-router-dom"; import { Outlet, useMatch, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { VocabularyList } from "./vocabulary-list"; import { VocabularyList } from "./vocabulary-list";
import { DetailDrawer } from "../components/detail-drawer";
import { useMediaQuery } from "../lib/use-media-query";
import { useDocumentTitle } from "../lib/use-document-title"; import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title"; import { PageTitle } from "@/components/ui/page-title";
export function VocabulariesPage() { export function VocabulariesPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate();
const detailMatch = useMatch("/vocabularies/:id");
const open = Boolean(detailMatch);
const isWide = useMediaQuery("(min-width: 1024px)");
useDocumentTitle(t("nav.vocabularies")); useDocumentTitle(t("nav.vocabularies"));
useBreadcrumb([{ label: t("nav.vocabularies") }]); useBreadcrumb([{ label: t("nav.vocabularies") }]);
const close = () => navigate("/vocabularies");
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageTitle className="px-4 pt-4 pb-2">{t("nav.vocabularies")}</PageTitle> <PageTitle className="px-4 pt-4 pb-2">{t("nav.vocabularies")}</PageTitle>
{isWide ? (
<div className="grid flex-1 grid-cols-[20rem_1fr] overflow-hidden"> <div className="grid flex-1 grid-cols-[20rem_1fr] overflow-hidden">
<div className="overflow-hidden border-r"> <div className="overflow-hidden border-r">
<VocabularyList /> <VocabularyList />
@@ -23,6 +32,16 @@ export function VocabulariesPage() {
<Outlet /> <Outlet />
</div> </div>
</div> </div>
) : (
<div className="flex-1 overflow-hidden">
<VocabularyList />
</div>
)}
{!isWide && open && (
<DetailDrawer open={open} onClose={close} ariaLabel={t("vocab.terms")}>
<Outlet />
</DetailDrawer>
)}
</div> </div>
); );
} }
+5 -3
View File
@@ -3,6 +3,8 @@ import { NavLink } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useVocabularies, useCreateVocabulary, useRenameVocabulary, useDeleteVocabulary } from "../api/queries"; import { useVocabularies, useCreateVocabulary, useRenameVocabulary, useDeleteVocabulary } from "../api/queries";
import { useLang } from "../lib/use-lang";
import { rowStateClass } from "../lib/class-recipes";
import { byKey } from "../lib/sort"; import { byKey } from "../lib/sort";
import { DeleteConfirmDialog } from "../components/delete-confirm-dialog"; import { DeleteConfirmDialog } from "../components/delete-confirm-dialog";
import { MutationError } from "../components/mutation-error"; import { MutationError } from "../components/mutation-error";
@@ -12,9 +14,9 @@ import { Label } from "@/components/ui/label";
import { ListSkeleton } from "@/components/ui/skeletons"; import { ListSkeleton } from "@/components/ui/skeletons";
export function VocabularyList() { export function VocabularyList() {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const lang = i18n.language.startsWith("sv") ? "sv" : "en"; const lang = useLang();
const { data, isLoading, isError } = useVocabularies(); const { data, isLoading, isError } = useVocabularies();
@@ -110,7 +112,7 @@ export function VocabularyList() {
<NavLink <NavLink
to={`/vocabularies/${v.id}`} to={`/vocabularies/${v.id}`}
className={({ isActive }) => className={({ isActive }) =>
`block flex-1 px-3 py-2 text-sm ${isActive ? "bg-primary/10" : "hover:bg-muted"}` `block flex-1 px-3 py-2 text-sm ${rowStateClass(isActive)}`
} }
> >
{v.key} {v.key}
+23 -96
View File
@@ -1,41 +1,21 @@
import { useState, type FormEvent } from "react";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { components } from "../api/schema";
import { useTerms, useAddTerm, useVocabularies } from "../api/queries"; import { useTerms, useAddTerm, useVocabularies } from "../api/queries";
import { byLabel } from "../lib/sort"; import { useLang } from "../lib/use-lang";
import { labelText } from "../lib/labels";
import { useBreadcrumb } from "../shell/use-breadcrumb"; import { useBreadcrumb } from "../shell/use-breadcrumb";
import { LabelEditor } from "../components/label-editor"; import { FilteredRecordList } from "../components/filtered-record-list";
import { MutationError } from "../components/mutation-error"; import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { TermRow } from "./term-row"; import { TermRow } from "./term-row";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ListSkeleton } from "@/components/ui/skeletons";
type LabelInput = components["schemas"]["LabelInput"];
export function VocabularyTerms() { export function VocabularyTerms() {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const { id } = useParams(); const { id } = useParams();
const lang = useLang();
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
const { data: terms, isLoading, isError } = useTerms(id); const { data: terms, isLoading, isError } = useTerms(id);
const addTerm = useAddTerm(); const addTerm = useAddTerm();
const [labels, setLabels] = useState<LabelInput[]>([]);
const [uri, setUri] = useState("");
const [filter, setFilter] = useState("");
const [error, setError] = useState(false);
const { data: vocabularies } = useVocabularies(); const { data: vocabularies } = useVocabularies();
const vocabKey = vocabularies?.find((v) => v.id === id)?.key; const vocabKey = vocabularies?.find((v) => v.id === id)?.key;
@@ -47,81 +27,28 @@ export function VocabularyTerms() {
if (!id) return null; if (!id) return null;
const onAdd = (event: FormEvent) => {
event.preventDefault();
if (!labels.some((l) => l.label)) {
setError(true);
return;
}
setError(false);
addTerm.mutate(
{ vocabularyId: id, external_uri: uri.trim() || null, labels },
{ onSuccess: () => { setLabels([]); setUri(""); } },
);
};
const q = filter.trim().toLowerCase();
const rows = [...(terms ?? [])]
.filter((term) => !q || labelText(term.labels, lang).toLowerCase().includes(q))
.sort(byLabel(lang));
return ( return (
<div className="overflow-auto p-4"> <div className="overflow-auto p-4">
<div className="mb-2 label-caption"> <div className="mb-2 label-caption">{t("vocab.terms")}</div>
{t("vocab.terms")}
</div> <FilteredRecordList
<div className="mb-3"> records={terms}
<Input lang={lang}
aria-label={t("common.filter")} isLoading={isLoading}
placeholder={t("common.filter")} isError={isError}
value={filter} loadErrorText={t("vocab.loadError")}
onChange={(e) => setFilter(e.target.value)} emptyText={t("vocab.noTerms")}
renderRow={(term) => <TermRow vocabularyId={id} term={term} lang={lang} />}
/> />
</div>
{isLoading ? ( <LabelledRecordCreateForm
<ListSkeleton className="mb-4" rows={5} /> heading={t("vocab.addTerm")}
) : ( submitLabel={t("vocab.addTerm")}
<ul className="mb-4"> pending={addTerm.isPending}
{isError && ( error={addTerm.error}
<li className="text-sm text-destructive">{t("vocab.loadError")}</li> onCreate={(labels, uri, reset) =>
)} addTerm.mutate({ vocabularyId: id, external_uri: uri, labels }, { onSuccess: reset })}
{!isError && terms?.length === 0 && (
<li className="text-sm text-muted-foreground">{t("vocab.noTerms")}</li>
)}
{!isError && terms && terms.length > 0 && rows.length === 0 && (
<li className="text-sm text-muted-foreground">{t("common.noMatches")}</li>
)}
{rows.map((term) => (
<TermRow key={term.id} vocabularyId={id} term={term} lang={lang} />
))}
</ul>
)}
<form onSubmit={onAdd} className="space-y-2 border-t pt-3">
<div className="text-sm font-medium">{t("vocab.addTerm")}</div>
<LabelEditor value={labels} onChange={setLabels} />
<div className="space-y-1">
<Label htmlFor="term-uri">{t("labels.externalUri")}</Label>
<Input
id="term-uri"
type="url"
placeholder={t("labels.uriPlaceholder")}
value={uri}
onChange={(e) => setUri(e.target.value)}
/> />
</div> </div>
{error && (
<p role="alert" className="text-xs text-destructive">
{t("form.required")}
</p>
)}
<MutationError error={addTerm.error} />
<Button type="submit" size="sm" disabled={addTerm.isPending}>
{t("vocab.addTerm")}
</Button>
</form>
</div>
); );
} }
+24
View File
@@ -16,6 +16,26 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src") "@": path.resolve(__dirname, "./src")
} }
}, },
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (/[\\/]node_modules[\\/]\.pnpm[\\/](react|react-dom|react-router|react-router-dom)@/.test(id)) {
return "react";
}
if (/[\\/]node_modules[\\/]\.pnpm[\\/]@base-ui\+react@/.test(id)) {
return "base-ui";
}
if (/[\\/]node_modules[\\/]\.pnpm[\\/]@tanstack\+react-query@/.test(id)) {
return "query";
}
if (/[\\/]node_modules[\\/]\.pnpm[\\/](i18next|react-i18next)@/.test(id)) {
return "i18n";
}
}
}
}
},
server: { server: {
proxy: { proxy: {
"/api": "http://localhost:8080", "/api": "http://localhost:8080",
@@ -28,6 +48,9 @@ export default defineConfig({
extends: true, extends: true,
test: { test: {
environment: "jsdom", environment: "jsdom",
// The CI runner is heavily resource-constrained; lazy-loaded chunks
// (e.g. the object-detail drawer) can exceed the 5s default.
testTimeout: 20000,
globals: true, globals: true,
setupFiles: ["./src/test/setup.ts"], setupFiles: ["./src/test/setup.ts"],
environmentOptions: { environmentOptions: {
@@ -46,6 +69,7 @@ export default defineConfig({
})], })],
test: { test: {
name: 'storybook', name: 'storybook',
testTimeout: 20000,
browser: { browser: {
enabled: true, enabled: true,
headless: true, headless: true,