feat(web): Kalender-Widget neu gebaut mit Monatsraster + Naechste Termine, Mindestgroesse 6x8

- calendar-widget.tsx komplett neu: Monatsraster (Nav-Zeile, Wochentagskopf, 42 Zellen, heutiger Tag, Zaehl-Plakette, Portal-Tooltip) + Block "Naechste Termine"; fetchEvents bekommt immer zwei Tagesgrenzen-ISO-Strings ueber computeFetchWindow
- Komponententest komplett neu geschrieben (9 Tests: Laden/Quellen, Raster, Plakette, Tooltip inkl. 5+-Kuerzung, Naechste-Termine-Filter, showMonth/maxEvents=0, Ladefenster, Blaettern)
- WIDGET_CONSTRAINTS.calendar auf { minW: 6, minH: 8, defaultW: 8, defaultH: 12 } angehoben (quick-260916-htc), Registry-Test A mitgezogen

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-16 13:10:33 +02:00
parent 0858102439
commit 61996dceef
4 changed files with 493 additions and 156 deletions
@@ -1,19 +1,46 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslations } from 'next-intl';
import type { WidgetProps } from '../widget-registry';
import { fetchEvents, fetchSources } from '@/lib/calendar-api';
import type { CalendarEvent } from '@/lib/calendar-api';
import {
buildCalendarDays,
computeFetchWindow,
formatEventDate,
formatEventTime,
formatMonthLabel,
groupEventsByDate,
resolveCalendarConfig,
selectUpcomingEvents,
WEEKDAY_LABELS,
} from './calendar-month';
/**
* Calendar widget (DASH-05, D-10 read-only).
* Calendar widget (DASH-05, D-10 read-only), neu gebaut nach dem Vorbild des
* alten persoenlichen Dashboards des Anwenders (quick-260916-htc).
*
* Shows upcoming events aggregated from visible calendar sources.
* Three states per UI-SPEC:
* 1. No sources configured -> t('widgets.calendar.emptyNoSources')
* 2. Sources but no events -> t('widgets.calendar.emptyNoEvents')
* 3. Events -> upcoming-events list with time, title, source color dot
* Oben ein Monatsraster (Nav-Zeile Zurueck/Monat/Weiter, Wochentagskopf,
* 42 Zellen ab Montag, Faehrmonatstage gedaempft, heutiger Tag hervorgehoben,
* Zaehl-Plakette an Tagen mit Terminen, Tooltip beim Ueberfahren), darunter
* der Block "Naechste Termine". Beide Bloecke lassen sich unabhaengig
* ein-/ausblenden (Config `showMonth`/`maxEvents`, siehe calendar-month.ts).
*
* Der Tooltip wird per `createPortal` in `document.body` gerendert, weil die
* Karte in widget-wrapper.tsx `overflow-hidden` traegt und ein absolut
* positionierter Tooltip sonst abgeschnitten wuerde.
*
* Das Ladefenster ist IMMER auf lokale Tagesgrenzen gerundet
* (`computeFetchWindow`), damit der Backend-Cache-Schluessel
* (`${userId}:${from.toISOString()}:${to.toISOString()}`) ueber den
* 5-Minuten-Refresh hinweg stabil bleibt — auch wenn die Monatsansicht
* ausgeblendet ist, deckt das Fenster weiterhin das 42-Tage-Raster des
* (dann immer heutigen) Monats ab, siehe SUMMARY.
*
* Mehrtaegige/ganztaegige Termine werden im Raster nur am Starttag gezaehlt
* (siehe calendar-month.ts).
*
* Refreshes every 5 minutes to match the backend cache TTL.
* NEVER fetches external calendars directly (RESEARCH anti-pattern).
@@ -23,8 +50,22 @@ export function CalendarWidget({ config }: WidgetProps) {
const [events, setEvents] = useState<CalendarEvent[]>([]);
const [hasSources, setHasSources] = useState<boolean | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [monthDate, setMonthDate] = useState(() => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), 1);
});
const [hover, setHover] = useState<{
key: string;
rect: { top: number; left: number; bottom: number; right: number };
} | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
const { showMonth, maxEvents, lookaheadDays } = useMemo(
() => resolveCalendarConfig(config),
// eslint-disable-next-line react-hooks/exhaustive-deps
[config.showMonth, config.maxEvents, config.lookaheadDays],
);
useEffect(() => {
let cancelled = false;
@@ -43,8 +84,10 @@ export function CalendarWidget({ config }: WidgetProps) {
setHasSources(true);
// Fetch aggregated events from visible sources
const eventData = await fetchEvents();
// Fetch aggregated events for the current grid/lookahead window —
// ALWAYS with both day-boundary ISO strings (T-HTC-03).
const { from, to } = computeFetchWindow(monthDate, lookaheadDays);
const eventData = await fetchEvents(from.toISOString(), to.toISOString());
if (cancelled) return;
setEvents(eventData);
} catch {
@@ -72,15 +115,35 @@ export function CalendarWidget({ config }: WidgetProps) {
clearInterval(intervalRef.current);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [monthDate.getTime(), lookaheadDays]);
const showPrev = useCallback(() => {
setHover(null);
setMonthDate((d) => new Date(d.getFullYear(), d.getMonth() - 1, 1));
}, []);
const showNext = useCallback(() => {
setHover(null);
setMonthDate((d) => new Date(d.getFullYear(), d.getMonth() + 1, 1));
}, []);
const showToday = useCallback(() => {
setHover(null);
const now = new Date();
setMonthDate(new Date(now.getFullYear(), now.getMonth(), 1));
}, []);
const eventsByDate = useMemo(() => groupEventsByDate(events), [events]);
const days = useMemo(() => buildCalendarDays(monthDate, eventsByDate), [monthDate, eventsByDate]);
const upcoming = useMemo(
() => selectUpcomingEvents(events, lookaheadDays, maxEvents),
[events, lookaheadDays, maxEvents],
);
// Loading state
if (isLoading) {
return (
<div className="flex h-full items-center justify-center p-2">
<span className="text-sm text-muted-foreground">
{t('calendar.loading')}
</span>
<span className="text-sm text-muted-foreground">{t('calendar.loading')}</span>
</div>
);
}
@@ -89,74 +152,167 @@ export function CalendarWidget({ config }: WidgetProps) {
if (hasSources === false) {
return (
<div className="flex h-full items-center justify-center p-2">
<span className="text-sm text-muted-foreground">
{t('calendar.emptyNoSources')}
</span>
<span className="text-sm text-muted-foreground">{t('calendar.emptyNoSources')}</span>
</div>
);
}
// Sources exist but no events
if (events.length === 0) {
// Both blocks hidden by configuration
if (!showMonth && maxEvents === 0) {
return (
<div className="flex h-full items-center justify-center p-2">
<span className="text-sm text-muted-foreground">
{t('calendar.emptyNoEvents')}
</span>
<span className="text-sm text-muted-foreground">{t('calendar.nothingSelected')}</span>
</div>
);
}
// Events list
const hoverEvents = hover ? (eventsByDate.get(hover.key) ?? []) : [];
return (
<div className="flex h-full flex-col overflow-y-auto p-1.5">
<ul className="space-y-2">
{events.map((event) => (
<li
key={event.id}
className="flex items-start gap-2 rounded px-2 py-1.5 text-sm hover:bg-muted/50"
<div className="flex h-full flex-col gap-1 overflow-hidden p-1.5">
{showMonth && (
<div data-testid="calendar-month" className="flex shrink-0 flex-col gap-1">
{/* Nav-Zeile */}
<div className="grid grid-cols-[1fr_1.4fr_1fr] gap-1">
<button
type="button"
className="widgetNoDrag rounded border border-border bg-muted/50 px-1 py-[clamp(2px,0.8cqh,6px)] text-[clamp(10px,2.6cqw,13px)] leading-none text-foreground hover:bg-muted"
onClick={showPrev}
>
{t('calendar.monthPrev')}
</button>
<button
type="button"
className="widgetNoDrag truncate rounded border border-border bg-muted/50 px-1 py-[clamp(2px,0.8cqh,6px)] text-[clamp(10px,2.6cqw,13px)] font-semibold leading-none text-foreground hover:bg-muted"
title={t('calendar.monthToday')}
onClick={showToday}
>
{formatMonthLabel(monthDate)}
</button>
<button
type="button"
className="widgetNoDrag rounded border border-border bg-muted/50 px-1 py-[clamp(2px,0.8cqh,6px)] text-[clamp(10px,2.6cqw,13px)] leading-none text-foreground hover:bg-muted"
onClick={showNext}
>
{t('calendar.monthNext')}
</button>
</div>
{/* Wochentagskopf */}
<div className="grid grid-cols-7 gap-px text-center text-[clamp(9px,2.2cqw,12px)] font-medium text-muted-foreground">
{WEEKDAY_LABELS.map((label) => (
<div key={label}>{label}</div>
))}
</div>
{/* Raster */}
<div className="grid grid-cols-7 gap-px">
{days.map((day) => {
const hasEvents = day.events.length > 0;
const cellClass = [
'widgetNoDrag relative flex min-h-[clamp(16px,5.5cqh,40px)] items-start rounded bg-muted/50 px-1 py-0.5 text-[clamp(9px,2.4cqw,13px)] leading-none',
day.inCurrentMonth ? 'text-foreground' : 'text-muted-foreground/60',
day.isToday ? 'ring-1 ring-primary font-semibold text-primary' : '',
hasEvents ? 'cursor-default hover:bg-muted' : '',
]
.filter(Boolean)
.join(' ');
return (
<div
key={day.key}
data-testid="calendar-day"
data-date={day.key}
data-today={day.isToday || undefined}
data-outside={!day.inCurrentMonth || undefined}
className={cellClass}
onMouseEnter={(e) =>
hasEvents &&
setHover({ key: day.key, rect: e.currentTarget.getBoundingClientRect() })
}
onMouseLeave={() => setHover(null)}
>
<span>{day.date.getDate()}</span>
{hasEvents && (
<span
data-testid="calendar-day-count"
className="absolute bottom-px right-px flex h-[clamp(10px,3cqw,16px)] min-w-[clamp(10px,3cqw,16px)] items-center justify-center rounded-full bg-primary px-0.5 text-[clamp(7px,1.8cqw,10px)] font-semibold leading-none text-primary-foreground"
>
{day.events.length}
</span>
)}
</div>
);
})}
</div>
</div>
)}
{maxEvents > 0 && (
<section className="flex min-h-0 flex-1 flex-col gap-1">
<h3 className="shrink-0 text-[clamp(10px,2.6cqw,13px)] font-semibold text-foreground">
{t('calendar.upcomingTitle')}
</h3>
{upcoming.length === 0 ? (
<p className="text-[clamp(9px,2.2cqw,12px)] text-muted-foreground">
{t('calendar.emptyNoEvents')}
</p>
) : (
<ul data-testid="calendar-upcoming" className="min-h-0 flex-1 space-y-1 overflow-y-auto">
{upcoming.map((event) => (
<li key={event.id} className="flex items-start gap-2 rounded bg-muted/50 px-2 py-1">
<span
data-testid="event-color-dot"
className="mt-1 h-2 w-2 shrink-0 rounded-full"
style={{ backgroundColor: event.color || 'var(--muted-foreground)' }}
aria-hidden="true"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-[clamp(9px,2.2cqw,12px)] text-muted-foreground">
{formatEventDate(event)}
</p>
<p className="truncate text-[clamp(10px,2.5cqw,14px)] font-semibold text-foreground">
{event.title}
</p>
{event.location && (
<p className="truncate text-[clamp(9px,2.1cqw,12px)] text-muted-foreground">
{event.location}
</p>
)}
</div>
</li>
))}
</ul>
)}
</section>
)}
{hover !== null &&
typeof document !== 'undefined' &&
createPortal(
<div
data-testid="calendar-day-tooltip"
role="tooltip"
className="pointer-events-none fixed z-50 w-60 rounded border border-border bg-card p-2 text-xs text-foreground shadow-lg"
style={{
top: hover.rect.bottom + 4,
left: Math.max(4, Math.min(hover.rect.left, window.innerWidth - 244)),
}}
>
{/* Source color dot (8px, UI-SPEC) */}
<span
data-testid="event-color-dot"
className="mt-1.5 h-2 w-2 shrink-0 rounded-full"
style={{ backgroundColor: event.color || 'var(--muted-foreground)' }}
aria-hidden="true"
/>
<div className="flex-1 min-w-0">
<p className="truncate font-medium text-foreground">
{event.title}
</p>
<p className="text-xs text-muted-foreground">
{formatEventTime(event)}
</p>
</div>
</li>
))}
</ul>
{hoverEvents.slice(0, 5).map((event) => (
<div key={event.id} className="flex gap-2">
<span className="shrink-0 tabular-nums text-muted-foreground">
{event.allDay ? t('calendar.allDay') : formatEventTime(event.start)}
</span>
<span className="truncate">{event.title}</span>
</div>
))}
{hoverEvents.length > 5 && (
<div className="mt-1 text-muted-foreground">{t('calendar.tooltipMore')}</div>
)}
</div>,
document.body,
)}
</div>
);
}
/**
* Format event time using locale-aware Intl.DateTimeFormat.
* All-day events show only the date; timed events show time range.
*/
function formatEventTime(event: CalendarEvent): string {
const start = new Date(event.start);
const end = new Date(event.end);
if (event.allDay) {
return new Intl.DateTimeFormat('de-DE', {
day: '2-digit',
month: 'short',
}).format(start);
}
const timeFormatter = new Intl.DateTimeFormat('de-DE', {
hour: '2-digit',
minute: '2-digit',
});
return `${timeFormatter.format(start)} – ${timeFormatter.format(end)}`;
}