Skip to content

Your favorite shift management application!

fix: shift toggle handling for concurrent date actions (#6)

panteLd33cd6066e44
diff --git a/app/page.tsx b/app/page.tsx
index a15bc79..aa5d7e4 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -109,7 +109,7 @@ function HomeContent() {
noteAction?: () => Promise<void>;
} | null>(null);
const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);
- const [isTogglingShift, setIsTogglingShift] = useState(false);
+ const [togglingDates, setTogglingDates] = useState<Set<string>>(new Set());
const [isConnected, setIsConnected] = useState(true);
const [version, setVersion] = useState<string | null>(null);
@@ -302,7 +302,11 @@ function HomeContent() {
setShowNoteDialog(true);
};
- const handleLongPress = (date: Date) => {
+ const handleDayClick = (date: Date) => {
+ handleAddShift(date);
+ };
+
+ const handleLongPressDay = (date: Date) => {
setSelectedDate(date);
const existingNote = notes.find(
(note) => note.date && isSameDay(new Date(note.date), date)
@@ -381,12 +385,20 @@ function HomeContent() {
};
const handleAddShift = async (date: Date) => {
- if (isTogglingShift || !selectedPresetId) return;
+ if (!selectedPresetId) return;
const preset = presets.find((p) => p.id === selectedPresetId);
if (!preset) return;
- setIsTogglingShift(true);
+ // Capture date immediately to prevent wrong date assignment
+ const targetDate = new Date(date);
+ const dateKey = formatDateToLocal(targetDate);
+
+ // Check if this date is already being toggled
+ if (togglingDates.has(dateKey)) return;
+
+ // Add date to toggling set
+ setTogglingDates((prev) => new Set(prev).add(dateKey));
try {
const password = selectedCalendar
@@ -409,10 +421,14 @@ function HomeContent() {
localStorage.removeItem(`calendar_password_${selectedCalendar}`);
setPendingAction({
type: "edit",
- presetAction: () => handleAddShift(date),
+ presetAction: () => handleAddShift(targetDate),
});
setShowPasswordDialog(true);
- setIsTogglingShift(false);
+ setTogglingDates((prev) => {
+ const next = new Set(prev);
+ next.delete(dateKey);
+ return next;
+ });
return;
}
}
@@ -420,13 +436,15 @@ function HomeContent() {
const existingShift = shifts.find(
(shift) =>
shift.date &&
- isSameDay(new Date(shift.date), date) &&
+ isSameDay(new Date(shift.date), targetDate) &&
shift.title === preset.title &&
shift.startTime === preset.startTime &&
shift.endTime === preset.endTime
);
if (existingShift) {
+ // Optimistic UI update - remove shift immediately
+ const previousShifts = [...shifts];
setShifts(shifts.filter((s) => s.id !== existingShift.id));
setStatsRefreshTrigger((prev) => prev + 1);
@@ -440,7 +458,8 @@ function HomeContent() {
});
if (!response.ok) {
- setShifts(shifts);
+ // Revert on error
+ setShifts(previousShifts);
setStatsRefreshTrigger((prev) => prev + 1);
toast.error(t("shift.deleteError"));
} else {
@@ -448,13 +467,14 @@ function HomeContent() {
}
} catch (error) {
console.error("Failed to delete shift:", error);
- setShifts(shifts);
+ // Revert on error
+ setShifts(previousShifts);
setStatsRefreshTrigger((prev) => prev + 1);
toast.error(t("shift.deleteError"));
}
} else {
const shiftData: ShiftFormData = {
- date: formatDateToLocal(date),
+ date: dateKey,
startTime: preset.startTime,
endTime: preset.endTime,
title: preset.title,
@@ -463,11 +483,19 @@ function HomeContent() {
presetId: preset.id,
isAllDay: preset.isAllDay || false,
};
- await createShiftHook(shiftData);
- setStatsRefreshTrigger((prev) => prev + 1);
+
+ const newShift = await createShiftHook(shiftData);
+ if (newShift) {
+ setStatsRefreshTrigger((prev) => prev + 1);
+ }
}
} finally {
- setIsTogglingShift(false);
+ // Remove date from toggling set
+ setTogglingDates((prev) => {
+ const next = new Set(prev);
+ next.delete(dateKey);
+ return next;
+ });
}
};
@@ -617,11 +645,11 @@ function HomeContent() {
shifts={shifts}
notes={notes}
selectedPresetId={selectedPresetId}
- isTogglingShift={isTogglingShift}
- onDayClick={handleAddShift}
+ togglingDates={togglingDates}
+ onDayClick={handleDayClick}
onDayRightClick={handleDayRightClick}
onNoteIconClick={handleNoteIconClick}
- onLongPress={handleLongPress}
+ onLongPress={handleLongPressDay}
/>
{/* Note Hint */}
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
index 0800e4f..c7f7bb7 100644
--- a/components/calendar-grid.tsx
+++ b/components/calendar-grid.tsx
@@ -5,6 +5,7 @@ import { CalendarNote } from "@/lib/db/schema";
import { isToday } from "date-fns";
import { useTranslations } from "next-intl";
import { useRef, useEffect } from "react";
+import { formatDateToLocal } from "@/lib/date-utils";
interface CalendarGridProps {
calendarDays: Date[];
@@ -12,7 +13,7 @@ interface CalendarGridProps {
shifts: ShiftWithCalendar[];
notes: CalendarNote[];
selectedPresetId: string | undefined;
- isTogglingShift: boolean;
+ togglingDates: Set<string>;
onDayClick: (date: Date) => void;
onDayRightClick: (e: React.MouseEvent, date: Date) => void;
onNoteIconClick: (e: React.MouseEvent, date: Date) => void;
@@ -25,7 +26,7 @@ export function CalendarGrid({
shifts,
notes,
selectedPresetId,
- isTogglingShift,
+ togglingDates,
onDayClick,
onDayRightClick,
onNoteIconClick,
@@ -84,7 +85,9 @@ export function CalendarGrid({
const isCurrentMonth = day.getMonth() === currentDate.getMonth();
const isTodayDate = isToday(day);
- const dayKey = `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`;
+ // Use formatDateToLocal to match the format used in handleAddShift
+ const dayKey = formatDateToLocal(day);
+ const isToggling = togglingDates.has(dayKey);
const handleTouchStart = (e: React.TouchEvent) => {
pressTimerRef.current[dayKey] = setTimeout(
@@ -110,7 +113,7 @@ export function CalendarGrid({
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
onTouchMove={handleTouchEnd}
- disabled={false}
+ disabled={isToggling}
whileTap={{ scale: 0.95 }}
style={{
WebkitUserSelect: "none",
@@ -133,6 +136,7 @@ export function CalendarGrid({
: "cursor-pointer"
}
${!isCurrentMonth ? "opacity-40" : ""}
+ ${isToggling ? "opacity-50 cursor-wait pointer-events-none" : ""}
`}
>
<div
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 4fe6d3f..8c3d34c 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -21,7 +21,7 @@ export function useShifts(calendarId: string | undefined) {
};
const createShift = async (formData: ShiftFormData) => {
- if (!calendarId) return;
+ if (!calendarId) return null;
const tempId = `temp-${Date.now()}`;
const optimisticShift: ShiftWithCalendar = {
@@ -58,7 +58,7 @@ export function useShifts(calendarId: string | undefined) {
);
setShifts((shifts) => shifts.filter((s) => s.id !== tempId));
toast.error(t("shift.createError"));
- return;
+ return null;
}
const newShift = await response.json();
@@ -66,10 +66,12 @@ export function useShifts(calendarId: string | undefined) {
shifts.map((s) => (s.id === tempId ? newShift : s))
);
toast.success(t("shift.created"));
+ return newShift;
} catch (error) {
console.error("Failed to create shift:", error);
setShifts((shifts) => shifts.filter((s) => s.id !== tempId));
toast.error(t("shift.createError"));
+ return null;
}
};