feat(05-04): calendar API client, calendar widget, registry wiring
- calendar-api.ts: fetchSources/addSource/updateSource/deleteSource/testSource/fetchEvents with credentials:'include' - calendar-widget.tsx: upcoming-events list with source color dots, three empty states (no sources/no events/loading) - widget-registry.tsx: wireCalendarWidget() replaces placeholder with real CalendarWidget - page.tsx: wires CalendarWidget into registry on mount - i18n: added calendar.loading key to de.json and en.json Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -5,9 +5,10 @@ import { useTranslations } from 'next-intl';
|
||||
import { DashboardGrid } from '@/components/dashboard/dashboard-grid';
|
||||
import { EditModeToggle } from '@/components/dashboard/edit-mode-toggle';
|
||||
import { WidgetCatalogModal } from '@/components/dashboard/widget-catalog-modal';
|
||||
import { wireClockWidget, wireSearchWidget, wireNoteWidget } from '@/components/dashboard/widget-registry';
|
||||
import { wireClockWidget, wireSearchWidget, wireCalendarWidget, wireNoteWidget } from '@/components/dashboard/widget-registry';
|
||||
import { ClockWidget } from '@/components/dashboard/widgets/clock-widget';
|
||||
import { SearchWidget } from '@/components/dashboard/widgets/search-widget';
|
||||
import { CalendarWidget } from '@/components/dashboard/widgets/calendar-widget';
|
||||
import { NoteWidget } from '@/components/dashboard/widgets/note-widget';
|
||||
import { useDashboardStore } from '@/lib/stores/dashboard-store';
|
||||
import type { WidgetType } from '@/components/dashboard/widget-registry';
|
||||
@@ -15,6 +16,7 @@ import type { WidgetType } from '@/components/dashboard/widget-registry';
|
||||
// Wire widget components into the registry (deferred to avoid circular deps)
|
||||
wireClockWidget(ClockWidget);
|
||||
wireSearchWidget(SearchWidget);
|
||||
wireCalendarWidget(CalendarWidget);
|
||||
wireNoteWidget(NoteWidget);
|
||||
|
||||
export default function DashboardPage() {
|
||||
|
||||
@@ -213,6 +213,16 @@ export function wireSearchWidget(
|
||||
}
|
||||
}
|
||||
|
||||
let calendarWired = false;
|
||||
export function wireCalendarWidget(
|
||||
component: ComponentType<WidgetProps>,
|
||||
) {
|
||||
if (!calendarWired) {
|
||||
WIDGET_REGISTRY.calendar.component = component;
|
||||
calendarWired = true;
|
||||
}
|
||||
}
|
||||
|
||||
let noteWired = false;
|
||||
export function wireNoteWidget(
|
||||
component: ComponentType<WidgetProps>,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
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';
|
||||
|
||||
/**
|
||||
* Calendar widget (DASH-05, D-10 read-only).
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* Refreshes every 5 minutes to match the backend cache TTL.
|
||||
* NEVER fetches external calendars directly (RESEARCH anti-pattern).
|
||||
*/
|
||||
export function CalendarWidget({ config }: WidgetProps) {
|
||||
const t = useTranslations('widgets');
|
||||
const [events, setEvents] = useState<CalendarEvent[]>([]);
|
||||
const [hasSources, setHasSources] = useState<boolean | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
// Check if user has any sources configured
|
||||
const sources = await fetchSources();
|
||||
if (cancelled) return;
|
||||
|
||||
if (sources.length === 0) {
|
||||
setHasSources(false);
|
||||
setEvents([]);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setHasSources(true);
|
||||
|
||||
// Fetch aggregated events from visible sources
|
||||
const eventData = await fetchEvents();
|
||||
if (cancelled) return;
|
||||
setEvents(eventData);
|
||||
} catch {
|
||||
// Silent fail — show empty state
|
||||
if (!cancelled) {
|
||||
setEvents([]);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadData();
|
||||
|
||||
// Refresh every 5 minutes (300000ms) to match backend cache TTL
|
||||
intervalRef.current = setInterval(() => {
|
||||
loadData();
|
||||
}, 300_000);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Loading state
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('calendar.loading')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// No sources configured
|
||||
if (hasSources === false) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('calendar.emptyNoSources')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Sources exist but no events
|
||||
if (events.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-4">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('calendar.emptyNoEvents')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Events list
|
||||
return (
|
||||
<div className="flex h-full flex-col overflow-y-auto p-3">
|
||||
<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"
|
||||
>
|
||||
{/* 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>
|
||||
</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)}`;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Calendar API client functions.
|
||||
* Consumes the calendar backend built in 05-03.
|
||||
* All calls use credentials: 'include' for cookie-based auth.
|
||||
*
|
||||
* Anti-pattern (RESEARCH): The browser NEVER fetches external calendars directly.
|
||||
* All event data flows through /api/calendar/events which proxies via the backend.
|
||||
*/
|
||||
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||
|
||||
// --- Types mirroring the 05-03 backend contract ---
|
||||
|
||||
/**
|
||||
* Calendar source as returned by GET /calendar/sources.
|
||||
* Note: encryptedPassword is NEVER returned (T-05-09).
|
||||
*/
|
||||
export interface CalendarSource {
|
||||
id: string;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
name: string;
|
||||
type: 'caldav' | 'ics' | 'exchange';
|
||||
exchangeMode?: string | null;
|
||||
url: string;
|
||||
username?: string | null;
|
||||
color?: string | null;
|
||||
isVisible: boolean;
|
||||
syncIntervalMin: number;
|
||||
lastSyncAt?: string | null;
|
||||
lastSyncError?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized calendar event from GET /calendar/events.
|
||||
* Mirrors CalendarEvent from calendar.service.ts.
|
||||
*/
|
||||
export interface CalendarEvent {
|
||||
id: string;
|
||||
sourceId: string;
|
||||
title: string;
|
||||
start: string;
|
||||
end: string;
|
||||
allDay: boolean;
|
||||
location?: string;
|
||||
description?: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload for creating a new calendar source.
|
||||
*/
|
||||
export interface CreateSourcePayload {
|
||||
name: string;
|
||||
type: 'caldav' | 'ics' | 'exchange';
|
||||
url: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
exchangeMode?: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload for updating an existing calendar source.
|
||||
* All fields are optional.
|
||||
*/
|
||||
export interface UpdateSourcePayload {
|
||||
name?: string;
|
||||
type?: 'caldav' | 'ics' | 'exchange';
|
||||
url?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
exchangeMode?: string;
|
||||
color?: string;
|
||||
isVisible?: boolean;
|
||||
}
|
||||
|
||||
// --- API functions ---
|
||||
|
||||
/**
|
||||
* Fetch all calendar sources for the current user.
|
||||
* GET /calendar/sources
|
||||
*/
|
||||
export async function fetchSources(): Promise<CalendarSource[]> {
|
||||
const res = await fetch(`${API_URL}/calendar/sources`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to fetch calendar sources');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new calendar source.
|
||||
* POST /calendar/sources
|
||||
*/
|
||||
export async function addSource(
|
||||
payload: CreateSourcePayload,
|
||||
): Promise<CalendarSource> {
|
||||
const res = await fetch(`${API_URL}/calendar/sources`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to add calendar source');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing calendar source (including isVisible toggle for CAL-02).
|
||||
* PATCH /calendar/sources/:id
|
||||
*/
|
||||
export async function updateSource(
|
||||
id: string,
|
||||
payload: UpdateSourcePayload,
|
||||
): Promise<CalendarSource> {
|
||||
const res = await fetch(`${API_URL}/calendar/sources/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to update calendar source');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a calendar source.
|
||||
* DELETE /calendar/sources/:id
|
||||
*/
|
||||
export async function deleteSource(id: string): Promise<void> {
|
||||
const res = await fetch(`${API_URL}/calendar/sources/${id}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to delete calendar source');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test connection to a calendar source.
|
||||
* POST /calendar/sources/:id/test
|
||||
* Returns { success: boolean } from the backend.
|
||||
*/
|
||||
export async function testSource(
|
||||
id: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
const res = await fetch(`${API_URL}/calendar/sources/${id}/test`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to test calendar source');
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch aggregated events from all visible sources.
|
||||
* GET /calendar/events?from=...&to=...
|
||||
* Default window: now to now + 30 days (backend default).
|
||||
*/
|
||||
export async function fetchEvents(
|
||||
from?: string,
|
||||
to?: string,
|
||||
): Promise<CalendarEvent[]> {
|
||||
const params = new URLSearchParams();
|
||||
if (from) params.set('from', from);
|
||||
if (to) params.set('to', to);
|
||||
|
||||
const queryStr = params.toString();
|
||||
const url = `${API_URL}/calendar/events${queryStr ? `?${queryStr}` : ''}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to fetch calendar events');
|
||||
return res.json();
|
||||
}
|
||||
@@ -130,6 +130,7 @@
|
||||
"search.placeholder": "Suchen...",
|
||||
"calendar.name": "Kalender",
|
||||
"calendar.description": "Kommende Termine",
|
||||
"calendar.loading": "Laden...",
|
||||
"calendar.emptyNoSources": "Keine Kalenderquellen konfiguriert",
|
||||
"calendar.emptyNoEvents": "Keine anstehenden Termine",
|
||||
"calendar.connectionSuccess": "Verbindung erfolgreich",
|
||||
|
||||
@@ -130,6 +130,7 @@
|
||||
"search.placeholder": "Search...",
|
||||
"calendar.name": "Calendar",
|
||||
"calendar.description": "Upcoming events",
|
||||
"calendar.loading": "Loading...",
|
||||
"calendar.emptyNoSources": "No calendar sources configured",
|
||||
"calendar.emptyNoEvents": "No upcoming events",
|
||||
"calendar.connectionSuccess": "Connection successful",
|
||||
|
||||
Reference in New Issue
Block a user