Your favorite shift management application!
chore: Improve robustness and state handling (#57)
panteLa517332cbb49
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.tsindex fe85bbe..3cbe1a7 100644--- a/app/api/calendars/[id]/route.ts+++ b/app/api/calendars/[id]/route.ts@@ -88,7 +88,7 @@ export async function PATCH(}}- const updateData: any = {};+ const updateData: Partial<typeof calendars.$inferInsert> = {};if (name) updateData.name = name;if (color) updateData.color = color;if (password !== undefined) {@@ -141,7 +141,7 @@ export async function DELETE(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/events/stream/route.ts b/app/api/events/stream/route.tsindex 8f355f5..7b694ac 100644--- a/app/api/events/stream/route.ts+++ b/app/api/events/stream/route.ts@@ -48,7 +48,7 @@ export async function GET(request: NextRequest) {const keepAliveInterval = setInterval(() => {try {controller.enqueue(encoder.encode(": keepalive\n\n"));- } catch (error) {+ } catch {// Client disconnectedclearInterval(keepAliveInterval);}diff --git a/app/api/external-syncs/[id]/route.ts b/app/api/external-syncs/[id]/route.tsindex d55de50..a1f7cc7 100644--- a/app/api/external-syncs/[id]/route.ts+++ b/app/api/external-syncs/[id]/route.ts@@ -237,7 +237,7 @@ export async function DELETE(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/external-syncs/[id]/sync/route.ts b/app/api/external-syncs/[id]/sync/route.tsindex 44d016a..05f69d9 100644--- a/app/api/external-syncs/[id]/sync/route.ts+++ b/app/api/external-syncs/[id]/sync/route.ts@@ -353,7 +353,7 @@ export async function POST(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.tsindex 4bf17dc..2b8ab4c 100644--- a/app/api/notes/[id]/route.ts+++ b/app/api/notes/[id]/route.ts@@ -160,7 +160,7 @@ export async function DELETE(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/notes/route.ts b/app/api/notes/route.tsindex 91c6d8f..1721e64 100644--- a/app/api/notes/route.ts+++ b/app/api/notes/route.ts@@ -44,7 +44,7 @@ export async function GET(request: Request) {}}- let query = db+ const query = db.select().from(calendarNotes).where(eq(calendarNotes.calendarId, calendarId));diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex b752028..c5d3c89 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -174,7 +174,7 @@ export async function DELETE(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex 8c62e59..3df15d4 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -129,7 +129,7 @@ export async function PATCH(}}- const updateData: any = {};+ const updateData: Partial<typeof shifts.$inferInsert> = {};if (date) updateData.date = new Date(date);if (startTime !== undefined) updateData.startTime = startTime;if (endTime !== undefined) updateData.endTime = endTime;@@ -179,7 +179,7 @@ export async function DELETE(try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/shifts/route.ts b/app/api/shifts/route.tsindex 3bd596f..9b1e54a 100644--- a/app/api/shifts/route.ts+++ b/app/api/shifts/route.ts@@ -44,7 +44,7 @@ export async function GET(request: Request) {}}- let query = db+ const query = db.select({id: shifts.id,calendarId: shifts.calendarId,diff --git a/app/api/sync-logs/route.ts b/app/api/sync-logs/route.tsindex 8fe873a..27a68bb 100644--- a/app/api/sync-logs/route.ts+++ b/app/api/sync-logs/route.ts@@ -79,7 +79,7 @@ export async function PATCH(request: NextRequest) {try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}@@ -149,7 +149,7 @@ export async function DELETE(request: NextRequest) {try {const body = await request.json();password = body.password || null;- } catch (e) {+ } catch {// If body parsing fails, continue with null password}}diff --git a/app/api/version/route.ts b/app/api/version/route.tsindex 92e4527..8817697 100644--- a/app/api/version/route.ts+++ b/app/api/version/route.ts@@ -31,7 +31,7 @@ function getDockerVersion(): string | null {cachedDockerVersion = readFileSync(versionFilePath, "utf-8").trim();return cachedDockerVersion;}- } catch (error) {+ } catch {console.log("No .version file found, not running in Docker");}diff --git a/app/page.tsx b/app/page.tsxindex 4d2245a..8ed912b 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -2,12 +2,13 @@import { useState, useEffect, Suspense } from "react";import { useRouter, useSearchParams } from "next/navigation";-import { useTranslations, useLocale } from "next-intl";+import { useLocale } from "next-intl";import { isSameDay } from "date-fns";import { Button } from "@/components/ui/button";import { Plus } from "lucide-react";import { getDateLocale } from "@/lib/locales";import { motion } from "motion/react";+import { ShiftWithCalendar } from "@/lib/types";import { useCalendars } from "@/hooks/useCalendars";import { useShifts } from "@/hooks/useShifts";import { usePresets } from "@/hooks/usePresets";@@ -33,7 +34,6 @@ import { getCalendarDays } from "@/lib/calendar-utils";function HomeContent() {const router = useRouter();const searchParams = useSearchParams();- const t = useTranslations();const locale = useLocale();const dateLocale = getDateLocale(locale);@@ -161,7 +161,7 @@ function HomeContent() {}, [selectedCalendar, router]);// Handle password success with data refresh- const handlePasswordSuccess = async (password: string) => {+ const handlePasswordSuccess = async () => {await Promise.all([refetchShifts(),refetchPresets(),@@ -263,13 +263,16 @@ function HomeContent() {noteActions.openNoteDialog(date, existingNote);};- const handleShowAllShifts = (date: Date, dayShifts: any[]) => {+ const handleShowAllShifts = (date: Date, dayShifts: ShiftWithCalendar[]) => {dialogStates.setSelectedDayDate(date);dialogStates.setSelectedDayShifts(dayShifts);dialogStates.setShowDayShiftsDialog(true);};- const handleShowSyncedShifts = (date: Date, syncedShifts: any[]) => {+ const handleShowSyncedShifts = (+ date: Date,+ syncedShifts: ShiftWithCalendar[]+ ) => {dialogStates.setSelectedDayDate(date);dialogStates.setSelectedSyncedShifts(syncedShifts);dialogStates.setShowSyncedShiftsDialog(true);@@ -341,9 +344,9 @@ function HomeContent() {) : selectedCalendar && !isCalendarUnlocked ? (<LockedCalendarViewcalendarId={selectedCalendar}- onUnlock={(password) => {+ onUnlock={() => {setIsCalendarUnlocked(true);- handlePasswordSuccess(password);+ handlePasswordSuccess();}}/>) : (diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsxindex b53522c..ba81ae4 100644--- a/components/calendar-grid.tsx+++ b/components/calendar-grid.tsx@@ -134,7 +134,7 @@ export function CalendarGrid({const dayKey = formatDateToLocal(day);const isToggling = togglingDates.has(dayKey);- const handleTouchStart = (e: React.TouchEvent) => {+ const handleTouchStart = () => {if (onLongPress) {pressTimerRef.current[dayKey] = setTimeout(() => onLongPress(day),@@ -260,8 +260,9 @@ export function CalendarGrid({...externalNormalShifts,];allSortedShifts = sortShifts(allNormalShifts);- sortedRegularShifts = [];- sortedExternalNormalShifts = [];+ // Keep the separate arrays for individual limits+ sortedRegularShifts = sortShifts(regularShifts);+ sortedExternalNormalShifts = sortShifts(externalNormalShifts);} else {// Separate mode: sort each group separatelysortedRegularShifts = sortShifts(regularShifts);@@ -269,31 +270,86 @@ export function CalendarGrid({allSortedShifts = [];}+ // Pre-compute index maps to avoid O(n²) complexity during rendering+ const regularIndexMap = new Map<string, number>();+ const externalIndexMap = new Map<string, number>();++ if (combinedSortMode) {+ sortedRegularShifts.forEach((shift, index) => {+ regularIndexMap.set(shift.id, index);+ });+ sortedExternalNormalShifts.forEach((shift, index) => {+ externalIndexMap.set(shift.id, index);+ });+ }+return (<>{combinedSortMode ? (- // Combined mode: display all shifts together+ // Combined mode: display all shifts together sorted, but respect individual limits<>- {(maxShiftsToShow === undefined- ? allSortedShifts- : allSortedShifts.slice(0, maxShiftsToShow)- ).map((shift) => (- <CalendarShiftCard- key={shift.id}- shift={shift}- showShiftNotes={showShiftNotes}- showFullTitles={showFullTitles}- />- ))}+ {/* Display combined sorted shifts with individual limits */}+ {allSortedShifts.map((shift) => {+ const isRegular = !shift.syncedFromExternal;+ const regularIndex = isRegular+ ? regularIndexMap.get(shift.id) ?? -1+ : -1;+ const externalIndex = !isRegular+ ? externalIndexMap.get(shift.id) ?? -1+ : -1;++ // Check if shift should be displayed based on its type's limit+ const shouldDisplay =+ (isRegular &&+ (maxShiftsToShow === undefined ||+ regularIndex < maxShiftsToShow)) ||+ (!isRegular &&+ (maxExternalShiftsToShow === undefined ||+ externalIndex < maxExternalShiftsToShow));++ if (!shouldDisplay) return null;- {/* Show "+X more" if limited by maxShiftsToShow */}+ return (+ <CalendarShiftCard+ key={shift.id}+ shift={shift}+ showShiftNotes={showShiftNotes}+ showFullTitles={showFullTitles}+ />+ );+ })}++ {/* Show "+X more" for regular shifts if limited */}{maxShiftsToShow !== undefined &&- allSortedShifts.length > maxShiftsToShow && (+ sortedRegularShifts.length > maxShiftsToShow && (+ <div+ onClick={(e) => {+ if (selectedPresetId) return;+ e.stopPropagation();+ onShowAllShifts?.(day, sortedRegularShifts);+ }}+ className={`text-[10px] sm:text-xs text-primary font-semibold text-center pt-0.5 transition-colors ${+ selectedPresetId+ ? "cursor-not-allowed opacity-50"+ : "hover:text-primary/80 hover:underline cursor-pointer"+ }`}+ >+ +{sortedRegularShifts.length - maxShiftsToShow}+ </div>+ )}++ {/* Show "+X more" for external shifts if limited */}+ {maxExternalShiftsToShow !== undefined &&+ sortedExternalNormalShifts.length >+ maxExternalShiftsToShow && (<divonClick={(e) => {if (selectedPresetId) return;e.stopPropagation();- onShowAllShifts?.(day, allSortedShifts);+ onShowSyncedShifts?.(+ day,+ sortedExternalNormalShifts+ );}}className={`text-[10px] sm:text-xs text-primary font-semibold text-center pt-0.5 transition-colors ${selectedPresetId@@ -301,7 +357,9 @@ export function CalendarGrid({: "hover:text-primary/80 hover:underline cursor-pointer"}`}>- +{allSortedShifts.length - maxShiftsToShow}+ ++ {sortedExternalNormalShifts.length -+ maxExternalShiftsToShow}</div>)}</>@@ -364,7 +422,7 @@ export function CalendarGrid({onClick={(e) => {if (selectedPresetId) return;e.stopPropagation();- onShowAllShifts?.(+ onShowSyncedShifts?.(day,sortedExternalNormalShifts);diff --git a/components/delete-calendar-dialog.tsx b/components/delete-calendar-dialog.tsxindex ebf10ea..560a351 100644--- a/components/delete-calendar-dialog.tsx+++ b/components/delete-calendar-dialog.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState } from "react";import { useTranslations } from "next-intl";import {Dialog,@@ -33,11 +33,12 @@ export function DeleteCalendarDialog({const t = useTranslations();const [password, setPassword] = useState("");- useEffect(() => {- if (!open) {+ const handleOpenChange = (newOpen: boolean) => {+ if (!newOpen) {setPassword("");}- }, [open]);+ onOpenChange(newOpen);+ };const handleSubmit = (e: React.FormEvent) => {e.preventDefault();@@ -45,7 +46,7 @@ export function DeleteCalendarDialog({};return (- <Dialog open={open} onOpenChange={onOpenChange}>+ <Dialog open={open} onOpenChange={handleOpenChange}><DialogContent className="sm:max-w-[480px] p-0 gap-0 border border-destructive/50 bg-gradient-to-b from-background via-background to-destructive/5 backdrop-blur-xl shadow-2xl shadow-destructive/10"><DialogHeader className="border-b border-destructive/30 bg-gradient-to-r from-destructive/15 via-destructive/10 to-transparent p-6 pb-5 space-y-1.5"><DialogTitle className="flex items-center gap-2.5 text-destructive text-xl font-semibold">diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsxindex 8639b8d..2890220 100644--- a/components/external-sync-manage-dialog.tsx+++ b/components/external-sync-manage-dialog.tsx@@ -8,6 +8,7 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { ExternalSync, SyncLog } from "@/lib/db/schema";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -22,7 +23,6 @@ import {import { ColorPicker } from "@/components/ui/color-picker";import { Slider } from "@/components/ui/slider";import { useTranslations } from "next-intl";-import { ExternalSync } from "@/lib/db/schema";import {Loader2,Trash2,@@ -121,11 +121,11 @@ export function ExternalSyncManageDialog({// Get the latest error for each external syncdata.forEach((sync: ExternalSync) => {const syncLogs = logs.filter(- (log: any) => log.externalSyncId === sync.id+ (log: SyncLog) => log.externalSyncId === sync.id);// Only show unread errorsconst latestError = syncLogs.find(- (log: any) => log.status === "error" && !log.isRead+ (log: SyncLog) => log.status === "error" && !log.isRead);if (latestError) {errors[sync.id] =@@ -293,55 +293,6 @@ export function ExternalSyncManageDialog({}};- const handleUpdateSync = async () => {- if (!editingSync || !formName.trim()) return;-- setIsLoading(true);- try {- const password = getCachedPassword(calendarId);-- const response = await fetch(`/api/external-syncs/${editingSync.id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: formName.trim(),- calendarUrl: formUrl.trim() || undefined,- color: formColor,- displayMode: formDisplayMode,- autoSyncInterval: formAutoSyncInterval,- password,- }),- });-- if (response.ok) {- setEditingSync(null);- setFormName("");- setFormUrl("");- setFormColor("#3b82f6");- setFormDisplayMode("normal");- setFormAutoSyncInterval(0);- await fetchSyncs();- onSyncComplete?.(); // Trigger refresh of shifts and externalSyncs- toast.success(- t("common.updated", { item: t("externalSync.syncTypeCustom") })- );- } else {- const data = await response.json();- toast.error(- data.error ||- t("common.updateError", { item: t("externalSync.syncTypeCustom") })- );- }- } catch (error) {- console.error("Failed to update sync:", error);- toast.error(- t("common.updateError", { item: t("externalSync.syncTypeCustom") })- );- } finally {- setIsLoading(false);- }- };-const handleSync = async (syncId: string) => {setIsSyncing(syncId);try {@@ -590,6 +541,7 @@ export function ExternalSyncManageDialog({}},[+ calendarId,editingSync,formName,formUrl,diff --git a/components/locked-calendar-view.tsx b/components/locked-calendar-view.tsxindex 999d26e..b17582c 100644--- a/components/locked-calendar-view.tsx+++ b/components/locked-calendar-view.tsx@@ -9,7 +9,7 @@ import { verifyAndCachePassword } from "@/lib/password-cache";interface LockedCalendarViewProps {calendarId: string;- onUnlock: (password: string) => void;+ onUnlock: () => void;}export function LockedCalendarView({@@ -27,7 +27,7 @@ export function LockedCalendarView({const result = await verifyAndCachePassword(calendarId, password);if (result.valid) {- onUnlock(password);+ onUnlock();} else {toast.error(t("validation.passwordIncorrect"));}diff --git a/components/manage-password-dialog.tsx b/components/manage-password-dialog.tsxindex ee3368e..07329e7 100644--- a/components/manage-password-dialog.tsx+++ b/components/manage-password-dialog.tsx@@ -83,7 +83,11 @@ export function ManagePasswordDialog({setLoading(true);try {- const requestBody: any = {+ const requestBody: {+ currentPassword?: string;+ isLocked: boolean;+ password?: string | null;+ } = {currentPassword: hasPassword ? currentPassword : undefined,isLocked: lockCalendar,};diff --git a/components/note-dialog.tsx b/components/note-dialog.tsxindex 91f7704..a933288 100644--- a/components/note-dialog.tsx+++ b/components/note-dialog.tsx@@ -38,23 +38,27 @@ export function NoteDialog({const t = useTranslations();const locale = useLocale();const dateLocale = getDateLocale(locale);- const [noteText, setNoteText] = useState("");const initialNoteRef = useRef<string>("");const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);const isInitialMount = useRef(true);+ const prevNoteIdRef = useRef<string | undefined>(undefined);const isNewNote = !note;+ // State initialization - useEffect handles all updates+ const [noteText, setNoteText] = useState("");++ // Update noteText when note changes (only when note ID actually changes)useEffect(() => {if (open) {- const initialNote = note?.note || "";- setNoteText(initialNote);- initialNoteRef.current = initialNote;- isInitialMount.current = true;- } else {- // Clear timeout when dialog closes- if (saveTimeoutRef.current) {- clearTimeout(saveTimeoutRef.current);- saveTimeoutRef.current = null;+ const currentNoteId = note?.id;+ // Only update if note ID changed to avoid cascading renders+ if (prevNoteIdRef.current !== currentNoteId) {+ const currentNote = note?.note || "";+ // eslint-disable-next-line react-hooks/set-state-in-effect+ setNoteText(currentNote);+ initialNoteRef.current = currentNote;+ isInitialMount.current = true;+ prevNoteIdRef.current = currentNoteId;}}}, [open, note]);@@ -127,7 +131,10 @@ export function NoteDialog({return (<Dialog open={open} onOpenChange={handleDialogClose}>- <DialogContent className="sm:max-w-[480px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogContent+ key={note?.id || "new-note"}+ className="sm:max-w-[480px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl"+ ><DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5"><DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text flex items-center gap-2"><div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/30">diff --git a/components/preset-edit-dialog.tsx b/components/preset-edit-dialog.tsxindex 842c579..b7ee932 100644--- a/components/preset-edit-dialog.tsx+++ b/components/preset-edit-dialog.tsx@@ -43,23 +43,9 @@ export function PresetEditDialog({onSave,}: PresetEditDialogProps) {const t = useTranslations();- const [formData, setFormData] = useState<PresetFormData>({- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- hideFromStats: false,- });- const initialDataRef = useRef<PresetFormData | null>(null);- const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const isInitialMount = useRef(true);-- useEffect(() => {- if (open && preset && !isCreating) {- const initialData = {+ const [formData, setFormData] = useState<PresetFormData>(() => {+ if (preset && !isCreating) {+ return {title: preset.title,startTime: preset.startTime,endTime: preset.endTime,@@ -69,29 +55,72 @@ export function PresetEditDialog({isAllDay: preset.isAllDay || false,hideFromStats: preset.hideFromStats || false,};- setFormData(initialData);- initialDataRef.current = initialData;- isInitialMount.current = true;- } else if (open && isCreating) {- const initialData = {- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- hideFromStats: false,- };- setFormData(initialData);- initialDataRef.current = initialData;- isInitialMount.current = true;- } else if (!open) {+ }+ return {+ title: "",+ startTime: "09:00",+ endTime: "17:00",+ color: PRESET_COLORS[0].value,+ notes: "",+ isSecondary: false,+ isAllDay: false,+ hideFromStats: false,+ };+ });+ const initialDataRef = useRef<PresetFormData | null>(null);+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const isInitialMount = useRef(true);+ const prevPresetIdRef = useRef<string | undefined>(undefined);+ const prevIsCreatingRef = useRef<boolean>(isCreating);++ // Update formData when preset changes (only when preset ID or mode actually changes)+ useEffect(() => {+ if (!open) {// Clear timeout when dialog closesif (saveTimeoutRef.current) {clearTimeout(saveTimeoutRef.current);saveTimeoutRef.current = null;}+ return;+ }++ const currentPresetId = preset?.id;+ const modeChanged = prevIsCreatingRef.current !== isCreating;++ // Only update if preset ID or mode changed to avoid cascading renders+ if (prevPresetIdRef.current !== currentPresetId || modeChanged) {+ if (preset && !isCreating) {+ const initialData = {+ title: preset.title,+ startTime: preset.startTime,+ endTime: preset.endTime,+ color: preset.color,+ notes: preset.notes || "",+ isSecondary: preset.isSecondary || false,+ isAllDay: preset.isAllDay || false,+ hideFromStats: preset.hideFromStats || false,+ };+ // eslint-disable-next-line react-hooks/set-state-in-effect+ setFormData(initialData);+ initialDataRef.current = initialData;+ isInitialMount.current = true;+ } else if (isCreating) {+ const initialData = {+ title: "",+ startTime: "09:00",+ endTime: "17:00",+ color: PRESET_COLORS[0].value,+ notes: "",+ isSecondary: false,+ isAllDay: false,+ hideFromStats: false,+ };+ setFormData(initialData);+ initialDataRef.current = initialData;+ isInitialMount.current = true;+ }+ prevPresetIdRef.current = currentPresetId;+ prevIsCreatingRef.current = isCreating;}}, [open, preset, isCreating]);@@ -147,7 +176,10 @@ export function PresetEditDialog({return (<Dialog open={open} onOpenChange={handleDialogClose}>- <DialogContent className="max-h-[90vh] overflow-y-auto overflow-x-hidden w-[95vw] max-w-[520px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogContent+ key={preset?.id || "new-preset"}+ className="max-h-[90vh] overflow-y-auto overflow-x-hidden w-[95vw] max-w-[520px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl"+ ><DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5"><DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">{isCreating ? t("preset.createNew") : t("preset.edit")}diff --git a/components/preset-selector.tsx b/components/preset-selector.tsxindex 63849d2..5442416 100644--- a/components/preset-selector.tsx+++ b/components/preset-selector.tsx@@ -158,6 +158,7 @@ export function PresetSelector({onPresetsChange();if (onShiftsChange) onShiftsChange();+ if (onStatsRefresh) onStatsRefresh();toast.success(t("common.deleted", { item: t("preset.create") }));} catch (error) {console.error("Failed to delete preset:", error);diff --git a/components/shift-dialog.tsx b/components/shift-dialog.tsxindex eceeab6..dc0a427 100644--- a/components/shift-dialog.tsx+++ b/components/shift-dialog.tsx@@ -59,7 +59,6 @@ export function ShiftDialog({applyPreset,saveAsPresetHandler,resetForm,- refetchPresets,} = useShiftForm({ open, shift, selectedDate, calendarId });const initialDataRef = useRef<ShiftFormData | null>(null);diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsxindex 52b2b63..71a6681 100644--- a/components/shift-form-fields.tsx+++ b/components/shift-form-fields.tsx@@ -1,4 +1,4 @@-import { motion, AnimatePresence } from "motion/react";+import { motion } from "motion/react";import { useTranslations } from "next-intl";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -7,7 +7,6 @@ import { Checkbox } from "@/components/ui/checkbox";import { ColorPicker } from "@/components/ui/color-picker";import { ShiftFormData } from "@/components/shift-dialog";import { PRESET_COLORS } from "@/lib/constants";-import { Check } from "lucide-react";interface ShiftFormFieldsProps {formData: ShiftFormData;@@ -30,7 +29,6 @@ export function ShiftFormFields({onPresetNameChange,isEditing,onBlur,- showSaved = false,}: ShiftFormFieldsProps) {const t = useTranslations();diff --git a/components/shift-stats.tsx b/components/shift-stats.tsxindex d61202f..e1276a0 100644--- a/components/shift-stats.tsx+++ b/components/shift-stats.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, useCallback, useRef } from "react";import { useTranslations } from "next-intl";import { Button } from "@/components/ui/button";import { BarChart3, ChevronDown, ChevronUp } from "lucide-react";@@ -29,46 +29,51 @@ export function ShiftStats({const [stats, setStats] = useState<ShiftStats | null>(null);const [loading, setLoading] = useState(false);const [isExpanded, setIsExpanded] = useState(true);+ const isInitialLoadRef = useRef(true);- useEffect(() => {- if (calendarId) {- fetchStats();- }- }, [calendarId, period, currentDate, refreshTrigger]);+ const fetchStats = useCallback(+ async (silent = false) => {+ if (!calendarId) return;- const fetchStats = async () => {- if (!calendarId) return;+ if (!silent) {+ setLoading(true);+ }- const isInitialLoad = stats === null;- if (isInitialLoad) {- setLoading(true);- }+ try {+ const password = getCachedPassword(calendarId);+ const params = new URLSearchParams({+ calendarId,+ period,+ date: currentDate.toISOString(),+ });+ if (password) {+ params.append("password", password);+ }- try {- const password = getCachedPassword(calendarId);- const params = new URLSearchParams({- calendarId,- period,- date: currentDate.toISOString(),- });- if (password) {- params.append("password", password);+ const response = await fetch(`/api/shifts/stats?${params}`);+ if (!response.ok) {+ return; // Calendar is locked and no valid password+ }+ const data = await response.json();+ setStats(data);+ } catch (error) {+ console.error("Failed to fetch shift statistics:", error);+ } finally {+ if (!silent) {+ setLoading(false);+ }}+ },+ [calendarId, period, currentDate]+ );- const response = await fetch(`/api/shifts/stats?${params}`);- if (!response.ok) {- return; // Calendar is locked and no valid password- }- const data = await response.json();- setStats(data);- } catch (error) {- console.error("Failed to fetch shift statistics:", error);- } finally {- if (isInitialLoad) {- setLoading(false);- }+ // Fetch stats when dependencies change+ useEffect(() => {+ if (calendarId) {+ fetchStats(!isInitialLoadRef.current);+ isInitialLoadRef.current = false;}- };+ }, [calendarId, refreshTrigger, fetchStats]);if (!calendarId) return null;diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsxindex 9aee04c..f29b1d3 100644--- a/components/sync-notification-dialog.tsx+++ b/components/sync-notification-dialog.tsx@@ -43,7 +43,6 @@ export function SyncNotificationDialog({onOpenChange,calendarId,onErrorsMarkedRead,- onSyncLogUpdate,syncLogRefreshTrigger,}: SyncNotificationDialogProps) {const t = useTranslations();diff --git a/components/theme-switcher.tsx b/components/theme-switcher.tsxindex dcdd37c..0cd9c53 100644--- a/components/theme-switcher.tsx+++ b/components/theme-switcher.tsx@@ -4,25 +4,10 @@ import { useTheme } from "next-themes";import { useTranslations } from "next-intl";import { Moon, Sun } from "lucide-react";import { Button } from "@/components/ui/button";-import { useEffect, useState } from "react";export function ThemeSwitcher() {const { theme, setTheme } = useTheme();const t = useTranslations();- const [mounted, setMounted] = useState(false);-- useEffect(() => {- setMounted(true);- }, []);-- if (!mounted) {- return (- <Button variant="ghost" size="icon" className="h-9 w-9" disabled>- <Sun className="h-4 w-4" />- <span className="sr-only">{t("common.loading")}</span>- </Button>- );- }const toggleTheme = () => {setTheme(theme === "dark" ? "light" : "dark");diff --git a/components/themed-toaster.tsx b/components/themed-toaster.tsxindex 8fbc107..a2b4125 100644--- a/components/themed-toaster.tsx+++ b/components/themed-toaster.tsx@@ -2,19 +2,9 @@import { Toaster } from "sonner";import { useTheme } from "next-themes";-import { useEffect, useState } from "react";export function ThemedToaster() {const { theme } = useTheme();- const [mounted, setMounted] = useState(false);-- useEffect(() => {- setMounted(true);- }, []);-- if (!mounted) {- return null;- }return (<Toasterdiff --git a/hooks/useCalendars.ts b/hooks/useCalendars.tsindex 4dc9ef9..155160f 100644--- a/hooks/useCalendars.ts+++ b/hooks/useCalendars.ts@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useCallback, useRef } from "react";import { CalendarWithCount } from "@/lib/types";import { toast } from "sonner";import { useTranslations } from "next-intl";@@ -12,26 +12,43 @@ export function useCalendars(initialCalendarId?: string | null) {>();const [loading, setLoading] = useState(true);- const fetchCalendars = async () => {+ // Capture initialCalendarId on mount to prevent dependency changes+ const initialCalendarIdRef = useRef(initialCalendarId);++ const fetchCalendars = useCallback(async () => {try {const response = await fetch("/api/calendars");const data = await response.json();setCalendars(data);- if (- initialCalendarId &&- data.some((cal: CalendarWithCount) => cal.id === initialCalendarId)- ) {- setSelectedCalendar(initialCalendarId);- } else if (data.length > 0 && !selectedCalendar) {- setSelectedCalendar(data[0].id);- }+ // Only auto-select on initial load+ setSelectedCalendar((current) => {+ // If a calendar is already selected and still exists, keep it+ if (+ current &&+ data.some((cal: CalendarWithCount) => cal.id === current)+ ) {+ return current;+ }+ // Otherwise, try initialCalendarId or fallback to first calendar+ if (+ initialCalendarIdRef.current &&+ data.some(+ (cal: CalendarWithCount) => cal.id === initialCalendarIdRef.current+ )+ ) {+ return initialCalendarIdRef.current;+ } else if (data.length > 0) {+ return data[0].id;+ }+ return undefined;+ });} catch (error) {console.error("Failed to fetch calendars:", error);} finally {setLoading(false);}- };+ }, []);const createCalendar = async (name: string,@@ -126,9 +143,10 @@ export function useCalendars(initialCalendarId?: string | null) {return false;};+ // Initial calendar fetchuseEffect(() => {fetchCalendars();- }, []);+ }, [fetchCalendars]);return {calendars,diff --git a/hooks/useExternalSync.ts b/hooks/useExternalSync.tsindex 7962619..223529c 100644--- a/hooks/useExternalSync.ts+++ b/hooks/useExternalSync.ts@@ -1,5 +1,5 @@import { useState, useEffect, useCallback } from "react";-import { ExternalSync } from "@/lib/db/schema";+import { ExternalSync, SyncLog } from "@/lib/db/schema";import { getCachedPassword } from "@/lib/password-cache";export function useExternalSync(selectedCalendar: string | null) {@@ -49,9 +49,9 @@ export function useExternalSync(selectedCalendar: string | null) {const response = await fetch(`/api/sync-logs?${params}`);if (response.ok) {- const logs = await response.json();+ const logs: SyncLog[] = await response.json();const hasErrors = logs.some(- (log: any) => log.status === "error" && !log.isRead+ (log: SyncLog) => log.status === "error" && !log.isRead);setHasSyncErrors(hasErrors);}@@ -60,10 +60,15 @@ export function useExternalSync(selectedCalendar: string | null) {}}, [selectedCalendar]);+ // Fetch syncs and error status when calendar changesuseEffect(() => {- fetchExternalSyncs();- fetchSyncErrorStatus();- }, [fetchExternalSyncs, fetchSyncErrorStatus]);+ if (selectedCalendar) {+ const initializeData = async () => {+ await Promise.all([fetchExternalSyncs(), fetchSyncErrorStatus()]);+ };+ initializeData();+ }+ }, [selectedCalendar, fetchExternalSyncs, fetchSyncErrorStatus]);return {externalSyncs,diff --git a/hooks/useNotes.ts b/hooks/useNotes.tsindex 154bcce..5071a96 100644--- a/hooks/useNotes.ts+++ b/hooks/useNotes.ts@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useCallback } from "react";import { CalendarNote } from "@/lib/db/schema";import { formatDateToLocal } from "@/lib/date-utils";import { toast } from "sonner";@@ -9,7 +9,7 @@ export function useNotes(calendarId: string | undefined) {const t = useTranslations();const [notes, setNotes] = useState<CalendarNote[]>([]);- const fetchNotes = async () => {+ const fetchNotes = useCallback(async () => {if (!calendarId) return;try {@@ -38,7 +38,7 @@ export function useNotes(calendarId: string | undefined) {// Network errors or other exceptions - don't clear existing notesconsole.error("Failed to fetch notes:", error);}- };+ }, [calendarId]);const createNote = async (noteText: string,@@ -167,13 +167,17 @@ export function useNotes(calendarId: string | undefined) {}};+ // Fetch notes when calendar changes+useEffect(() => {- if (calendarId) {- fetchNotes();- } else {+ if (!calendarId) {+ // Data fetching on mount/calendar change is a valid effect use case+ // eslint-disable-next-line react-hooks/set-state-in-effectsetNotes([]);+ return;}- }, [calendarId]);+ fetchNotes();+ }, [calendarId, fetchNotes]);return {notes,diff --git a/hooks/usePasswordManagement.ts b/hooks/usePasswordManagement.tsindex 07e3052..2cbd7d2 100644--- a/hooks/usePasswordManagement.ts+++ b/hooks/usePasswordManagement.ts@@ -25,7 +25,7 @@ export function usePasswordManagement(const [isCalendarUnlocked, setIsCalendarUnlocked] = useState(true);const [isVerifyingCalendarPassword, setIsVerifyingCalendarPassword] =useState(false);- const [passwordCacheTrigger, setPasswordCacheTrigger] = useState(0);+ const [forceUpdate, setForceUpdate] = useState(0);const selectedCalendarData = useMemo(() => {return calendars.find((c) => c.id === selectedCalendar);@@ -36,7 +36,8 @@ export function usePasswordManagement(const requiresPassword = !!selectedCalendarData.passwordHash;const hasPassword = !!getCachedPassword(selectedCalendar);return requiresPassword && !hasPassword;- }, [selectedCalendar, selectedCalendarData, passwordCacheTrigger]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selectedCalendar, selectedCalendarData, forceUpdate]);const selectedCalendarIsLocked = useMemo(() => {if (!selectedCalendar) return false;@@ -46,41 +47,67 @@ export function usePasswordManagement(// Verify password when calendar changesuseEffect(() => {- if (!selectedCalendar) {- setIsCalendarUnlocked(true);- setIsVerifyingCalendarPassword(false);- return;- }-- if (selectedCalendarIsLocked) {- const cachedPassword = getCachedPassword(selectedCalendar);-- if (cachedPassword) {- setIsVerifyingCalendarPassword(true);- setIsCalendarUnlocked(false);-- verifyAndCachePassword(selectedCalendar, cachedPassword)- .then((result) => {- setIsCalendarUnlocked(result.valid);- })- .catch(() => {+ let cancelled = false;++ const verifyCalendar = async () => {+ if (!selectedCalendar) {+ if (!cancelled) {+ setIsCalendarUnlocked(true);+ setIsVerifyingCalendarPassword(false);+ }+ return;+ }++ if (selectedCalendarIsLocked) {+ const cachedPassword = getCachedPassword(selectedCalendar);++ if (cachedPassword) {+ if (!cancelled) {+ setIsVerifyingCalendarPassword(true);+ setIsCalendarUnlocked(false);+ }++ verifyAndCachePassword(selectedCalendar, cachedPassword)+ .then((result) => {+ if (!cancelled) {+ setIsCalendarUnlocked(result.valid);+ }+ })+ .catch(() => {+ if (!cancelled) {+ setIsCalendarUnlocked(false);+ }+ })+ .finally(() => {+ if (!cancelled) {+ setIsVerifyingCalendarPassword(false);+ }+ });+ } else {+ if (!cancelled) {setIsCalendarUnlocked(false);- })- .finally(() => {setIsVerifyingCalendarPassword(false);- });+ }+ }} else {- setIsCalendarUnlocked(false);- setIsVerifyingCalendarPassword(false);+ if (!cancelled) {+ setIsCalendarUnlocked(true);+ setIsVerifyingCalendarPassword(false);+ }}- } else {- setIsCalendarUnlocked(true);- setIsVerifyingCalendarPassword(false);- }+ };++ verifyCalendar();++ return () => {+ cancelled = true;+ };}, [selectedCalendar, selectedCalendarIsLocked]);const handlePasswordSuccess = useCallback(() => {- setPasswordCacheTrigger((prev) => prev + 1);+ // Password is now verified and cached - trigger re-render to update shouldHideUIElements+ setIsCalendarUnlocked(true);+ setForceUpdate((prev) => prev + 1);}, []);const verifyPasswordForAction = useCallback(diff --git a/hooks/usePresets.ts b/hooks/usePresets.tsindex 2a2f543..4ddfcc9 100644--- a/hooks/usePresets.ts+++ b/hooks/usePresets.ts@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useCallback } from "react";import { ShiftPreset } from "@/lib/db/schema";import { getCachedPassword } from "@/lib/password-cache";@@ -6,37 +6,44 @@ export function usePresets(calendarId: string | undefined) {const [presets, setPresets] = useState<ShiftPreset[]>([]);const [loading, setLoading] = useState(true);- const fetchPresets = async () => {- if (!calendarId) {- setPresets([]);- setLoading(false);- return;- }+ const fetchPresets = useCallback(+ async (silent = false) => {+ if (!calendarId) {+ setPresets([]);+ setLoading(false);+ return;+ }- setLoading(true);- try {- const password = getCachedPassword(calendarId);- const params = new URLSearchParams({ calendarId });- if (password) {- params.append("password", password);+ if (!silent) {+ setLoading(true);}+ try {+ const password = getCachedPassword(calendarId);+ const params = new URLSearchParams({ calendarId });+ if (password) {+ params.append("password", password);+ }- const response = await fetch(`/api/presets?${params}`);- if (!response.ok) {- // Calendar is locked and no valid password - return empty array+ const response = await fetch(`/api/presets?${params}`);+ if (!response.ok) {+ // Calendar is locked and no valid password - return empty array+ setPresets([]);+ setLoading(false);+ return;+ }+ const data = await response.json();+ setPresets(data);+ } catch (error) {+ console.error("Failed to fetch presets:", error);setPresets([]);- setLoading(false);- return;+ } finally {+ if (!silent) {+ setLoading(false);+ }}- const data = await response.json();- setPresets(data);- } catch (error) {- console.error("Failed to fetch presets:", error);- setPresets([]);- } finally {- setLoading(false);- }- };+ },+ [calendarId]+ );useEffect(() => {if (calendarId) {@@ -45,7 +52,7 @@ export function usePresets(calendarId: string | undefined) {setPresets([]);setLoading(false);}- }, [calendarId]);+ }, [calendarId, fetchPresets]);return {presets,diff --git a/hooks/useSSEConnection.ts b/hooks/useSSEConnection.tsindex f6bb7f0..ec57171 100644--- a/hooks/useSSEConnection.ts+++ b/hooks/useSSEConnection.ts@@ -20,16 +20,22 @@ export function useSSEConnection({onNoteUpdate,onStatsRefresh,onSyncLogUpdate,- isConnected,setIsConnected,}: SSEConnectionOptions) {const t = useTranslations();const eventSourceRef = useRef<EventSource | null>(null);- const lastSyncTimeRef = useRef<number>(Date.now());+ const lastSyncTimeRef = useRef<number>(0);const disconnectTimeRef = useRef<number | null>(null);const errorTimeoutRef = useRef<NodeJS.Timeout | null>(null);const resyncTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ // Initialize lastSyncTimeRef on mount+ useEffect(() => {+ if (lastSyncTimeRef.current === 0) {+ lastSyncTimeRef.current = Date.now();+ }+ }, []);+// Refs to avoid stale closures in SSE handlersconst shiftUpdateRef = useRef(onShiftUpdate);const presetUpdateRef = useRef(onPresetUpdate);diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.tsindex 08cc004..0ba4995 100644--- a/hooks/useShiftForm.ts+++ b/hooks/useShiftForm.ts@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useRef } from "react";import { ShiftFormData } from "@/components/shift-dialog";import { ShiftPreset } from "@/lib/db/schema";import { ShiftWithCalendar } from "@/lib/types";@@ -101,10 +101,14 @@ export function useShiftForm({setSaveAsPreset(false);};- // Update form data when dialog opens or shift/date changes+ // Sync form data when dialog state changes (refs only)+ const formDataRef = useRef(formData);+ formDataRef.current = formData;++ // Only update on mount or when key changesuseEffect(() => {if (open) {- setFormData({+ const newFormData = {date:shift?.date && shift.date instanceof Date? formatDateToLocal(shift.date)@@ -117,11 +121,26 @@ export function useShiftForm({notes: shift?.notes || "",color: shift?.color || "#3b82f6",isAllDay: shift?.isAllDay || false,- });- setSaveAsPreset(false);- setPresetName("");+ };++ // Compare form data fields directly+ const needsUpdate =+ formDataRef.current.date !== newFormData.date ||+ formDataRef.current.startTime !== newFormData.startTime ||+ formDataRef.current.endTime !== newFormData.endTime ||+ formDataRef.current.title !== newFormData.title ||+ formDataRef.current.notes !== newFormData.notes ||+ formDataRef.current.color !== newFormData.color ||+ formDataRef.current.isAllDay !== newFormData.isAllDay;++ if (needsUpdate) {+ setFormData(newFormData);+ setSaveAsPreset(false);+ setPresetName("");+ }}- }, [open, selectedDate, shift]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, shift?.id, selectedDate?.toString()]);return {formData,diff --git a/hooks/useShifts.ts b/hooks/useShifts.tsindex 4d53877..0f9c3fe 100644--- a/hooks/useShifts.ts+++ b/hooks/useShifts.ts@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useCallback } from "react";import { ShiftWithCalendar } from "@/lib/types";import { ShiftFormData } from "@/components/shift-dialog";import { toast } from "sonner";@@ -9,7 +9,7 @@ export function useShifts(calendarId: string | undefined) {const t = useTranslations();const [shifts, setShifts] = useState<ShiftWithCalendar[]>([]);- const fetchShifts = async () => {+ const fetchShifts = useCallback(async () => {if (!calendarId) return;try {@@ -31,7 +31,7 @@ export function useShifts(calendarId: string | undefined) {console.error("Failed to fetch shifts:", error);setShifts([]);}- };+ }, [calendarId]);const createShift = async (formData: ShiftFormData) => {if (!calendarId) return null;@@ -168,13 +168,17 @@ export function useShifts(calendarId: string | undefined) {}};+ // Fetch shifts when calendar changes+useEffect(() => {- if (calendarId) {- fetchShifts();- } else {+ if (!calendarId) {+ // Data fetching on mount/calendar change is a valid effect use case+ // eslint-disable-next-line react-hooks/set-state-in-effectsetShifts([]);+ return;}- }, [calendarId]);+ fetchShifts();+ }, [calendarId, fetchShifts]);return {shifts,diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.tsindex c2f570c..babe0c2 100644--- a/lib/auto-sync-service.ts+++ b/lib/auto-sync-service.ts@@ -6,7 +6,7 @@import { db } from "@/lib/db";import { externalSyncs } from "@/lib/db/schema";-import { gt, eq } from "drizzle-orm";+import { gt } from "drizzle-orm";import { eventEmitter } from "@/lib/event-emitter";import { syncExternalCalendar } from "@/app/api/external-syncs/[id]/sync/route";diff --git a/lib/request.ts b/lib/request.tsindex 90b59cd..87b8264 100644--- a/lib/request.ts+++ b/lib/request.ts@@ -1,4 +1,3 @@-import { notFound } from "next/navigation";import { getRequestConfig } from "next-intl/server";import { locales } from "./locales";@@ -6,7 +5,7 @@ export default getRequestConfig(async ({ requestLocale }) => {let locale = await requestLocale;// Ensure that the incoming locale is valid- if (!locale || !locales.includes(locale as any)) {+ if (!locale || !(locales as readonly string[]).includes(locale)) {locale = "en";}