feat(persons): clean filterable paginated directory with crash fix

Rewrite /persons: server-side filter chips (type, family-only, has-documents)
that AND within the clean reader default (familyMember OR documentCount > 0),
a writer-only show-all/Zu-prüfen toggle, and reused Pagination. Extract
PersonCard (fixes the null-lastName render crash and never shows a "?" initial —
provisional/UNKNOWN/"?" entries get a neutral placeholder avatar + a text+icon
"unbestätigt" badge, WCAG 1.4.1) and PersonFilterBar (44px aria-pressed chips,
role=switch toggle with the count in its accessible name). The loader applies
the reader restriction unless review=1 and surfaces a cheap needsReviewCount.
i18n keys added for de/en/es.

Refs #667

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-05-27 13:55:18 +02:00
parent 67272178a9
commit 888adcb185
12 changed files with 802 additions and 87 deletions

View File

@@ -130,6 +130,29 @@
"persons_search_placeholder": "Namen suchen...",
"persons_empty_heading": "Keine Personen gefunden.",
"persons_empty_text": "Versuchen Sie einen anderen Suchbegriff.",
"persons_empty_filtered": "Keine Personen für diese Filter.",
"persons_filter_group_label": "Filter",
"persons_filter_type_person": "Person",
"persons_filter_type_group": "Gruppe",
"persons_filter_type_institution": "Institution",
"persons_filter_family_only": "Nur Familie",
"persons_filter_has_documents": "Mit Dokumenten",
"persons_toggle_show_all": "Alle anzeigen",
"persons_toggle_needs_review": "Zu prüfen ({count})",
"person_badge_unconfirmed": "unbestätigt",
"persons_review_heading": "Personen prüfen",
"persons_review_intro": "Vom Import erzeugte, noch nicht bestätigte Personen. Zusammenführen, umbenennen, bestätigen oder löschen.",
"persons_review_action_merge": "Zusammenführen",
"persons_review_action_rename": "Umbenennen",
"persons_review_action_confirm": "Bestätigen",
"persons_review_action_delete": "Löschen",
"persons_review_action_cancel": "Abbrechen",
"persons_review_action_save": "Speichern",
"persons_review_empty": "Keine Personen zu prüfen.",
"persons_review_delete_confirm_title": "Person löschen",
"persons_review_delete_confirm_text": "Diese Person wird endgültig gelöscht. Dokumentverweise bleiben erhalten, verlieren aber diese Person.",
"persons_review_delete_confirm_button": "Person löschen",
"persons_review_merge_label": "Mit welcher Person zusammenführen?",
"persons_new_heading": "Neue Person",
"persons_section_details": "Angaben zur Person",
"person_edit_heading": "Person bearbeiten",

View File

@@ -130,6 +130,29 @@
"persons_search_placeholder": "Search names...",
"persons_empty_heading": "No persons found.",
"persons_empty_text": "Try a different search term.",
"persons_empty_filtered": "No persons match these filters.",
"persons_filter_group_label": "Filter",
"persons_filter_type_person": "Person",
"persons_filter_type_group": "Group",
"persons_filter_type_institution": "Institution",
"persons_filter_family_only": "Family only",
"persons_filter_has_documents": "With documents",
"persons_toggle_show_all": "Show all",
"persons_toggle_needs_review": "Needs review ({count})",
"person_badge_unconfirmed": "unconfirmed",
"persons_review_heading": "Review persons",
"persons_review_intro": "Import-generated persons not yet confirmed. Merge, rename, confirm or delete.",
"persons_review_action_merge": "Merge",
"persons_review_action_rename": "Rename",
"persons_review_action_confirm": "Confirm",
"persons_review_action_delete": "Delete",
"persons_review_action_cancel": "Cancel",
"persons_review_action_save": "Save",
"persons_review_empty": "No persons to review.",
"persons_review_delete_confirm_title": "Delete person",
"persons_review_delete_confirm_text": "This person will be permanently deleted. Document references are kept but lose this person.",
"persons_review_delete_confirm_button": "Delete person",
"persons_review_merge_label": "Merge into which person?",
"persons_new_heading": "New person",
"persons_section_details": "Person details",
"person_edit_heading": "Edit person",

View File

@@ -130,6 +130,29 @@
"persons_search_placeholder": "Buscar nombres...",
"persons_empty_heading": "No se encontraron personas.",
"persons_empty_text": "Pruebe con otro término de búsqueda.",
"persons_empty_filtered": "Ninguna persona coincide con estos filtros.",
"persons_filter_group_label": "Filtro",
"persons_filter_type_person": "Persona",
"persons_filter_type_group": "Grupo",
"persons_filter_type_institution": "Institución",
"persons_filter_family_only": "Solo familia",
"persons_filter_has_documents": "Con documentos",
"persons_toggle_show_all": "Mostrar todo",
"persons_toggle_needs_review": "Por revisar ({count})",
"person_badge_unconfirmed": "sin confirmar",
"persons_review_heading": "Revisar personas",
"persons_review_intro": "Personas generadas por la importación aún sin confirmar. Fusionar, renombrar, confirmar o eliminar.",
"persons_review_action_merge": "Fusionar",
"persons_review_action_rename": "Renombrar",
"persons_review_action_confirm": "Confirmar",
"persons_review_action_delete": "Eliminar",
"persons_review_action_cancel": "Cancelar",
"persons_review_action_save": "Guardar",
"persons_review_empty": "No hay personas por revisar.",
"persons_review_delete_confirm_title": "Eliminar persona",
"persons_review_delete_confirm_text": "Esta persona se eliminará de forma permanente. Las referencias de documentos se conservan pero pierden a esta persona.",
"persons_review_delete_confirm_button": "Eliminar persona",
"persons_review_merge_label": "¿Fusionar con qué persona?",
"persons_new_heading": "Nueva persona",
"persons_section_details": "Datos de la persona",
"person_edit_heading": "Editar persona",

View File

@@ -0,0 +1,146 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates';
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
import type { components } from '$lib/generated/api';
type Person = components['schemas']['PersonSummaryDTO'];
let { person }: { person: Person } = $props();
// A card is "unconfirmed" when the importer could not identify the person: the explicit
// provisional flag, the placeholder UNKNOWN type, or a literal "?" name from the spreadsheet.
const isUnconfirmed = $derived(
person.provisional === true ||
person.personType === 'UNKNOWN' ||
person.lastName === '?' ||
(person.lastName ?? '').trim() === ''
);
// A non-PERSON type (institution/group) gets a glyph; everything that is a real, confirmed
// person gets initials. Unconfirmed persons never get a "?" initial — they get the neutral
// placeholder glyph instead. Reading lastName[0] on a null/empty name would throw, so the
// initials branch is gated on a non-empty name.
const showGlyph = $derived(
isUnconfirmed || (person.personType != null && person.personType !== 'PERSON')
);
const initials = $derived.by(() => {
const first = person.firstName?.[0] ?? '';
const last = person.lastName?.[0] ?? '';
return (first || last) + last;
});
const documentCount = $derived(person.documentCount ?? 0);
</script>
<a href="/persons/{person.id}" class="group block">
<div
class="flex h-full flex-col items-center gap-2 rounded border border-line bg-surface px-4 py-6 text-center shadow-sm transition-all duration-200 hover:border-l-4 hover:border-accent hover:shadow-md"
>
<!-- Avatar: confirmed persons get a primary-coloured initials disc; institutions/groups
and unconfirmed entries get a neutral, muted glyph so "unverified" is pre-attentive. -->
<div
class={[
'flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full font-serif text-base font-bold transition-colors',
isUnconfirmed ? 'bg-muted text-ink-2' : 'bg-primary text-primary-fg'
]}
>
{#if showGlyph}
{#if person.personType === 'INSTITUTION'}
<svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0H5m14 0h2m-2 0v-2M5 21H3m2 0v-2m4-12h2m-2 4h2m4-4h2m-2 4h2"
/>
</svg>
{:else if person.personType === 'GROUP'}
<svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
/>
</svg>
{:else}
<!-- Neutral person glyph for unconfirmed / UNKNOWN entries (never a "?" initial). -->
<img
src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Account-MD.svg"
alt=""
aria-hidden="true"
class="h-6 w-6 opacity-70"
/>
{/if}
{:else}
{initials}
{/if}
</div>
<!-- Name -->
<p class="font-serif text-sm font-bold text-ink group-hover:underline">
{person.displayName}
</p>
{#if isUnconfirmed}
<!-- State conveyed by text + the muted placeholder shape, never colour alone (WCAG 1.4.1). -->
<span
class="inline-flex items-center gap-1 rounded-full border border-line bg-muted px-2.5 py-0.5 font-sans text-xs font-semibold text-ink-2"
aria-label={m.person_badge_unconfirmed()}
>
<svg
class="h-3 w-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 9v3.75m0 3.75h.008M10.34 3.94l-7.5 12.99A1.5 1.5 0 004.14 19.5h15.72a1.5 1.5 0 001.3-2.57l-7.5-12.99a1.5 1.5 0 00-2.62 0z"
/>
</svg>
{m.person_badge_unconfirmed()}
</span>
{:else if person.personType && person.personType !== 'PERSON'}
<PersonTypeBadge personType={person.personType} />
{/if}
<!-- Alias -->
{#if person.alias}
<p class="font-sans text-sm text-ink-2 italic">{person.alias}"</p>
{/if}
<!-- Life dates -->
{#if person.birthYear || person.deathYear}
<p class="font-sans text-sm text-ink-3">
{formatLifeDateRange(person.birthYear, person.deathYear)}
</p>
{/if}
<!-- Doc count chip -->
{#if documentCount > 0}
<span
class="mt-1 inline-flex items-center rounded-full border border-line bg-muted px-2.5 py-0.5 font-sans text-sm font-semibold text-ink-2"
>
{documentCount === 1
? m.person_card_doc_count_one()
: m.person_card_doc_count_many({ count: documentCount })}
</span>
{/if}
</div>
</a>

View File

@@ -0,0 +1,66 @@
import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import PersonCard from './PersonCard.svelte';
import type { components } from '$lib/generated/api';
type Person = components['schemas']['PersonSummaryDTO'];
const makePerson = (overrides: Partial<Person> = {}): Person => ({
id: 'p-1',
firstName: 'Anna',
lastName: 'Schmidt',
displayName: 'Anna Schmidt',
personType: 'PERSON',
familyMember: false,
provisional: false,
documentCount: 0,
...overrides
});
afterEach(cleanup);
describe('PersonCard — confirmed person', () => {
it('renders the display name', async () => {
render(PersonCard, { props: { person: makePerson() } });
await expect.element(page.getByText('Anna Schmidt')).toBeVisible();
});
it('does not show an unconfirmed badge for a confirmed person', async () => {
render(PersonCard, { props: { person: makePerson() } });
await expect.element(page.getByText('unbestätigt')).not.toBeInTheDocument();
});
});
describe('PersonCard — unconfirmed / malformed (regression: null-lastName crash)', () => {
it('renders without throwing when lastName is null', async () => {
// Before the fix, `lastName[0]` threw at render for a null lastName.
const person = makePerson({
lastName: null as unknown as string,
displayName: '?',
provisional: true
});
render(PersonCard, { props: { person } });
// No throw + the placeholder avatar (an <img>) is present, never a "?" initial.
await expect.element(page.getByText('unbestätigt')).toBeVisible();
});
it('shows an unbestätigt badge for a provisional person', async () => {
render(PersonCard, { props: { person: makePerson({ provisional: true }) } });
await expect.element(page.getByText('unbestätigt')).toBeVisible();
});
it('shows a placeholder (no "?" initial) for a "?" name', async () => {
render(PersonCard, {
props: { person: makePerson({ firstName: undefined, lastName: '?', displayName: '?' }) }
});
await expect.element(page.getByText('unbestätigt')).toBeVisible();
});
it('treats an UNKNOWN type as unconfirmed', async () => {
render(PersonCard, {
props: { person: makePerson({ personType: 'UNKNOWN', displayName: 'Unklar' }) }
});
await expect.element(page.getByText('unbestätigt')).toBeVisible();
});
});

View File

@@ -0,0 +1,160 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { m } from '$lib/paraglide/messages.js';
type PersonType = 'PERSON' | 'INSTITUTION' | 'GROUP';
interface Props {
type?: PersonType;
familyOnly: boolean;
hasDocuments: boolean;
review: boolean;
needsReviewCount: number;
canWrite: boolean;
}
let { type, familyOnly, hasDocuments, review, needsReviewCount, canWrite }: Props = $props();
const typeChips: { value: PersonType; label: () => string }[] = [
{ value: 'PERSON', label: m.persons_filter_type_person },
{ value: 'GROUP', label: m.persons_filter_type_group },
{ value: 'INSTITUTION', label: m.persons_filter_type_institution }
];
// Compose the next URL from the live params so a chip toggle never wipes q / page / other
// active chips. Any filter change resets to page 0.
function navigate(mutate: (params: SvelteURLSearchParams) => void) {
const params = new SvelteURLSearchParams(page.url.searchParams);
params.delete('page');
mutate(params);
const qs = params.toString();
goto(qs ? `/persons?${qs}` : '/persons', { keepFocus: true, noScroll: true });
}
function toggleType(value: PersonType) {
navigate((params) => {
if (type === value) params.delete('type');
else params.set('type', value);
});
}
function toggleFlag(key: 'familyOnly' | 'hasDocuments', active: boolean) {
navigate((params) => {
if (active) params.delete(key);
else params.set(key, 'true');
});
}
function setReview(next: boolean) {
navigate((params) => {
if (next) params.set('review', 'true');
else params.delete('review');
});
}
const chipBase =
'inline-flex min-h-[44px] min-w-[44px] items-center gap-1.5 rounded-sm border px-4 py-2 font-sans text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:ring-offset-2 focus-visible:outline-none';
const chipActive = 'border-brand-navy bg-brand-navy text-white';
const chipInactive = 'border-line bg-surface text-ink hover:bg-muted';
</script>
<div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
<!-- Type + boolean filter chips -->
<div role="group" aria-label={m.persons_filter_group_label()} class="flex flex-wrap gap-2">
{#each typeChips as chip (chip.value)}
{@const active = type === chip.value}
<button
type="button"
aria-pressed={active}
class={[chipBase, active ? chipActive : chipInactive]}
onclick={() => toggleType(chip.value)}
>
{#if active}
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
{/if}
{chip.label()}
</button>
{/each}
<button
type="button"
aria-pressed={familyOnly}
class={[chipBase, familyOnly ? chipActive : chipInactive]}
onclick={() => toggleFlag('familyOnly', familyOnly)}
>
{#if familyOnly}
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
{/if}
{m.persons_filter_family_only()}
</button>
<button
type="button"
aria-pressed={hasDocuments}
class={[chipBase, hasDocuments ? chipActive : chipInactive]}
onclick={() => toggleFlag('hasDocuments', hasDocuments)}
>
{#if hasDocuments}
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
{/if}
{m.persons_filter_has_documents()}
</button>
</div>
<!-- Show-all / Zu prüfen toggle: transcriber-only, reveals the import noise. -->
{#if canWrite}
<button
type="button"
role="switch"
aria-checked={review}
aria-label={m.persons_toggle_needs_review({ count: needsReviewCount })}
class={[chipBase, 'sm:ml-auto', review ? chipActive : chipInactive]}
onclick={() => setReview(!review)}
>
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
/>
</svg>
{review ? m.persons_toggle_show_all() : m.persons_toggle_needs_review({ count: needsReviewCount })}
</button>
{/if}
</div>

View File

@@ -0,0 +1,90 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page as browserPage } from 'vitest/browser';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import PersonFilterBar from './PersonFilterBar.svelte';
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
vi.mock('$app/state', () => ({ page: { url: new URL('http://localhost/persons') } }));
const gotoMock = vi.mocked(goto);
function setUrl(search: string) {
(page as unknown as { url: URL }).url = new URL(`http://localhost/persons${search}`);
}
beforeEach(() => {
gotoMock.mockClear();
setUrl('');
});
afterEach(cleanup);
const baseProps = {
type: undefined,
familyOnly: false,
hasDocuments: false,
review: false,
needsReviewCount: 12,
canWrite: true
};
describe('PersonFilterBar — chip activation', () => {
it('activating a type chip sets type and resets page', async () => {
setUrl('?page=3&q=Anna');
render(PersonFilterBar, { props: baseProps });
await browserPage.getByRole('button', { name: 'Institution' }).click();
expect(gotoMock).toHaveBeenCalled();
const target = gotoMock.mock.calls.at(-1)![0] as string;
const url = new URL(target, 'http://localhost');
expect(url.searchParams.get('type')).toBe('INSTITUTION');
expect(url.searchParams.get('q')).toBe('Anna'); // preserved
expect(url.searchParams.get('page')).toBeNull(); // reset
});
it('activating "Nur Familie" sets familyOnly=true', async () => {
render(PersonFilterBar, { props: baseProps });
await browserPage.getByRole('button', { name: 'Nur Familie' }).click();
const target = gotoMock.mock.calls.at(-1)![0] as string;
const url = new URL(target, 'http://localhost');
expect(url.searchParams.get('familyOnly')).toBe('true');
});
it('deactivating an already-active chip removes the param', async () => {
render(PersonFilterBar, { props: { ...baseProps, hasDocuments: true } });
await browserPage.getByRole('button', { name: 'Mit Dokumenten' }).click();
const target = gotoMock.mock.calls.at(-1)![0] as string;
const url = new URL(target, 'http://localhost');
expect(url.searchParams.get('hasDocuments')).toBeNull();
});
});
describe('PersonFilterBar — review toggle', () => {
it('renders a switch with the needs-review count in its accessible name', async () => {
render(PersonFilterBar, { props: baseProps });
await expect
.element(browserPage.getByRole('switch', { name: /Zu prüfen \(12\)/ }))
.toBeVisible();
});
it('is hidden for users without write permission', async () => {
render(PersonFilterBar, { props: { ...baseProps, canWrite: false } });
await expect.element(browserPage.getByRole('switch')).not.toBeInTheDocument();
});
it('toggling on sets review=true', async () => {
render(PersonFilterBar, { props: baseProps });
await browserPage.getByRole('switch').click();
const target = gotoMock.mock.calls.at(-1)![0] as string;
const url = new URL(target, 'http://localhost');
expect(url.searchParams.get('review')).toBe('true');
});
});

View File

@@ -2,8 +2,23 @@ import { error } from '@sveltejs/kit';
import { createApiClient } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';
const PAGE_SIZE = 50;
type PersonType = 'PERSON' | 'INSTITUTION' | 'GROUP';
function parseType(raw: string | null): PersonType | undefined {
return raw === 'PERSON' || raw === 'INSTITUTION' || raw === 'GROUP' ? raw : undefined;
}
export async function load({ url, fetch, locals }) {
const q = url.searchParams.get('q') || '';
const page = Math.max(0, Number.parseInt(url.searchParams.get('page') ?? '0', 10) || 0);
const review =
url.searchParams.get('review') === '1' || url.searchParams.get('review') === 'true';
const type = parseType(url.searchParams.get('type'));
const familyOnly = url.searchParams.get('familyOnly') === 'true';
const hasDocuments = url.searchParams.get('hasDocuments') === 'true';
const api = createApiClient(fetch);
const canWrite =
@@ -11,15 +26,32 @@ export async function load({ url, fetch, locals }) {
g.permissions.includes('WRITE_ALL')
) ?? false;
const [personsResult, statsResult] = await Promise.all([
api.GET('/api/persons', { params: { query: { q: q || undefined } } }),
api.GET('/api/stats', {})
const filters = {
q: q || undefined,
type,
familyOnly: familyOnly || undefined,
hasDocuments: hasDocuments || undefined,
review: review || undefined,
page,
size: PAGE_SIZE
};
// The "Zu prüfen (N)" link count is the totalElements of a provisional-only query. A size=1
// page keeps the extra request cheap — we only need the count, not the rows.
const [personsResult, statsResult, reviewCountResult] = await Promise.all([
api.GET('/api/persons', { params: { query: filters } }),
api.GET('/api/stats', {}),
canWrite
? api.GET('/api/persons', { params: { query: { provisional: true, review: true, size: 1 } } })
: Promise.resolve(null)
]);
if (!personsResult.response.ok) {
throw error(personsResult.response.status, getErrorMessage(undefined));
}
const result = personsResult.data!;
const stats = statsResult.response.ok
? {
totalPersons: statsResult.data!.totalPersons ?? 0,
@@ -27,5 +59,21 @@ export async function load({ url, fetch, locals }) {
}
: { totalPersons: 0, totalDocuments: 0 };
return { persons: personsResult.data!, stats, q, canWrite };
const needsReviewCount =
reviewCountResult && reviewCountResult.response.ok
? (reviewCountResult.data!.totalElements ?? 0)
: 0;
return {
persons: result.items,
totalElements: result.totalElements,
totalPages: result.totalPages,
pageNumber: result.pageNumber,
pageSize: result.pageSize,
filters: { type, familyOnly, hasDocuments, review },
needsReviewCount,
stats,
q,
canWrite
};
}

View File

@@ -1,9 +1,12 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { untrack } from 'svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates';
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
import PersonCard from '$lib/person/PersonCard.svelte';
import PersonFilterBar from '$lib/person/PersonFilterBar.svelte';
import Pagination from '$lib/shared/primitives/Pagination.svelte';
import PersonsStatsBar from './PersonsStatsBar.svelte';
import PersonsEmptyState from './PersonsEmptyState.svelte';
@@ -18,12 +21,31 @@ $effect(() => {
let searchTimeout: ReturnType<typeof setTimeout>;
// Debounced search must preserve the active filters/review flag — compose over the live URL,
// never a bare `?q=` that would wipe page/type/review.
function handleSearch() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
goto(`/persons?q=${q}`, { keepFocus: true });
const params = new SvelteURLSearchParams(page.url.searchParams);
params.delete('page');
if (q) params.set('q', q);
else params.delete('q');
const qs = params.toString();
goto(qs ? `/persons?${qs}` : '/persons', { keepFocus: true });
}, 300);
}
// Pagination links preserve every active param and only change the page index.
function buildPageHref(targetPage: number): string {
const params = new SvelteURLSearchParams(page.url.searchParams);
params.set('page', String(targetPage));
return `/persons?${params.toString()}`;
}
const hasResults = $derived(data.persons.length > 0);
const noFiltersActive = $derived(
!data.q && !data.filters.type && !data.filters.familyOnly && !data.filters.hasDocuments
);
</script>
<svelte:head>
@@ -32,7 +54,7 @@ function handleSearch() {
<div class="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
<!-- Header: title+stats on left, search+CTA on right -->
<div class="mb-10 flex flex-wrap items-end justify-between gap-4 border-b border-ink/10 pb-6">
<div class="mb-6 flex flex-wrap items-end justify-between gap-4 border-b border-ink/10 pb-6">
<div>
<h1 class="font-serif text-3xl font-medium text-ink">{m.page_title_persons()}</h1>
<div class="mt-2">
@@ -46,7 +68,7 @@ function handleSearch() {
<div class="flex items-center gap-3">
<!-- Search -->
<div class="relative">
<label for="search" class="sr-only">Suche</label>
<label for="search" class="sr-only">{m.persons_search_placeholder()}</label>
<input
id="search"
type="text"
@@ -69,11 +91,21 @@ function handleSearch() {
</div>
</div>
<!-- Triage link (transcriber only) -->
{#if data.canWrite}
<a
href="/persons/review"
class="inline-flex min-h-[44px] items-center gap-1.5 rounded-sm border border-line bg-surface px-4 py-2 font-sans text-sm font-semibold text-ink transition-colors hover:bg-muted"
>
{m.persons_toggle_needs_review({ count: data.needsReviewCount })}
</a>
{/if}
<!-- New person CTA -->
{#if data.canWrite}
<a
href="/persons/new"
class="inline-flex items-center gap-1.5 rounded-sm bg-primary px-4 py-2.5 font-sans text-sm font-bold tracking-wide text-primary-fg transition-colors hover:bg-primary/80"
class="inline-flex min-h-[44px] items-center gap-1.5 rounded-sm bg-primary px-4 py-2.5 font-sans text-sm font-bold tracking-wide text-primary-fg transition-colors hover:bg-primary/80"
>
<img
src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Add/Add-General-MD.svg"
@@ -87,86 +119,35 @@ function handleSearch() {
</div>
</div>
{#if data.persons.length === 0}
<PersonsEmptyState />
<!-- Filter chips + show-all toggle -->
<div class="mb-8">
<PersonFilterBar
type={data.filters.type}
familyOnly={data.filters.familyOnly}
hasDocuments={data.filters.hasDocuments}
review={data.filters.review}
needsReviewCount={data.needsReviewCount}
canWrite={data.canWrite}
/>
</div>
{#if !hasResults}
{#if noFiltersActive}
<PersonsEmptyState />
{:else}
<div
class="flex flex-col items-center justify-center rounded-lg border border-dashed border-line bg-surface py-16 text-center"
>
<p class="font-serif text-lg text-ink">{m.persons_empty_filtered()}</p>
</div>
{/if}
{:else}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{#each data.persons as person (person.id)}
<a href="/persons/{person.id}" class="group block">
<div
class="flex h-full flex-col items-center gap-2 rounded border border-line bg-surface px-4 py-6 text-center shadow-sm transition-all duration-200 hover:border-l-4 hover:border-accent hover:shadow-md"
>
<!-- Avatar -->
<div
class="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-primary font-serif text-base font-bold text-primary-fg transition-colors"
>
{#if person.personType && person.personType !== 'PERSON'}
<svg
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
{#if person.personType === 'INSTITUTION'}
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0H5m14 0h2m-2 0v-2M5 21H3m2 0v-2m4-12h2m-2 4h2m4-4h2m-2 4h2"
/>
{:else if person.personType === 'GROUP'}
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
/>
{:else}
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01"
/>
{/if}
</svg>
{:else}
{person.firstName ? person.firstName[0] : person.lastName[0]}{person.lastName[0]}
{/if}
</div>
<!-- Name -->
<p class="font-serif text-sm font-bold text-ink group-hover:underline">
{person.displayName}
</p>
{#if person.personType && person.personType !== 'PERSON'}
<PersonTypeBadge personType={person.personType} />
{/if}
<!-- Alias -->
{#if person.alias}
<p class="font-sans text-xs text-ink-2 italic">{person.alias}"</p>
{/if}
<!-- Life dates -->
{#if person.birthYear || person.deathYear}
<p class="font-sans text-[11px] text-ink-3">
{formatLifeDateRange(person.birthYear, person.deathYear)}
</p>
{/if}
<!-- Doc count chip -->
{#if (person.documentCount ?? 0) > 0}
<span
class="mt-1 inline-flex items-center rounded-full border border-line bg-muted px-2.5 py-0.5 font-sans text-[11px] font-semibold text-ink-2"
>
{person.documentCount === 1
? m.person_card_doc_count_one()
: m.person_card_doc_count_many({ count: person.documentCount ?? 0 })}
</span>
{/if}
</div>
</a>
<PersonCard person={person} />
{/each}
</div>
<Pagination page={data.pageNumber} totalPages={data.totalPages} makeHref={buildPageHref} />
{/if}
</div>

View File

@@ -0,0 +1,137 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
vi.mock('$lib/shared/api.server', () => ({
createApiClient: vi.fn(),
extractErrorCode: (e: unknown) => (e as { code?: string } | undefined)?.code
}));
import { load } from './+page.server';
import { createApiClient } from '$lib/shared/api.server';
beforeEach(() => vi.clearAllMocks());
function makeUrl(params: Record<string, string> = {}) {
const url = new URL('http://localhost/persons');
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
return url;
}
/** Invokes the loader with a minimal event; the partial event is cast to satisfy the type. */
function runLoad(url: URL, user: unknown) {
return load({
url,
fetch: vi.fn() as unknown as typeof fetch,
request: new Request('http://localhost/persons'),
locals: { user } as App.Locals
} as unknown as Parameters<typeof load>[0]);
}
/** Mock the typed client. /api/persons returns a paged envelope; /api/stats returns counts. */
function mockApi() {
const personsResult = {
response: { ok: true, status: 200 },
data: { items: [], totalElements: 0, pageNumber: 0, pageSize: 50, totalPages: 0 }
};
// Loose `...args` signature (matching the documents loader spec) so call tuples aren't
// narrowed to length 1 — the test inspects calls[i][1].params.query.
const get = vi.fn((...args: unknown[]) => {
if (args[0] === '/api/stats') {
return Promise.resolve({
response: { ok: true, status: 200 },
data: { totalPersons: 7, totalDocuments: 3 }
});
}
return Promise.resolve(personsResult);
});
vi.mocked(createApiClient).mockReturnValue({ GET: get } as unknown as ReturnType<
typeof createApiClient
>);
return get;
}
const writer = { groups: [{ permissions: ['READ_ALL', 'WRITE_ALL'] }] };
const reader = { groups: [{ permissions: ['READ_ALL'] }] };
type GetCall = [string, { params: { query: Record<string, unknown> } }];
/** Find the GET call to a path, optionally narrowing by a query predicate. */
function findCall(
get: ReturnType<typeof vi.fn>,
path: string,
matchQuery?: (q: Record<string, unknown>) => boolean
): GetCall | undefined {
return (get.mock.calls as unknown as GetCall[]).find(
(c) => c[0] === path && (!matchQuery || matchQuery(c[1].params.query))
);
}
describe('persons page load — reader default', () => {
it('does NOT pass review when no review param is present (clean reader default)', async () => {
const get = mockApi();
await runLoad(makeUrl(), reader);
const personsCall = findCall(get, '/api/persons');
expect(personsCall?.[1].params.query.review).toBeUndefined();
});
it('passes review=true when review=1 is in the URL', async () => {
const get = mockApi();
await runLoad(makeUrl({ review: '1' }), reader);
const personsCall = findCall(get, '/api/persons');
expect(personsCall?.[1].params.query.review).toBe(true);
});
});
describe('persons page load — filter forwarding', () => {
it('forwards type, familyOnly, hasDocuments and page to the API', async () => {
const get = mockApi();
await runLoad(
makeUrl({ type: 'INSTITUTION', familyOnly: 'true', hasDocuments: 'true', page: '2' }),
reader
);
const personsCall = findCall(get, '/api/persons');
expect(personsCall?.[1].params.query).toMatchObject({
type: 'INSTITUTION',
familyOnly: true,
hasDocuments: true,
page: 2,
size: 50
});
});
it('clamps a negative page to 0', async () => {
const get = mockApi();
await runLoad(makeUrl({ page: '-5' }), reader);
const personsCall = findCall(get, '/api/persons');
expect(personsCall?.[1].params.query.page).toBe(0);
});
});
describe('persons page load — needsReviewCount', () => {
it('fires a provisional count request for writers', async () => {
const get = mockApi();
await runLoad(makeUrl(), writer);
const provisionalCall = findCall(get, '/api/persons', (query) => query.provisional === true);
expect(provisionalCall).toBeDefined();
});
it('does not fire a provisional count request for read-only users', async () => {
const get = mockApi();
const result = await runLoad(makeUrl(), reader);
const provisionalCall = findCall(get, '/api/persons', (query) => query.provisional === true);
expect(provisionalCall).toBeUndefined();
expect(result.needsReviewCount).toBe(0);
expect(result.canWrite).toBe(false);
});
});

View File

@@ -6,6 +6,7 @@ import Page from './+page.svelte';
const tick = () => new Promise((r) => setTimeout(r, 0));
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
vi.mock('$app/state', () => ({ page: { url: new URL('http://localhost/persons') } }));
const makePerson = (overrides = {}) => ({
id: '1',
@@ -13,6 +14,8 @@ const makePerson = (overrides = {}) => ({
lastName: 'Mustermann',
displayName: 'Max Mustermann',
documentCount: 0,
provisional: false,
personType: 'PERSON',
...overrides
});
@@ -24,7 +27,13 @@ const emptyData = {
canBlogWrite: false,
q: '',
persons: [],
stats: defaultStats
stats: defaultStats,
totalElements: 0,
totalPages: 0,
pageNumber: 0,
pageSize: 50,
filters: { type: undefined, familyOnly: false, hasDocuments: false, review: false },
needsReviewCount: 0
};
const dataWithPersons = {
...emptyData,

View File

@@ -16,6 +16,8 @@ vi.mock('$app/navigation', () => ({
onNavigate: () => () => {}
}));
vi.mock('$app/state', () => ({ page: { url: new URL('http://localhost/persons') } }));
const { default: PersonsListPage } = await import('./+page.svelte');
afterEach(cleanup);
@@ -31,8 +33,15 @@ const baseData = (overrides: Record<string, unknown> = {}) => ({
birthYear?: number;
deathYear?: number;
documentCount?: number;
provisional?: boolean;
}>,
stats: { totalPersons: 0, totalDocuments: 0 },
totalElements: 0,
totalPages: 0,
pageNumber: 0,
pageSize: 50,
filters: { type: undefined, familyOnly: false, hasDocuments: false, review: false },
needsReviewCount: 0,
canWrite: false,
q: '',
...overrides