Skip to content

Your favorite shift management application!

feat: Consolidates calendar delete and preset management (#72)

panteLc6764233e2f0
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index abdd92c..3ab5a00 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -166,7 +166,7 @@ The translation files use a centralized structure to eliminate duplicates and en
// Success/Error Messages - use {item} parameter
toast.success(t("common.created", { item: t("common.shifts") }));
toast.error(t("common.createError", { item: t("calendar.title") }));
-toast.success(t("common.updated", { item: t("preset.create") }));
+toast.success(t("common.updated", { item: t("preset.preset") }));
toast.error(t("common.deleteError", { item: t("note.note") }));
// Available: common.created, common.updated, common.deleted
diff --git a/app/page.tsx b/app/page.tsx
index cf11760..124e7bd 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -184,20 +184,11 @@ function HomeContent() {
};
// Calendar operations
- const initiateDeleteCalendar = (id: string) => {
- dialogStates.setCalendarToDelete(id);
- dialogStates.setShowDeleteCalendarDialog(true);
- };
-
const handleDeleteCalendar = async (password?: string) => {
- if (!dialogStates.calendarToDelete) return;
- const success = await deleteCalendarHook(
- dialogStates.calendarToDelete,
- password
- );
+ if (!selectedCalendar) return;
+ const success = await deleteCalendarHook(selectedCalendar, password);
if (success) {
- dialogStates.setShowDeleteCalendarDialog(false);
- dialogStates.setCalendarToDelete(undefined);
+ dialogStates.setShowCalendarSettingsDialog(false);
}
};
@@ -334,7 +325,6 @@ function HomeContent() {
onManagePassword={() =>
dialogStates.setShowCalendarSettingsDialog(true)
}
- onDeleteCalendar={initiateDeleteCalendar}
onExternalSync={handleExternalSyncClick}
onSyncNotifications={handleSyncNotifications}
onPresetsChange={refetchPresets}
@@ -447,9 +437,6 @@ function HomeContent() {
dialogStates.setShowCalendarSettingsDialog
}
onCalendarSettingsSuccess={refetchCalendars}
- showDeleteCalendarDialog={dialogStates.showDeleteCalendarDialog}
- onDeleteCalendarDialogChange={dialogStates.setShowDeleteCalendarDialog}
- calendarToDelete={dialogStates.calendarToDelete}
onDeleteCalendar={handleDeleteCalendar}
showExternalSyncDialog={dialogStates.showExternalSyncDialog}
onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
diff --git a/components/app-header.tsx b/components/app-header.tsx
index 67cca02..2701e70 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -15,7 +15,6 @@ import {
import {
Calendar as CalendarIcon,
Plus,
- Settings2,
Bell,
ExternalLink,
} from "lucide-react";
@@ -36,7 +35,6 @@ interface AppHeaderProps {
onSelectPreset: (id: string | undefined) => void;
onCreateCalendar: () => void;
onManagePassword: () => void;
- onDeleteCalendar: (id: string) => void;
onExternalSync: () => void;
onSyncNotifications: () => void;
onPresetsChange: () => void;
@@ -61,7 +59,6 @@ export function AppHeader({
onSelectPreset,
onCreateCalendar,
onManagePassword,
- onDeleteCalendar,
onExternalSync,
onSyncNotifications,
onPresetsChange,
@@ -146,7 +143,6 @@ export function AppHeader({
onSelect={onSelectCalendar}
onCreateNew={onCreateCalendar}
onManagePassword={onManagePassword}
- onDelete={onDeleteCalendar}
onExternalSync={onExternalSync}
onSyncNotifications={onSyncNotifications}
hasSyncErrors={hasSyncErrors}
@@ -270,39 +266,20 @@ export function AppHeader({
{/* Preset Selector */}
{selectedCalendar && (
- <div className="flex flex-col sm:flex-row gap-3 px-0.5 sm:px-0">
- <div className="flex-1">
- <PresetSelector
- calendars={calendars}
- presets={presets}
- selectedPresetId={selectedPresetId}
- onSelectPreset={onSelectPreset}
- onPresetsChange={onPresetsChange}
- onShiftsChange={onShiftsChange}
- onStatsRefresh={onStatsRefresh}
- calendarId={selectedCalendar}
- onPasswordRequired={onPasswordRequired}
- loading={presetsLoading}
- />
- </div>
-
- {/* View Settings Button */}
- <motion.div
- className="shrink-0"
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.2 }}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={onViewSettingsClick}
- className="h-10 w-full sm:w-auto gap-2 bg-muted/30 backdrop-blur-sm border-border/50 hover:bg-accent/50 shadow-sm"
- >
- <Settings2 className="h-4 w-4" />
- <span>{t("view.settingsTitleShort")}</span>
- </Button>
- </motion.div>
+ <div className="px-0.5 sm:px-0">
+ <PresetSelector
+ calendars={calendars}
+ presets={presets}
+ selectedPresetId={selectedPresetId}
+ onSelectPreset={onSelectPreset}
+ onPresetsChange={onPresetsChange}
+ onShiftsChange={onShiftsChange}
+ onStatsRefresh={onStatsRefresh}
+ calendarId={selectedCalendar}
+ onPasswordRequired={onPasswordRequired}
+ onViewSettingsClick={onViewSettingsClick}
+ loading={presetsLoading}
+ />
</div>
)}
</div>
@@ -342,7 +319,6 @@ export function AppHeader({
onMobileCalendarDialogChange(false);
onManagePassword();
}}
- onDelete={onDeleteCalendar}
onExternalSync={() => {
onMobileCalendarDialogChange(false);
onExternalSync();
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
index e0867e3..31a6c28 100644
--- a/components/calendar-selector.tsx
+++ b/components/calendar-selector.tsx
@@ -10,7 +10,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
-import { Plus, CalendarCog, Trash2, Cloud, Bell } from "lucide-react";
+import { Plus, CalendarCog, Cloud, Bell } from "lucide-react";
import { getCachedPassword } from "@/lib/password-cache";
interface CalendarSelectorProps {
@@ -19,7 +19,6 @@ interface CalendarSelectorProps {
onSelect: (id: string) => void;
onCreateNew: () => void;
onManagePassword?: () => void;
- onDelete?: (id: string) => void;
onExternalSync?: () => void;
onSyncNotifications?: () => void;
hasSyncErrors?: boolean;
@@ -32,7 +31,6 @@ export function CalendarSelector({
onSelect,
onCreateNew,
onManagePassword,
- onDelete,
onExternalSync,
onSyncNotifications,
hasSyncErrors = false,
@@ -114,17 +112,6 @@ export function CalendarSelector({
)}
</Button>
)}
- {onDelete && selectedId && (
- <Button
- onClick={() => onDelete(selectedId)}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10 text-destructive hover:text-destructive"
- title={t("calendar.deleteCalendar")}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- )}
<Button
onClick={onCreateNew}
size="icon"
@@ -162,7 +149,7 @@ export function CalendarSelector({
{/* Action Buttons - Even distribution */}
{selectedId && (
- <div className="grid grid-cols-4 gap-2">
+ <div className="grid grid-cols-3 gap-2">
{onManagePassword && (
<Button
onClick={onManagePassword}
@@ -209,17 +196,6 @@ export function CalendarSelector({
)}
</Button>
)}
- {onDelete && (
- <Button
- onClick={() => onDelete(selectedId)}
- size="sm"
- variant="outline"
- className="h-9 text-destructive hover:text-destructive"
- title={t("calendar.deleteCalendar")}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- )}
</div>
)}
diff --git a/components/calendar-settings-dialog.tsx b/components/calendar-settings-dialog.tsx
index 01c92a6..d97fa10 100644
--- a/components/calendar-settings-dialog.tsx
+++ b/components/calendar-settings-dialog.tsx
@@ -16,6 +16,7 @@ import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { removeCachedPassword, setCachedPassword } from "@/lib/password-cache";
import { PRESET_COLORS } from "@/lib/constants";
+import { AlertTriangle, Trash2 } from "lucide-react";
interface CalendarSettingsDialogProps {
open: boolean;
@@ -26,6 +27,7 @@ interface CalendarSettingsDialogProps {
hasPassword: boolean;
isLocked: boolean;
onSuccess: () => void;
+ onDelete: (password?: string) => void;
}
export function CalendarSettingsDialog({
@@ -37,6 +39,7 @@ export function CalendarSettingsDialog({
hasPassword,
isLocked,
onSuccess,
+ onDelete,
}: CalendarSettingsDialogProps) {
const t = useTranslations();
const [name, setName] = useState(calendarName);
@@ -48,6 +51,7 @@ export function CalendarSettingsDialog({
const [lockCalendar, setLockCalendar] = useState(isLocked);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
useEffect(() => {
if (open) {
@@ -59,6 +63,7 @@ export function CalendarSettingsDialog({
setRemovePassword(false);
setLockCalendar(isLocked);
setError("");
+ setShowDeleteConfirm(false);
}
}, [open, calendarName, calendarColor, isLocked]);
@@ -150,6 +155,15 @@ export function CalendarSettingsDialog({
}
};
+ const handleDelete = () => {
+ if (hasPassword && !currentPassword) {
+ setError(t("validation.passwordRequired"));
+ return;
+ }
+ onDelete(hasPassword ? currentPassword : undefined);
+ onOpenChange(false);
+ };
+
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<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">
@@ -341,6 +355,66 @@ export function CalendarSettingsDialog({
</p>
)}
+ {/* Delete Section */}
+ <div className="pt-4 mt-4 border-t border-border/50">
+ <div className="space-y-3">
+ {!showDeleteConfirm ? (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowDeleteConfirm(true)}
+ className="w-full h-11 border-destructive/30 text-destructive hover:bg-destructive/10 hover:border-destructive/50"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("calendar.deleteCalendar")}
+ </Button>
+ ) : (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ className="space-y-3"
+ >
+ <div className="p-3 bg-destructive/5 rounded-lg border border-destructive/20">
+ <div className="flex items-start gap-2.5 text-destructive mb-2">
+ <AlertTriangle className="h-5 w-5 flex-shrink-0 mt-0.5" />
+ <div className="flex-1 space-y-1">
+ <p className="text-sm font-semibold">
+ {t("common.deleteConfirm", {
+ item: t("calendar.title"),
+ name: calendarName,
+ })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("calendar.deleteWarning")}
+ </p>
+ </div>
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowDeleteConfirm(false)}
+ className="flex-1 h-11"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={handleDelete}
+ className="flex-1 h-11 shadow-lg shadow-destructive/25"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t("common.delete")}
+ </Button>
+ </div>
+ </motion.div>
+ )}
+ </div>
+ </div>
+
<div className="flex gap-2.5 pt-2">
<Button
type="button"
diff --git a/components/delete-calendar-dialog.tsx b/components/delete-calendar-dialog.tsx
deleted file mode 100644
index 560a351..0000000
--- a/components/delete-calendar-dialog.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { AlertTriangle } from "lucide-react";
-
-interface DeleteCalendarDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarName: string;
- hasPassword: boolean;
- onConfirm: (password?: string) => void;
-}
-
-export function DeleteCalendarDialog({
- open,
- onOpenChange,
- calendarName,
- hasPassword,
- onConfirm,
-}: DeleteCalendarDialogProps) {
- const t = useTranslations();
- const [password, setPassword] = useState("");
-
- const handleOpenChange = (newOpen: boolean) => {
- if (!newOpen) {
- setPassword("");
- }
- onOpenChange(newOpen);
- };
-
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- onConfirm(hasPassword ? password : undefined);
- };
-
- return (
- <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">
- <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-destructive to-destructive/80 flex items-center justify-center shadow-lg shadow-destructive/30">
- <AlertTriangle className="h-5 w-5 text-white" />
- </div>
- {t("calendar.deleteCalendar")}
- </DialogTitle>
- <DialogDescription asChild>
- <div className="space-y-2.5 pt-2 pl-12">
- <div className="font-semibold text-foreground flex items-center gap-2">
- <div className="w-1 h-4 bg-gradient-to-b from-destructive to-destructive/50 rounded-full"></div>
- {t("common.deleteConfirm", {
- item: t("calendar.title"),
- name: calendarName,
- })}
- </div>
- <div className="text-sm text-muted-foreground bg-destructive/5 p-3 rounded-lg border border-destructive/20">
- {t("calendar.deleteWarning", {
- default:
- "This action cannot be undone. All shifts, presets, and notes will be permanently deleted.",
- })}
- </div>
- </div>
- </DialogDescription>
- </DialogHeader>
- <form onSubmit={handleSubmit} className="p-6 space-y-5">
- {hasPassword && (
- <div className="space-y-2.5">
- <Label
- htmlFor="password"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-destructive to-destructive/50 rounded-full"></div>
- {t("form.passwordLabel")}
- </Label>
- <Input
- id="password"
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder={t("form.passwordPlaceholder")}
- className="h-11 border-destructive/30 focus:border-destructive/50 focus:ring-destructive/20 bg-background/50"
- required
- autoFocus
- />
- </div>
- )}
- <DialogFooter className="gap-2.5 pt-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="flex-1 sm:flex-none h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- variant="destructive"
- className="flex-1 sm:flex-none h-11 shadow-lg shadow-destructive/25"
- >
- {t("common.delete")}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index b88d06f..5def474 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -2,7 +2,6 @@ import { CalendarDialog } from "@/components/calendar-dialog";
import { ShiftDialog, ShiftFormData } from "@/components/shift-dialog";
import { PasswordDialog } from "@/components/password-dialog";
import { CalendarSettingsDialog } from "@/components/calendar-settings-dialog";
-import { DeleteCalendarDialog } from "@/components/delete-calendar-dialog";
import { ExternalSyncManageDialog } from "@/components/external-sync-manage-dialog";
import { SyncNotificationDialog } from "@/components/sync-notification-dialog";
import { DayShiftsDialog } from "@/components/day-shifts-dialog";
@@ -40,11 +39,6 @@ interface DialogManagerProps {
showCalendarSettingsDialog: boolean;
onCalendarSettingsDialogChange: (open: boolean) => void;
onCalendarSettingsSuccess: () => void;
-
- // Delete Calendar Dialog
- showDeleteCalendarDialog: boolean;
- onDeleteCalendarDialogChange: (open: boolean) => void;
- calendarToDelete?: string;
onDeleteCalendar: (password?: string) => void;
// External Sync Dialog
@@ -157,6 +151,7 @@ export function DialogManager(props: DialogManagerProps) {
?.isLocked || false
}
onSuccess={props.onCalendarSettingsSuccess}
+ onDelete={props.onDeleteCalendar}
/>
<ExternalSyncManageDialog
@@ -178,22 +173,6 @@ export function DialogManager(props: DialogManagerProps) {
</>
)}
- {props.calendarToDelete && (
- <DeleteCalendarDialog
- open={props.showDeleteCalendarDialog}
- onOpenChange={props.onDeleteCalendarDialogChange}
- calendarName={
- props.calendars.find((c) => c.id === props.calendarToDelete)
- ?.name || ""
- }
- hasPassword={
- !!props.calendars.find((c) => c.id === props.calendarToDelete)
- ?.passwordHash
- }
- onConfirm={props.onDeleteCalendar}
- />
- )}
-
<DayShiftsDialog
open={props.showDayShiftsDialog}
onOpenChange={props.onDayShiftsDialogChange}
diff --git a/components/preset-edit-dialog.tsx b/components/preset-edit-dialog.tsx
deleted file mode 100644
index b7ee932..0000000
--- a/components/preset-edit-dialog.tsx
+++ /dev/null
@@ -1,367 +0,0 @@
-import { useState, useEffect, useRef } from "react";
-import { useTranslations } from "next-intl";
-import { motion } from "motion/react";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Checkbox } from "@/components/ui/checkbox";
-import { ColorPicker } from "@/components/ui/color-picker";
-import { ShiftPreset } from "@/lib/db/schema";
-import { PRESET_COLORS } from "@/lib/constants";
-
-interface PresetFormData {
- title: string;
- startTime: string;
- endTime: string;
- color: string;
- notes: string;
- isSecondary: boolean;
- isAllDay: boolean;
- hideFromStats: boolean;
-}
-
-interface PresetEditDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- preset: ShiftPreset | null;
- isCreating: boolean;
- onSave: (data: PresetFormData) => void;
-}
-
-export function PresetEditDialog({
- open,
- onOpenChange,
- preset,
- isCreating,
- onSave,
-}: PresetEditDialogProps) {
- const t = useTranslations();
- const [formData, setFormData] = useState<PresetFormData>(() => {
- if (preset && !isCreating) {
- return {
- 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,
- };
- }
- 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 closes
- if (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]);
-
- // 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={handleDialogClose}>
- <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")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {isCreating
- ? t("preset.createDescription", {
- default: "Create a new preset for quick shift creation",
- })
- : t("preset.editDescription", {
- default: "Update preset details",
- })}
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-5 p-6">
- <div className="space-y-2.5">
- <Label
- htmlFor="preset-title"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("shift.titleLabel")}
- </Label>
- <Input
- id="preset-title"
- placeholder={t("form.namePlaceholder", {
- example: t("preset.presetName"),
- })}
- value={formData.title}
- onChange={(e) =>
- setFormData({ ...formData, title: e.target.value })
- }
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
-
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="preset-allday"
- checked={formData.isAllDay}
- onCheckedChange={(checked) =>
- setFormData({ ...formData, isAllDay: !!checked })
- }
- />
- <Label
- htmlFor="preset-allday"
- className="text-sm font-medium cursor-pointer"
- >
- {t("shift.allDayShift")}
- </Label>
- </div>
-
- {!formData.isAllDay && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="grid grid-cols-2 gap-3"
- >
- <div className="space-y-2">
- <Label htmlFor="preset-start" className="text-sm font-medium">
- {t("shift.startTime")}
- </Label>
- <Input
- id="preset-start"
- type="time"
- value={formData.startTime}
- onChange={(e) =>
- setFormData({ ...formData, startTime: e.target.value })
- }
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="preset-end" className="text-sm font-medium">
- {t("shift.endTime")}
- </Label>
- <Input
- id="preset-end"
- type="time"
- value={formData.endTime}
- onChange={(e) =>
- setFormData({ ...formData, endTime: e.target.value })
- }
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
- </motion.div>
- )}
-
- <ColorPicker
- color={formData.color}
- onChange={(color) => setFormData({ ...formData, color })}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
- />
-
- <div className="space-y-2.5">
- <Label
- htmlFor="preset-notes"
- className="text-sm font-medium flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("form.notesLabel")}
- </Label>
- <Input
- id="preset-notes"
- placeholder={t("form.notesPlaceholder")}
- value={formData.notes}
- onChange={(e) =>
- setFormData({ ...formData, notes: e.target.value })
- }
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
-
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="preset-secondary"
- checked={formData.isSecondary}
- onCheckedChange={(checked) =>
- setFormData({ ...formData, isSecondary: !!checked })
- }
- />
- <Label
- htmlFor="preset-secondary"
- className="text-sm font-medium cursor-pointer"
- >
- {t("preset.markAsSecondary")}
- </Label>
- </div>
-
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="preset-hide-stats"
- checked={formData.hideFromStats}
- onCheckedChange={(checked) =>
- setFormData({ ...formData, hideFromStats: !!checked })
- }
- />
- <div className="flex-1">
- <Label
- htmlFor="preset-hide-stats"
- className="text-sm font-medium cursor-pointer"
- >
- {t("preset.hideFromStats")}
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t("preset.hideFromStatsHint")}
- </p>
- </div>
- </div>
-
- <div className="flex gap-2.5 pt-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="flex-1 h-11 border-border/50 hover:bg-muted/50"
- >
- {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>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
-
-export type { PresetFormData };
diff --git a/components/preset-list.tsx b/components/preset-list.tsx
index 0b7d364..cfb33f4 100644
--- a/components/preset-list.tsx
+++ b/components/preset-list.tsx
@@ -1,7 +1,14 @@
import { motion } from "motion/react";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
-import { Check, Plus, Settings, ChevronDown, ChevronUp } from "lucide-react";
+import {
+ Check,
+ Plus,
+ Settings,
+ Settings2,
+ ChevronDown,
+ ChevronUp,
+} from "lucide-react";
import { ShiftPreset } from "@/lib/db/schema";
import { CalendarWithCount } from "@/lib/types";
import { getCachedPassword } from "@/lib/password-cache";
@@ -15,6 +22,7 @@ interface PresetListProps {
onSelectPreset: (presetId: string | undefined) => void;
onCreateNew?: () => void;
onManageClick?: () => void;
+ onViewSettingsClick?: () => void;
onUnlock?: () => void;
loading?: boolean;
}
@@ -25,8 +33,8 @@ export function PresetList({
presets,
selectedPresetId,
onSelectPreset,
- onCreateNew,
onManageClick,
+ onViewSettingsClick,
onUnlock,
loading = false,
}: PresetListProps) {
@@ -116,10 +124,10 @@ export function PresetList({
{t("preset.createFirstDescription")}
</p>
<Button
- onClick={onCreateNew}
+ onClick={onManageClick}
size="sm"
className="gap-2"
- disabled={!onCreateNew}
+ disabled={!onManageClick}
>
<Plus className="h-4 w-4" />
<span className="text-xs sm:text-sm">
@@ -149,24 +157,27 @@ export function PresetList({
<Button
variant="outline"
size="sm"
- onClick={onCreateNew}
- disabled={!onCreateNew}
- className="gap-1 text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"
- >
- <Plus className="h-3 sm:h-4 w-3 sm:w-4" />
- <span className="hidden xs:inline sm:inline">
- {t("preset.create")}
- </span>
- </Button>
- <Button
- variant="ghost"
- size="sm"
onClick={onManageClick}
disabled={!onManageClick}
- className="h-8 sm:h-9 w-8 sm:w-9 p-0"
+ className="gap-1.5 text-xs sm:text-sm px-2.5 sm:px-4 h-8 sm:h-9 border-primary/30 hover:border-primary/50 hover:bg-primary/5"
+ title={t("preset.manage")}
>
- <Settings className="h-3 sm:h-4 w-3 sm:w-4" />
+ <Settings className="h-3.5 sm:h-4 w-3.5 sm:w-4" />
</Button>
+ {onViewSettingsClick && (
+ <>
+ <div className="flex-1" />
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onViewSettingsClick}
+ className="gap-1.5 text-xs sm:text-sm px-2.5 sm:px-4 h-8 sm:h-9 border-primary/30 hover:border-primary/50 hover:bg-primary/5"
+ title={t("view.settingsTitle")}
+ >
+ <Settings2 className="h-3.5 sm:h-4 w-3.5 sm:w-4" />
+ </Button>
+ </>
+ )}
</div>
{/* Secondary Presets - Collapsible */}
diff --git a/components/preset-manage-dialog.tsx b/components/preset-manage-dialog.tsx
index 11a7b4e..4f897fd 100644
--- a/components/preset-manage-dialog.tsx
+++ b/components/preset-manage-dialog.tsx
@@ -1,4 +1,8 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
import { useTranslations } from "next-intl";
+import { motion } from "motion/react";
import {
Dialog,
DialogContent,
@@ -7,94 +11,632 @@ import {
DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
-import { Plus, Trash2 } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Checkbox } from "@/components/ui/checkbox";
+import { ColorPicker } from "@/components/ui/color-picker";
import { ShiftPreset } from "@/lib/db/schema";
+import { PRESET_COLORS } from "@/lib/constants";
+import { Plus, Trash2, Edit2, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+import { getCachedPassword } from "@/lib/password-cache";
+
+interface PresetFormData {
+ title: string;
+ startTime: string;
+ endTime: string;
+ color: string;
+ notes: string;
+ isSecondary: boolean;
+ isAllDay: boolean;
+ hideFromStats: boolean;
+}
interface PresetManageDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
+ calendarId: string;
presets: ShiftPreset[];
- onCreateNew: () => void;
- onEdit: (preset: ShiftPreset) => void;
- onDelete: (presetId: string) => void;
+ onPresetsChange: () => void;
}
export function PresetManageDialog({
open,
onOpenChange,
+ calendarId,
presets,
- onCreateNew,
- onEdit,
- onDelete,
+ onPresetsChange,
}: PresetManageDialogProps) {
const t = useTranslations();
+ const [isLoading, setIsLoading] = useState(false);
+ const [isDeleting, setIsDeleting] = useState<string | null>(null);
+ const [showAddForm, setShowAddForm] = useState(false);
+ const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);
+
+ // Form state
+ 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 saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const initialFormDataRef = useRef<PresetFormData | null>(null);
+ const isInitialMount = useRef(true);
+
+ // Reset state when dialog closes
+ useEffect(() => {
+ if (!open) {
+ setShowAddForm(false);
+ setEditingPreset(null);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ setIsLoading(false);
+ setIsDeleting(null);
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ }
+ }, [open]);
+
+ const handleAddPreset = async () => {
+ if (!calendarId || !formData.title.trim()) return;
+
+ setIsLoading(true);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch("/api/presets", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ calendarId,
+ ...formData,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ setShowAddForm(false);
+ onPresetsChange();
+ toast.success(t("common.created", { item: t("preset.preset") }));
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error || t("common.createError", { item: t("preset.preset") })
+ );
+ }
+ } catch (error) {
+ console.error("Failed to create preset:", error);
+ toast.error(t("common.createError", { item: t("preset.preset") }));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleDelete = async (presetId: string) => {
+ if (!confirm(t("preset.deleteConfirm"))) {
+ return;
+ }
+
+ setIsDeleting(presetId);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/presets/${presetId}`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password }),
+ });
+
+ if (response.ok) {
+ onPresetsChange();
+ toast.success(t("common.deleted", { item: t("preset.preset") }));
+ // If we're editing the deleted preset, close the edit form
+ if (editingPreset?.id === presetId) {
+ setEditingPreset(null);
+ }
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error || t("common.deleteError", { item: t("preset.preset") })
+ );
+ }
+ } catch (error) {
+ console.error("Delete error:", error);
+ toast.error(t("common.deleteError", { item: t("preset.preset") }));
+ } finally {
+ setIsDeleting(null);
+ }
+ };
+
+ const startEdit = (preset: ShiftPreset) => {
+ const initialData: PresetFormData = {
+ 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,
+ };
+ setEditingPreset(preset);
+ setFormData(initialData);
+ setShowAddForm(false);
+ initialFormDataRef.current = initialData;
+ isInitialMount.current = true;
+ };
+
+ const cancelEdit = () => {
+ setEditingPreset(null);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ initialFormDataRef.current = null;
+
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ };
+
+ const startAdd = () => {
+ setShowAddForm(true);
+ setEditingPreset(null);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ };
+
+ const savePresetChanges = useCallback(
+ async (updateInitialRef: boolean = false): Promise<boolean> => {
+ if (!editingPreset) return false;
+
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/presets/${editingPreset.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...formData,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ onPresetsChange();
+ if (updateInitialRef) {
+ initialFormDataRef.current = formData;
+ }
+ toast.success(t("common.updated", { item: t("preset.preset") }));
+ return true;
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error || t("common.updateError", { item: t("preset.preset") })
+ );
+ return false;
+ }
+ } catch (error) {
+ console.error("Failed to save preset:", error);
+ toast.error(t("common.updateError", { item: t("preset.preset") }));
+ return false;
+ }
+ },
+ [calendarId, editingPreset, formData, onPresetsChange, t]
+ );
+
+ // Auto-save with debouncing (only for editing existing presets)
+ useEffect(() => {
+ if (!editingPreset || !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 and title is not empty
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialFormDataRef.current);
+
+ if (hasChanged && formData.title.trim()) {
+ saveTimeoutRef.current = setTimeout(() => {
+ savePresetChanges(true);
+ }, 1000); // 1 second debounce
+ }
+
+ return () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+ };
+ }, [formData, editingPreset, savePresetChanges]);
+
+ // 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 preset, check for unsaved changes
+ if (editingPreset && initialFormDataRef.current) {
+ // Cancel pending timeout
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+
+ // Check if data has changed
+ const hasChanged =
+ JSON.stringify(formData) !== JSON.stringify(initialFormDataRef.current);
+
+ // Save immediately if data changed and title is not empty
+ if (hasChanged && formData.title.trim()) {
+ const success = await savePresetChanges(false);
+ if (!success) {
+ // Failed to save, keep dialog open
+ return;
+ }
+ }
+ }
+
+ // Close the dialog
+ onOpenChange(false);
+ };
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[520px] 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">
+ <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">
{t("preset.manage")}
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground">
- {t("preset.manageDescription", {
- default: "Edit or delete your shift presets",
- })}
+ {t("preset.manageDescription")}
</DialogDescription>
</DialogHeader>
+
<div className="space-y-3 overflow-y-auto flex-1 p-6">
- <Button
- onClick={onCreateNew}
- className="w-full h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
- variant="default"
- >
- <Plus className="mr-2 h-4 w-4" />
- {t("preset.createNew")}
- </Button>
- {presets.map((preset) => (
- <div
- key={preset.id}
- className="flex items-center justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
- style={{ borderLeftColor: preset.color, borderLeftWidth: 4 }}
- >
- <div className="flex-1">
- <div className="font-semibold flex items-center gap-2">
+ {/* Existing Presets List - hide when adding new preset, show only edited preset when editing */}
+ {presets.length > 0 && !showAddForm && (
+ <div className="space-y-3">
+ {presets
+ .filter(
+ (preset) => !editingPreset || preset.id === editingPreset.id
+ )
+ .map((preset) => (
<div
- className="w-1 h-4 rounded-full"
- style={{ backgroundColor: preset.color }}
- ></div>
- {preset.title}
- </div>
- <div className="text-sm text-muted-foreground mt-1">
- {preset.isAllDay ? (
- <span>{t("shift.allDay")}</span>
- ) : (
- <>
- {preset.startTime} - {preset.endTime}
- </>
- )}
- </div>
+ key={preset.id}
+ className="flex flex-col gap-3 p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
+ style={{
+ borderLeftColor: preset.color,
+ borderLeftWidth: 4,
+ }}
+ >
+ {/* Title row */}
+ <div className="flex items-start gap-2">
+ <div
+ className="w-1 h-4 rounded-full shrink-0 mt-0.5"
+ style={{ backgroundColor: preset.color }}
+ />
+ <span className="font-semibold flex-1 min-w-0 break-words">
+ {preset.title}
+ </span>
+ </div>
+
+ {/* Info and buttons row */}
+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm text-muted-foreground">
+ {preset.isAllDay ? (
+ t("shift.allDay")
+ ) : (
+ <>
+ {preset.startTime} - {preset.endTime}
+ </>
+ )}
+ </span>
+ {preset.isSecondary && (
+ <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/20 font-medium">
+ {t("preset.secondary")}
+ </span>
+ )}
+ {preset.hideFromStats && (
+ <span className="text-xs px-2 py-0.5 rounded-full bg-gray-500/10 text-gray-600 dark:text-gray-400 border border-gray-500/20 font-medium">
+ {t("preset.hiddenFromStats")}
+ </span>
+ )}
+ </div>
+ <div className="flex gap-1 shrink-0">
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => startEdit(preset)}
+ disabled={!!isDeleting}
+ >
+ <Edit2 className="h-4 w-4" />
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={() => handleDelete(preset.id)}
+ disabled={!!isDeleting}
+ >
+ {isDeleting === preset.id ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Add/Edit Form */}
+ {(showAddForm || editingPreset) && (
+ <div className="rounded-xl border border-border/50 bg-muted/20 p-4 space-y-4">
+ <h3 className="font-semibold">
+ {editingPreset ? t("preset.edit") : t("preset.createNew")}
+ </h3>
+
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="preset-title"
+ className="text-sm font-medium flex items-center gap-2"
+ >
+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
+ {t("shift.titleLabel")}
+ </Label>
+ <Input
+ id="preset-title"
+ placeholder={t("form.namePlaceholder", {
+ example: t("preset.presetName"),
+ })}
+ value={formData.title}
+ onChange={(e) =>
+ setFormData({ ...formData, title: e.target.value })
+ }
+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ disabled={isLoading}
+ />
+ </div>
+
+ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
+ <Checkbox
+ id="preset-allday"
+ checked={formData.isAllDay}
+ onCheckedChange={(checked) =>
+ setFormData({ ...formData, isAllDay: !!checked })
+ }
+ disabled={isLoading}
+ />
+ <Label
+ htmlFor="preset-allday"
+ className="text-sm font-medium cursor-pointer"
+ >
+ {t("shift.allDayShift")}
+ </Label>
</div>
- <div className="flex gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => onEdit(preset)}
- className="h-9"
+
+ {!formData.isAllDay && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.2 }}
+ className="grid grid-cols-2 gap-3"
+ >
+ <div className="space-y-2">
+ <Label
+ htmlFor="preset-start"
+ className="text-sm font-medium"
+ >
+ {t("shift.startTime")}
+ </Label>
+ <Input
+ id="preset-start"
+ type="time"
+ value={formData.startTime}
+ onChange={(e) =>
+ setFormData({ ...formData, startTime: e.target.value })
+ }
+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ disabled={isLoading}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="preset-end" className="text-sm font-medium">
+ {t("shift.endTime")}
+ </Label>
+ <Input
+ id="preset-end"
+ type="time"
+ value={formData.endTime}
+ onChange={(e) =>
+ setFormData({ ...formData, endTime: e.target.value })
+ }
+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ disabled={isLoading}
+ />
+ </div>
+ </motion.div>
+ )}
+
+ <ColorPicker
+ color={formData.color}
+ onChange={(color) => setFormData({ ...formData, color })}
+ label={t("form.colorLabel")}
+ presetColors={PRESET_COLORS}
+ />
+
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="preset-notes"
+ className="text-sm font-medium flex items-center gap-2"
>
- {t("common.edit")}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onDelete(preset.id)}
- className="h-9 w-9 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
+ {t("form.notesLabel")}
+ </Label>
+ <Input
+ id="preset-notes"
+ placeholder={t("form.notesPlaceholder")}
+ value={formData.notes}
+ onChange={(e) =>
+ setFormData({ ...formData, notes: e.target.value })
+ }
+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ disabled={isLoading}
+ />
+ </div>
+
+ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
+ <Checkbox
+ id="preset-secondary"
+ checked={formData.isSecondary}
+ onCheckedChange={(checked) =>
+ setFormData({ ...formData, isSecondary: !!checked })
+ }
+ disabled={isLoading}
+ />
+ <Label
+ htmlFor="preset-secondary"
+ className="text-sm font-medium cursor-pointer"
>
- <Trash2 className="h-4 w-4" />
- </Button>
+ {t("preset.markAsSecondary")}
+ </Label>
</div>
+
+ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
+ <Checkbox
+ id="preset-hide-stats"
+ checked={formData.hideFromStats}
+ onCheckedChange={(checked) =>
+ setFormData({ ...formData, hideFromStats: !!checked })
+ }
+ disabled={isLoading}
+ />
+ <div className="flex-1">
+ <Label
+ htmlFor="preset-hide-stats"
+ className="text-sm font-medium cursor-pointer"
+ >
+ {t("preset.hideFromStats")}
+ </Label>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t("preset.hideFromStatsHint")}
+ </p>
+ </div>
+ </div>
+
+ {editingPreset ? (
+ <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);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ }}
+ disabled={isLoading}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ onClick={handleAddPreset}
+ disabled={isLoading || !formData.title.trim()}
+ >
+ {isLoading ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : null}
+ {t("common.add")}
+ </Button>
+ </div>
+ )}
</div>
- ))}
+ )}
+
+ {/* Add Button */}
+ {!showAddForm && !editingPreset && (
+ <Button
+ onClick={startAdd}
+ className="w-full 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={!!isDeleting}
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ {t("preset.createNew")}
+ </Button>
+ )}
</div>
</DialogContent>
</Dialog>
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index 5442416..2cd7441 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -1,15 +1,9 @@
"use client";
-import { useTranslations } from "next-intl";
import { ShiftPreset } from "@/lib/db/schema";
import { CalendarWithCount } from "@/lib/types";
import { useState } from "react";
-import { toast } from "sonner";
import { PresetList } from "@/components/preset-list";
-import {
- PresetEditDialog,
- PresetFormData,
-} from "@/components/preset-edit-dialog";
import { PresetManageDialog } from "@/components/preset-manage-dialog";
import { usePasswordProtection } from "@/hooks/usePasswordProtection";
@@ -23,6 +17,7 @@ interface PresetSelectorProps {
onStatsRefresh?: () => void;
calendarId: string;
onPasswordRequired: (action: () => Promise<void>) => void;
+ onViewSettingsClick?: () => void;
loading?: boolean;
}
@@ -36,135 +31,26 @@ export function PresetSelector({
onStatsRefresh,
calendarId,
onPasswordRequired,
+ onViewSettingsClick,
loading = false,
}: PresetSelectorProps) {
- const t = useTranslations();
const [showManageDialog, setShowManageDialog] = useState(false);
- const [showEditDialog, setShowEditDialog] = useState(false);
- const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);
- const [isCreatingNew, setIsCreatingNew] = useState(false);
- const { withPasswordCheck, getPassword } = usePasswordProtection({
+ const { withPasswordCheck } = usePasswordProtection({
calendarId,
onPasswordRequired,
});
- const handleCreateNew = async () => {
+ const handleManageClick = async () => {
await withPasswordCheck(async () => {
- setIsCreatingNew(true);
- setEditingPreset(null);
- setShowEditDialog(true);
+ setShowManageDialog(true);
});
};
- const handleEditPreset = async (preset: ShiftPreset) => {
- await withPasswordCheck(async () => {
- setIsCreatingNew(false);
- setEditingPreset(preset);
- setShowEditDialog(true);
- });
- };
-
- const handleSavePreset = async (formData: PresetFormData) => {
- try {
- const password = getPassword();
-
- if (isCreatingNew) {
- const response = await fetch("/api/presets", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- calendarId,
- ...formData,
- password,
- }),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(
- `Failed to create preset: ${response.status} ${response.statusText}`,
- errorText
- );
- toast.error(t("common.createError", { item: t("preset.create") }));
- return;
- }
-
- toast.success(t("common.created", { item: t("preset.create") }));
- } else if (editingPreset) {
- const response = await fetch(`/api/presets/${editingPreset.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ...formData, password }),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(
- `Failed to update preset: ${response.status} ${response.statusText}`,
- errorText
- );
- toast.error(t("common.updateError", { item: t("preset.create") }));
- return;
- }
-
- toast.success(t("common.updated", { item: t("preset.create") }));
-
- if (onShiftsChange) onShiftsChange();
- if (onStatsRefresh) onStatsRefresh();
- }
-
- onPresetsChange();
-
- if (isCreatingNew) {
- setShowEditDialog(false);
- setEditingPreset(null);
- setIsCreatingNew(false);
- }
- } catch (error) {
- console.error("Failed to save preset:", error);
- toast.error(t("common.updateError", { item: t("preset.create") }));
- }
- };
-
- const handleDeletePreset = async (id: string) => {
- await withPasswordCheck(async () => {
- if (!confirm(t("preset.deleteConfirm"))) return;
-
- try {
- const password = getPassword();
-
- const response = await fetch(`/api/presets/${id}`, {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ password }),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(
- `Failed to delete preset: ${response.status} ${response.statusText}`,
- errorText
- );
- toast.error(t("common.deleteError", { item: t("preset.create") }));
- return;
- }
-
- if (selectedPresetId === id) {
- onSelectPreset(undefined);
- }
-
- 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);
- toast.error(t("common.deleteError", { item: t("preset.create") }));
- }
- });
+ const handlePresetsChange = () => {
+ onPresetsChange();
+ if (onShiftsChange) onShiftsChange();
+ if (onStatsRefresh) onStatsRefresh();
};
return (
@@ -175,8 +61,9 @@ export function PresetSelector({
presets={presets}
selectedPresetId={selectedPresetId}
onSelectPreset={onSelectPreset}
- onCreateNew={handleCreateNew}
- onManageClick={() => setShowManageDialog(true)}
+ onCreateNew={handleManageClick}
+ onManageClick={handleManageClick}
+ onViewSettingsClick={onViewSettingsClick}
onUnlock={() => onPasswordRequired(async () => {})}
loading={loading}
/>
@@ -184,24 +71,9 @@ export function PresetSelector({
<PresetManageDialog
open={showManageDialog}
onOpenChange={setShowManageDialog}
+ calendarId={calendarId}
presets={presets}
- onCreateNew={() => {
- setShowManageDialog(false);
- handleCreateNew();
- }}
- onEdit={(preset) => {
- setShowManageDialog(false);
- handleEditPreset(preset);
- }}
- onDelete={handleDeletePreset}
- />
-
- <PresetEditDialog
- open={showEditDialog}
- onOpenChange={setShowEditDialog}
- preset={editingPreset}
- isCreating={isCreatingNew}
- onSave={handleSavePreset}
+ onPresetsChange={handlePresetsChange}
/>
</>
);
diff --git a/hooks/useDialogStates.ts b/hooks/useDialogStates.ts
index 435de7e..72b021a 100644
--- a/hooks/useDialogStates.ts
+++ b/hooks/useDialogStates.ts
@@ -9,8 +9,6 @@ export function useDialogStates() {
useState(false);
const [showMobileCalendarDialog, setShowMobileCalendarDialog] =
useState(false);
- const [showDeleteCalendarDialog, setShowDeleteCalendarDialog] =
- useState(false);
const [showExternalSyncDialog, setShowExternalSyncDialog] = useState(false);
const [showSyncNotificationDialog, setShowSyncNotificationDialog] =
useState(false);
@@ -25,9 +23,6 @@ export function useDialogStates() {
const [selectedSyncedShifts, setSelectedSyncedShifts] = useState<
ShiftWithCalendar[]
>([]);
- const [calendarToDelete, setCalendarToDelete] = useState<
- string | undefined
- >();
return {
showCalendarDialog,
@@ -40,8 +35,6 @@ export function useDialogStates() {
setShowCalendarSettingsDialog,
showMobileCalendarDialog,
setShowMobileCalendarDialog,
- showDeleteCalendarDialog,
- setShowDeleteCalendarDialog,
showExternalSyncDialog,
setShowExternalSyncDialog,
showSyncNotificationDialog,
@@ -58,7 +51,5 @@ export function useDialogStates() {
setSelectedDayShifts,
selectedSyncedShifts,
setSelectedSyncedShifts,
- calendarToDelete,
- setCalendarToDelete,
};
}
diff --git a/messages/de.json b/messages/de.json
index 62f0b9f..c716e78 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -119,7 +119,7 @@
"saveChanges": "Änderungen speichern"
},
"preset": {
- "create": "Neue Vorlage",
+ "preset": "Vorlage",
"createNew": "Neue Vorlage erstellen",
"createYourFirst": "Erstelle deine erste Vorlage",
"edit": "Vorlage bearbeiten",
@@ -134,9 +134,11 @@
"createFirstDescription": "Erstelle deine erste Vorlage, um Schichten schnell zu deinem Kalender hinzuzufügen. Vorlagen speichern deine häufig genutzten Schichtzeiten und Details.",
"deleteConfirm": "Diese Vorlage löschen? Alle aus dieser Vorlage erstellten Schichten werden ebenfalls gelöscht.",
"secondaryPresets": "Sekundäre Vorlagen",
+ "secondary": "Sekundär",
"markAsSecondary": "Als sekundär markieren (standardmäßig eingeklappt)",
"hideFromStats": "Aus Statistik ausblenden",
- "hideFromStatsHint": "Schichten dieser Vorlage aus der Statistik ausschließen"
+ "hideFromStatsHint": "Schichten dieser Vorlage aus der Statistik ausschließen",
+ "hiddenFromStats": "Aus Statistik ausgeblendet"
},
"calendar_grid": {
"monday": "Mo",
@@ -148,7 +150,6 @@
"sunday": "So"
},
"view": {
- "settingsTitleShort": "Ansicht",
"settingsTitle": "Ansichtseinstellungen",
"settingsDescription": "Passe an, wie Schichten in allen Kalendern angezeigt werden",
"shiftsPerDay": "Normale Schichten pro Tag",
diff --git a/messages/en.json b/messages/en.json
index 57c3f6c..3848730 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -119,7 +119,7 @@
"saveChanges": "Save Changes"
},
"preset": {
- "create": "New Preset",
+ "preset": "Preset",
"createNew": "Create New Preset",
"createYourFirst": "Create Your First Preset",
"edit": "Edit Preset",
@@ -134,9 +134,11 @@
"createFirstDescription": "Create your first preset to quickly add shifts to your calendar. Presets save your frequently used shift times and details.",
"deleteConfirm": "Delete this preset? This will also delete all shifts created from this preset.",
"secondaryPresets": "Secondary Presets",
+ "secondary": "Secondary",
"markAsSecondary": "Mark as secondary (collapsed by default)",
"hideFromStats": "Hide from statistics",
- "hideFromStatsHint": "Exclude shifts from this preset from statistics"
+ "hideFromStatsHint": "Exclude shifts from this preset from statistics",
+ "hiddenFromStats": "Hidden from statistics"
},
"calendar_grid": {
"monday": "Mon",
@@ -148,7 +150,6 @@
"sunday": "Sun"
},
"view": {
- "settingsTitleShort": "View",
"settingsTitle": "View Settings",
"settingsDescription": "Customize how shifts are displayed in all calendars",
"shiftsPerDay": "Regular shifts per day",
diff --git a/messages/it.json b/messages/it.json
index 625efe5..fa08f87 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -119,7 +119,7 @@
"saveChanges": "Salva Modifiche"
},
"preset": {
- "create": "Nuovo Preset",
+ "preset": "Preset",
"createNew": "Crea Nuovo Preset",
"createYourFirst": "Crea il Tuo Primo Preset",
"edit": "Modifica Preset",
@@ -134,9 +134,11 @@
"createFirstDescription": "Crea il tuo primo preset per aggiungere rapidamente turni al tuo calendario. I preset salvano gli orari e i dettagli dei turni utilizzati di frequente.",
"deleteConfirm": "Eliminare questo preset? Verranno eliminati anche tutti i turni creati da questo preset.",
"secondaryPresets": "Preset Secondari",
+ "secondary": "Secondario",
"markAsSecondary": "Segna come secondario (compresso di default)",
"hideFromStats": "Nascondi dalle statistiche",
- "hideFromStatsHint": "Escludi i turni da questo preset dalle statistiche"
+ "hideFromStatsHint": "Escludi i turni da questo preset dalle statistiche",
+ "hiddenFromStats": "Nascosto dalle statistiche"
},
"calendar_grid": {
"monday": "Lun",
@@ -148,7 +150,6 @@
"sunday": "Dom"
},
"view": {
- "settingsTitleShort": "Vista",
"settingsTitle": "Impostazioni Vista",
"settingsDescription": "Personalizza come vengono visualizzati i turni in tutti i calendari",
"shiftsPerDay": "Turni regolari al giorno",