Skip to content

Your favorite shift management application!

feat: Adds debounced auto-save to edit dialogs (#25)

panteLb28c649d6d28
diff --git a/app/page.tsx b/app/page.tsx
index 39252ea..ebd92e8 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -386,18 +386,14 @@ function HomeContent() {
noteText,
handlePasswordRequired
);
- if (success) {
- setShowNoteDialog(false);
- }
+ // Dialog stays open for Auto-Save
} else if (selectedDate) {
const success = await createNoteHook(
noteText,
selectedDate,
handlePasswordRequired
);
- if (success) {
- setShowNoteDialog(false);
- }
+ // Dialog stays open for Auto-Save
}
};
@@ -421,7 +417,7 @@ function HomeContent() {
handlePasswordRequired
);
if (success) {
- setShowNoteDialog(false);
+ setShowNoteDialog(false); // Close dialog after deletion
}
};
diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsx
index 0833bda..fcd2a63 100644
--- a/components/external-sync-manage-dialog.tsx
+++ b/components/external-sync-manage-dialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useCallback } from "react";
+import { useState, useEffect, useCallback, useRef } from "react";
import {
Dialog,
DialogContent,
@@ -60,6 +60,15 @@ export function ExternalSyncManageDialog({
const [formDisplayMode, setFormDisplayMode] = useState("normal");
const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);
+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const initialFormDataRef = useRef<{
+ name: string;
+ color: string;
+ displayMode: string;
+ autoSyncInterval: number;
+ } | null>(null);
+ const isInitialMount = useRef(true);
+
const fetchSyncs = useCallback(async () => {
if (!calendarId) return;
@@ -270,6 +279,15 @@ export function ExternalSyncManageDialog({
setFormDisplayMode(sync.displayMode || "normal");
setFormAutoSyncInterval(sync.autoSyncInterval || 0);
setShowAddForm(false);
+
+ // Set initial data for auto-save comparison
+ initialFormDataRef.current = {
+ name: sync.name,
+ color: sync.color,
+ displayMode: sync.displayMode || "normal",
+ autoSyncInterval: sync.autoSyncInterval || 0,
+ };
+ isInitialMount.current = true;
};
const cancelEdit = () => {
@@ -280,6 +298,13 @@ export function ExternalSyncManageDialog({
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
+ initialFormDataRef.current = null;
+
+ // Clear any pending save timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
};
const handleToggleVisibility = async (
@@ -345,6 +370,150 @@ export function ExternalSyncManageDialog({
setFormAutoSyncInterval(0);
};
+ // Shared function to save external sync changes
+ const saveExternalSyncChanges = useCallback(
+ async (updateInitialRef: boolean = false): Promise<boolean> => {
+ if (!editingSync) return false;
+
+ try {
+ const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: formName.trim(),
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ }),
+ });
+
+ if (response.ok) {
+ await fetchSyncs();
+ onSyncComplete?.();
+ if (updateInitialRef) {
+ // Update initial data ref after successful save
+ initialFormDataRef.current = {
+ name: formName,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ };
+ }
+ toast.success(t("externalSync.updateSuccess"));
+ return true;
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("externalSync.updateError"));
+ return false;
+ }
+ } catch (error) {
+ console.error("Failed to save sync:", error);
+ toast.error(t("externalSync.updateError"));
+ return false;
+ }
+ },
+ [
+ editingSync,
+ formName,
+ formColor,
+ formDisplayMode,
+ formAutoSyncInterval,
+ fetchSyncs,
+ onSyncComplete,
+ t,
+ ]
+ );
+
+ // Auto-save for editing external syncs
+ useEffect(() => {
+ if (!editingSync || !initialFormDataRef.current) return;
+
+ // Skip initial mount
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ return;
+ }
+
+ // Clear existing timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+
+ // Check if data has changed
+ const currentFormData = {
+ name: formName,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ };
+
+ const hasChanged =
+ JSON.stringify(currentFormData) !==
+ JSON.stringify(initialFormDataRef.current);
+
+ if (hasChanged && formName.trim()) {
+ saveTimeoutRef.current = setTimeout(() => {
+ saveExternalSyncChanges(true);
+ }, 1000); // 1 second debounce
+ }
+
+ return () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+ };
+ }, [
+ formName,
+ formColor,
+ formDisplayMode,
+ formAutoSyncInterval,
+ editingSync,
+ saveExternalSyncChanges,
+ ]);
+
+ // Handle dialog close with immediate save if needed
+ const handleDialogClose = async (open: boolean) => {
+ // If opening the dialog, proceed immediately
+ if (open) {
+ onOpenChange(open);
+ return;
+ }
+
+ // If closing and editing an existing sync, check for unsaved changes
+ if (editingSync && initialFormDataRef.current) {
+ // Cancel pending timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+
+ // Check if data has changed
+ const currentFormData = {
+ name: formName,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ };
+
+ const hasChanged =
+ JSON.stringify(currentFormData) !==
+ JSON.stringify(initialFormDataRef.current);
+
+ // Save immediately if data changed and name is not empty
+ if (hasChanged && formName.trim()) {
+ const success = await saveExternalSyncChanges(false);
+ if (!success) {
+ // Failed to save, keep dialog open
+ return;
+ }
+ // Save succeeded, proceed to close
+ }
+ }
+
+ // Close the dialog (only reached after successful save or no changes)
+ onOpenChange(false);
+ };
+
// Get URL placeholder and hint based on sync type
const getUrlPlaceholder = () => {
if (formSyncType === "google") {
@@ -361,7 +530,7 @@ export function ExternalSyncManageDialog({
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
+ <Dialog open={open} onOpenChange={handleDialogClose}>
<DialogContent className="sm:max-w-[600px] max-w-[95vw] max-h-[85vh] flex flex-col 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">
@@ -603,71 +772,81 @@ export function ExternalSyncManageDialog({
</div>
{editingSync && (
- <div className="space-y-3 pt-2 border-t border-border/30">
- <div className="flex items-center gap-2">
- <Checkbox
- id="hide-calendar"
- checked={editingSync.isHidden || false}
- onCheckedChange={() => {
- handleToggleVisibility(
- editingSync.id,
- "isHidden",
- editingSync.isHidden || false
- );
- }}
- />
- <Label
- htmlFor="hide-calendar"
- className="text-sm font-normal cursor-pointer"
- >
- {t("externalSync.hideCalendar")}
- </Label>
- </div>
- <p className="text-xs text-muted-foreground pl-6">
- {t("externalSync.hideCalendarHint")}
- </p>
-
- <div className="flex items-center gap-2">
- <Checkbox
- id="hide-from-stats"
- checked={
- editingSync.isHidden ||
- editingSync.hideFromStats ||
- false
- }
- onCheckedChange={() => {
- handleToggleVisibility(
- editingSync.id,
- "hideFromStats",
- editingSync.hideFromStats || false
- );
- }}
- disabled={editingSync.isHidden}
- />
- <Label
- htmlFor="hide-from-stats"
- className={`text-sm font-normal ${
- editingSync.isHidden
- ? "cursor-not-allowed opacity-50"
- : "cursor-pointer"
- }`}
- >
- {t("externalSync.hideFromStats")}
- </Label>
+ <>
+ <div className="space-y-3 pt-2 border-t border-border/30">
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="hide-calendar"
+ checked={editingSync.isHidden || false}
+ onCheckedChange={() => {
+ handleToggleVisibility(
+ editingSync.id,
+ "isHidden",
+ editingSync.isHidden || false
+ );
+ }}
+ />
+ <Label
+ htmlFor="hide-calendar"
+ className="text-sm font-normal cursor-pointer"
+ >
+ {t("externalSync.hideCalendar")}
+ </Label>
+ </div>
+ <p className="text-xs text-muted-foreground pl-6">
+ {t("externalSync.hideCalendarHint")}
+ </p>
+
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="hide-from-stats"
+ checked={
+ editingSync.isHidden ||
+ editingSync.hideFromStats ||
+ false
+ }
+ onCheckedChange={() => {
+ handleToggleVisibility(
+ editingSync.id,
+ "hideFromStats",
+ editingSync.hideFromStats || false
+ );
+ }}
+ disabled={editingSync.isHidden}
+ />
+ <Label
+ htmlFor="hide-from-stats"
+ className={`text-sm font-normal ${
+ editingSync.isHidden
+ ? "cursor-not-allowed opacity-50"
+ : "cursor-pointer"
+ }`}
+ >
+ {t("externalSync.hideFromStats")}
+ </Label>
+ </div>
+ <p className="text-xs text-muted-foreground pl-6">
+ {t("externalSync.hideFromStatsHint")}
+ </p>
</div>
- <p className="text-xs text-muted-foreground pl-6">
- {t("externalSync.hideFromStatsHint")}
- </p>
- </div>
+ </>
)}
- <div className="flex gap-2">
- <Button
- variant="outline"
- onClick={() => {
- if (editingSync) {
- cancelEdit();
- } else {
+ {editingSync ? (
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => cancelEdit()}
+ className="flex-1"
+ >
+ {t("common.close")}
+ </Button>
+ </div>
+ ) : (
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => {
setShowAddForm(false);
setFormName("");
setFormUrl("");
@@ -675,26 +854,22 @@ export function ExternalSyncManageDialog({
setFormColor("#3b82f6");
setFormDisplayMode("normal");
setFormAutoSyncInterval(0);
- }
- }}
- disabled={isLoading}
- >
- {t("common.cancel")}
- </Button>
- <Button
- onClick={editingSync ? handleUpdateSync : handleAddSync}
- disabled={
- isLoading ||
- !formName.trim() ||
- (!editingSync && !formUrl.trim())
- }
- >
- {isLoading ? (
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- ) : null}
- {editingSync ? t("common.save") : t("externalSync.addSync")}
- </Button>
- </div>
+ }}
+ disabled={isLoading}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ onClick={handleAddSync}
+ disabled={isLoading || !formName.trim() || !formUrl.trim()}
+ >
+ {isLoading ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ {t("externalSync.addSync")}
+ </Button>
+ </div>
+ )}
</div>
)}
diff --git a/components/note-dialog.tsx b/components/note-dialog.tsx
index 2523c6a..729f41b 100644
--- a/components/note-dialog.tsx
+++ b/components/note-dialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import { motion } from "motion/react";
import { StickyNote } from "lucide-react";
@@ -40,22 +40,73 @@ export function NoteDialog({
const t = useTranslations();
const locale = useLocale();
const [noteText, setNoteText] = useState("");
+ const initialNoteRef = useRef<string>("");
+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const isInitialMount = useRef(true);
useEffect(() => {
if (open) {
- setNoteText(note?.note || "");
+ 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;
+ }
}
}, [open, note]);
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- if (noteText.trim()) {
- onSubmit(noteText);
- setNoteText("");
- onOpenChange(false);
+ // Handle dialog close with immediate save if needed
+ const handleDialogClose = (open: boolean) => {
+ if (!open && noteText !== initialNoteRef.current) {
+ // Cancel pending timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ // Save immediately
+ if (noteText.trim()) {
+ onSubmit(noteText);
+ }
}
+ onOpenChange(open);
};
+ // Auto-save with debouncing
+ useEffect(() => {
+ if (!open) return;
+
+ // Skip initial mount
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ return;
+ }
+
+ // Clear existing timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+
+ // Only save if text has changed from initial value
+ if (noteText !== initialNoteRef.current) {
+ saveTimeoutRef.current = setTimeout(() => {
+ if (noteText.trim()) {
+ onSubmit(noteText);
+ initialNoteRef.current = noteText;
+ }
+ }, 1000); // 1 second debounce
+ }
+
+ return () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+ };
+ }, [noteText, open, onSubmit, onDelete, note]);
+
const handleDelete = () => {
if (onDelete) {
onDelete();
@@ -69,7 +120,7 @@ export function NoteDialog({
: "";
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
+ <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">
<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">
@@ -85,7 +136,7 @@ export function NoteDialog({
</div>
</DialogDescription>
</DialogHeader>
- <form onSubmit={handleSubmit} className="p-6 space-y-5">
+ <div className="p-6 space-y-5">
<div className="space-y-2.5">
<Label
htmlFor="note"
@@ -100,7 +151,6 @@ export function NoteDialog({
onChange={(e) => setNoteText(e.target.value)}
placeholder={t("note.notePlaceholder")}
className="min-h-[120px] border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-primary/5 backdrop-blur-sm resize-none"
- required
/>
</div>
<div className="flex justify-between items-center pt-2">
@@ -123,17 +173,11 @@ export function NoteDialog({
onClick={() => onOpenChange(false)}
className="h-11 border-border/50 hover:bg-muted/50"
>
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- className="h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
- >
- {t("common.save")}
+ {t("common.close")}
</Button>
</div>
</div>
- </form>
+ </div>
</DialogContent>
</Dialog>
);
diff --git a/components/preset-edit-dialog.tsx b/components/preset-edit-dialog.tsx
index 9d2408a..ca4e7fa 100644
--- a/components/preset-edit-dialog.tsx
+++ b/components/preset-edit-dialog.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import { motion } from "motion/react";
import {
@@ -53,10 +53,13 @@ export function PresetEditDialog({
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) {
- setFormData({
+ const initialData = {
title: preset.title,
startTime: preset.startTime,
endTime: preset.endTime,
@@ -65,9 +68,12 @@ export function PresetEditDialog({
isSecondary: preset.isSecondary || false,
isAllDay: preset.isAllDay || false,
hideFromStats: preset.hideFromStats || false,
- });
+ };
+ setFormData(initialData);
+ initialDataRef.current = initialData;
+ isInitialMount.current = true;
} else if (open && isCreating) {
- setFormData({
+ const initialData = {
title: "",
startTime: "09:00",
endTime: "17:00",
@@ -76,17 +82,71 @@ export function PresetEditDialog({
isSecondary: false,
isAllDay: false,
hideFromStats: false,
- });
+ };
+ setFormData(initialData);
+ initialDataRef.current = initialData;
+ isInitialMount.current = true;
+ } else if (!open) {
+ // Clear timeout when dialog closes
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
}
}, [open, preset, isCreating]);
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- onSave(formData);
+ // Auto-save with debouncing (only for editing existing presets)
+ useEffect(() => {
+ if (!open || isCreating || !initialDataRef.current) return;
+
+ // Skip initial mount
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ return;
+ }
+
+ // Clear existing timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+
+ // Check if data has changed and title is not empty
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialDataRef.current);
+ if (hasChanged && formData.title.trim()) {
+ saveTimeoutRef.current = setTimeout(() => {
+ onSave(formData);
+ initialDataRef.current = formData;
+ }, 1000); // 1 second debounce
+ }
+
+ return () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+ };
+ }, [formData, open, isCreating, onSave]);
+
+ // Handle dialog close with immediate save if needed
+ const handleDialogClose = (open: boolean) => {
+ if (!open && !isCreating && initialDataRef.current) {
+ // Cancel pending timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ // Save immediately if data changed and title is not empty
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialDataRef.current);
+ if (hasChanged && formData.title.trim()) {
+ onSave(formData);
+ }
+ }
+ onOpenChange(open);
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
+ <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">
<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">
@@ -102,7 +162,7 @@ export function PresetEditDialog({
})}
</DialogDescription>
</DialogHeader>
- <form onSubmit={handleSubmit} className="space-y-5 p-6">
+ <div className="space-y-5 p-6">
<div className="space-y-2.5">
<Label
htmlFor="preset-title"
@@ -119,7 +179,6 @@ export function PresetEditDialog({
setFormData({ ...formData, title: e.target.value })
}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- required
/>
</div>
@@ -248,17 +307,24 @@ export function PresetEditDialog({
onClick={() => onOpenChange(false)}
className="flex-1 h-11 border-border/50 hover:bg-muted/50"
>
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- disabled={!formData.title.trim()}
- className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
- >
- {isCreating ? t("common.create") : t("common.save")}
+ {t("common.close")}
</Button>
+ {isCreating && (
+ <Button
+ type="button"
+ onClick={() => {
+ if (formData.title.trim()) {
+ onSave(formData);
+ }
+ }}
+ disabled={!formData.title.trim()}
+ className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
+ >
+ {t("common.create")}
+ </Button>
+ )}
</div>
- </form>
+ </div>
</DialogContent>
</Dialog>
);
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index 194a79a..dfedd3a 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -112,9 +112,12 @@ export function PresetSelector({
}
onPresetsChange();
- setShowEditDialog(false);
- setEditingPreset(null);
- setIsCreatingNew(false);
+
+ if (isCreatingNew) {
+ setShowEditDialog(false);
+ setEditingPreset(null);
+ setIsCreatingNew(false);
+ }
} catch (error) {
console.error("Failed to save preset:", error);
toast.error(t("preset.saveError"));
diff --git a/components/shift-dialog.tsx b/components/shift-dialog.tsx
index ca1b8d4..eceeab6 100644
--- a/components/shift-dialog.tsx
+++ b/components/shift-dialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import {
Dialog,
@@ -13,6 +14,7 @@ import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormFields } from "@/components/shift-form-fields";
import { PresetSelect } from "@/components/preset-select";
import { useShiftForm } from "@/hooks/useShiftForm";
+import { formatDateToLocal } from "@/lib/date-utils";
interface ShiftDialogProps {
open: boolean;
@@ -60,7 +62,96 @@ export function ShiftDialog({
refetchPresets,
} = useShiftForm({ open, shift, selectedDate, calendarId });
- const handleSubmit = async (e: React.FormEvent) => {
+ const initialDataRef = useRef<ShiftFormData | null>(null);
+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const isInitialMount = useRef(true);
+
+ // Track initial data for auto-save comparison
+ useEffect(() => {
+ if (open && shift) {
+ initialDataRef.current = {
+ date:
+ shift.date && shift.date instanceof Date
+ ? formatDateToLocal(shift.date)
+ : formatDateToLocal(new Date()),
+ startTime: shift.startTime,
+ endTime: shift.endTime,
+ title: shift.title,
+ notes: shift.notes || "",
+ color: shift.color,
+ isAllDay: shift.isAllDay || false,
+ };
+ isInitialMount.current = true;
+ } else if (!open) {
+ // Clear timeout when dialog closes
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ }
+ }, [open, shift]);
+
+ // Auto-save for editing existing shifts
+ useEffect(() => {
+ if (!open || !shift || !initialDataRef.current) return;
+
+ // Skip initial mount
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ return;
+ }
+
+ // Clear existing timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+
+ // Check if data has changed and title is not empty
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialDataRef.current);
+ if (hasChanged && formData.title.trim()) {
+ saveTimeoutRef.current = setTimeout(() => {
+ const submitData = {
+ ...formData,
+ startTime: formData.isAllDay ? "00:00" : formData.startTime,
+ endTime: formData.isAllDay ? "23:59" : formData.endTime,
+ };
+ onSubmit(submitData);
+ initialDataRef.current = formData;
+ }, 1000); // 1 second debounce
+ }
+
+ return () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+ };
+ }, [formData, open, shift, onSubmit]);
+
+ // Handle dialog close with immediate save if needed
+ const handleDialogClose = (open: boolean) => {
+ if (!open && shift && initialDataRef.current) {
+ // Cancel pending timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ // Save immediately if data changed and title is not empty
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialDataRef.current);
+ if (hasChanged && formData.title.trim()) {
+ const submitData = {
+ ...formData,
+ startTime: formData.isAllDay ? "00:00" : formData.startTime,
+ endTime: formData.isAllDay ? "23:59" : formData.endTime,
+ };
+ onSubmit(submitData);
+ }
+ }
+ onOpenChange(open);
+ };
+
+ const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.title.trim()) return;
@@ -74,25 +165,25 @@ export function ShiftDialog({
onSubmit(submitData);
// Save as preset if enabled and it's a new shift
- if (!shift && saveAsPreset && presetName.trim()) {
+ if (saveAsPreset && presetName.trim()) {
const success = await saveAsPresetHandler(submitData);
if (success && onPresetsChange) {
onPresetsChange();
}
}
- if (!shift) {
- resetForm();
- }
+ resetForm();
onOpenChange(false);
};
- const handlePresetSelect = async (preset: Parameters<typeof applyPreset>[0]) => {
+ const handlePresetSelect = async (
+ preset: Parameters<typeof applyPreset>[0]
+ ) => {
applyPreset(preset);
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
+ <Dialog open={open} onOpenChange={handleDialogClose}>
<DialogContent className="sm:max-w-[520px] max-h-[90vh] flex flex-col 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 flex-shrink-0">
<DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
@@ -108,10 +199,15 @@ export function ShiftDialog({
})}
</DialogDescription>
</DialogHeader>
- <form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
+ <div className="flex flex-col flex-1 min-h-0">
<div className="p-6 space-y-5 overflow-y-auto flex-1">
{/* Preset Selection */}
- {!shift && <PresetSelect presets={presets} onPresetSelect={handlePresetSelect} />}
+ {!shift && (
+ <PresetSelect
+ presets={presets}
+ onPresetSelect={handlePresetSelect}
+ />
+ )}
<ShiftFormFields
formData={formData}
@@ -131,17 +227,20 @@ export function ShiftDialog({
onClick={() => onOpenChange(false)}
className="flex-1 h-11 border-border/50 hover:bg-muted/50"
>
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- disabled={!formData.title.trim()}
- className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
- >
- {shift ? t("shift.saveChanges") : t("shift.addShift")}
+ {t("common.close")}
</Button>
+ {!shift && (
+ <Button
+ type="button"
+ onClick={handleCreate}
+ disabled={!formData.title.trim()}
+ className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"
+ >
+ {t("shift.addShift")}
+ </Button>
+ )}
</div>
- </form>
+ </div>
</DialogContent>
</Dialog>
);
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index d6b76a1..dae7ae4 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -1,4 +1,4 @@
-import { motion } from "motion/react";
+import { motion, AnimatePresence } from "motion/react";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -7,6 +7,7 @@ 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;
@@ -16,6 +17,8 @@ interface ShiftFormFieldsProps {
presetName: string;
onPresetNameChange: (value: string) => void;
isEditing: boolean;
+ onBlur?: () => void;
+ showSaved?: boolean;
}
export function ShiftFormFields({
@@ -26,6 +29,8 @@ export function ShiftFormFields({
presetName,
onPresetNameChange,
isEditing,
+ onBlur,
+ showSaved = false,
}: ShiftFormFieldsProps) {
const t = useTranslations();
@@ -46,6 +51,7 @@ export function ShiftFormFields({
onChange={(e) =>
onFormDataChange({ ...formData, date: e.target.value })
}
+ onBlur={onBlur}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
/>
</div>
@@ -54,9 +60,10 @@ export function ShiftFormFields({
<Checkbox
id="allDay"
checked={formData.isAllDay}
- onCheckedChange={(checked) =>
- onFormDataChange({ ...formData, isAllDay: !!checked })
- }
+ onCheckedChange={(checked) => {
+ onFormDataChange({ ...formData, isAllDay: !!checked });
+ setTimeout(() => onBlur?.(), 10);
+ }}
/>
<Label htmlFor="allDay" className="text-sm font-medium cursor-pointer">
{t("shift.allDayShift")}
@@ -82,6 +89,7 @@ export function ShiftFormFields({
onChange={(e) =>
onFormDataChange({ ...formData, startTime: e.target.value })
}
+ onBlur={onBlur}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
/>
</div>
@@ -96,6 +104,7 @@ export function ShiftFormFields({
onChange={(e) =>
onFormDataChange({ ...formData, endTime: e.target.value })
}
+ onBlur={onBlur}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
/>
</div>
@@ -117,6 +126,7 @@ export function ShiftFormFields({
onChange={(e) =>
onFormDataChange({ ...formData, title: e.target.value })
}
+ onBlur={onBlur}
className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
autoFocus
/>
@@ -137,6 +147,7 @@ export function ShiftFormFields({
onChange={(e) =>
onFormDataChange({ ...formData, notes: e.target.value })
}
+ onBlur={onBlur}
rows={3}
className="border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 resize-none"
/>
diff --git a/messages/de.json b/messages/de.json
index 9973291..58128df 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -1,6 +1,7 @@
{
"common": {
"cancel": "Abbrechen",
+ "close": "Schließen",
"save": "Speichern",
"delete": "Löschen",
"edit": "Bearbeiten",
@@ -65,7 +66,7 @@
"create": "Neue Notiz",
"edit": "Notiz bearbeiten",
"note": "Notiz",
- "notePlaceholder": "z.B. Frühdienst weil nachmittags Friseur...",
+ "notePlaceholder": "z.B. Frühdienst weil nachmittags Termin...",
"hintMobile": "Langes Drücken auf einen Tag öffnet Notizen. Das Notiz-Icon zeigt vorhandene Notizen an.",
"hintDesktop": "Rechtsklick auf einen Tag öffnet Notizen. Das Notiz-Icon zeigt vorhandene Notizen an.",
"created": "Notiz erfolgreich erstellt",
diff --git a/messages/en.json b/messages/en.json
index 712e2d0..2f1576a 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1,6 +1,7 @@
{
"common": {
"cancel": "Cancel",
+ "close": "Close",
"save": "Save",
"delete": "Delete",
"edit": "Edit",