feat(timeline): show curator event note on Zeitstrahl (#844) #883

Merged
marcel merged 6 commits from feat/issue-844-event-note into main 2026-06-16 16:27:54 +02:00
15 changed files with 305 additions and 11 deletions

View File

@@ -209,3 +209,11 @@
| REQ-013 | `GET /api/timeline` failure → existing localized error state via `getErrorMessage(code)` (unchanged #779) | #850 | inline-event-clustering | `frontend/src/routes/zeitstrahl/+page.svelte` (unchanged error path) | covered by #779 `zeitstrahl` error-state tests (regression — no change) | Done |
| REQ-014 | HISTORICAL curated event with ≥1 linked letter keeps its full-width WorldBand — never clusters into a card (preserves #779 REQ-009); its letters stay loose | #850 | inline-event-clustering | `frontend/src/lib/timeline/eventClustering.ts` (`buildEventLookup` excludes HISTORICAL) | `eventClustering.spec.ts#excludes a HISTORICAL event so its letters stay loose, keeping its WorldBand (REQ-014)`; `TimelineView.svelte.spec.ts#keeps a HISTORICAL event a WorldBand with a same-year linked letter — never clusters (REQ-014)` | Done |
| REQ-015 | a cross-year ✉ card is placed at its earliest linked letter's chronological position in the band — never appended after later-dated loose letters | #850 | inline-event-clustering | `frontend/src/lib/timeline/YearBand.svelte` | `YearBand.svelte.spec.ts#interleaves a cross-year card before a later-dated loose letter in the same band (REQ-015)` | Done |
| REQ-001 | `TimelineEvent.description` flows through `TimelineEntryDTO` to the frontend; null for letters and derived events | #844 | event-note-display | `backend/.../timeline/TimelineEntryDTO.java`, `backend/.../timeline/TimelineService.java#mapEvent`, `frontend/src/lib/generated/api.ts` | `TimelineServiceTest#mapEvent_populates_description_from_event`, `#mapEvent_leaves_description_null_when_event_has_none`, `#mapDocument_leaves_description_null_for_letter`; `TimelineControllerTest#timelineIncludesEventDescription` | Done |
| REQ-002 | description text is HTML-escaped; no `{@html}` — Svelte `{...}` interpolation ensures XSS safety (CWE-79) | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#escapesHtml — renders XSS payload as inert text, no injected element` | Done |
| REQ-003 | newlines in the description are preserved visually via `white-space: pre-line` | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#preservesLineBreaks — note element carries whitespace-pre-line class` | Done |
| REQ-004 | description renders below the title/subtitle line in EventPill (PERSONAL) and WorldBand (HISTORICAL) | #844 | event-note-display | `frontend/src/lib/timeline/EventPill.svelte`, `frontend/src/lib/timeline/WorldBand.svelte` | `e2e/zeitstrahl-note.spec.ts#PERSONAL curated event note appears below its title`, `#HISTORICAL curated event note appears below its title` | Done |
| REQ-005 | description longer than 3 lines is clamped and shows a disclosure toggle with aria-expanded=false (show more) | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#clampsAndShowsToggle — long note shows "mehr anzeigen" with aria-expanded=false` | Done |
| REQ-006 | short description (≤ 3 lines) renders fully with no toggle | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#shortNoteNoToggle — a one-line note renders fully with no disclosure control` | Done |
| REQ-007 | clicking the toggle expands the note (aria-expanded=true, "show less"); clicking again collapses it | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#toggleExpandsCollapses — click expands, re-click collapses` | Done |
| REQ-008 | null, empty, or blank-only description renders nothing (no note element in DOM) | #844 | event-note-display | `frontend/src/lib/timeline/EventNote.svelte` | `event-note.svelte.spec.ts#blankNoteRendersNothing — null/empty string/blank-only string produces no note element` (3 cases) | Done |

View File

@@ -35,6 +35,11 @@ import java.util.UUID;
* entries. Deliberately NOT {@code @Schema(requiredMode = REQUIRED)} so the generated TypeScript
* type stays optional.
*
* <p><b>Event description ({@code description}):</b> curator-authored context note for a curated
* {@link Kind#EVENT} entry (#844). Populated from {@link TimelineEvent#getDescription()} — null
* for {@link Kind#LETTER} and derived entries. Deliberately NOT
* {@code @Schema(requiredMode = REQUIRED)} so the generated TypeScript type stays optional.
*
* <p>Callers of {@code TimelineEventService.assembleDerivedEvents()} must independently enforce
* {@code READ_ALL} authorization before invoking that method (see ADR-043).
*/
@@ -55,6 +60,7 @@ public record TimelineEntryDTO(
UUID rootTagId,
String rootTagName,
String rootTagColor,
UUID linkedEventId
UUID linkedEventId,
String description
) {
}

View File

@@ -267,7 +267,7 @@ public class TimelineEventService {
p.getBirthDate(), null,
p.getDisplayName(), EventType.PERSONAL,
null, null, List.of(p.getId()), DerivedEventType.BIRTH,
null, null, null, null))
null, null, null, null, null))
.toList();
}
@@ -279,7 +279,7 @@ public class TimelineEventService {
p.getDeathDate(), null,
p.getDisplayName(), EventType.PERSONAL,
null, null, List.of(p.getId()), DerivedEventType.DEATH,
null, null, null, null))
null, null, null, null, null))
.toList();
}
@@ -304,7 +304,7 @@ public class TimelineEventService {
null, null,
List.of(r.getPerson().getId(), r.getRelatedPerson().getId()),
DerivedEventType.MARRIAGE,
null, null, null, null));
null, null, null, null, null));
}
}
return result;

View File

@@ -238,7 +238,8 @@ public class TimelineService {
null,
null,
null,
null
null,
ev.getDescription()
);
}
@@ -262,7 +263,8 @@ public class TimelineService {
root == null ? null : root.id(),
root == null ? null : root.name(),
root == null ? null : root.color(),
eventByDocId.get(doc.getId())
eventByDocId.get(doc.getId()),
null
);
}

View File

@@ -74,6 +74,28 @@ class TimelineControllerTest {
.andExpect(jsonPath("$.undated").isArray());
}
// ─── REQ-001: description field serialised ───────────────────────────────
@Test
@org.springframework.security.test.context.support.WithMockUser(authorities = "READ_ALL")
void timelineIncludesEventDescription() throws Exception {
// REQ-001 (controller slice): a curated event entry with description "Kontext" is
// serialised into the timeline response at the correct JSON path.
var entry = new TimelineEntryDTO(Kind.EVENT, org.raddatz.familienarchiv.document.DatePrecision.DAY,
false, "", "",
java.time.LocalDate.of(1914, 8, 1), null, "Kriegsbeginn",
EventType.HISTORICAL, UUID.randomUUID(), null, List.of(), null,
null, null, null, null, "Kontext");
when(timelineService.assemble(any()))
.thenReturn(new TimelineDTO(
List.of(new TimelineYearDTO(1914, List.of(entry))),
List.of()));
mockMvc.perform(get("/api/timeline"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.years[0].entries[0].description", is("Kontext")));
}
// ─── Parameter binding ────────────────────────────────────────────────────
@Test

View File

@@ -69,10 +69,10 @@ class TimelineServiceTest {
UUID id2 = UUID.fromString("00000000-0000-0000-0000-000000000002");
var e1 = new TimelineEntryDTO(Kind.LETTER, DatePrecision.DAY, false, "", "",
LocalDate.of(1914, 7, 28), null, "Same Title", null, null, id1, List.of(), null,
null, null, null, null);
null, null, null, null, null);
var e2 = new TimelineEntryDTO(Kind.LETTER, DatePrecision.DAY, false, "", "",
LocalDate.of(1914, 7, 28), null, "Same Title", null, null, id2, List.of(), null,
null, null, null, null);
null, null, null, null, null);
var sorted = List.of(e2, e1).stream()
.sorted(TimelineService.WITHIN_BAND_ORDER)
@@ -511,6 +511,53 @@ class TimelineServiceTest {
verify(tagService, times(1)).resolveRootTags(anyList());
}
// ─── event description (#844, REQ-001) ───────────────────────────────────
@Test
void mapEvent_populates_description_from_event() {
// REQ-001: a curated event with a description surfaces it on the assembled entry.
TimelineEvent ev = TimelineEvent.builder().id(UUID.randomUUID())
.title("Kriegsbeginn").type(EventType.HISTORICAL)
.eventDate(LocalDate.of(1914, 8, 1)).precision(DatePrecision.DAY)
.description("Kontext")
.build();
when(eventRepository.findAll()).thenReturn(List.of(ev));
when(timelineEventService.assembleDerivedEvents()).thenReturn(List.of());
when(documentService.getAllForTimeline()).thenReturn(List.of());
TimelineDTO result = timelineService.assemble(noFilters());
TimelineEntryDTO entry = result.years().get(0).entries().get(0);
assertThat(entry.description()).isEqualTo("Kontext");
}
@Test
void mapEvent_leaves_description_null_when_event_has_none() {
// REQ-001: an event without a description → null on the entry.
TimelineEvent ev = TimelineEvent.builder().id(UUID.randomUUID())
.title("Ereignis").type(EventType.PERSONAL)
.eventDate(LocalDate.of(1920, 1, 1)).precision(DatePrecision.YEAR)
.build();
when(eventRepository.findAll()).thenReturn(List.of(ev));
when(timelineEventService.assembleDerivedEvents()).thenReturn(List.of());
when(documentService.getAllForTimeline()).thenReturn(List.of());
TimelineEntryDTO entry = timelineService.assemble(noFilters()).years().get(0).entries().get(0);
assertThat(entry.description()).isNull();
}
@Test
void mapDocument_leaves_description_null_for_letter() {
// REQ-001: LETTER entries carry null description, regardless of any document fields.
Document doc = docWithDate(LocalDate.of(1916, 3, 1), DatePrecision.MONTH);
when(eventRepository.findAll()).thenReturn(List.of());
when(timelineEventService.assembleDerivedEvents()).thenReturn(List.of());
when(documentService.getAllForTimeline()).thenReturn(List.of(doc));
TimelineEntryDTO entry = onlyLetterEntry(timelineService.assemble(noFilters()));
assertThat(entry.description()).isNull();
}
// ─── letter→event link (#850, REQ-009) ───────────────────────────────────
@Test
@@ -623,7 +670,7 @@ class TimelineServiceTest {
private static TimelineEntryDTO letter(LocalDate date, DatePrecision precision, String title) {
return new TimelineEntryDTO(Kind.LETTER, precision, false, "", "",
date, null, title, null, null, UUID.randomUUID(), List.of(), null,
null, null, null, null);
null, null, null, null, null);
}
private static Document docWithDate(LocalDate date, DatePrecision precision) {

View File

@@ -0,0 +1,77 @@
import { test, expect, type APIRequestContext } from '@playwright/test';
/**
* Curator-note display on /zeitstrahl (#844) — validates that a description saved
* against a curated timeline event surfaces in the DOM under that event's title.
* Covers REQ-001 (description flows from backend) and REQ-004 (rendered below title).
*/
const stamp = () => new Date().toISOString().replace(/[^0-9]/g, '');
async function createEvent(
request: APIRequestContext,
type: 'PERSONAL' | 'HISTORICAL',
title: string,
description: string
): Promise<string> {
const res = await request.post('/api/timeline/events', {
data: {
title,
type,
eventDate: '1918-11-11',
precision: 'DAY',
description
}
});
if (!res.ok()) throw new Error(`create event failed: ${res.status()} ${await res.text()}`);
return (await res.json()).id as string;
}
async function deleteEvent(request: APIRequestContext, id: string): Promise<void> {
await request.delete(`/api/timeline/events/${id}`);
}
test.describe('Zeitstrahl event note (#844)', () => {
let personalEventId: string;
let historicalEventId: string;
const personalTitle = `E2E Persönlich ${stamp()}`;
const historicalTitle = `E2E Historisch ${stamp()}`;
const personalNote = 'Persönliche Notiz für diesen Moment.';
const historicalNote = 'Historischer Kontext für dieses Ereignis.';
test.beforeAll(async ({ request }) => {
personalEventId = await createEvent(request, 'PERSONAL', personalTitle, personalNote);
historicalEventId = await createEvent(request, 'HISTORICAL', historicalTitle, historicalNote);
});
test.afterAll(async ({ request }) => {
if (personalEventId) await deleteEvent(request, personalEventId);
if (historicalEventId) await deleteEvent(request, historicalEventId);
});
test('PERSONAL curated event note appears below its title on /zeitstrahl (REQ-001, REQ-004)', async ({
page
}) => {
await page.goto('/zeitstrahl');
const personalEntry = page.locator('li').filter({ hasText: personalTitle }).first();
await expect(personalEntry).toBeVisible({ timeout: 10000 });
const note = personalEntry.locator('[data-testid="event-note"]');
await expect(note).toBeVisible();
await expect(note).toContainText(personalNote);
});
test('HISTORICAL curated event note appears below its title on /zeitstrahl (REQ-001, REQ-004)', async ({
page
}) => {
await page.goto('/zeitstrahl');
const historicalEntry = page.locator('li').filter({ hasText: historicalTitle }).first();
await expect(historicalEntry).toBeVisible({ timeout: 10000 });
const note = historicalEntry.locator('[data-testid="event-note"]');
await expect(note).toBeVisible();
await expect(note).toContainText(historicalNote);
});
});

View File

@@ -1069,6 +1069,8 @@
"timeline_filter_trigger_active": "Filter ({count} aktiv)",
"timeline_filter_reset": "Filter zurücksetzen",
"timeline_filter_empty_state": "Keine Einträge entsprechen diesen Filtern.",
"timeline_note_show_more": "mehr anzeigen",
"timeline_note_show_less": "weniger anzeigen",
"event_editor_new_title": "Neues Ereignis",
"event_editor_edit_title": "Ereignis bearbeiten",
"event_editor_section_when": "Wann",

View File

@@ -1069,6 +1069,8 @@
"timeline_filter_trigger_active": "Filter ({count} active)",
"timeline_filter_reset": "Reset filters",
"timeline_filter_empty_state": "No entries match these filters.",
"timeline_note_show_more": "show more",
"timeline_note_show_less": "show less",
"event_editor_new_title": "New event",
"event_editor_edit_title": "Edit event",
"event_editor_section_when": "When",

View File

@@ -1069,6 +1069,8 @@
"timeline_filter_trigger_active": "Filtro ({count} activos)",
"timeline_filter_reset": "Restablecer filtros",
"timeline_filter_empty_state": "Ninguna entrada coincide con estos filtros.",
"timeline_note_show_more": "mostrar más",
"timeline_note_show_less": "mostrar menos",
"event_editor_new_title": "Nuevo evento",
"event_editor_edit_title": "Editar evento",
"event_editor_section_when": "Cuándo",

View File

@@ -2469,6 +2469,7 @@ export interface components {
rootTagColor?: string;
/** Format: uuid */
linkedEventId?: string;
description?: string;
};
TimelineYearDTO: {
/** Format: int32 */
@@ -2648,11 +2649,11 @@ export interface components {
empty?: boolean;
};
PageableObject: {
paged?: boolean;
/** Format: int32 */
pageNumber?: number;
/** Format: int32 */
pageSize?: number;
paged?: boolean;
/** Format: int64 */
offset?: number;
sort?: components["schemas"]["SortObject"];

View File

@@ -0,0 +1,47 @@
<script lang="ts">
import * as m from '$lib/paraglide/messages.js';
let { description }: { description?: string | null } = $props();
let expanded = $state(false);
let clamped = $state(false);
let noteEl: HTMLElement | undefined = $state();
$effect(() => {
if (noteEl) {
clamped = noteEl.scrollHeight > noteEl.clientHeight;
}
});
function toggle() {
expanded = !expanded;
}
const hasContent = $derived(!!description && description.trim().length > 0);
</script>
{#if hasContent}
<div class="mt-1">
<p
data-testid="event-note"
bind:this={noteEl}
class="font-sans text-xs whitespace-pre-line text-ink-2"
style={expanded
? 'white-space:pre-line'
: 'white-space:pre-line;overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3'}
>
{description}
</p>
{#if clamped || expanded}
<button
data-testid="note-toggle"
type="button"
class="mt-0.5 font-sans text-xs text-ink-3 hover:text-brand-navy focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-navy"
aria-expanded={expanded ? 'true' : 'false'}
onclick={toggle}
>
{expanded ? m.timeline_note_show_less() : m.timeline_note_show_more()}
</button>
{/if}
</div>
{/if}

View File

@@ -1,5 +1,6 @@
<script lang="ts">
import EventHeader from './EventHeader.svelte';
import EventNote from './EventNote.svelte';
import { getAccentConfig } from './eventCardConfig';
import type { components } from '$lib/generated/api';
@@ -18,7 +19,7 @@ let { entry, canWrite = false }: { entry: TimelineEntryDTO; canWrite?: boolean }
const config = $derived(getAccentConfig(entry));
</script>
<div class="flex justify-center">
<div class="flex flex-col items-center justify-center">
<div
class="inline-flex items-center gap-2 rounded-full bg-surface px-3 py-1 shadow-sm {config.accent ===
'curated'
@@ -27,4 +28,5 @@ const config = $derived(getAccentConfig(entry));
>
<EventHeader entry={entry} canWrite={canWrite} />
</div>
<EventNote description={entry.description} />
</div>

View File

@@ -2,6 +2,7 @@
import * as m from '$lib/paraglide/messages.js';
import { getAccentConfig, canEditEvent } from './eventCardConfig';
import { timelineDateLabel } from './dateLabel';
import EventNote from './EventNote.svelte';
import type { components } from '$lib/generated/api';
type TimelineEntryDTO = components['schemas']['TimelineEntryDTO'];
@@ -61,4 +62,5 @@ const canEdit = $derived(canEditEvent(entry, canWrite));
<span class="sr-only">{m.btn_edit()}</span>
</a>
{/if}
<EventNote description={entry.description} />
</div>

View File

@@ -0,0 +1,74 @@
import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { tick } from 'svelte';
import * as m from '$lib/paraglide/messages.js';
import EventNote from './EventNote.svelte';
afterEach(() => cleanup());
const LONG_NOTE = Array.from({ length: 15 }, (_, i) => `Zeile ${i + 1}`).join('\n');
describe('EventNote (REQ-002008)', () => {
it('escapesHtml — renders XSS payload as inert text, no injected element (REQ-002)', () => {
render(EventNote, { description: '<script>alert(1)</script>' });
// The literal string should appear as text content
expect(document.body.textContent).toContain('<script>alert(1)</script>');
// No injected <script> with alert() should exist (Svelte's own scripts don't contain it)
const scripts = Array.from(document.querySelectorAll('script'));
expect(scripts.some((s) => s.textContent?.includes('alert(1)'))).toBe(false);
});
it('preservesLineBreaks — note element carries whitespace-pre-line class (REQ-003)', () => {
render(EventNote, { description: 'A\n\nB' });
const note = document.querySelector('[data-testid="event-note"]') as HTMLElement;
expect(note).not.toBeNull();
expect(note.className).toContain('whitespace-pre-line');
});
it('blankNoteRendersNothing — null description produces no note element (REQ-008)', () => {
render(EventNote, { description: null });
expect(document.querySelector('[data-testid="event-note"]')).toBeNull();
});
it('blankNoteRendersNothing — empty string produces no note element (REQ-008)', () => {
render(EventNote, { description: '' });
expect(document.querySelector('[data-testid="event-note"]')).toBeNull();
});
it('blankNoteRendersNothing — blank-only string produces no note element (REQ-008)', () => {
render(EventNote, { description: ' ' });
expect(document.querySelector('[data-testid="event-note"]')).toBeNull();
});
it('shortNoteNoToggle — a one-line note renders fully with no disclosure control (REQ-006)', async () => {
render(EventNote, { description: 'Kurze Notiz.' });
await tick();
expect(document.body.textContent).toContain('Kurze Notiz.');
expect(document.querySelector('[data-testid="note-toggle"]')).toBeNull();
});
it('clampsAndShowsToggle — long note shows "mehr anzeigen" with aria-expanded=false (REQ-005)', async () => {
render(EventNote, { description: LONG_NOTE });
await tick();
const btn = document.querySelector('[data-testid="note-toggle"]') as HTMLButtonElement;
expect(btn).not.toBeNull();
expect(btn.textContent?.trim()).toBe(m.timeline_note_show_more());
expect(btn.getAttribute('aria-expanded')).toBe('false');
});
it('toggleExpandsCollapses — click expands, re-click collapses (REQ-007)', async () => {
render(EventNote, { description: LONG_NOTE });
await tick();
const btn = document.querySelector('[data-testid="note-toggle"]') as HTMLButtonElement;
btn.click();
await tick();
expect(btn.getAttribute('aria-expanded')).toBe('true');
expect(btn.textContent?.trim()).toBe(m.timeline_note_show_less());
btn.click();
await tick();
expect(btn.getAttribute('aria-expanded')).toBe('false');
expect(btn.textContent?.trim()).toBe(m.timeline_note_show_more());
});
});