Your favorite shift management application!
feat: implement server-sent events for calendar changes, add event emitter, and enhance synchronization in the UI with connection status handling
panteLx03fdcf97182e
diff --git a/README.md b/README.mdindex 61fdc64..c60b7fa 100644--- a/README.md+++ b/README.md@@ -13,6 +13,7 @@ A modern shift management application built with Next.js and SQLite. BetterShift- π **Password Protection**: Secure calendars with optional passwords- π **Internationalization (i18n)**: Supports multiple languages with automatic detection and manual switching- π **Shift Statistics**: View statistics for shifts over different time periods+- π **Real-time Synchronization**: Automatic data refresh and offline handling with server-sent events- πΎ **SQLite Database**: Lightweight, file-based database with Drizzle ORM- π³ **Docker Support**: Easy deployment with Docker and Docker Composediff --git a/app/api/events/stream/route.ts b/app/api/events/stream/route.tsnew file mode 100644index 0000000..8f355f5--- /dev/null+++ b/app/api/events/stream/route.ts@@ -0,0 +1,73 @@+import { NextRequest } from "next/server";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";++// Disable default body parsing+export const dynamic = "force-dynamic";++export async function GET(request: NextRequest) {+ const searchParams = request.nextUrl.searchParams;+ const calendarId = searchParams.get("calendarId");++ if (!calendarId) {+ return new Response(JSON.stringify({ error: "Calendar ID is required" }), {+ status: 400,+ headers: { "Content-Type": "application/json" },+ });+ }++ // Create a readable stream for SSE+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ // Send initial connection message+ const connectMessage = `data: ${JSON.stringify({+ type: "connected",+ calendarId,+ })}\n\n`;+ controller.enqueue(encoder.encode(connectMessage));++ // Event handler for calendar changes+ const handleCalendarChange = (data: unknown) => {+ const event = data as CalendarChangeEvent;+ // Only send events for the subscribed calendar+ if (event.calendarId === calendarId) {+ const message = `data: ${JSON.stringify(event)}\n\n`;+ try {+ controller.enqueue(encoder.encode(message));+ } catch (error) {+ console.error("Error sending SSE message:", error);+ // Client likely disconnected, will be cleaned up below+ }+ }+ };++ // Subscribe to calendar changes+ eventEmitter.on("calendar-change", handleCalendarChange);++ // Send keepalive ping every 30 seconds to prevent timeout+ const keepAliveInterval = setInterval(() => {+ try {+ controller.enqueue(encoder.encode(": keepalive\n\n"));+ } catch (error) {+ // Client disconnected+ clearInterval(keepAliveInterval);+ }+ }, 30000);++ // Clean up on disconnect+ request.signal.addEventListener("abort", () => {+ clearInterval(keepAliveInterval);+ eventEmitter.off("calendar-change", handleCalendarChange);+ controller.close();+ });+ },+ });++ return new Response(stream, {+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ },+ });+}diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.tsindex 48f85e6..f6c383b 100644--- a/app/api/notes/[id]/route.ts+++ b/app/api/notes/[id]/route.ts@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendarNotes } from "@/lib/db/schema";import { eq } from "drizzle-orm";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// GET single calendar noteexport async function GET(@@ -62,6 +63,14 @@ export async function PUT();}+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "note",+ action: "update",+ calendarId: updated.calendarId,+ data: updated,+ } as CalendarChangeEvent);+return NextResponse.json(updated);} catch (error) {console.error("Failed to update calendar note:", error);@@ -92,6 +101,14 @@ export async function DELETE();}+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "note",+ action: "delete",+ calendarId: result[0].calendarId,+ data: { id },+ } as CalendarChangeEvent);+return NextResponse.json({ success: true });} catch (error) {console.error("Failed to delete calendar note:", error);diff --git a/app/api/notes/route.ts b/app/api/notes/route.tsindex 5c3eace..035718a 100644--- a/app/api/notes/route.ts+++ b/app/api/notes/route.ts@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendarNotes } from "@/lib/db/schema";import { eq, and, gte, lte } from "drizzle-orm";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// GET calendar notes for a calendar (with optional date filter)export async function GET(request: Request) {@@ -73,6 +74,14 @@ export async function POST(request: Request) {}).returning();+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "note",+ action: "create",+ calendarId,+ data: calendarNote,+ } as CalendarChangeEvent);+return NextResponse.json(calendarNote);} catch (error) {console.error("Failed to create calendar note:", error);diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex 4b67d9a..d4048e2 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -3,6 +3,7 @@ import { db } from "@/lib/db";import { shiftPresets, shifts, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { verifyPassword } from "@/lib/password-utils";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// PATCH update a presetexport async function PATCH(@@ -85,6 +86,14 @@ export async function PATCH(}).where(eq(shifts.presetId, id));+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "preset",+ action: "update",+ calendarId: existingPreset.calendarId,+ data: updatedPreset,+ } as CalendarChangeEvent);+return NextResponse.json(updatedPreset);} catch (error) {console.error("Error updating preset:", error);@@ -144,6 +153,14 @@ export async function DELETE(// Delete the presetawait db.delete(shiftPresets).where(eq(shiftPresets.id, id));+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "preset",+ action: "delete",+ calendarId: preset.calendarId,+ data: { id },+ } as CalendarChangeEvent);+return NextResponse.json({ success: true });} catch (error) {console.error("Error deleting preset:", error);diff --git a/app/api/presets/route.ts b/app/api/presets/route.tsindex 9b80703..da20652 100644--- a/app/api/presets/route.ts+++ b/app/api/presets/route.ts@@ -3,6 +3,7 @@ import { db } from "@/lib/db";import { shiftPresets, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { verifyPassword } from "@/lib/password-utils";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// GET all presets for a calendarexport async function GET(request: NextRequest) {@@ -91,6 +92,14 @@ export async function POST(request: NextRequest) {}).returning();+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "preset",+ action: "create",+ calendarId,+ data: preset,+ } as CalendarChangeEvent);+return NextResponse.json(preset);} catch (error) {console.error("Error creating preset:", error);diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex e0d5620..c70ca3c 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -3,6 +3,7 @@ import { db } from "@/lib/db";import { calendars, shifts } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { verifyPassword } from "@/lib/password-utils";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// GET single shiftexport async function GET(@@ -118,6 +119,14 @@ export async function PATCH(.where(eq(shifts.id, id)).returning();+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "shift",+ action: "update",+ calendarId: existingShift.calendarId,+ data: { ...shift, calendar },+ } as CalendarChangeEvent);+return NextResponse.json({ ...shift, calendar });} catch (error) {console.error("Failed to update shift:", error);@@ -170,6 +179,14 @@ export async function DELETE(await db.delete(shifts).where(eq(shifts.id, id));+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "shift",+ action: "delete",+ calendarId: shift.calendarId,+ data: { id },+ } as CalendarChangeEvent);+return NextResponse.json({ success: true });} catch (error) {console.error("Failed to delete shift:", error);diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.tsindex 3a8bcca..e3633e1 100644--- a/app/api/shifts/route.ts+++ b/app/api/shifts/route.ts@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";import { db } from "@/lib/db";import { calendars, shifts } from "@/lib/db/schema";import { eq, and, gte, lte } from "drizzle-orm";+import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";// GET shifts for a calendar (with optional date filter)export async function GET(request: Request) {@@ -112,6 +113,14 @@ export async function POST(request: Request) {.from(calendars).where(eq(calendars.id, calendarId));+ // Emit event for SSE+ eventEmitter.emit("calendar-change", {+ type: "shift",+ action: "create",+ calendarId,+ data: { ...shift, calendar },+ } as CalendarChangeEvent);+return NextResponse.json({ ...shift, calendar }, { status: 201 });} catch (error) {console.error("Failed to create shift:", error);diff --git a/app/page.tsx b/app/page.tsxindex 7e98c70..9b0bb60 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -92,19 +92,78 @@ function HomeContent() {const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);const [isTogglingShift, setIsTogglingShift] = useState(false);const [showShiftsSection, setShowShiftsSection] = useState(false);- const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);+ const eventSourceRef = useRef<EventSource | null>(null);+ const [isConnected, setIsConnected] = useState(true);+ const lastSyncTimeRef = useRef<number>(Date.now());+ const disconnectTimeRef = useRef<number | null>(null);// Fetch calendars on mount and setup cleanupuseEffect(() => {fetchCalendars();return () => {- if (pollingIntervalRef.current) {- clearInterval(pollingIntervalRef.current);+ if (eventSourceRef.current) {+ eventSourceRef.current.close();}};}, []);+ // Handle page visibility changes (tab switching, app backgrounding)+ useEffect(() => {+ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible" && selectedCalendar) {+ const now = Date.now();+ const timeSinceLastSync = now - lastSyncTimeRef.current;++ // If more than 30 seconds passed or we were disconnected, resync+ if (timeSinceLastSync > 30000 || disconnectTimeRef.current) {+ console.log("Tab became visible, resyncing data...");+ toast.info(t("sync.refreshing"), { duration: Infinity });+ fetchShifts();+ fetchPresets();+ fetchNotes();+ setStatsRefreshTrigger((prev) => prev + 1);+ lastSyncTimeRef.current = now;+ disconnectTimeRef.current = null;+ // Dismiss the refreshing toast after data is loaded+ setTimeout(() => toast.dismiss(), 1000);+ }+ }+ };++ const handleOnline = () => {+ console.log("Network connection restored");+ toast.dismiss(); // Dismiss all persistent error toasts+ toast.success(t("sync.reconnected"));+ setIsConnected(true);+ if (selectedCalendar) {+ fetchShifts();+ fetchPresets();+ fetchNotes();+ setStatsRefreshTrigger((prev) => prev + 1);+ lastSyncTimeRef.current = Date.now();+ disconnectTimeRef.current = null;+ }+ };++ const handleOffline = () => {+ console.log("Network connection lost");+ toast.error(t("sync.offline"), { duration: Infinity });+ setIsConnected(false);+ disconnectTimeRef.current = Date.now();+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("online", handleOnline);+ window.addEventListener("offline", handleOffline);++ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ window.removeEventListener("online", handleOnline);+ window.removeEventListener("offline", handleOffline);+ };+ }, [selectedCalendar, t]);+// Update URL when selected calendar changesuseEffect(() => {if (selectedCalendar) {@@ -112,33 +171,105 @@ function HomeContent() {}}, [selectedCalendar, router]);- // Fetch shifts and presets when calendar changes and setup polling+ // Fetch shifts and presets when calendar changes and setup SSEuseEffect(() => {if (selectedCalendar) {fetchShifts();fetchPresets();fetchNotes();- // Setup polling for live sync (every 5 seconds)- if (pollingIntervalRef.current) {- clearInterval(pollingIntervalRef.current);+ // Close existing SSE connection if any+ if (eventSourceRef.current) {+ eventSourceRef.current.close();}- const interval = setInterval(() => {- fetchShifts();- fetchPresets();- fetchNotes();- }, 5000);- pollingIntervalRef.current = interval;++ // Setup Server-Sent Events for real-time updates+ const eventSource = new EventSource(+ `/api/events/stream?calendarId=${selectedCalendar}`+ );++ eventSource.onopen = () => {+ setIsConnected(true);+ toast.dismiss(); // Dismiss any persistent error/info toasts++ // If we were disconnected for more than 10 seconds, resync all data+ if (disconnectTimeRef.current) {+ const disconnectDuration = Date.now() - disconnectTimeRef.current;+ if (disconnectDuration > 10000) {+ console.log("Reconnected after long disconnect, resyncing...");+ toast.info(t("sync.resyncing"), { duration: Infinity });+ fetchShifts();+ fetchPresets();+ fetchNotes();+ setStatsRefreshTrigger((prev) => prev + 1);+ }+ disconnectTimeRef.current = null;+ }+ lastSyncTimeRef.current = Date.now();+ };++ eventSource.onmessage = (event) => {+ try {+ const data = JSON.parse(event.data);++ // Handle connection message+ if (data.type === "connected") {+ console.log("SSE connected for calendar:", data.calendarId);+ return;+ }++ // Handle calendar change events+ if (data.type === "shift") {+ fetchShifts();+ setStatsRefreshTrigger((prev) => prev + 1);+ } else if (data.type === "preset") {+ fetchPresets();+ } else if (data.type === "note") {+ fetchNotes();+ }++ lastSyncTimeRef.current = Date.now();+ } catch (error) {+ console.error("Error parsing SSE message:", error);+ }+ };++ eventSource.onerror = (error) => {+ console.error("SSE connection error:", error);+ setIsConnected(false);+ disconnectTimeRef.current = Date.now();+ eventSource.close();++ // Show error message if offline for more than 5 seconds+ const errorTimeout = setTimeout(() => {+ if (!navigator.onLine) {+ toast.error(t("sync.disconnected"), { duration: Infinity });+ }+ }, 5000);++ // Attempt to reconnect after 3 seconds+ setTimeout(() => {+ clearTimeout(errorTimeout);+ if (selectedCalendar && navigator.onLine) {+ console.log("Attempting to reconnect and resync...");+ fetchShifts();+ fetchPresets();+ fetchNotes();+ }+ }, 3000);+ };++ eventSourceRef.current = eventSource;return () => {- clearInterval(interval);+ eventSource.close();};} else {setShifts([]);setPresets([]);setNotes([]);- if (pollingIntervalRef.current) {- clearInterval(pollingIntervalRef.current);+ if (eventSourceRef.current) {+ eventSourceRef.current.close();}}}, [selectedCalendar]);@@ -798,7 +929,17 @@ function HomeContent() {<div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-xl shadow-primary/30 ring-2 ring-primary/20"><CalendarIcon className="h-6 w-6 text-primary-foreground" /></div>- <div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-green-500 rounded-full border-2 border-background animate-pulse"></div>+ {/* Connection Status Indicator */}+ <div+ className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${+ isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"+ }`}+ title={+ isConnected+ ? t("sync.reconnected")+ : t("sync.disconnected")+ }+ ></div></div><div><h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text">@@ -1081,15 +1222,8 @@ function HomeContent() {</div><div className="flex-1 space-y-0.5 sm:space-y-1 overflow-hidden">{dayShifts.slice(0, 2).map((shift) => (- <motion.div+ <divkey={shift.id}- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: -8 }}- transition={{- duration: 0.15,- ease: "easeOut",- }}className="text-[10px] sm:text-xs px-0.5 py-0.5 sm:px-1.5 sm:py-1 rounded"style={{backgroundColor: shift.color@@ -1111,7 +1245,7 @@ function HomeContent() {? t("shift.allDay"): shift.startTime.substring(0, 5)}</div>- </motion.div>+ </div>))}{dayShifts.length > 2 && (<div className="text-[10px] sm:text-xs text-muted-foreground font-medium text-center pt-0.5">diff --git a/lib/event-emitter.ts b/lib/event-emitter.tsnew file mode 100644index 0000000..96e45d4--- /dev/null+++ b/lib/event-emitter.ts@@ -0,0 +1,46 @@+/**+ * Simple event emitter for server-sent events+ * Allows broadcasting changes across API routes to connected SSE clients+ */++type EventCallback = (data: unknown) => void;++class EventEmitter {+ private listeners: Map<string, Set<EventCallback>> = new Map();++ on(event: string, callback: EventCallback) {+ if (!this.listeners.has(event)) {+ this.listeners.set(event, new Set());+ }+ this.listeners.get(event)!.add(callback);+ }++ off(event: string, callback: EventCallback) {+ const callbacks = this.listeners.get(event);+ if (callbacks) {+ callbacks.delete(callback);+ }+ }++ emit(event: string, data: unknown) {+ const callbacks = this.listeners.get(event);+ if (callbacks) {+ callbacks.forEach((callback) => callback(data));+ }+ }++ listenerCount(event: string): number {+ return this.listeners.get(event)?.size || 0;+ }+}++// Global singleton instance+export const eventEmitter = new EventEmitter();++// Event types+export type CalendarChangeEvent = {+ type: "shift" | "preset" | "note" | "calendar";+ action: "create" | "update" | "delete";+ calendarId: string;+ data?: unknown;+};diff --git a/messages/de.json b/messages/de.jsonindex 071b91f..a0e332f 100644--- a/messages/de.json+++ b/messages/de.json@@ -143,6 +143,13 @@"total": "Gesamt","noData": "Keine Schichten in diesem Zeitraum"},+ "sync": {+ "refreshing": "Aktualisiere Daten...",+ "resyncing": "Synchronisiere nach Verbindungsunterbrechung...",+ "reconnected": "Verbindung wiederhergestellt",+ "offline": "Keine Internetverbindung",+ "disconnected": "Verbindung zum Server verloren"+ },"onboarding": {"welcome": "Willkommen bei BetterShift","description": "Erstelle deinen ersten Kalender, um deine Schichten zu verwalten.",diff --git a/messages/en.json b/messages/en.jsonindex 0358f57..c52a495 100644--- a/messages/en.json+++ b/messages/en.json@@ -143,9 +143,16 @@"total": "Total","noData": "No shifts in this period"},+ "sync": {+ "refreshing": "Refreshing data...",+ "resyncing": "Resyncing after disconnect...",+ "reconnected": "Connection restored",+ "offline": "No internet connection",+ "disconnected": "Connection to server lost"+ },"onboarding": {"welcome": "Welcome to BetterShift",- "description": "Get started by creating your first calendar to track your shifts.",+ "description": "Create your first calendar to manage your shifts.","createCalendar": "Create Calendar"}}