Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3aff10557c | |||
| e8fe24f755 | |||
| fc170ccf10 | |||
| 3ae9d87e6e | |||
| 3dbede6bc2 | |||
| ba238ca962 | |||
| 7cabebc338 | |||
| 74cde67a54 | |||
| 900f85f8ac | |||
| 00a7ce772e | |||
| 71dee23028 | |||
| 91716e628a | |||
| 002af9d1f8 | |||
| d8d8035850 | |||
| 704b159d48 | |||
| c1bddb47c4 | |||
| a21ab85576 | |||
| 7ddf6967ce |
@@ -7,7 +7,9 @@ on:
|
||||
|
||||
jobs:
|
||||
web:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: aceofba-cluster
|
||||
container:
|
||||
image: ghcr.io/catthehacker/ubuntu:act-22.04
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web
|
||||
@@ -18,12 +20,13 @@ jobs:
|
||||
version: 11
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: web/pnpm-lock.yaml
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
- 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,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).
|
||||
@@ -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
|
||||
* source of truth shared by the global toast fallback and every inline display. */
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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),
|
||||
);
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { useConfig } from "../config/config-context";
|
||||
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";
|
||||
|
||||
/** Accept only a single-leading-slash local path; reject protocol-relative
|
||||
* ("//host") and absolute URLs to avoid an open redirect. */
|
||||
@@ -46,7 +47,7 @@ export function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-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 && (
|
||||
<p className="text-sm text-muted-foreground">{t("auth.sessionExpired")}</p>
|
||||
)}
|
||||
|
||||
@@ -6,17 +6,17 @@ 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 { useLang } from "../lib/use-lang";
|
||||
import { segmentClass } from "../lib/class-recipes";
|
||||
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 { t } = useTranslation();
|
||||
const { kind } = useParams();
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
const lang = useLang();
|
||||
|
||||
const isValidKind = (KINDS as readonly string[]).includes(kind ?? "");
|
||||
const currentKind = isValidKind ? (kind as string) : "person";
|
||||
@@ -37,9 +37,7 @@ export function AuthoritiesPage() {
|
||||
<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")
|
||||
}
|
||||
className={({ isActive }) => segmentClass(isActive, "px-3 py-1 text-sm")}
|
||||
>
|
||||
{t(`authorities.${k}`)}
|
||||
</NavLink>
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -2,12 +2,13 @@ import { useEffect, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { api } from "../api/client";
|
||||
import { keys } from "../api/query-keys";
|
||||
import i18n, { LOCALE_KEY } from "../i18n";
|
||||
import { ConfigContext, DEFAULTS, type ConfigView } from "./config-context";
|
||||
|
||||
export function ConfigProvider({ children }: { children: ReactNode }) {
|
||||
const { data } = useQuery({
|
||||
queryKey: ["config"],
|
||||
queryKey: keys.config(),
|
||||
queryFn: async (): Promise<ConfigView> => {
|
||||
const { data, error } = await api.GET("/api/config");
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { useFieldDefinitions, useDeleteFieldDefinition } from "../api/queries";
|
||||
import { useLang } from "../lib/use-lang";
|
||||
import { rowStateClass } from "../lib/class-recipes";
|
||||
import { labelText } from "../lib/labels";
|
||||
import { byLabel, compareStrings } from "../lib/sort";
|
||||
import { focusRing } from "../lib/focus-ring";
|
||||
@@ -21,10 +23,10 @@ export function FieldList({
|
||||
selectedKey: string | null;
|
||||
onSelect: (def: FieldDefinitionView) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const { data, isLoading, isError } = useFieldDefinitions();
|
||||
const deleteField = useDeleteFieldDefinition();
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
const lang = useLang();
|
||||
const [filter, setFilter] = useState("");
|
||||
|
||||
if (isLoading) return <ListSkeleton rows={6} />;
|
||||
@@ -82,9 +84,9 @@ export function FieldList({
|
||||
{[...defs].sort(byLabel(lang)).map((def) => (
|
||||
<li
|
||||
key={def.key}
|
||||
className={`flex items-center gap-2 border-b px-3 py-2 text-sm ${
|
||||
def.key === selectedKey ? "bg-primary/10" : ""
|
||||
}`}
|
||||
className={`flex items-center gap-2 border-b px-3 py-2 text-sm ${rowStateClass(
|
||||
def.key === selectedKey,
|
||||
)}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -94,9 +96,9 @@ export function FieldList({
|
||||
>
|
||||
<span className="font-medium">{labelText(def.labels, lang)}</span>
|
||||
<span className="text-xs text-muted-foreground">{def.key}</span>
|
||||
<span className="rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
|
||||
<Badge variant="secondary">
|
||||
{t(`fields.types.${def.data_type}`)}
|
||||
</span>
|
||||
</Badge>
|
||||
{def.required && (
|
||||
<span
|
||||
className="text-xs text-destructive"
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
import type { components } from "../api/schema";
|
||||
import { useAuthorities, useTerms } from "../api/queries";
|
||||
import { useConfig } from "../config/config-context";
|
||||
import { useLang } from "../lib/use-lang";
|
||||
import { labelText } from "../lib/labels";
|
||||
import { OptionsCombobox } from "./options-combobox";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
@@ -27,9 +28,9 @@ export function FieldInput<TValues extends { fields: Record<string, unknown> }>(
|
||||
definition: FieldDefinitionView;
|
||||
form: FieldForm<TValues>;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const { default_language } = useConfig();
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
const lang = useLang();
|
||||
const label = labelText(definition.labels, lang);
|
||||
const name = fieldPath<TValues>(definition.key);
|
||||
const placeholder = t("form.selectPlaceholder");
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import { Drawer, DrawerClose, DrawerContent } from "@/components/ui/drawer";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/**
|
||||
* Narrow-viewport object detail: the nested <Outlet/> inside a Base UI Drawer that
|
||||
@@ -30,7 +31,7 @@ export function ObjectDetailDrawer({
|
||||
<div className="flex justify-end border-b p-2">
|
||||
<DrawerClose
|
||||
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" />
|
||||
</DrawerClose>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { useObject, useFieldDefinitions } from "../api/queries";
|
||||
import { useLang } from "../lib/use-lang";
|
||||
import { groupDefinitions } from "../lib/group-fields";
|
||||
import { formatDate } from "../lib/format-date";
|
||||
import { useDocumentTitle } from "../lib/use-document-title";
|
||||
@@ -49,14 +50,14 @@ export function ObjectDetail() {
|
||||
}
|
||||
|
||||
function ObjectDetailLoaded({ object }: { object: AdminObjectView }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const { data: definitions } = useFieldDefinitions();
|
||||
|
||||
useDocumentTitle(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.
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
const lang = useLang();
|
||||
const labelFor = (key: string) => {
|
||||
const labels = definitions?.find((d) => d.key === key)?.labels;
|
||||
const byLang = labels?.find((l) => l.lang === lang)?.label;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
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 { server } from "../test/server";
|
||||
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 () => {
|
||||
let postCount = 0;
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
server.use(
|
||||
http.post("/api/admin/objects", async () => {
|
||||
postCount += 1;
|
||||
await delay(50);
|
||||
await gate;
|
||||
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 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();
|
||||
|
||||
release();
|
||||
|
||||
await waitFor(() => expect(screen.getByText("detail view")).toBeInTheDocument());
|
||||
expect(postCount).toBe(1);
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ObjectsTable } from "./objects-table";
|
||||
import { useMediaQuery } from "../lib/use-media-query";
|
||||
import { useDocumentTitle } from "../lib/use-document-title";
|
||||
import { useBreadcrumb } from "../shell/use-breadcrumb";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PageTitle } from "@/components/ui/page-title";
|
||||
|
||||
const ObjectDetailDrawer = lazy(() =>
|
||||
@@ -47,14 +48,14 @@ export function ObjectsPage() {
|
||||
{open && (
|
||||
<div className="flex h-full flex-col overflow-hidden border-l">
|
||||
<div className="flex justify-end border-b p-2">
|
||||
<button
|
||||
type="button"
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
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>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-auto">
|
||||
<Outlet />
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { components } from "../api/schema";
|
||||
import { useObjectsPage } from "../api/queries";
|
||||
import { useDebouncedValue } from "../lib/use-debounced-value";
|
||||
import { focusRing } from "../lib/focus-ring";
|
||||
import { segmentClass, rowStateClass } from "../lib/class-recipes";
|
||||
import { useConfig } from "../config/config-context";
|
||||
import { VisibilityBadge } from "./visibility-badge";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
@@ -171,7 +172,7 @@ export function ObjectsTable() {
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
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}`)}
|
||||
</button>
|
||||
@@ -248,9 +249,7 @@ export function ObjectsTable() {
|
||||
<tr
|
||||
key={object.id}
|
||||
onClick={() => navigate(`/objects/${object.id}?${params}`)}
|
||||
className={`cursor-pointer border-b text-sm ${
|
||||
selected ? "bg-primary/10" : "hover:bg-muted"
|
||||
}`}
|
||||
className={`cursor-pointer border-b text-sm ${rowStateClass(selected)}`}
|
||||
>
|
||||
<td className="px-3 py-2 text-muted-foreground">
|
||||
<Link
|
||||
|
||||
@@ -4,9 +4,8 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useSearch, HttpError } from "../api/queries";
|
||||
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 { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ListSkeleton } from "@/components/ui/skeletons";
|
||||
@@ -73,7 +72,7 @@ export function SearchPanel() {
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
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}`)}
|
||||
</button>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NavLink } from "react-router-dom";
|
||||
|
||||
import type { components } from "../api/schema";
|
||||
import { VisibilityBadge } from "../objects/visibility-badge";
|
||||
import { rowStateClass } from "../lib/class-recipes";
|
||||
import { Highlight } from "./highlight";
|
||||
|
||||
type SearchHitView = components["schemas"]["SearchHitView"];
|
||||
@@ -12,7 +13,7 @@ export function SearchResultRow({ hit }: { hit: SearchHitView }) {
|
||||
<NavLink
|
||||
to={`/search/${hit.id}`}
|
||||
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>
|
||||
|
||||
@@ -20,7 +20,7 @@ export function HeaderSearch() {
|
||||
<form onSubmit={onSubmit} className="hidden sm:block">
|
||||
<div className="relative">
|
||||
<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
|
||||
/>
|
||||
<Input
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { focusRing } from "../lib/focus-ring";
|
||||
import { Tooltip } from "@/components/ui/tooltip";
|
||||
import { useMediaQuery } from "@/lib/use-media-query";
|
||||
import { useConfig } from "../config/config-context";
|
||||
@@ -43,7 +44,7 @@ function navLinkClass(collapsed: boolean) {
|
||||
return ({ isActive }: { isActive: boolean }) =>
|
||||
cn(
|
||||
"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",
|
||||
isActive && "bg-accent font-medium",
|
||||
);
|
||||
@@ -85,7 +86,8 @@ export function Sidebar() {
|
||||
title={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")}
|
||||
className={cn(
|
||||
"flex items-center justify-center rounded-md p-1 outline-none",
|
||||
"hover:bg-accent focus-visible:ring-3 focus-visible:ring-ring/50",
|
||||
"hover:bg-accent",
|
||||
focusRing,
|
||||
"disabled:pointer-events-none disabled:opacity-50",
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -36,7 +36,7 @@ export function ThemeSwitch() {
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4" aria-hidden />
|
||||
<Icon className="size-4" aria-hidden />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { delay, http, HttpResponse } from "msw";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { server } from "../test/server";
|
||||
import { renderApp } from "../test/render";
|
||||
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 () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
server.use(
|
||||
http.post("/api/admin/logout", async () => {
|
||||
await delay(50);
|
||||
await gate;
|
||||
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);
|
||||
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();
|
||||
|
||||
release();
|
||||
await waitFor(() => expect(menu.queryByText(/signing out/i)).toBeNull());
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ export function UserMenu() {
|
||||
<MenuTrigger
|
||||
render={
|
||||
<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>
|
||||
</Button>
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { NavLink } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
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 { DeleteConfirmDialog } from "../components/delete-confirm-dialog";
|
||||
import { MutationError } from "../components/mutation-error";
|
||||
@@ -12,9 +14,9 @@ import { Label } from "@/components/ui/label";
|
||||
import { ListSkeleton } from "@/components/ui/skeletons";
|
||||
|
||||
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();
|
||||
|
||||
@@ -110,7 +112,7 @@ export function VocabularyList() {
|
||||
<NavLink
|
||||
to={`/vocabularies/${v.id}`}
|
||||
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}
|
||||
|
||||
@@ -2,15 +2,16 @@ import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useTerms, useAddTerm, useVocabularies } from "../api/queries";
|
||||
import { useLang } from "../lib/use-lang";
|
||||
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 { t } = useTranslation();
|
||||
const { id } = useParams();
|
||||
const lang = i18n.language.startsWith("sv") ? "sv" : "en";
|
||||
const lang = useLang();
|
||||
|
||||
const { data: terms, isLoading, isError } = useTerms(id);
|
||||
const addTerm = useAddTerm();
|
||||
|
||||
@@ -28,6 +28,9 @@ export default defineConfig({
|
||||
extends: true,
|
||||
test: {
|
||||
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,
|
||||
setupFiles: ["./src/test/setup.ts"],
|
||||
environmentOptions: {
|
||||
@@ -46,6 +49,7 @@ export default defineConfig({
|
||||
})],
|
||||
test: {
|
||||
name: 'storybook',
|
||||
testTimeout: 20000,
|
||||
browser: {
|
||||
enabled: true,
|
||||
headless: true,
|
||||
|
||||
Reference in New Issue
Block a user