Skip to content

Your favorite shift management application!

feat: Migrates form dialogs to Sheets UI (#83)

panteL2f6fbe993ea0
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 3ab5a00..af57c9c 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -1,15 +1,21 @@
-# BetterShift AI Coding Assistant Instructions
+# BetterShift Copilot Instructions
-## Architecture Overview
+## Quick Reference
-**BetterShift** is a Next.js 16 App Router shift management application with SQLite database for managing work schedules across multiple calendars.
+- **Framework**: Next.js 16 App Router + React 19
+- **Database**: SQLite + Drizzle ORM (`./data/sqlite.db`)
+- **UI**: Tailwind CSS 4 + shadcn/ui + BaseSheet component
+- **i18n**: next-intl (de/en/it) - always use informal "du" in German
+- **Critical**: Never use `db:push`, always generate migrations
+
+## Core Architecture
### Tech Stack
- **Framework**: Next.js 16 with App Router (`app/` directory)
- **UI**: React 19, Tailwind CSS 4, shadcn/ui components (`components/ui/`)
- **Database**: SQLite via Drizzle ORM (file: `./data/sqlite.db`)
-- **i18n**: next-intl (German/English, cookie-based + browser detection)
+- **i18n**: next-intl (German/English/Italian, cookie-based + browser detection)
- **State**: Client-side with React hooks, custom hooks in `hooks/`
### Database Schema (`lib/db/schema.ts`)
@@ -221,45 +227,128 @@ When adding new features, ensure all translation keys are actually used in compo
### Component Design Patterns
-- **Dialogs**: Control state via props, reset on close
-- **Forms**: Prevent default, validate, callback to parent
+#### BaseSheet Component (Preferred)
+
+**Use `BaseSheet` from `components/ui/base-sheet.tsx` for simple sheets** (create, edit, settings). Only build custom sheets for complex multi-step forms or specialized layouts.
+
+**BaseSheet Usage**:
+
+```typescript
+import { BaseSheet } from "@/components/ui/base-sheet";
+
+<BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("sheet.title")}
+ description={t("sheet.description")}
+ showSaveButton
+ onSave={handleSave}
+ isSaving={isSaving}
+ saveDisabled={!isValid || !isDirty}
+ hasUnsavedChanges={isDirty}
+ maxWidth="md" // sm(480px) | md(600px) | lg(700px) | xl(800px)
+>
+ {/* Your form content */}
+</BaseSheet>;
+```
+
+**BaseSheet Features**:
+
+- Automatic dirty state tracking with confirmation dialog
+- Built-in Save/Cancel buttons with loading states
+- Consistent styling (gradients, borders, spacing)
+- Responsive max-width options
+- Custom footer support via `footer` prop
+
+**When to Use Custom Sheets**:
+
+- Multi-step wizards
+- Complex layouts with tabs or sidebars
+- Sheets requiring custom footer actions (e.g., Delete + Save)
+
+#### Custom Sheet Pattern (Complex Cases Only)
+
+For complex sheets, follow this structure:
+
+```tsx
+<SheetContent
+ side="right"
+ className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+>
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {t("sheet.title")}
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("sheet.description")}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-6 py-6 space-y-4">
+ {/* Sheet content */}
+ </div>
+
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <div className="flex gap-2.5 w-full">
+ <Button variant="outline" onClick={handleClose} disabled={isSaving}>
+ {t("common.cancel")}
+ </Button>
+ <Button onClick={handleSave} disabled={!isValid || isSaving}>
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ </SheetFooter>
+</SheetContent>
+```
+
+**Dirty State Tracking**: ALWAYS use `useDirtyState` hook for unsaved changes:
+
+```typescript
+const {
+ isDirty,
+ handleClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+} = useDirtyState({
+ open,
+ onClose: onOpenChange,
+ hasChanges: () => name !== initialName,
+ onConfirm: () => resetForm(), // Optional cleanup
+});
+```
+
+#### Other Patterns
+
+- **Dialogs**: Only for read-only info or simple confirmations (no forms)
+- **Confirmation Dialogs**: NEVER use native `confirm()` - always use `ConfirmationDialog` component with state management
+
+- **Forms**: Prevent default, validate, show errors, use explicit save actions
- **Colors**: Use `PRESET_COLORS` array, hex format (`#3b82f6`), 20% opacity for backgrounds
- **Dates**: `formatDateToLocal()` for YYYY-MM-DD format
### UI/UX Design Principles
-**Live Updates**: All components must support real-time updates via Server-Sent Events (SSE):
+#### Live Updates via SSE
+
+All components must support real-time updates via Server-Sent Events:
- Listen to relevant SSE events (shift, preset, note, sync-log updates)
- Use silent refresh patterns: `fetchData(false)` to update without loading states
- Implement refresh triggers: counter-based props (e.g., `syncLogRefreshTrigger`)
- Avoid flashing/blinking during updates - update data smoothly without UI disruption
-**Consistent Dialog Design**: All dialogs must follow the unified design pattern:
+#### Sheet Design Standards
-```tsx
-<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("dialog.title")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("dialog.description")}
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">
- {/* Dialog content */}
- </div>
-</DialogContent>
-```
-
-Key design elements:
-
-- Gradient backgrounds for visual depth
-- Consistent padding (`p-6`, `px-6`, `pb-6`)
-- Border styling with reduced opacity (`border-border/50`)
-- Backdrop blur effects for modern aesthetics
-- Gradient text for titles (`bg-gradient-to-r from-foreground to-foreground/70`)
+- **Simple Sheets**: Use `BaseSheet` component (handles styling, dirty state, buttons)
+- **Complex Sheets**: Follow custom pattern (see Component Design Patterns section)
+- **Key Requirements**:
+ - Gradient backgrounds for visual depth
+ - Consistent padding (`px-6`, `py-6`, `py-4`)
+ - Border styling with reduced opacity (`border-border/50`)
+ - Sticky footer with always-visible Save button
+ - Full-height layout: `flex flex-col` with `flex-1 overflow-y-auto`
+ - Gradient text for titles (`bg-gradient-to-r from-foreground to-foreground/70`)
### Calendar Interactions
@@ -293,7 +382,7 @@ docker compose exec bettershift npm run db:migrate
1. **Next.js 16**: Dynamic route params are async - always `await params`
2. **SQLite Timestamps**: Use `{ mode: "timestamp" }`, stored as integers, auto-converted to Date
3. **Cascade Deletes**: Deleting calendar removes all shifts/presets/notes
-4. **Preset Auto-Save**: Shift dialog has `saveAsPreset` enabled by default
+4. **Sheets vs Dialogs**: Use BaseSheet for simple forms, custom sheets for complex layouts, Dialogs only for read-only info
5. **Color Format**: Store hex (`#3b82f6`), use 20% opacity for backgrounds (`${color}20`)
6. **Mobile UI**: Separate calendar selector with `showMobileCalendarDialog`
@@ -305,7 +394,17 @@ docker compose exec bettershift npm run db:migrate
2. Export types: `export type TableName = typeof tableName.$inferSelect;`
3. Run `npm run db:generate && npm run db:migrate`
4. Create API routes: `app/api/tablename/route.ts` and `app/api/tablename/[id]/route.ts`
-5. Add translations to `messages/de.json` and `messages/en.json`
+5. Add translations to `messages/de.json`, `messages/en.json`, and `messages/it.json`
+
+### New Component with Sheet
+
+1. Create in `components/` - prefer `BaseSheet` for simple forms
+2. Props: `open`, `onOpenChange`, `onSubmit`, optional `onDelete`
+3. Use `useTranslations()` for all text
+4. For BaseSheet: Pass `showSaveButton`, `onSave`, `isSaving`, `saveDisabled`, `hasUnsavedChanges`
+5. For custom sheets: Include explicit Save button in SheetFooter with loading state
+6. Reset local state when `open` changes to false
+7. Import and integrate in parent component
### New Component with Dialog
diff --git a/app/page.tsx b/app/page.tsx
index f5b49a9..3e838b3 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -30,7 +30,6 @@ import { CalendarContent } from "@/components/calendar-content";
import { AppFooter } from "@/components/app-footer";
import { AppHeader } from "@/components/app-header";
import { DialogManager } from "@/components/dialog-manager";
-import { CalendarDialog } from "@/components/calendar-dialog";
import { getCalendarDays } from "@/lib/calendar-utils";
import { getCachedPassword } from "@/lib/password-cache";
@@ -296,16 +295,9 @@ function HomeContent() {
// Empty state
if (calendars.length === 0) {
return (
- <>
- <EmptyCalendarState
- onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
- />
- <CalendarDialog
- open={dialogStates.showCalendarDialog}
- onOpenChange={dialogStates.setShowCalendarDialog}
- onSubmit={createCalendarHook}
- />
- </>
+ <EmptyCalendarState
+ onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
+ />
);
}
diff --git a/components/calendar-dialog.tsx b/components/calendar-dialog.tsx
deleted file mode 100644
index db40840..0000000
--- a/components/calendar-dialog.tsx
+++ /dev/null
@@ -1,257 +0,0 @@
-"use client";
-
-import { useState } 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 { PRESET_COLORS } from "@/lib/constants";
-
-interface CalendarDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onSubmit: (
- name: string,
- color: string,
- password?: string,
- isLocked?: boolean
- ) => void;
-}
-
-export function CalendarDialog({
- open,
- onOpenChange,
- onSubmit,
-}: CalendarDialogProps) {
- const t = useTranslations();
- const [name, setName] = useState("");
- const [selectedColor, setSelectedColor] = useState(PRESET_COLORS[0].value);
- const [password, setPassword] = useState("");
- const [confirmPassword, setConfirmPassword] = useState("");
- const [usePassword, setUsePassword] = useState(false);
- const [lockCalendar, setLockCalendar] = useState(false);
- const [error, setError] = useState("");
-
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- setError("");
-
- if (!name.trim()) return;
-
- // Validate password if enabled
- if (usePassword) {
- if (!password) {
- setError(t("password.errorRequired"));
- return;
- }
- if (password !== confirmPassword) {
- setError(t("password.errorMatch"));
- return;
- }
- }
-
- // Can't lock without password
- if (lockCalendar && !usePassword) {
- setError(t("calendar.lockRequiresPassword"));
- return;
- }
-
- onSubmit(
- name.trim(),
- selectedColor,
- usePassword && password ? password : undefined,
- lockCalendar
- );
- setName("");
- setSelectedColor(PRESET_COLORS[0].value);
- setPassword("");
- setConfirmPassword("");
- setUsePassword(false);
- setLockCalendar(false);
- setError("");
- onOpenChange(false);
- };
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <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">
- {t("calendar.create")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("calendar.createDescription", {
- default: "Create a new calendar to organize your shifts",
- })}
- </DialogDescription>
- </DialogHeader>
- <form onSubmit={handleSubmit} className="p-6 space-y-6">
- <div className="space-y-2.5">
- <Label
- htmlFor="name"
- 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("calendar.name")}
- </Label>
- <Input
- id="name"
- placeholder={t("form.namePlaceholder", {
- example: t("calendar.name"),
- })}
- value={name}
- onChange={(e) => setName(e.target.value)}
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm transition-all"
- autoFocus
- />
- </div>
- <div className="space-y-3">
- <Label 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.colorLabel")}
- </Label>
- <div className="grid grid-cols-4 gap-3 p-4 bg-muted/30 rounded-xl border border-border/30">
- {PRESET_COLORS.map((colorObj) => (
- <button
- key={colorObj.value}
- type="button"
- onClick={() => setSelectedColor(colorObj.value)}
- className={`
- relative w-full aspect-square rounded-xl transition-all duration-200
- hover:scale-110 active:scale-95
- ${
- selectedColor === colorObj.value
- ? "ring-4 ring-primary/30 shadow-lg scale-105"
- : "ring-2 ring-border/20 hover:ring-border/40"
- }
- `}
- style={{
- backgroundColor: colorObj.value,
- boxShadow:
- selectedColor === colorObj.value
- ? `0 8px 24px ${colorObj.value}40`
- : `0 2px 8px ${colorObj.value}20`,
- }}
- aria-label={colorObj.name}
- >
- {selectedColor === colorObj.value && (
- <motion.div
- initial={{ scale: 0 }}
- animate={{ scale: 1 }}
- className="absolute inset-0 flex items-center justify-center"
- >
- <div className="w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-lg">
- <div className="w-2 h-2 bg-primary rounded-full"></div>
- </div>
- </motion.div>
- )}
- </button>
- ))}
- </div>
- </div>
- <div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">
- <div className="flex items-center space-x-2">
- <Checkbox
- id="usePassword"
- checked={usePassword}
- onCheckedChange={(checked) => setUsePassword(!!checked)}
- />
- <Label
- htmlFor="usePassword"
- className="text-sm font-medium cursor-pointer flex items-center gap-2"
- >
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("password.optional")}
- </Label>
- </div>
- {usePassword && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="space-y-3 pt-1"
- >
- <div className="space-y-2">
- <Label htmlFor="password" className="text-sm">
- {t("form.passwordLabel")}
- </Label>
- <Input
- id="password"
- type="password"
- placeholder={t("form.passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="confirmPassword" className="text-sm">
- {t("password.confirmPassword")}
- </Label>
- <Input
- id="confirmPassword"
- type="password"
- placeholder={t("password.confirmPasswordPlaceholder")}
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
- />
- </div>
- <div className="flex items-center space-x-2 pt-1">
- <Checkbox
- id="lockCalendar"
- checked={lockCalendar}
- onCheckedChange={(checked) => setLockCalendar(!!checked)}
- />
- <div className="flex-1">
- <Label
- htmlFor="lockCalendar"
- className="text-sm font-medium cursor-pointer"
- >
- {t("calendar.lockCalendar")}
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t("calendar.lockCalendarHint")}
- </p>
- </div>
- </div>
- </motion.div>
- )}
- </div>
- {error && (
- <p className="text-sm text-red-500 flex items-center gap-1.5 bg-red-500/10 p-3 rounded-lg border border-red-500/20">
- {error}
- </p>
- )}
- <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.cancel")}
- </Button>
- <Button
- type="submit"
- disabled={!name.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>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/calendar-settings-dialog.tsx b/components/calendar-settings-dialog.tsx
deleted file mode 100644
index d975770..0000000
--- a/components/calendar-settings-dialog.tsx
+++ /dev/null
@@ -1,477 +0,0 @@
-"use client";
-
-import { useState, useEffect } 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 {
- removeCachedPassword,
- setCachedPassword,
- getCachedPassword,
-} from "@/lib/password-cache";
-import { PRESET_COLORS } from "@/lib/constants";
-import { AlertTriangle, Trash2, Download } from "lucide-react";
-import { ExportDialog } from "@/components/export-dialog";
-
-interface CalendarSettingsDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string;
- calendarName: string;
- calendarColor: string;
- hasPassword: boolean;
- isLocked: boolean;
- onSuccess: () => void;
- onDelete: (password?: string) => void;
-}
-
-export function CalendarSettingsDialog({
- open,
- onOpenChange,
- calendarId,
- calendarName,
- calendarColor,
- hasPassword,
- isLocked,
- onSuccess,
- onDelete,
-}: CalendarSettingsDialogProps) {
- const t = useTranslations();
- const [name, setName] = useState(calendarName);
- const [selectedColor, setSelectedColor] = useState(calendarColor);
- const [currentPassword, setCurrentPassword] = useState("");
- const [newPassword, setNewPassword] = useState("");
- const [confirmPassword, setConfirmPassword] = useState("");
- const [removePassword, setRemovePassword] = useState(false);
- const [lockCalendar, setLockCalendar] = useState(isLocked);
- const [error, setError] = useState("");
- const [loading, setLoading] = useState(false);
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const [showExportDialog, setShowExportDialog] = useState(false);
- const [canExport, setCanExport] = useState(false);
-
- useEffect(() => {
- if (open) {
- setName(calendarName);
- setSelectedColor(calendarColor);
- setCurrentPassword("");
- setNewPassword("");
- setConfirmPassword("");
- setRemovePassword(false);
- setLockCalendar(isLocked);
- setError("");
- setShowDeleteConfirm(false);
- setShowExportDialog(false);
-
- // Check if export is allowed (no password or password is cached)
- if (!hasPassword || !isLocked) {
- setCanExport(true);
- } else {
- const cachedPassword = getCachedPassword(calendarId);
- setCanExport(!!cachedPassword);
- }
- }
- }, [open, calendarName, calendarColor, isLocked, hasPassword, calendarId]);
-
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault();
- setError("");
-
- // Always require current password when calendar has password
- if (hasPassword && !currentPassword) {
- setError(t("validation.passwordRequired"));
- return;
- }
-
- // Validate new password fields if changing password
- const isChangingPassword = !removePassword && newPassword;
- if (isChangingPassword) {
- if (newPassword !== confirmPassword) {
- setError(t("validation.passwordMatch"));
- return;
- }
- }
-
- // If trying to lock without password
- if (lockCalendar && removePassword) {
- setError(t("calendar.lockRequiresPassword"));
- return;
- }
-
- setLoading(true);
-
- try {
- const requestBody: {
- name?: string;
- color?: string;
- currentPassword?: string;
- isLocked: boolean;
- password?: string | null;
- } = {
- name: name !== calendarName ? name : undefined,
- color: selectedColor !== calendarColor ? selectedColor : undefined,
- currentPassword: hasPassword ? currentPassword : undefined,
- isLocked: lockCalendar,
- };
-
- // Include password fields if changing password
- if (removePassword) {
- requestBody.password = null;
- } else if (newPassword) {
- requestBody.password = newPassword;
- }
-
- const response = await fetch(`/api/calendars/${calendarId}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(requestBody),
- });
-
- if (response.status === 401) {
- setError(t("validation.passwordIncorrect"));
- setLoading(false);
- return;
- }
-
- if (!response.ok) {
- setError(t("validation.passwordIncorrect"));
- setLoading(false);
- return;
- }
-
- // Handle localStorage based on what changed
- if (removePassword) {
- // Only remove from localStorage if password was actually removed
- removeCachedPassword(calendarId);
- } else if (newPassword) {
- // New password was set, update localStorage
- setCachedPassword(calendarId, newPassword);
- } else if (hasPassword && currentPassword) {
- // Only isLocked changed, keep the current password cached
- setCachedPassword(calendarId, currentPassword);
- }
-
- onSuccess();
- onOpenChange(false);
- } catch (error) {
- console.error("Failed to update calendar:", error);
- setError(t("validation.passwordIncorrect"));
- } finally {
- setLoading(false);
- }
- };
-
- 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">
- <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("calendar.settings", { name: calendarName })}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("calendar.settingsDescription")}
- </DialogDescription>
- </DialogHeader>
- <form
- onSubmit={handleSubmit}
- className="space-y-4 overflow-y-auto flex-1 px-6 pb-6"
- >
- {/* Calendar Name */}
- <div className="space-y-2.5 pt-6">
- <Label
- htmlFor="calendarName"
- 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.nameLabel")}
- </Label>
- <Input
- id="calendarName"
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder={t("form.namePlaceholder", {
- example: t("calendar.name"),
- })}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- required
- />
- </div>
-
- {/* Calendar Color */}
- <div className="space-y-2.5">
- <Label 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.colorLabel")}
- </Label>
- <div className="grid grid-cols-4 gap-2">
- {PRESET_COLORS.map((colorObj) => (
- <button
- key={colorObj.value}
- type="button"
- onClick={() => setSelectedColor(colorObj.value)}
- className={`h-11 rounded-lg transition-all ${
- selectedColor === colorObj.value
- ? "ring-2 ring-primary ring-offset-2 ring-offset-background scale-105"
- : "hover:scale-105"
- }`}
- style={{ backgroundColor: colorObj.value }}
- title={colorObj.name}
- />
- ))}
- </div>
- </div>
-
- {/* Password Section Header */}
- <div className="pt-2 pb-1">
- <div className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
- <div className="flex-1 h-px bg-border"></div>
- <span>{t("password.optional")}</span>
- <div className="flex-1 h-px bg-border"></div>
- </div>
- </div>
-
- {hasPassword && (
- <div className="space-y-2.5">
- <Label
- htmlFor="currentPassword"
- 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("password.currentPassword")}
- </Label>
- <Input
- id="currentPassword"
- type="password"
- value={currentPassword}
- onChange={(e) => setCurrentPassword(e.target.value)}
- placeholder={t("password.currentPasswordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- <p className="text-xs text-muted-foreground">
- {t("calendar.currentlyProtected")}
- </p>
- </div>
- )}
-
- {hasPassword && (
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="removePassword"
- checked={removePassword}
- onCheckedChange={(checked) => {
- const isChecked = !!checked;
- setRemovePassword(isChecked);
- // Automatically unlock if removing password
- if (isChecked) {
- setLockCalendar(false);
- }
- }}
- />
- <Label
- htmlFor="removePassword"
- className="text-sm font-medium cursor-pointer"
- >
- {t("password.removePassword")}
- </Label>
- </div>
- )}
-
- {hasPassword && !removePassword && (
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="lockCalendar"
- checked={lockCalendar}
- onCheckedChange={(checked) => setLockCalendar(!!checked)}
- />
- <div className="flex-1">
- <Label
- htmlFor="lockCalendar"
- className="text-sm font-medium cursor-pointer"
- >
- {t("calendar.lockCalendar")}
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t("calendar.lockCalendarHint")}
- </p>
- </div>
- </div>
- )}
-
- {!removePassword && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="space-y-4"
- >
- <div className="space-y-2.5">
- <Label
- htmlFor="newPassword"
- 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>
- {hasPassword
- ? t("password.newPassword")
- : t("form.passwordLabel")}
- </Label>
- <Input
- id="newPassword"
- type="password"
- value={newPassword}
- onChange={(e) => setNewPassword(e.target.value)}
- placeholder={t("password.newPasswordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
-
- <div className="space-y-2.5">
- <Label
- htmlFor="confirmPassword"
- 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("password.confirmPassword")}
- </Label>
- <Input
- id="confirmPassword"
- type="password"
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- placeholder={t("password.confirmPasswordPlaceholder")}
- className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
- />
- </div>
- </motion.div>
- )}
-
- {error && (
- <p className="text-sm text-red-500 flex items-center gap-1.5 bg-red-500/10 p-3 rounded-lg border border-red-500/20">
- {error}
- </p>
- )}
-
- {/* Export Section */}
- {canExport && (
- <div className="pt-4 mt-4 border-t border-border/50">
- <Button
- type="button"
- variant="outline"
- onClick={() => setShowExportDialog(true)}
- className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
- >
- <Download className="h-4 w-4 mr-2" />
- {t("export.exportCalendar")}
- </Button>
- </div>
- )}
-
- {/* 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"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="flex-1 h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- disabled={loading}
- 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"
- >
- {loading ? t("common.loading") : t("common.save")}
- </Button>
- </div>
- </form>
- </DialogContent>
-
- <ExportDialog
- open={showExportDialog}
- onOpenChange={setShowExportDialog}
- calendarId={calendarId}
- calendarName={calendarName}
- />
- </Dialog>
- );
-}
diff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsx
new file mode 100644
index 0000000..29da2a1
--- /dev/null
+++ b/components/calendar-settings-sheet.tsx
@@ -0,0 +1,581 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { motion } from "motion/react";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+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 {
+ removeCachedPassword,
+ setCachedPassword,
+ getCachedPassword,
+} from "@/lib/password-cache";
+import { PRESET_COLORS } from "@/lib/constants";
+import { AlertTriangle, Trash2, Download } from "lucide-react";
+import { ExportDialog } from "@/components/export-dialog";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { toast } from "sonner";
+import { useDirtyState } from "@/hooks/useDirtyState";
+
+interface CalendarSettingsSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ calendarName: string;
+ calendarColor: string;
+ hasPassword: boolean;
+ isLocked: boolean;
+ onSuccess: () => void;
+ onDelete: (password?: string) => void;
+}
+
+interface FormState {
+ name: string;
+ selectedColor: string;
+ lockCalendar: boolean;
+ removePassword: boolean;
+}
+
+export function CalendarSettingsSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ calendarName,
+ calendarColor,
+ hasPassword,
+ isLocked,
+ onSuccess,
+ onDelete,
+}: CalendarSettingsSheetProps) {
+ const t = useTranslations();
+ const [name, setName] = useState(calendarName);
+ const [selectedColor, setSelectedColor] = useState(calendarColor);
+ const [currentPassword, setCurrentPassword] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [removePassword, setRemovePassword] = useState(false);
+ const [lockCalendar, setLockCalendar] = useState(isLocked);
+ const [loading, setLoading] = useState(false);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const [showExportDialog, setShowExportDialog] = useState(false);
+ const [canExport, setCanExport] = useState(false);
+ const [passwordError, setPasswordError] = useState(false);
+ const initialFormStateRef = useRef<FormState | null>(null);
+ const currentPasswordRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (open) {
+ setName(calendarName);
+ setSelectedColor(calendarColor);
+ setCurrentPassword("");
+ setNewPassword("");
+ setConfirmPassword("");
+ setRemovePassword(false);
+ setLockCalendar(isLocked);
+ setPasswordError(false);
+ setShowDeleteConfirm(false);
+ setShowExportDialog(false);
+
+ // Store initial form state for change detection
+ initialFormStateRef.current = {
+ name: calendarName,
+ selectedColor: calendarColor,
+ lockCalendar: isLocked,
+ removePassword: false,
+ };
+
+ // Check if export is allowed (no password or password is cached)
+ if (!hasPassword || !isLocked) {
+ setCanExport(true);
+ } else {
+ const cachedPassword = getCachedPassword(calendarId);
+ setCanExport(!!cachedPassword);
+ }
+ } else {
+ initialFormStateRef.current = null;
+ }
+ }, [open, calendarName, calendarColor, isLocked, hasPassword, calendarId]);
+
+ const hasChanges = () => {
+ if (!initialFormStateRef.current) return false;
+
+ const current: FormState = {
+ name,
+ selectedColor,
+ lockCalendar,
+ removePassword,
+ };
+
+ // Check basic fields
+ const basicChanges =
+ JSON.stringify(current) !== JSON.stringify(initialFormStateRef.current);
+
+ // Check password fields
+ const passwordChanges =
+ newPassword.trim() !== "" || confirmPassword.trim() !== "";
+
+ return basicChanges || passwordChanges;
+ };
+
+ const {
+ isDirty,
+ handleClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+ } = useDirtyState({
+ open,
+ onClose: onOpenChange,
+ hasChanges,
+ });
+
+ const handleSubmit = async () => {
+ // Always require current password when calendar has password
+ if (hasPassword && !currentPassword) {
+ setPasswordError(true);
+ toast.error(t("validation.passwordRequired"));
+ currentPasswordRef.current?.focus();
+ return;
+ }
+
+ // Validate new password fields if changing password
+ const isChangingPassword = !removePassword && newPassword;
+ if (isChangingPassword) {
+ if (newPassword !== confirmPassword) {
+ toast.error(t("validation.passwordMatch"));
+ return;
+ }
+ }
+
+ // If trying to lock without password
+ if (lockCalendar && removePassword) {
+ toast.error(t("calendar.lockRequiresPassword"));
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const requestBody: {
+ name?: string;
+ color?: string;
+ currentPassword?: string;
+ isLocked: boolean;
+ password?: string | null;
+ } = {
+ name: name !== calendarName ? name : undefined,
+ color: selectedColor !== calendarColor ? selectedColor : undefined,
+ currentPassword: hasPassword ? currentPassword : undefined,
+ isLocked: lockCalendar,
+ };
+
+ // Include password fields if changing password
+ if (removePassword) {
+ requestBody.password = null;
+ } else if (newPassword) {
+ requestBody.password = newPassword;
+ }
+
+ const response = await fetch(`/api/calendars/${calendarId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (response.status === 401) {
+ toast.error(t("validation.passwordIncorrect"));
+ setPasswordError(true);
+ currentPasswordRef.current?.focus();
+ setLoading(false);
+ return;
+ }
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ toast.error(
+ errorData.error ||
+ t("common.updateError", { item: t("calendar.title") })
+ );
+ setLoading(false);
+ return;
+ }
+
+ // Handle localStorage based on what changed
+ if (removePassword) {
+ // Only remove from localStorage if password was actually removed
+ removeCachedPassword(calendarId);
+ } else if (newPassword) {
+ // New password was set, update localStorage
+ setCachedPassword(calendarId, newPassword);
+ } else if (hasPassword && currentPassword) {
+ // Only isLocked changed, keep the current password cached
+ setCachedPassword(calendarId, currentPassword);
+ }
+
+ onSuccess();
+ onOpenChange(false);
+ } catch (error) {
+ console.error("Failed to update calendar:", error);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("common.updateError", { item: t("calendar.title") })
+ );
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleDelete = () => {
+ if (hasPassword && !currentPassword) {
+ toast.error(t("validation.passwordRequired"));
+ return;
+ }
+ onDelete(hasPassword ? currentPassword : undefined);
+ onOpenChange(false);
+ };
+
+ return (
+ <>
+ <Sheet open={open} onOpenChange={handleClose}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {t("calendar.settings", { name: calendarName })}
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("calendar.settingsDescription")}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
+ {/* Password Required Notice */}
+ {hasPassword && (
+ <div className="p-4 bg-primary/10 border border-primary/20 rounded-xl space-y-2">
+ <div className="flex items-center gap-2 text-primary">
+ <AlertTriangle className="h-5 w-5" />
+ <span className="font-semibold text-sm">
+ {t("calendar.passwordProtected")}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("calendar.passwordRequiredToEdit")}
+ </p>
+ </div>
+ )}
+
+ {/* Calendar Name */}
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="calendarName"
+ 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.nameLabel")}
+ </Label>
+ <Input
+ id="calendarName"
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("form.namePlaceholder", {
+ example: t("calendar.name"),
+ })}
+ className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ required
+ />
+ </div>
+
+ {/* Calendar Color */}
+ <div className="space-y-2.5">
+ <Label 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.colorLabel")}
+ </Label>
+ <div className="grid grid-cols-4 gap-2">
+ {PRESET_COLORS.map((colorObj) => (
+ <button
+ key={colorObj.value}
+ type="button"
+ onClick={() => setSelectedColor(colorObj.value)}
+ className={`h-11 rounded-lg transition-all ${
+ selectedColor === colorObj.value
+ ? "ring-2 ring-primary ring-offset-2 ring-offset-background scale-105"
+ : "hover:scale-105"
+ }`}
+ style={{ backgroundColor: colorObj.value }}
+ title={colorObj.name}
+ />
+ ))}
+ </div>
+ </div>
+
+ {/* Password Section */}
+ <div className="space-y-4 pt-2">
+ <div className="flex items-center gap-2 text-sm font-semibold">
+ <div className="flex-1 h-px bg-border"></div>
+ <span>{t("password.management")}</span>
+ <div className="flex-1 h-px bg-border"></div>
+ </div>
+
+ {hasPassword && (
+ <div className="space-y-4 p-4 bg-muted/30 rounded-xl border border-border/30">
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="currentPassword"
+ className="text-sm font-medium flex items-center gap-2"
+ >
+ <div className="w-1 h-4 bg-gradient-to-b from-amber-500 to-amber-600 rounded-full"></div>
+ {t("password.currentPassword")}
+ <span className="text-xs text-destructive">*</span>
+ </Label>
+ <Input
+ ref={currentPasswordRef}
+ id="currentPassword"
+ type="password"
+ value={currentPassword}
+ onChange={(e) => {
+ setCurrentPassword(e.target.value);
+ setPasswordError(false);
+ }}
+ placeholder={t("password.currentPasswordPlaceholder")}
+ className={`h-11 bg-background ${
+ passwordError
+ ? "border-destructive focus:border-destructive focus:ring-destructive/20"
+ : "border-amber-500/30 focus:border-amber-500/50 focus:ring-amber-500/20"
+ }`}
+ />
+ {passwordError ? (
+ <p className="text-xs text-destructive">
+ {t("validation.passwordRequired")}
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {t("calendar.currentPasswordRequired")}
+ </p>
+ )}
+ </div>
+
+ <div className="flex items-center space-x-2 pt-2">
+ <Checkbox
+ id="removePassword"
+ checked={removePassword}
+ onCheckedChange={(checked: boolean) => {
+ const isChecked = !!checked;
+ setRemovePassword(isChecked);
+ // Automatically unlock if removing password
+ if (isChecked) {
+ setLockCalendar(false);
+ }
+ }}
+ />
+ <Label
+ htmlFor="removePassword"
+ className="text-sm font-medium cursor-pointer"
+ >
+ {t("password.removePassword")}
+ </Label>
+ </div>
+
+ {!removePassword && (
+ <div className="flex items-center space-x-2 pt-2">
+ <Checkbox
+ id="lockCalendar"
+ checked={lockCalendar}
+ onCheckedChange={(checked: boolean) =>
+ setLockCalendar(!!checked)
+ }
+ />
+ <div className="flex-1">
+ <Label
+ htmlFor="lockCalendar"
+ className="text-sm font-medium cursor-pointer"
+ >
+ {t("calendar.lockCalendar")}
+ </Label>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t("calendar.lockCalendarHint")}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {!removePassword && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.2 }}
+ className="space-y-4"
+ >
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="newPassword"
+ 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>
+ {hasPassword
+ ? t("password.newPassword")
+ : t("form.passwordLabel")}
+ </Label>
+ <Input
+ id="newPassword"
+ type="password"
+ value={newPassword}
+ onChange={(e) => setNewPassword(e.target.value)}
+ placeholder={t("password.newPasswordPlaceholder")}
+ className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ />
+ </div>
+
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="confirmPassword"
+ 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("password.confirmPassword")}
+ </Label>
+ <Input
+ id="confirmPassword"
+ type="password"
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ placeholder={t("password.confirmPasswordPlaceholder")}
+ className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ />
+ </div>
+ </motion.div>
+ )}
+ </div>
+
+ {/* Export Section */}
+ {canExport && (
+ <div className="pt-4 mt-4 border-t border-border/50">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowExportDialog(true)}
+ className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
+ >
+ <Download className="h-4 w-4 mr-2" />
+ {t("export.exportCalendar")}
+ </Button>
+ </div>
+ )}
+
+ {/* 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>
+
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <div className="flex gap-2.5 w-full">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={loading}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSubmit}
+ disabled={loading || !isDirty}
+ 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"
+ >
+ {loading ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+
+ <ExportDialog
+ open={showExportDialog}
+ onOpenChange={setShowExportDialog}
+ calendarId={calendarId}
+ calendarName={calendarName}
+ />
+
+ <ConfirmationDialog
+ open={showConfirmDialog}
+ onOpenChange={setShowConfirmDialog}
+ onConfirm={handleConfirmClose}
+ />
+ </>
+ );
+}
diff --git a/components/calendar-sheet.tsx b/components/calendar-sheet.tsx
new file mode 100644
index 0000000..cce9759
--- /dev/null
+++ b/components/calendar-sheet.tsx
@@ -0,0 +1,260 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { motion } from "motion/react";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Checkbox } from "@/components/ui/checkbox";
+import { PRESET_COLORS } from "@/lib/constants";
+
+interface CalendarSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (
+ name: string,
+ color: string,
+ password?: string,
+ isLocked?: boolean
+ ) => void;
+}
+
+export function CalendarSheet({
+ open,
+ onOpenChange,
+ onSubmit,
+}: CalendarSheetProps) {
+ const t = useTranslations();
+ const initialColor = PRESET_COLORS[0].value;
+ const [name, setName] = useState("");
+ const [selectedColor, setSelectedColor] = useState(initialColor);
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [usePassword, setUsePassword] = useState(false);
+ const [lockCalendar, setLockCalendar] = useState(false);
+ const [error, setError] = useState("");
+ const [isSaving, setIsSaving] = useState(false);
+
+ const hasChanges = () => {
+ return (
+ name.trim() !== "" ||
+ selectedColor !== initialColor ||
+ (usePassword && password !== "") ||
+ (usePassword && confirmPassword !== "")
+ );
+ };
+
+ const resetForm = () => {
+ setName("");
+ setSelectedColor(initialColor);
+ setPassword("");
+ setConfirmPassword("");
+ setUsePassword(false);
+ setLockCalendar(false);
+ setError("");
+ };
+
+ const handleSave = async () => {
+ setError("");
+
+ if (!name.trim() || isSaving) return;
+
+ // Validate password if enabled
+ if (usePassword) {
+ if (!password) {
+ setError(t("validation.passwordRequired"));
+ return;
+ }
+ if (password !== confirmPassword) {
+ setError(t("validation.passwordMatch"));
+ return;
+ }
+ }
+
+ // Can't lock without password
+ if (lockCalendar && !usePassword) {
+ setError(t("calendar.lockRequiresPassword"));
+ return;
+ }
+
+ setIsSaving(true);
+ try {
+ await onSubmit(
+ name.trim(),
+ selectedColor,
+ usePassword && password ? password : undefined,
+ lockCalendar
+ );
+
+ // Reset form on success
+ resetForm();
+ onOpenChange(false);
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("calendar.create")}
+ description={t("calendar.createDescription", {
+ default: "Create a new calendar to organize your shifts",
+ })}
+ showSaveButton
+ onSave={handleSave}
+ isSaving={isSaving}
+ saveDisabled={!name.trim()}
+ hasUnsavedChanges={hasChanges()}
+ maxWidth="md"
+ >
+ <div className="space-y-6">
+ <div className="space-y-2.5">
+ <Label
+ htmlFor="name"
+ 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("calendar.name")}
+ </Label>
+ <Input
+ id="name"
+ placeholder={t("form.namePlaceholder", {
+ example: t("calendar.name"),
+ })}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm transition-all"
+ autoFocus
+ />
+ </div>
+
+ <div className="space-y-3">
+ <Label 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.colorLabel")}
+ </Label>
+ <div className="grid grid-cols-4 gap-3 p-4 bg-muted/30 rounded-xl border border-border/30">
+ {PRESET_COLORS.map((colorObj) => (
+ <button
+ key={colorObj.value}
+ type="button"
+ onClick={() => setSelectedColor(colorObj.value)}
+ className={`
+ relative w-full aspect-square rounded-xl transition-all duration-200
+ hover:scale-110 active:scale-95
+ ${
+ selectedColor === colorObj.value
+ ? "ring-4 ring-primary/30 shadow-lg scale-105"
+ : "ring-2 ring-border/20 hover:ring-border/40"
+ }
+ `}
+ style={{
+ backgroundColor: colorObj.value,
+ boxShadow:
+ selectedColor === colorObj.value
+ ? `0 8px 24px ${colorObj.value}40`
+ : `0 2px 8px ${colorObj.value}20`,
+ }}
+ aria-label={colorObj.name}
+ >
+ {selectedColor === colorObj.value && (
+ <motion.div
+ initial={{ scale: 0 }}
+ animate={{ scale: 1 }}
+ className="absolute inset-0 flex items-center justify-center"
+ >
+ <div className="w-6 h-6 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-lg">
+ <div className="w-2 h-2 bg-primary rounded-full"></div>
+ </div>
+ </motion.div>
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="usePassword"
+ checked={usePassword}
+ onCheckedChange={(checked: boolean) => setUsePassword(!!checked)}
+ />
+ <Label
+ htmlFor="usePassword"
+ className="text-sm font-medium cursor-pointer flex items-center gap-2"
+ >
+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
+ {t("password.optional")}
+ </Label>
+ </div>
+ {usePassword && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: "auto" }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.2 }}
+ className="space-y-3 pt-1"
+ >
+ <div className="space-y-2">
+ <Label htmlFor="password" className="text-sm">
+ {t("form.passwordLabel")}
+ </Label>
+ <Input
+ id="password"
+ type="password"
+ placeholder={t("form.passwordPlaceholder")}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="confirmPassword" className="text-sm">
+ {t("password.confirmPassword")}
+ </Label>
+ <Input
+ id="confirmPassword"
+ type="password"
+ placeholder={t("password.confirmPasswordPlaceholder")}
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
+ />
+ </div>
+ <div className="flex items-center space-x-2 pt-1">
+ <Checkbox
+ id="lockCalendar"
+ checked={lockCalendar}
+ onCheckedChange={(checked: boolean) =>
+ setLockCalendar(!!checked)
+ }
+ />
+ <div className="flex-1">
+ <Label
+ htmlFor="lockCalendar"
+ className="text-sm font-medium cursor-pointer"
+ >
+ {t("calendar.lockCalendar")}
+ </Label>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t("calendar.lockCalendarHint")}
+ </p>
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </div>
+
+ {error && (
+ <p className="text-sm text-red-500 flex items-center gap-1.5 bg-red-500/10 p-3 rounded-lg border border-red-500/20">
+ {error}
+ </p>
+ )}
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/day-shifts-dialog.tsx b/components/day-shifts-dialog.tsx
deleted file mode 100644
index aeb5d77..0000000
--- a/components/day-shifts-dialog.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-"use client";
-
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { ShiftWithCalendar } from "@/lib/types";
-import { useTranslations } from "next-intl";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { Button } from "@/components/ui/button";
-import { Trash2 } from "lucide-react";
-
-interface DayShiftsDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- date: Date | null;
- shifts: ShiftWithCalendar[];
- locale: string;
- onDeleteShift?: (shiftId: string) => void;
-}
-
-export function DayShiftsDialog({
- open,
- onOpenChange,
- date,
- shifts,
- locale,
- onDeleteShift,
-}: DayShiftsDialogProps) {
- const t = useTranslations();
-
- if (!date) return null;
-
- const dateLocale = getDateLocale(locale);
- const formattedDate = format(date, "EEEE, d. MMMM yyyy", {
- locale: dateLocale,
- });
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px] 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">
- {formattedDate}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {shifts.length}{" "}
- {shifts.length === 1 ? t("shift.shift_one") : t("common.shifts")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-3 overflow-y-auto flex-1 p-6">
- {shifts.map((shift) => (
- <div
- key={shift.id}
- className="flex items-start justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
- style={{ borderLeftColor: shift.color, borderLeftWidth: 4 }}
- >
- <div className="flex-1 min-w-0">
- <div className="font-semibold flex items-center gap-2">
- <div
- className="w-1 h-4 rounded-full"
- style={{ backgroundColor: shift.color }}
- />
- <span className="truncate">{shift.title}</span>
- </div>
- <div className="text-sm text-muted-foreground mt-1">
- {shift.isAllDay ? (
- <span className="font-medium">{t("shift.allDay")}</span>
- ) : (
- <span>
- {shift.startTime} - {shift.endTime}
- </span>
- )}
- </div>
- {shift.notes && (
- <p className="text-xs text-muted-foreground mt-2 line-clamp-2">
- {shift.notes}
- </p>
- )}
- </div>
- {onDeleteShift && !shift.externalSyncId && (
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
- onClick={() => onDeleteShift(shift.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- )}
- </div>
- ))}
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index 5def474..0e946a0 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -1,13 +1,12 @@
-import { CalendarDialog } from "@/components/calendar-dialog";
-import { ShiftDialog, ShiftFormData } from "@/components/shift-dialog";
+import { CalendarSheet } from "@/components/calendar-sheet";
+import { ShiftSheet, ShiftFormData } from "@/components/shift-sheet";
import { PasswordDialog } from "@/components/password-dialog";
-import { CalendarSettingsDialog } from "@/components/calendar-settings-dialog";
-import { ExternalSyncManageDialog } from "@/components/external-sync-manage-dialog";
+import { CalendarSettingsSheet } from "@/components/calendar-settings-sheet";
+import { ExternalSyncManageSheet } from "@/components/external-sync-manage-sheet";
import { SyncNotificationDialog } from "@/components/sync-notification-dialog";
-import { DayShiftsDialog } from "@/components/day-shifts-dialog";
-import { SyncedShiftsDialog } from "@/components/synced-shifts-dialog";
-import { ViewSettingsDialog } from "@/components/view-settings-dialog";
-import { NoteDialog } from "@/components/note-dialog";
+import { ShiftsOverviewDialog } from "@/components/shifts-overview-dialog";
+import { ViewSettingsSheet } from "@/components/view-settings-sheet";
+import { NoteSheet } from "@/components/note-sheet";
import { CalendarWithCount, ShiftWithCalendar } from "@/lib/types";
import { CalendarNote } from "@/lib/db/schema";
@@ -41,7 +40,7 @@ interface DialogManagerProps {
onCalendarSettingsSuccess: () => void;
onDeleteCalendar: (password?: string) => void;
- // External Sync Dialog
+ // External Sync Sheet
showExternalSyncDialog: boolean;
onExternalSyncDialogChange: (open: boolean) => void;
syncErrorRefreshTrigger: number;
@@ -53,7 +52,7 @@ interface DialogManagerProps {
onErrorsMarkedRead: () => void;
onSyncLogUpdate: () => void;
- // Day Shifts Dialog
+ // Shifts Overview Dialog (for day shifts and synced shifts)
showDayShiftsDialog: boolean;
onDayShiftsDialogChange: (open: boolean) => void;
selectedDayDate: Date | null;
@@ -61,7 +60,7 @@ interface DialogManagerProps {
locale: string;
onDeleteShiftFromDayDialog: (id: string) => void;
- // Synced Shifts Dialog
+ // Synced Shifts Overview
showSyncedShiftsDialog: boolean;
onSyncedShiftsDialogChange: (open: boolean) => void;
selectedSyncedShifts: ShiftWithCalendar[];
@@ -102,13 +101,13 @@ interface DialogManagerProps {
export function DialogManager(props: DialogManagerProps) {
return (
<>
- <CalendarDialog
+ <CalendarSheet
open={props.showCalendarDialog}
onOpenChange={props.onCalendarDialogChange}
onSubmit={props.onCreateCalendar}
/>
- <ShiftDialog
+ <ShiftSheet
open={props.showShiftDialog}
onOpenChange={props.onShiftDialogChange}
onSubmit={props.onShiftSubmit}
@@ -130,7 +129,7 @@ export function DialogManager(props: DialogManagerProps) {
onSuccess={props.onPasswordSuccess}
/>
- <CalendarSettingsDialog
+ <CalendarSettingsSheet
open={props.showCalendarSettingsDialog}
onOpenChange={props.onCalendarSettingsDialogChange}
calendarId={props.selectedCalendar}
@@ -154,7 +153,7 @@ export function DialogManager(props: DialogManagerProps) {
onDelete={props.onDeleteCalendar}
/>
- <ExternalSyncManageDialog
+ <ExternalSyncManageSheet
open={props.showExternalSyncDialog}
onOpenChange={props.onExternalSyncDialogChange}
calendarId={props.selectedCalendar}
@@ -173,23 +172,22 @@ export function DialogManager(props: DialogManagerProps) {
</>
)}
- <DayShiftsDialog
+ <ShiftsOverviewDialog
open={props.showDayShiftsDialog}
onOpenChange={props.onDayShiftsDialogChange}
date={props.selectedDayDate}
shifts={props.selectedDayShifts}
- locale={props.locale}
onDeleteShift={props.onDeleteShiftFromDayDialog}
/>
- <SyncedShiftsDialog
+ <ShiftsOverviewDialog
open={props.showSyncedShiftsDialog}
onOpenChange={props.onSyncedShiftsDialogChange}
date={props.selectedDayDate}
shifts={props.selectedSyncedShifts}
/>
- <ViewSettingsDialog
+ <ViewSettingsSheet
open={props.showViewSettingsDialog}
onOpenChange={props.onViewSettingsDialogChange}
shiftsPerDay={props.viewSettings.shiftsPerDay}
@@ -222,7 +220,7 @@ export function DialogManager(props: DialogManagerProps) {
}
/>
- <NoteDialog
+ <NoteSheet
open={props.showNoteDialog}
onOpenChange={props.onNoteDialogChange}
onSubmit={props.onNoteSubmit}
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index b41a677..c429347 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -163,11 +163,11 @@ export function ExportDialog({
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
- toast.success(t("export.success"));
+ toast.success(t("common.success"));
onOpenChange(false);
} catch (error) {
console.error("Export error:", error);
- toast.error(t("export.error"));
+ toast.error(t("common.error"));
} finally {
setLoading(false);
}
diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsx
deleted file mode 100644
index 030dc10..0000000
--- a/components/external-sync-manage-dialog.tsx
+++ /dev/null
@@ -1,1208 +0,0 @@
-"use client";
-
-import { useState, useEffect, useCallback, useRef } from "react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { ExternalSync, SyncLog } from "@/lib/db/schema";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Checkbox } from "@/components/ui/checkbox";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { ColorPicker } from "@/components/ui/color-picker";
-import { Slider } from "@/components/ui/slider";
-import { useTranslations } from "next-intl";
-import {
- Trash2,
- RefreshCw,
- Plus,
- Edit2,
- ChevronDown,
- Loader2,
-} from "lucide-react";
-import { toast } from "sonner";
-import { PRESET_COLORS } from "@/lib/constants";
-import { getCachedPassword } from "@/lib/password-cache";
-import {
- isValidCalendarUrl,
- detectCalendarSyncType,
- type CalendarSyncType,
-} from "@/lib/external-calendar-utils";
-
-interface ExternalSyncManageDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string | null;
- onSyncComplete?: () => void;
- syncErrorRefreshTrigger?: number;
-}
-
-export function ExternalSyncManageDialog({
- open,
- onOpenChange,
- calendarId,
- onSyncComplete,
- syncErrorRefreshTrigger,
-}: ExternalSyncManageDialogProps) {
- const t = useTranslations();
- const [syncs, setSyncs] = useState<ExternalSync[]>([]);
- const [syncErrors, setSyncErrors] = useState<Record<string, string>>({});
- const [isLoading, setIsLoading] = useState(false);
- const [isSyncing, setIsSyncing] = useState<string | null>(null);
- const [isDeleting, setIsDeleting] = useState<string | null>(null);
- const [showAddForm, setShowAddForm] = useState(false);
- const [editingSync, setEditingSync] = useState<ExternalSync | null>(null);
-
- // Form state
- const [formName, setFormName] = useState("");
- const [formUrl, setFormUrl] = useState("");
- const [formColor, setFormColor] = useState("#3b82f6");
- const [formDisplayMode, setFormDisplayMode] = useState("normal");
- const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);
- const [icsFile, setIcsFile] = useState<File | null>(null);
- const [importType, setImportType] = useState<"url" | "file">("url");
- const [formIsHidden, setFormIsHidden] = useState(false);
- const [formHideFromStats, setFormHideFromStats] = useState(false);
- const [expandedHint, setExpandedHint] = useState<CalendarSyncType | null>(
- null
- );
-
- const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
- const initialFormDataRef = useRef<{
- name: string;
- url: string;
- color: string;
- displayMode: string;
- autoSyncInterval: number;
- } | null>(null);
- const isInitialMount = useRef(true);
-
- const fetchSyncs = useCallback(
- async (showLoadingState = true) => {
- if (!calendarId) return;
-
- if (showLoadingState) {
- setIsLoading(true);
- }
- try {
- const password = getCachedPassword(calendarId);
- const params = new URLSearchParams({ calendarId });
- if (password) {
- params.append("password", password);
- }
-
- const response = await fetch(`/api/external-syncs?${params}`);
- if (response.ok) {
- const data = await response.json();
- setSyncs(data);
-
- // Fetch last sync logs to check for errors
- const logsParams = new URLSearchParams({ calendarId, limit: "50" });
- if (password) {
- logsParams.append("password", password);
- }
-
- const logsResponse = await fetch(`/api/sync-logs?${logsParams}`);
- if (logsResponse.ok) {
- const logs = await logsResponse.json();
- const errors: Record<string, string> = {};
-
- // Get the latest error for each external sync
- data.forEach((sync: ExternalSync) => {
- const syncLogs = logs.filter(
- (log: SyncLog) => log.externalSyncId === sync.id
- );
- // Only show unread errors
- const latestError = syncLogs.find(
- (log: SyncLog) => log.status === "error" && !log.isRead
- );
- if (latestError) {
- errors[sync.id] =
- latestError.errorMessage ||
- t("syncNotifications.statusError");
- }
- });
-
- setSyncErrors(errors);
- }
- }
- } catch (error) {
- console.error("Failed to fetch syncs:", error);
- } finally {
- if (showLoadingState) {
- setIsLoading(false);
- }
- }
- },
- [calendarId, t]
- );
-
- // Silent refresh for sync error updates (triggered by SSE)
- useEffect(() => {
- if (
- open &&
- calendarId &&
- syncErrorRefreshTrigger &&
- syncErrorRefreshTrigger > 0
- ) {
- // Silently refresh sync errors without loading state
- fetchSyncs(false);
- }
- }, [syncErrorRefreshTrigger, open, calendarId, fetchSyncs]);
-
- // Load syncs when dialog opens, reset state when it closes
- useEffect(() => {
- if (open && calendarId) {
- fetchSyncs();
- } else {
- // Reset all internal state when dialog closes or calendarId becomes falsy
- setSyncs([]);
- setIsLoading(false);
- setIsSyncing(null);
- setIsDeleting(null);
- setShowAddForm(false);
- setEditingSync(null);
- setFormName("");
- setFormUrl("");
- setFormColor("#3b82f6");
- setFormDisplayMode("normal");
- setFormAutoSyncInterval(0);
- setIcsFile(null);
- setImportType("url");
- setFormIsHidden(false);
- setFormHideFromStats(false);
- }
- }, [open, calendarId, fetchSyncs]);
-
- const handleAddSync = async () => {
- if (!calendarId || !formName.trim()) return;
-
- // For file upload
- if (importType === "file") {
- if (!icsFile) {
- toast.error(t("validation.fileRequired"));
- return;
- }
- } else {
- // For URL-based imports
- if (!formUrl.trim()) {
- toast.error(t("validation.urlRequired"));
- return;
- }
-
- // Detect and validate calendar URL format
- const detectedType = detectCalendarSyncType(formUrl.trim());
- if (!isValidCalendarUrl(formUrl.trim(), detectedType)) {
- toast.error(t("validation.urlInvalid"));
- return;
- }
-
- // Check if URL already exists (only for URL-based imports, not file uploads)
- const normalizedUrl = formUrl.trim().toLowerCase();
- const urlExists = syncs.some(
- (sync) =>
- !sync.isOneTimeImport &&
- sync.calendarUrl.toLowerCase() === normalizedUrl
- );
-
- if (urlExists) {
- toast.error(t("validation.urlAlreadyExists"));
- return;
- }
- }
-
- setIsLoading(true);
- try {
- let icsContent: string | undefined;
-
- // Read file content if file upload
- if (importType === "file" && icsFile) {
- // Check file size (limit: 5MB)
- const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
- if (icsFile.size > MAX_FILE_SIZE) {
- toast.error(t("validation.fileTooLarge", { maxSize: "5MB" }));
- setIsLoading(false);
- return;
- }
- icsContent = await icsFile.text();
- }
-
- const password = getCachedPassword(calendarId);
-
- const response = await fetch("/api/external-syncs", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- calendarId,
- name: formName.trim(),
- calendarUrl: formUrl.trim() || undefined,
- color: formColor,
- displayMode: formDisplayMode,
- autoSyncInterval: formAutoSyncInterval,
- icsContent,
- isHidden: formIsHidden,
- hideFromStats: formHideFromStats,
- password,
- }),
- });
-
- if (response.ok) {
- const newSync = await response.json();
- setFormName("");
- setFormUrl("");
- setFormColor("#3b82f6");
- setFormDisplayMode("normal");
- setFormAutoSyncInterval(0);
- setIcsFile(null);
- setImportType("url");
- setFormIsHidden(false);
- setFormHideFromStats(false);
- setShowAddForm(false);
- await fetchSyncs();
- onSyncComplete?.(); // Trigger refresh to update parent state
- toast.success(
- t("common.created", { item: t("externalSync.syncTypeCustom") })
- );
- // Auto-sync the newly created sync
- await handleSync(newSync.id);
- } else {
- const data = await response.json();
- toast.error(
- data.error ||
- t("common.createError", { item: t("externalSync.syncTypeCustom") })
- );
- }
- } catch (error) {
- console.error("Failed to create sync:", error);
- toast.error(
- t("common.createError", { item: t("externalSync.syncTypeCustom") })
- );
- } finally {
- setIsLoading(false);
- }
- };
-
- const handleSync = async (syncId: string) => {
- setIsSyncing(syncId);
- try {
- const password = getCachedPassword(calendarId);
-
- const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
- });
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new Error(data.error || "Failed to sync calendar");
- }
-
- await fetchSyncs();
- onSyncComplete?.();
-
- // Show sync statistics
- const stats = data.stats || { created: 0, updated: 0, deleted: 0 };
- toast.success(
- `${t("externalSync.syncSuccess")}: ${stats.created} ${t(
- "externalSync.statsCreated"
- )}, ${stats.updated} ${t("externalSync.statsUpdated")}, ${
- stats.deleted
- } ${t("externalSync.statsDeleted")}`
- );
- } catch (error) {
- console.error("Sync error:", error);
- toast.error(
- error instanceof Error ? error.message : t("externalSync.syncError")
- );
- } finally {
- setIsSyncing(null);
- }
- };
-
- const handleDelete = async (syncId: string) => {
- if (!confirm(t("externalSync.deleteConfirm"))) return;
-
- setIsDeleting(syncId);
- try {
- const password = getCachedPassword(calendarId);
-
- const response = await fetch(`/api/external-syncs/${syncId}`, {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ password }),
- });
-
- if (response.ok) {
- await fetchSyncs();
- onSyncComplete?.();
- toast.success(
- t("common.deleted", { item: t("externalSync.syncTypeCustom") })
- );
- } else {
- const data = await response.json();
- toast.error(
- data.error ||
- t("common.deleteError", { item: t("externalSync.syncTypeCustom") })
- );
- }
- } catch (error) {
- console.error("Delete error:", error);
- toast.error(
- t("common.deleteError", { item: t("externalSync.syncTypeCustom") })
- );
- } finally {
- setIsDeleting(null);
- }
- };
-
- const startEdit = (sync: ExternalSync) => {
- setEditingSync(sync);
- setFormName(sync.name || "");
- setFormUrl(sync.calendarUrl || "");
- setFormColor(sync.color || "#3b82f6");
- setFormDisplayMode(sync.displayMode || "normal");
- setFormAutoSyncInterval(sync.autoSyncInterval || 0);
- setFormIsHidden(sync.isHidden || false);
- setFormHideFromStats(sync.hideFromStats || false);
- setShowAddForm(false);
-
- // Set initial data for auto-save comparison
- initialFormDataRef.current = {
- name: sync.name || "",
- url: sync.calendarUrl || "",
- color: sync.color || "#3b82f6",
- displayMode: sync.displayMode || "normal",
- autoSyncInterval: sync.autoSyncInterval || 0,
- };
- isInitialMount.current = true;
- };
-
- const cancelEdit = () => {
- setEditingSync(null);
- setFormName("");
- setFormUrl("");
- 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 (
- syncId: string,
- field: "isHidden" | "hideFromStats",
- currentValue: boolean
- ) => {
- // Optimistically update local editingSync state for immediate UI feedback
- if (editingSync && editingSync.id === syncId) {
- setEditingSync({
- ...editingSync,
- [field]: !currentValue,
- });
- }
-
- try {
- const password = getCachedPassword(calendarId);
-
- const response = await fetch(`/api/external-syncs/${syncId}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- [field]: !currentValue,
- password,
- }),
- });
-
- if (response.ok) {
- await fetchSyncs();
- onSyncComplete?.(); // Trigger refresh
- toast.success(
- t("common.updated", { item: t("externalSync.syncTypeCustom") })
- );
- } else {
- const data = await response.json();
- toast.error(
- data.error ||
- t("common.updateError", { item: t("externalSync.syncTypeCustom") })
- );
-
- // Revert optimistic update on error
- if (editingSync && editingSync.id === syncId) {
- setEditingSync({
- ...editingSync,
- [field]: currentValue,
- });
- }
- }
- } catch (error) {
- console.error("Failed to update visibility:", error);
- toast.error(
- t("common.updateError", { item: t("externalSync.syncTypeCustom") })
- );
-
- // Revert optimistic update on error
- if (editingSync && editingSync.id === syncId) {
- setEditingSync({
- ...editingSync,
- [field]: currentValue,
- });
- }
- }
- };
-
- const startAdd = () => {
- setShowAddForm(true);
- setEditingSync(null);
- setFormName("");
- setFormUrl("");
- setFormColor("#3b82f6");
- setFormDisplayMode("normal");
- setFormAutoSyncInterval(0);
- setIcsFile(null);
- setImportType("url");
- setFormIsHidden(false);
- setFormHideFromStats(false);
- };
-
- // Shared function to save external sync changes
- const saveExternalSyncChanges = useCallback(
- async (updateInitialRef: boolean = false): Promise<boolean> => {
- if (!editingSync) return false;
-
- try {
- const password = getCachedPassword(calendarId);
-
- const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- name: formName.trim(),
- calendarUrl: !editingSync.isOneTimeImport
- ? formUrl.trim()
- : undefined,
- color: formColor,
- displayMode: formDisplayMode,
- autoSyncInterval: formAutoSyncInterval,
- password,
- }),
- });
-
- if (response.ok) {
- await fetchSyncs();
- onSyncComplete?.();
- if (updateInitialRef) {
- // Update initial data ref after successful save
- initialFormDataRef.current = {
- name: formName,
- url: formUrl,
- color: formColor,
- displayMode: formDisplayMode,
- autoSyncInterval: formAutoSyncInterval,
- };
- }
- toast.success(
- t("common.updated", { item: t("externalSync.syncTypeCustom") })
- );
- return true;
- } else {
- const data = await response.json();
- toast.error(
- data.error ||
- t("common.updateError", {
- item: t("externalSync.syncTypeCustom"),
- })
- );
- return false;
- }
- } catch (error) {
- console.error("Failed to save sync:", error);
- toast.error(
- t("common.updateError", { item: t("externalSync.syncTypeCustom") })
- );
- return false;
- }
- },
- [
- calendarId,
- editingSync,
- formName,
- formUrl,
- 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,
- url: formUrl,
- 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,
- formUrl,
- 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,
- url: formUrl,
- 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 - show generic placeholder for all
- const getUrlPlaceholder = () => {
- return t("form.urlPlaceholder");
- };
-
- const getUrlHint = () => {
- if (!editingSync) {
- // When creating new calendar, show custom hint
- return t("externalSync.urlHintCustom");
- }
- };
-
- return (
- <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("externalSync.manageTitle")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("externalSync.manageDescription")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-3 overflow-y-auto flex-1 p-6">
- {/* Existing Syncs List - hide when adding new sync, show only edited sync when editing */}
- {syncs.length > 0 && !showAddForm && (
- <div className="space-y-3">
- {syncs
- .filter((sync) => !editingSync || sync.id === editingSync.id)
- .map((sync) => (
- <div
- key={sync.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: sync.color, borderLeftWidth: 4 }}
- >
- {/* Title row - always full width on mobile */}
- <div className="flex items-start gap-2">
- <div
- className="w-1 h-4 rounded-full shrink-0 mt-0.5"
- style={{ backgroundColor: sync.color }}
- />
- <span className="font-semibold flex-1 min-w-0 break-words">
- {sync.name}
- </span>
- </div>
-
- {/* Badges 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-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/20 font-medium">
- {sync.syncType === "google"
- ? t("externalSync.syncTypeGoogle")
- : sync.syncType === "custom"
- ? t("externalSync.syncTypeCustom")
- : t("externalSync.syncTypeICloud")}
- </span>
- {sync.isOneTimeImport && (
- <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("externalSync.oneTimeImport")}
- </span>
- )}
- {!sync.isOneTimeImport && sync.autoSyncInterval > 0 ? (
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400 border border-green-500/20 text-xs font-medium">
- <RefreshCw className="h-3 w-3" />
- {sync.autoSyncInterval < 60
- ? `${sync.autoSyncInterval} min`
- : sync.autoSyncInterval < 1440
- ? `${sync.autoSyncInterval / 60} h`
- : `${sync.autoSyncInterval / 1440} d`}
- </span>
- ) : (
- !sync.isOneTimeImport && (
- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-gray-500/10 text-gray-600 dark:text-gray-400 border border-gray-500/20 text-xs font-medium">
- {t("externalSync.autoSyncManual")}
- </span>
- )
- )}
- </div>
- <div className="flex gap-1 shrink-0">
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8"
- onClick={() => startEdit(sync)}
- disabled={!!isSyncing || !!isDeleting}
- >
- <Edit2 className="h-4 w-4" />
- </Button>
- {!sync.isOneTimeImport && (
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8"
- onClick={() => handleSync(sync.id)}
- disabled={!!isSyncing || !!isDeleting}
- >
- {isSyncing === sync.id ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <RefreshCw 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(sync.id)}
- disabled={!!isSyncing || !!isDeleting}
- >
- {isDeleting === sync.id ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Trash2 className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Last synced info and errors - always below badges */}
- {(sync.lastSyncedAt || syncErrors[sync.id]) && (
- <div className="pt-1 border-t border-border/30 space-y-1.5">
- {sync.lastSyncedAt && (
- <div className="text-xs text-muted-foreground">
- {t("externalSync.lastSynced")}:{" "}
- {new Date(sync.lastSyncedAt).toLocaleString()}
- </div>
- )}
- {syncErrors[sync.id] && (
- <div className="text-xs text-red-100 bg-red-950/90 p-2 rounded border border-red-800">
- <div className="font-medium mb-0.5">
- {t("syncNotifications.errorMessage")}:
- </div>
- <div className="text-red-200">
- {syncErrors[sync.id]}
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* Add/Edit Form */}
- {(showAddForm || editingSync) && (
- <div className="rounded-xl border border-border/50 bg-muted/20 p-4 space-y-4">
- <h3 className="font-semibold">
- {editingSync ? t("externalSync.editSync") : t("common.add")}
- </h3>
-
- <div className="space-y-2">
- <Label htmlFor="sync-name">{t("form.nameLabel")}</Label>
- <Input
- id="sync-name"
- type="text"
- placeholder={t("form.namePlaceholder", {
- example: t("externalSync.syncTypeCustom"),
- })}
- value={formName}
- onChange={(e) => setFormName(e.target.value)}
- disabled={isLoading}
- />
- </div>
-
- {!editingSync && (
- <div className="space-y-2">
- <Label htmlFor="import-type">
- {t("externalSync.importMethod")}
- </Label>
- <Select
- value={importType}
- onValueChange={(value: "url" | "file") => {
- setImportType(value);
- setFormUrl("");
- setIcsFile(null);
- }}
- >
- <SelectTrigger
- id="import-type"
- className="bg-background/50"
- >
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="url">
- {t("externalSync.importMethodUrl")}
- </SelectItem>
- <SelectItem value="file">
- {t("externalSync.importMethodFile")}
- </SelectItem>
- </SelectContent>
- </Select>
- <p className="text-xs text-muted-foreground">
- {importType === "url"
- ? t("externalSync.importMethodUrlHint")
- : t("externalSync.importMethodFileHint")}
- </p>
- </div>
- )}
-
- {!editingSync && importType === "file" ? (
- <div className="space-y-2">
- <Label htmlFor="ics-file">
- {t("externalSync.fileLabel")}
- </Label>
- <Input
- id="ics-file"
- type="file"
- accept=".ics,.ical"
- onChange={(e) => {
- const file = e.target.files?.[0];
- setIcsFile(file || null);
- }}
- disabled={isLoading}
- className="cursor-pointer"
- value=""
- />
- {icsFile && (
- <p className="text-xs text-muted-foreground">
- {t("externalSync.fileSelected")}: {icsFile.name}
- </p>
- )}
- </div>
- ) : (
- // Show URL input for new syncs OR when editing non-one-time-import syncs
- (!editingSync || !editingSync.isOneTimeImport) && (
- <div className="space-y-2">
- <Label htmlFor="sync-url">{t("form.urlLabel")}</Label>
- <Input
- id="sync-url"
- type="text"
- placeholder={getUrlPlaceholder()}
- value={formUrl || ""}
- onChange={(e) => setFormUrl(e.target.value)}
- disabled={isLoading}
- readOnly={!!editingSync}
- className={
- editingSync
- ? "bg-muted/30 cursor-default font-mono text-sm"
- : ""
- }
- />
- <p className="text-xs text-muted-foreground">
- {getUrlHint()}
- </p>
- </div>
- )
- )}
-
- <div className="space-y-2">
- <ColorPicker
- color={formColor}
- onChange={setFormColor}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
- />
- <p className="text-xs text-muted-foreground">
- {t("externalSync.colorHint")}
- </p>
- </div>
-
- <div className="space-y-2">
- <Label htmlFor="sync-display-mode">
- {t("externalSync.displayMode")}
- </Label>
- <Select
- value={formDisplayMode}
- onValueChange={setFormDisplayMode}
- >
- <SelectTrigger
- id="sync-display-mode"
- className="bg-background/50"
- >
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="normal">
- {t("externalSync.displayModeNormal")}
- </SelectItem>
- <SelectItem value="minimal">
- {t("externalSync.displayModeMinimal")}
- </SelectItem>
- </SelectContent>
- </Select>
- <p className="text-xs text-muted-foreground">
- {t("externalSync.displayModeHint")}
- </p>
- </div>
-
- {/* Only show auto-sync for URL-based imports (both creating and editing) */}
- {!(importType === "file") &&
- !(editingSync && editingSync.isOneTimeImport) && (
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <Label>{t("externalSync.autoSyncLabel")}</Label>
- <span className="text-sm font-medium text-primary">
- {formAutoSyncInterval === 0
- ? t("externalSync.autoSyncManual")
- : formAutoSyncInterval < 60
- ? `${formAutoSyncInterval} min`
- : formAutoSyncInterval < 1440
- ? `${formAutoSyncInterval / 60} h`
- : `${formAutoSyncInterval / 1440} d`}
- </span>
- </div>
- <Slider
- value={[
- (() => {
- const intervals = [
- 0, 5, 15, 30, 60, 120, 360, 720, 1440,
- ];
- const index = intervals.indexOf(formAutoSyncInterval);
- return index >= 0 ? index : 0;
- })(),
- ]}
- onValueChange={(value: number[]) => {
- const intervals = [
- 0, 5, 15, 30, 60, 120, 360, 720, 1440,
- ];
- setFormAutoSyncInterval(intervals[value[0]]);
- }}
- max={8}
- step={1}
- className="w-full"
- />
- <div className="flex justify-between text-xs text-muted-foreground">
- <span>{t("externalSync.autoSyncManual")}</span>
- <span>{t("externalSync.autoSync24hShort")}</span>
- </div>
- <p className="text-xs text-muted-foreground">
- {t("externalSync.autoSyncHint")}
- </p>
- </div>
- )}
-
- {/* Visibility options - both for creating and editing */}
- <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 ? editingSync.isHidden || false : formIsHidden
- }
- onCheckedChange={(checked) => {
- if (editingSync) {
- handleToggleVisibility(
- editingSync.id,
- "isHidden",
- editingSync.isHidden || false
- );
- } else {
- setFormIsHidden(checked as boolean);
- }
- }}
- />
- <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
- ? editingSync.isHidden ||
- editingSync.hideFromStats ||
- false
- : formIsHidden || formHideFromStats
- }
- onCheckedChange={(checked) => {
- if (editingSync) {
- handleToggleVisibility(
- editingSync.id,
- "hideFromStats",
- editingSync.hideFromStats || false
- );
- } else {
- setFormHideFromStats(checked as boolean);
- }
- }}
- disabled={editingSync ? editingSync.isHidden : formIsHidden}
- />
- <Label
- htmlFor="hide-from-stats"
- className={`text-sm font-normal ${
- (editingSync ? editingSync.isHidden : formIsHidden)
- ? "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>
-
- {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("");
- setFormColor("#3b82f6");
- setFormDisplayMode("normal");
- setFormAutoSyncInterval(0);
- setIcsFile(null);
- setImportType("url");
- setFormIsHidden(false);
- setFormHideFromStats(false);
- }}
- disabled={isLoading}
- >
- {t("common.cancel")}
- </Button>
- <Button
- onClick={handleAddSync}
- disabled={
- isLoading ||
- !formName.trim() ||
- (importType === "file" ? !icsFile : !formUrl.trim())
- }
- >
- {isLoading ? (
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- ) : null}
- {t("common.add")}
- </Button>
- </div>
- )}
- </div>
- )}
-
- {/* Add Button */}
- {!showAddForm && !editingSync && (
- <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={!!isSyncing || !!isDeleting}
- >
- <Plus className="mr-2 h-4 w-4" />
- {t("externalSync.addNewSync")}
- </Button>
- )}
-
- {/* Hints Section - show only when creating */}
- {showAddForm && (
- <div className="rounded-xl border border-border/50 bg-gradient-to-br from-blue-50/50 to-indigo-50/50 dark:from-blue-950/20 dark:to-indigo-950/20 p-4 space-y-2">
- <h4 className="text-sm font-semibold text-foreground/90">
- {t("externalSync.hintsTitle")}
- </h4>
- <p className="text-xs text-muted-foreground">
- {t("externalSync.hintsDescription")}
- </p>
-
- {/* iCloud Hint */}
- <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
- <button
- type="button"
- onClick={() =>
- setExpandedHint(expandedHint === "icloud" ? null : "icloud")
- }
- className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
- >
- <span className="text-sm font-medium">
- {t("externalSync.syncTypeICloud")}
- </span>
- <ChevronDown
- className={`h-4 w-4 transition-transform ${
- expandedHint === "icloud" ? "rotate-180" : ""
- }`}
- />
- </button>
- {expandedHint === "icloud" && (
- <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
- <p>{t("externalSync.hintICloud")}</p>
- </div>
- )}
- </div>
-
- {/* Google Hint */}
- <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
- <button
- type="button"
- onClick={() =>
- setExpandedHint(expandedHint === "google" ? null : "google")
- }
- className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
- >
- <span className="text-sm font-medium">
- {t("externalSync.syncTypeGoogle")}
- </span>
- <ChevronDown
- className={`h-4 w-4 transition-transform ${
- expandedHint === "google" ? "rotate-180" : ""
- }`}
- />
- </button>
- {expandedHint === "google" && (
- <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
- <p>{t("externalSync.hintGoogle")}</p>
- </div>
- )}
- </div>
-
- {/* Custom Calendar Hint */}
- <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
- <button
- type="button"
- onClick={() =>
- setExpandedHint(expandedHint === "custom" ? null : "custom")
- }
- className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
- >
- <span className="text-sm font-medium">
- {t("externalSync.customCalendar")}
- </span>
- <ChevronDown
- className={`h-4 w-4 transition-transform ${
- expandedHint === "custom" ? "rotate-180" : ""
- }`}
- />
- </button>
- {expandedHint === "custom" && (
- <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
- <p>{t("externalSync.hintCustom")}</p>
- </div>
- )}
- </div>
- </div>
- )}
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/external-sync-manage-sheet.tsx b/components/external-sync-manage-sheet.tsx
new file mode 100644
index 0000000..18fea74
--- /dev/null
+++ b/components/external-sync-manage-sheet.tsx
@@ -0,0 +1,1249 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { ExternalSync, SyncLog } from "@/lib/db/schema";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { ColorPicker } from "@/components/ui/color-picker";
+import { Slider } from "@/components/ui/slider";
+import { useTranslations } from "next-intl";
+import {
+ Trash2,
+ RefreshCw,
+ Plus,
+ Edit2,
+ ChevronDown,
+ Loader2,
+} from "lucide-react";
+import { toast } from "sonner";
+import { PRESET_COLORS } from "@/lib/constants";
+import { getCachedPassword } from "@/lib/password-cache";
+import {
+ isValidCalendarUrl,
+ detectCalendarSyncType,
+ type CalendarSyncType,
+} from "@/lib/external-calendar-utils";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { useDirtyState } from "@/hooks/useDirtyState";
+
+interface ExternalSyncManageSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string | null;
+ onSyncComplete?: () => void;
+ syncErrorRefreshTrigger?: number;
+}
+
+export function ExternalSyncManageSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ onSyncComplete,
+ syncErrorRefreshTrigger,
+}: ExternalSyncManageSheetProps) {
+ const t = useTranslations();
+ const [syncs, setSyncs] = useState<ExternalSync[]>([]);
+ const [syncErrors, setSyncErrors] = useState<Record<string, string>>({});
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSyncing, setIsSyncing] = useState<string | null>(null);
+ const [isDeleting, setIsDeleting] = useState<string | null>(null);
+ const [showAddForm, setShowAddForm] = useState(false);
+ const [editingSync, setEditingSync] = useState<ExternalSync | null>(null);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
+
+ // Form state
+ const [formName, setFormName] = useState("");
+ const [formUrl, setFormUrl] = useState("");
+ const [formColor, setFormColor] = useState("#3b82f6");
+ const [formDisplayMode, setFormDisplayMode] = useState("normal");
+ const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);
+ const [icsFile, setIcsFile] = useState<File | null>(null);
+ const [importType, setImportType] = useState<"url" | "file">("url");
+ const [formIsHidden, setFormIsHidden] = useState(false);
+ const [formHideFromStats, setFormHideFromStats] = useState(false);
+ const [expandedHint, setExpandedHint] = useState<CalendarSyncType | null>(
+ null
+ );
+
+ const initialFormDataRef = useRef<{
+ name: string;
+ url: string;
+ color: string;
+ displayMode: string;
+ autoSyncInterval: number;
+ } | null>(null);
+ const [isSavingEdit, setIsSavingEdit] = useState(false);
+
+ const fetchSyncs = useCallback(
+ async (showLoadingState = true) => {
+ if (!calendarId) return;
+
+ if (showLoadingState) {
+ setIsLoading(true);
+ }
+ try {
+ const password = getCachedPassword(calendarId);
+ const params = new URLSearchParams({ calendarId });
+ if (password) {
+ params.append("password", password);
+ }
+
+ const response = await fetch(`/api/external-syncs?${params}`);
+ if (response.ok) {
+ const data = await response.json();
+ setSyncs(data);
+
+ // Fetch last sync logs to check for errors
+ const logsParams = new URLSearchParams({ calendarId, limit: "50" });
+ if (password) {
+ logsParams.append("password", password);
+ }
+
+ const logsResponse = await fetch(`/api/sync-logs?${logsParams}`);
+ if (logsResponse.ok) {
+ const logs = await logsResponse.json();
+ const errors: Record<string, string> = {};
+
+ // Get the latest error for each external sync
+ data.forEach((sync: ExternalSync) => {
+ const syncLogs = logs.filter(
+ (log: SyncLog) => log.externalSyncId === sync.id
+ );
+ // Only show unread errors
+ const latestError = syncLogs.find(
+ (log: SyncLog) => log.status === "error" && !log.isRead
+ );
+ if (latestError) {
+ errors[sync.id] =
+ latestError.errorMessage ||
+ t("syncNotifications.statusError");
+ }
+ });
+
+ setSyncErrors(errors);
+ }
+ }
+ } catch (error) {
+ console.error("Failed to fetch syncs:", error);
+ } finally {
+ if (showLoadingState) {
+ setIsLoading(false);
+ }
+ }
+ },
+ [calendarId, t]
+ );
+
+ // Silent refresh for sync error updates (triggered by SSE)
+ useEffect(() => {
+ if (
+ open &&
+ calendarId &&
+ syncErrorRefreshTrigger &&
+ syncErrorRefreshTrigger > 0
+ ) {
+ // Silently refresh sync errors without loading state
+ fetchSyncs(false);
+ }
+ }, [syncErrorRefreshTrigger, open, calendarId, fetchSyncs]);
+
+ // Load syncs when dialog opens, reset state when it closes
+ useEffect(() => {
+ if (open && calendarId) {
+ fetchSyncs();
+ } else {
+ // Reset all internal state when dialog closes or calendarId becomes falsy
+ setSyncs([]);
+ setIsLoading(false);
+ setIsSyncing(null);
+ setIsDeleting(null);
+ setShowAddForm(false);
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
+ setIcsFile(null);
+ setImportType("url");
+ setFormIsHidden(false);
+ setFormHideFromStats(false);
+ }
+ }, [open, calendarId, fetchSyncs]);
+
+ const handleAddSync = async () => {
+ if (!calendarId || !formName.trim()) return;
+
+ // For file upload
+ if (importType === "file") {
+ if (!icsFile) {
+ toast.error(t("validation.fileRequired"));
+ return;
+ }
+ } else {
+ // For URL-based imports
+ if (!formUrl.trim()) {
+ toast.error(t("validation.urlRequired"));
+ return;
+ }
+
+ // Detect and validate calendar URL format
+ const detectedType = detectCalendarSyncType(formUrl.trim());
+ if (!isValidCalendarUrl(formUrl.trim(), detectedType)) {
+ toast.error(t("validation.urlInvalid"));
+ return;
+ }
+
+ // Check if URL already exists (only for URL-based imports, not file uploads)
+ const normalizedUrl = formUrl.trim().toLowerCase();
+ const urlExists = syncs.some(
+ (sync) =>
+ !sync.isOneTimeImport &&
+ sync.calendarUrl.toLowerCase() === normalizedUrl
+ );
+
+ if (urlExists) {
+ toast.error(t("validation.urlAlreadyExists"));
+ return;
+ }
+ }
+
+ setIsLoading(true);
+ try {
+ let icsContent: string | undefined;
+
+ // Read file content if file upload
+ if (importType === "file" && icsFile) {
+ // Check file size (limit: 5MB)
+ const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
+ if (icsFile.size > MAX_FILE_SIZE) {
+ toast.error(t("validation.fileTooLarge", { maxSize: "5MB" }));
+ setIsLoading(false);
+ return;
+ }
+ icsContent = await icsFile.text();
+ }
+
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch("/api/external-syncs", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ calendarId,
+ name: formName.trim(),
+ calendarUrl: formUrl.trim() || undefined,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ icsContent,
+ isHidden: formIsHidden,
+ hideFromStats: formHideFromStats,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ const newSync = await response.json();
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
+ setIcsFile(null);
+ setImportType("url");
+ setFormIsHidden(false);
+ setFormHideFromStats(false);
+ setShowAddForm(false);
+ await fetchSyncs();
+ onSyncComplete?.(); // Trigger refresh to update parent state
+ toast.success(
+ t("common.created", { item: t("externalSync.syncTypeCustom") })
+ );
+ // Auto-sync the newly created sync
+ await handleSync(newSync.id);
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error ||
+ t("common.createError", { item: t("externalSync.syncTypeCustom") })
+ );
+ }
+ } catch (error) {
+ console.error("Failed to create sync:", error);
+ toast.error(
+ t("common.createError", { item: t("externalSync.syncTypeCustom") })
+ );
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSync = async (syncId: string) => {
+ setIsSyncing(syncId);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password }),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to sync calendar");
+ }
+
+ await fetchSyncs();
+ onSyncComplete?.();
+
+ // Show sync statistics
+ const stats = data.stats || { created: 0, updated: 0, deleted: 0 };
+ toast.success(
+ `${t("common.success")}: ${t("common.createdCount", {
+ count: stats.created,
+ })}, ${t("common.updatedCount", {
+ count: stats.updated,
+ })}, ${t("common.deletedCount", { count: stats.deleted })}`
+ );
+ } catch (error) {
+ console.error("Sync error:", error);
+ toast.error(error instanceof Error ? error.message : t("common.error"));
+ } finally {
+ setIsSyncing(null);
+ }
+ };
+
+ const handleDelete = async (syncId: string) => {
+ setDeleteTargetId(syncId);
+ setShowDeleteConfirm(true);
+ };
+
+ const confirmDelete = async () => {
+ if (!deleteTargetId) return;
+
+ setIsDeleting(deleteTargetId);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/external-syncs/${deleteTargetId}`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password }),
+ });
+
+ if (response.ok) {
+ await fetchSyncs();
+ onSyncComplete?.();
+ toast.success(
+ t("common.deleted", { item: t("externalSync.syncTypeCustom") })
+ );
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error ||
+ t("common.deleteError", { item: t("externalSync.syncTypeCustom") })
+ );
+ }
+ } catch (error) {
+ console.error("Error deleting sync:", error);
+ toast.error(
+ t("common.deleteError", { item: t("externalSync.syncTypeCustom") })
+ );
+ } finally {
+ setIsDeleting(null);
+ setDeleteTargetId(null);
+ setShowDeleteConfirm(false);
+ }
+ };
+
+ const startEdit = (sync: ExternalSync) => {
+ setEditingSync(sync);
+ setFormName(sync.name || "");
+ setFormUrl(sync.calendarUrl || "");
+ setFormColor(sync.color || "#3b82f6");
+ setFormDisplayMode(sync.displayMode || "normal");
+ setFormAutoSyncInterval(sync.autoSyncInterval || 0);
+ setFormIsHidden(sync.isHidden || false);
+ setFormHideFromStats(sync.hideFromStats || false);
+ setShowAddForm(false);
+
+ // Set initial data for change detection
+ initialFormDataRef.current = {
+ name: sync.name || "",
+ url: sync.calendarUrl || "",
+ color: sync.color || "#3b82f6",
+ displayMode: sync.displayMode || "normal",
+ autoSyncInterval: sync.autoSyncInterval || 0,
+ };
+ };
+
+ const cancelEdit = () => {
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
+ initialFormDataRef.current = null;
+ };
+
+ const handleToggleVisibility = async (
+ syncId: string,
+ field: "isHidden" | "hideFromStats",
+ currentValue: boolean
+ ) => {
+ // Optimistically update local editingSync state for immediate UI feedback
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: !currentValue,
+ });
+ }
+
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/external-syncs/${syncId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ [field]: !currentValue,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ await fetchSyncs();
+ onSyncComplete?.(); // Trigger refresh
+ toast.success(
+ t("common.updated", { item: t("externalSync.syncTypeCustom") })
+ );
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error ||
+ t("common.updateError", { item: t("externalSync.syncTypeCustom") })
+ );
+
+ // Revert optimistic update on error
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: currentValue,
+ });
+ }
+ }
+ } catch (error) {
+ console.error("Failed to update visibility:", error);
+ toast.error(
+ t("common.updateError", { item: t("externalSync.syncTypeCustom") })
+ );
+
+ // Revert optimistic update on error
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: currentValue,
+ });
+ }
+ }
+ };
+
+ const startAdd = () => {
+ setShowAddForm(true);
+ setEditingSync(null);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
+ setIcsFile(null);
+ setImportType("url");
+ setFormIsHidden(false);
+ setFormHideFromStats(false);
+ };
+
+ // Function to check if form has changes
+ const hasFormChanges = useCallback((): boolean => {
+ // For edit mode: compare with initial values
+ if (editingSync && initialFormDataRef.current) {
+ const currentFormData = {
+ name: formName,
+ url: formUrl,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ };
+
+ return (
+ JSON.stringify(currentFormData) !==
+ JSON.stringify(initialFormDataRef.current)
+ );
+ }
+
+ // For add mode: check if any field has been filled
+ if (showAddForm) {
+ return !!(
+ formName.trim() ||
+ formUrl.trim() ||
+ formColor !== "#3b82f6" ||
+ formDisplayMode !== "normal" ||
+ formAutoSyncInterval !== 0 ||
+ icsFile
+ );
+ }
+
+ return false;
+ }, [
+ editingSync,
+ showAddForm,
+ formName,
+ formUrl,
+ formColor,
+ formDisplayMode,
+ formAutoSyncInterval,
+ icsFile,
+ ]);
+
+ // Shared function to save external sync changes
+ const saveExternalSyncChanges = useCallback(async (): Promise<boolean> => {
+ if (!editingSync) return false;
+
+ setIsSavingEdit(true);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: formName.trim(),
+ calendarUrl: !editingSync.isOneTimeImport
+ ? formUrl.trim()
+ : undefined,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ await fetchSyncs();
+ onSyncComplete?.();
+ // Update initial data ref after successful save
+ initialFormDataRef.current = {
+ name: formName,
+ url: formUrl,
+ color: formColor,
+ displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
+ };
+ toast.success(
+ t("common.updated", { item: t("externalSync.syncTypeCustom") })
+ );
+ return true;
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error ||
+ t("common.updateError", {
+ item: t("externalSync.syncTypeCustom"),
+ })
+ );
+ return false;
+ }
+ } catch (error) {
+ console.error("Failed to save sync:", error);
+ toast.error(
+ t("common.updateError", { item: t("externalSync.syncTypeCustom") })
+ );
+ return false;
+ } finally {
+ setIsSavingEdit(false);
+ }
+ }, [
+ calendarId,
+ editingSync,
+ formName,
+ formUrl,
+ formColor,
+ formDisplayMode,
+ formAutoSyncInterval,
+ fetchSyncs,
+ onSyncComplete,
+ t,
+ ]);
+
+ const {
+ isDirty,
+ handleClose: handleDialogClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+ } = useDirtyState({
+ open,
+ onClose: onOpenChange,
+ hasChanges: hasFormChanges,
+ onConfirm: () => {
+ // Reset form state for both add and edit modes
+ if (showAddForm) {
+ setShowAddForm(false);
+ }
+ if (editingSync) {
+ cancelEdit();
+ }
+ // Ensure the sheet closes
+ onOpenChange(false);
+ },
+ });
+
+ // Get URL placeholder - show generic placeholder for all
+ const getUrlPlaceholder = () => {
+ return t("form.urlPlaceholder");
+ };
+
+ const getUrlHint = () => {
+ if (!editingSync) {
+ // When creating new calendar, show custom hint
+ return t("externalSync.urlHintCustom");
+ }
+ };
+
+ return (
+ <>
+ <Sheet open={open} onOpenChange={handleDialogClose}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {t("externalSync.manageTitle")}
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("externalSync.manageDescription")}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-6 py-6 space-y-3">
+ {/* Empty state when no syncs exist */}
+ {syncs.length === 0 && !showAddForm && !editingSync && (
+ <p className="text-center text-muted-foreground py-8">
+ {t("externalSync.noSyncs")}
+ </p>
+ )}
+
+ {/* Existing Syncs List - hide when adding new sync, show only edited sync when editing */}
+ {syncs.length > 0 && !showAddForm && (
+ <div className="space-y-3">
+ {syncs
+ .filter((sync) => !editingSync || sync.id === editingSync.id)
+ .map((sync) => (
+ <div
+ key={sync.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: sync.color,
+ borderLeftWidth: 4,
+ }}
+ >
+ {/* Title row - always full width on mobile */}
+ <div className="flex items-start gap-2">
+ <div
+ className="w-1 h-4 rounded-full shrink-0 mt-0.5"
+ style={{ backgroundColor: sync.color }}
+ />
+ <span className="font-semibold flex-1 min-w-0 break-words">
+ {sync.name}
+ </span>
+ </div>
+
+ {/* Badges 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-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/20 font-medium">
+ {sync.syncType === "google"
+ ? t("externalSync.syncTypeGoogle")
+ : sync.syncType === "custom"
+ ? t("externalSync.syncTypeCustom")
+ : t("externalSync.syncTypeICloud")}
+ </span>
+ {sync.isOneTimeImport && (
+ <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("externalSync.oneTimeImport")}
+ </span>
+ )}
+ {!sync.isOneTimeImport &&
+ sync.autoSyncInterval > 0 ? (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400 border border-green-500/20 text-xs font-medium">
+ <RefreshCw className="h-3 w-3" />
+ {sync.autoSyncInterval < 60
+ ? `${sync.autoSyncInterval} min`
+ : sync.autoSyncInterval < 1440
+ ? `${sync.autoSyncInterval / 60} h`
+ : `${sync.autoSyncInterval / 1440} d`}
+ </span>
+ ) : (
+ !sync.isOneTimeImport && (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-gray-500/10 text-gray-600 dark:text-gray-400 border border-gray-500/20 text-xs font-medium">
+ {t("externalSync.autoSyncManual")}
+ </span>
+ )
+ )}
+ </div>
+ <div className="flex gap-1 shrink-0">
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => startEdit(sync)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ <Edit2 className="h-4 w-4" />
+ </Button>
+ {!sync.isOneTimeImport && (
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8"
+ onClick={() => handleSync(sync.id)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ {isSyncing === sync.id ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <RefreshCw 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(sync.id)}
+ disabled={!!isSyncing || !!isDeleting}
+ >
+ {isDeleting === sync.id ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ {/* Last synced info and errors - always below badges */}
+ {(sync.lastSyncedAt || syncErrors[sync.id]) && (
+ <div className="pt-1 border-t border-border/30 space-y-1.5">
+ {sync.lastSyncedAt && (
+ <div className="text-xs text-muted-foreground">
+ {t("externalSync.lastSynced")}:{" "}
+ {new Date(sync.lastSyncedAt).toLocaleString()}
+ </div>
+ )}
+ {syncErrors[sync.id] && (
+ <div className="text-xs text-red-100 bg-red-950/90 p-2 rounded border border-red-800">
+ <div className="font-medium mb-0.5">
+ {t("syncNotifications.errorMessage")}:
+ </div>
+ <div className="text-red-200">
+ {syncErrors[sync.id]}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Add/Edit Form */}
+ {(showAddForm || editingSync) && (
+ <div className="rounded-xl border border-border/50 bg-muted/20 p-4 space-y-4">
+ <h3 className="font-semibold">
+ {editingSync ? t("externalSync.editSync") : t("common.add")}
+ </h3>
+
+ <div className="space-y-2">
+ <Label htmlFor="sync-name">{t("form.nameLabel")}</Label>
+ <Input
+ id="sync-name"
+ type="text"
+ placeholder={t("form.namePlaceholder", {
+ example: t("externalSync.syncTypeCustom"),
+ })}
+ value={formName}
+ onChange={(e) => setFormName(e.target.value)}
+ disabled={isLoading}
+ />
+ </div>
+
+ {!editingSync && (
+ <div className="space-y-2">
+ <Label htmlFor="import-type">
+ {t("externalSync.importMethod")}
+ </Label>
+ <Select
+ value={importType}
+ onValueChange={(value: "url" | "file") => {
+ setImportType(value);
+ setFormUrl("");
+ setIcsFile(null);
+ }}
+ >
+ <SelectTrigger
+ id="import-type"
+ className="bg-background/50"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="url">
+ {t("externalSync.importMethodUrl")}
+ </SelectItem>
+ <SelectItem value="file">
+ {t("externalSync.importMethodFile")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {importType === "url"
+ ? t("externalSync.importMethodUrlHint")
+ : t("externalSync.importMethodFileHint")}
+ </p>
+ </div>
+ )}
+
+ {!editingSync && importType === "file" ? (
+ <div className="space-y-2">
+ <Label htmlFor="ics-file">
+ {t("externalSync.fileLabel")}
+ </Label>
+ <Input
+ id="ics-file"
+ type="file"
+ accept=".ics,.ical"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ setIcsFile(file || null);
+ }}
+ disabled={isLoading}
+ className="cursor-pointer"
+ value=""
+ />
+ {icsFile && (
+ <p className="text-xs text-muted-foreground">
+ {t("externalSync.fileSelected")}: {icsFile.name}
+ </p>
+ )}
+ </div>
+ ) : (
+ // Show URL input for new syncs OR when editing non-one-time-import syncs
+ (!editingSync || !editingSync.isOneTimeImport) && (
+ <div className="space-y-2">
+ <Label htmlFor="sync-url">{t("form.urlLabel")}</Label>
+ <Input
+ id="sync-url"
+ type="text"
+ placeholder={getUrlPlaceholder()}
+ value={formUrl || ""}
+ onChange={(e) => setFormUrl(e.target.value)}
+ disabled={isLoading}
+ readOnly={!!editingSync}
+ className={
+ editingSync
+ ? "bg-muted/30 cursor-default font-mono text-sm"
+ : ""
+ }
+ />
+ <p className="text-xs text-muted-foreground">
+ {getUrlHint()}
+ </p>
+ </div>
+ )
+ )}
+
+ <div className="space-y-2">
+ <ColorPicker
+ color={formColor}
+ onChange={setFormColor}
+ label={t("form.colorLabel")}
+ presetColors={PRESET_COLORS}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("externalSync.colorHint")}
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="sync-display-mode">
+ {t("externalSync.displayMode")}
+ </Label>
+ <Select
+ value={formDisplayMode}
+ onValueChange={setFormDisplayMode}
+ >
+ <SelectTrigger
+ id="sync-display-mode"
+ className="bg-background/50"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="normal">
+ {t("externalSync.displayModeNormal")}
+ </SelectItem>
+ <SelectItem value="minimal">
+ {t("externalSync.displayModeMinimal")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {t("externalSync.displayModeHint")}
+ </p>
+ </div>
+
+ {/* Only show auto-sync for URL-based imports (both creating and editing) */}
+ {!(importType === "file") &&
+ !(editingSync && editingSync.isOneTimeImport) && (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <Label>{t("externalSync.autoSyncLabel")}</Label>
+ <span className="text-sm font-medium text-primary">
+ {formAutoSyncInterval === 0
+ ? t("externalSync.autoSyncManual")
+ : formAutoSyncInterval < 60
+ ? `${formAutoSyncInterval} min`
+ : formAutoSyncInterval < 1440
+ ? `${formAutoSyncInterval / 60} h`
+ : `${formAutoSyncInterval / 1440} d`}
+ </span>
+ </div>
+ <Slider
+ value={[
+ (() => {
+ const intervals = [
+ 0, 5, 15, 30, 60, 120, 360, 720, 1440,
+ ];
+ const index =
+ intervals.indexOf(formAutoSyncInterval);
+ return index >= 0 ? index : 0;
+ })(),
+ ]}
+ onValueChange={(value: number[]) => {
+ const intervals = [
+ 0, 5, 15, 30, 60, 120, 360, 720, 1440,
+ ];
+ setFormAutoSyncInterval(intervals[value[0]]);
+ }}
+ max={8}
+ step={1}
+ className="w-full"
+ />
+ <div className="flex justify-between text-xs text-muted-foreground">
+ <span>{t("externalSync.autoSyncManual")}</span>
+ <span>{t("externalSync.autoSync24hShort")}</span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("externalSync.autoSyncHint")}
+ </p>
+ </div>
+ )}
+
+ {/* Visibility options - both for creating and editing */}
+ <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
+ ? editingSync.isHidden || false
+ : formIsHidden
+ }
+ onCheckedChange={(checked) => {
+ if (editingSync) {
+ handleToggleVisibility(
+ editingSync.id,
+ "isHidden",
+ editingSync.isHidden || false
+ );
+ } else {
+ setFormIsHidden(checked as boolean);
+ }
+ }}
+ />
+ <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
+ ? editingSync.isHidden ||
+ editingSync.hideFromStats ||
+ false
+ : formIsHidden || formHideFromStats
+ }
+ onCheckedChange={(checked) => {
+ if (editingSync) {
+ handleToggleVisibility(
+ editingSync.id,
+ "hideFromStats",
+ editingSync.hideFromStats || false
+ );
+ } else {
+ setFormHideFromStats(checked as boolean);
+ }
+ }}
+ disabled={
+ editingSync ? editingSync.isHidden : formIsHidden
+ }
+ />
+ <Label
+ htmlFor="hide-from-stats"
+ className={`text-sm font-normal ${
+ (editingSync ? editingSync.isHidden : formIsHidden)
+ ? "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>
+ </div>
+ )}
+
+ {/* Hints Section - show only when creating */}
+ {showAddForm && (
+ <div className="rounded-xl border border-border/50 bg-gradient-to-br from-blue-50/50 to-indigo-50/50 dark:from-blue-950/20 dark:to-indigo-950/20 p-4 space-y-2">
+ <h4 className="text-sm font-semibold text-foreground/90">
+ {t("externalSync.hintsTitle")}
+ </h4>
+ <p className="text-xs text-muted-foreground">
+ {t("externalSync.hintsDescription")}
+ </p>
+
+ {/* iCloud Hint */}
+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
+ <button
+ type="button"
+ onClick={() =>
+ setExpandedHint(
+ expandedHint === "icloud" ? null : "icloud"
+ )
+ }
+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
+ >
+ <span className="text-sm font-medium">
+ {t("externalSync.syncTypeICloud")}
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${
+ expandedHint === "icloud" ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {expandedHint === "icloud" && (
+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
+ <p>{t("externalSync.hintICloud")}</p>
+ </div>
+ )}
+ </div>
+
+ {/* Google Hint */}
+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
+ <button
+ type="button"
+ onClick={() =>
+ setExpandedHint(
+ expandedHint === "google" ? null : "google"
+ )
+ }
+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
+ >
+ <span className="text-sm font-medium">
+ {t("externalSync.syncTypeGoogle")}
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${
+ expandedHint === "google" ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {expandedHint === "google" && (
+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
+ <p>{t("externalSync.hintGoogle")}</p>
+ </div>
+ )}
+ </div>
+
+ {/* Custom Calendar Hint */}
+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">
+ <button
+ type="button"
+ onClick={() =>
+ setExpandedHint(
+ expandedHint === "custom" ? null : "custom"
+ )
+ }
+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
+ >
+ <span className="text-sm font-medium">
+ {t("externalSync.customCalendar")}
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${
+ expandedHint === "custom" ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {expandedHint === "custom" && (
+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">
+ <p>{t("externalSync.hintCustom")}</p>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Sticky Footer */}
+ {!showAddForm && !editingSync && (
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <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={!!isSyncing || !!isDeleting}
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ {t("externalSync.addNewSync")}
+ </Button>
+ </SheetFooter>
+ )}
+
+ {/* Sticky Footer for Edit Form */}
+ {editingSync && (
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <div className="flex gap-2.5 w-full">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => cancelEdit()}
+ disabled={isSavingEdit}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={saveExternalSyncChanges}
+ disabled={isSavingEdit || !formName.trim() || !isDirty}
+ 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"
+ >
+ {isSavingEdit ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ </SheetFooter>
+ )}
+
+ {/* Sticky Footer for Add Form */}
+ {showAddForm && (
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <div className="flex gap-2.5 w-full">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ setShowAddForm(false);
+ setFormName("");
+ setFormUrl("");
+ setFormColor("#3b82f6");
+ setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
+ setIcsFile(null);
+ setImportType("url");
+ setFormIsHidden(false);
+ setFormHideFromStats(false);
+ }}
+ disabled={isLoading}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleAddSync}
+ disabled={
+ isLoading ||
+ !formName.trim() ||
+ (importType === "file" ? !icsFile : !formUrl.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"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t("common.saving")}
+ </>
+ ) : (
+ t("common.add")
+ )}
+ </Button>
+ </div>
+ </SheetFooter>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <ConfirmationDialog
+ open={showConfirmDialog}
+ onOpenChange={setShowConfirmDialog}
+ onConfirm={handleConfirmClose}
+ />
+
+ <ConfirmationDialog
+ open={showDeleteConfirm}
+ onOpenChange={setShowDeleteConfirm}
+ onConfirm={confirmDelete}
+ title={t("common.confirmDelete")}
+ description={t("externalSync.deleteConfirm")}
+ />
+ </>
+ );
+}
diff --git a/components/note-dialog.tsx b/components/note-dialog.tsx
deleted file mode 100644
index a933288..0000000
--- a/components/note-dialog.tsx
+++ /dev/null
@@ -1,207 +0,0 @@
-"use client";
-
-import { useState, useEffect, useRef } from "react";
-import { useTranslations } from "next-intl";
-import { StickyNote } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import { CalendarNote } from "@/lib/db/schema";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
-
-interface NoteDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- onSubmit: (note: string) => void;
- onDelete?: () => void;
- selectedDate?: Date;
- note?: CalendarNote;
-}
-
-export function NoteDialog({
- open,
- onOpenChange,
- onSubmit,
- onDelete,
- selectedDate,
- note,
-}: NoteDialogProps) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const initialNoteRef = useRef<string>("");
- const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
- const isInitialMount = useRef(true);
- const prevNoteIdRef = useRef<string | undefined>(undefined);
- const isNewNote = !note;
-
- // State initialization - useEffect handles all updates
- const [noteText, setNoteText] = useState("");
-
- // Update noteText when note changes (only when note ID actually changes)
- useEffect(() => {
- if (open) {
- const currentNoteId = note?.id;
- // Only update if note ID changed to avoid cascading renders
- if (prevNoteIdRef.current !== currentNoteId) {
- const currentNote = note?.note || "";
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setNoteText(currentNote);
- initialNoteRef.current = currentNote;
- isInitialMount.current = true;
- prevNoteIdRef.current = currentNoteId;
- }
- }
- }, [open, note]);
-
- // Handle dialog close with immediate save if needed (only for existing notes)
- const handleDialogClose = (open: boolean) => {
- if (!open && !isNewNote && 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 (only for existing notes)
- useEffect(() => {
- if (!open || isNewNote) 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, isNewNote]);
-
- const handleDelete = () => {
- if (onDelete) {
- onDelete();
- onOpenChange(false);
- }
- };
-
- const handleAdd = () => {
- if (noteText.trim()) {
- onSubmit(noteText);
- onOpenChange(false);
- }
- };
-
- const formattedDate = selectedDate
- ? format(selectedDate, "PPP", { locale: dateLocale })
- : "";
-
- return (
- <Dialog open={open} onOpenChange={handleDialogClose}>
- <DialogContent
- key={note?.id || "new-note"}
- className="sm:max-w-[480px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl"
- >
- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">
- <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text flex items-center gap-2">
- <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/30">
- <StickyNote className="h-5 w-5 text-white" />
- </div>
- {note ? t("note.edit") : t("note.create")}
- </DialogTitle>
- <DialogDescription asChild>
- <div className="text-sm text-muted-foreground flex items-center gap-2 pl-11">
- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {formattedDate}
- </div>
- </DialogDescription>
- </DialogHeader>
- <div className="p-6 space-y-5">
- <div className="space-y-2.5">
- <Label
- htmlFor="note"
- 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("note.note")}
- </Label>
- <Textarea
- id="note"
- value={noteText}
- 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"
- />
- </div>
- <div className="flex justify-between items-center pt-2">
- <div>
- {note && onDelete && (
- <Button
- type="button"
- variant="destructive"
- onClick={handleDelete}
- className="h-11 shadow-lg hover:shadow-xl transition-all"
- >
- {t("common.delete")}
- </Button>
- )}
- </div>
- <div className="flex gap-2.5">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.close")}
- </Button>
- {isNewNote && (
- <Button
- type="button"
- onClick={handleAdd}
- disabled={!noteText.trim()}
- className="h-11 shadow-lg hover:shadow-xl transition-all"
- >
- {t("common.add")}
- </Button>
- )}
- </div>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/note-sheet.tsx b/components/note-sheet.tsx
new file mode 100644
index 0000000..81e99c0
--- /dev/null
+++ b/components/note-sheet.tsx
@@ -0,0 +1,163 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { useTranslations, useLocale } from "next-intl";
+import { BaseSheet } from "@/components/ui/base-sheet";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { CalendarNote } from "@/lib/db/schema";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+
+interface NoteSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (note: string) => void;
+ onDelete?: () => void;
+ selectedDate?: Date;
+ note?: CalendarNote;
+}
+
+export function NoteSheet({
+ open,
+ onOpenChange,
+ onSubmit,
+ onDelete,
+ selectedDate,
+ note,
+}: NoteSheetProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const [noteText, setNoteText] = useState("");
+ const [isSaving, setIsSaving] = useState(false);
+ const initialNoteTextRef = useRef<string>("");
+
+ // Reset state when dialog opens/closes or note changes
+ useEffect(() => {
+ if (open) {
+ const initialText = note?.note || "";
+ setNoteText(initialText);
+ if (note) {
+ initialNoteTextRef.current = initialText;
+ }
+ } else {
+ initialNoteTextRef.current = "";
+ }
+ }, [open, note]);
+
+ const hasChanges = () => {
+ if (note) {
+ // Edit mode: check if text changed from initial
+ return noteText !== initialNoteTextRef.current;
+ } else {
+ // Create mode: check if any text was entered
+ return noteText.trim() !== "";
+ }
+ };
+
+ const handleSave = async () => {
+ if (!noteText.trim() || isSaving) return;
+
+ setIsSaving(true);
+ try {
+ onSubmit(noteText);
+ onOpenChange(false);
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const handleDelete = () => {
+ if (onDelete) {
+ onDelete();
+ onOpenChange(false);
+ }
+ };
+
+ const formattedDate = selectedDate
+ ? format(selectedDate, "PPP", { locale: dateLocale })
+ : "";
+
+ const customFooter = note ? (
+ // Edit mode: Delete button on left, Cancel/Save on right
+ <div className="flex gap-2.5 w-full">
+ {onDelete && (
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={handleDelete}
+ disabled={isSaving}
+ className="h-11 shadow-lg shadow-destructive/25"
+ >
+ {t("common.delete")}
+ </Button>
+ )}
+ <div className="flex-1" />
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isSaving}
+ className="h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSave}
+ disabled={isSaving || !noteText.trim() || !hasChanges()}
+ 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 disabled:opacity-50 disabled:shadow-none"
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ ) : (
+ // Create mode: Full-width buttons
+ <div className="flex gap-2.5 w-full">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isSaving}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSave}
+ disabled={isSaving || !noteText.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"
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ </div>
+ );
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={note ? t("note.edit") : t("note.create")}
+ description={formattedDate}
+ footer={customFooter}
+ hasUnsavedChanges={hasChanges()}
+ maxWidth="md"
+ >
+ <div className="space-y-3">
+ <Label htmlFor="note-text" className="text-sm font-medium">
+ {t("note.note")}
+ </Label>
+ <Textarea
+ id="note-text"
+ value={noteText}
+ onChange={(e) => setNoteText(e.target.value)}
+ placeholder={t("note.placeholder")}
+ className="min-h-[300px] resize-none focus-visible:ring-primary/30 border-border/50"
+ />
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/preset-manage-dialog.tsx b/components/preset-manage-dialog.tsx
deleted file mode 100644
index 6d6a539..0000000
--- a/components/preset-manage-dialog.tsx
+++ /dev/null
@@ -1,883 +0,0 @@
-"use client";
-
-import { useState, useEffect, useCallback, useRef, memo } from "react";
-import { useTranslations } from "next-intl";
-import { motion } from "motion/react";
-import {
- DndContext,
- closestCenter,
- KeyboardSensor,
- PointerSensor,
- useSensor,
- useSensors,
- DragEndEvent,
-} from "@dnd-kit/core";
-import {
- arrayMove,
- SortableContext,
- sortableKeyboardCoordinates,
- useSortable,
- verticalListSortingStrategy,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-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";
-import { Plus, Trash2, Edit2, Loader2, GripVertical } 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[];
- onPresetsChange: () => void;
-}
-
-// Sortable preset item component
-interface SortablePresetItemProps {
- preset: ShiftPreset;
- isDeleting: boolean;
- onEdit: (preset: ShiftPreset) => void;
- onDelete: (id: string) => void;
- t: (key: string) => string;
- showDragHandle?: boolean;
-}
-
-const SortablePresetItem = memo(function SortablePresetItem({
- preset,
- isDeleting,
- onEdit,
- onDelete,
- t,
- showDragHandle = true,
-}: SortablePresetItemProps) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- isDragging,
- } = useSortable({ id: preset.id });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition: isDragging ? undefined : transition, // Disable transition during drag for smoother performance
- opacity: isDragging ? 0.5 : 1,
- zIndex: isDragging ? 1 : 0,
- };
-
- return (
- <div
- ref={setNodeRef}
- style={style}
- className="flex flex-col gap-3 p-4 rounded-xl border border-border/50 bg-muted/20 transition-colors"
- {...attributes}
- >
- <div className="flex items-start gap-2">
- {showDragHandle && (
- <button
- className="cursor-grab active:cursor-grabbing p-1 hover:bg-muted/50 rounded transition-colors shrink-0"
- {...listeners}
- >
- <GripVertical className="h-4 w-4 text-muted-foreground" />
- </button>
- )}
- <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>
-
- <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between pl-7">
- <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={() => onEdit(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={() => onDelete(preset.id)}
- disabled={isDeleting}
- >
- {isDeleting ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Trash2 className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- </div>
- );
-});
-
-export function PresetManageDialog({
- open,
- onOpenChange,
- calendarId,
- presets,
- 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);
- const [orderedPrimaryPresets, setOrderedPrimaryPresets] = useState<
- ShiftPreset[]
- >([]);
- const [orderedSecondaryPresets, setOrderedSecondaryPresets] = useState<
- ShiftPreset[]
- >([]);
-
- // Update local ordered presets when presets prop changes
- useEffect(() => {
- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
- }, [presets]);
-
- // Drag and drop sensors with activation constraint to prevent accidental drags
- const sensors = useSensors(
- useSensor(PointerSensor, {
- activationConstraint: {
- distance: 8, // Require 8px movement before drag starts
- },
- }),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- })
- );
-
- // 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);
-
- // Handle drag end for primary presets
- const handlePrimaryDragEnd = async (event: DragEndEvent) => {
- const { active, over } = event;
-
- if (!over || active.id === over.id) {
- return;
- }
-
- const oldIndex = orderedPrimaryPresets.findIndex((p) => p.id === active.id);
- const newIndex = orderedPrimaryPresets.findIndex((p) => p.id === over.id);
-
- const newOrderedPrimary = arrayMove(
- orderedPrimaryPresets,
- oldIndex,
- newIndex
- );
- setOrderedPrimaryPresets(newOrderedPrimary);
-
- // Save new order to backend
- await savePresetOrder([...newOrderedPrimary, ...orderedSecondaryPresets]);
- };
-
- // Handle drag end for secondary presets
- const handleSecondaryDragEnd = async (event: DragEndEvent) => {
- const { active, over } = event;
-
- if (!over || active.id === over.id) {
- return;
- }
-
- const oldIndex = orderedSecondaryPresets.findIndex(
- (p) => p.id === active.id
- );
- const newIndex = orderedSecondaryPresets.findIndex((p) => p.id === over.id);
-
- const newOrderedSecondary = arrayMove(
- orderedSecondaryPresets,
- oldIndex,
- newIndex
- );
- setOrderedSecondaryPresets(newOrderedSecondary);
-
- // Save new order to backend
- await savePresetOrder([...orderedPrimaryPresets, ...newOrderedSecondary]);
- };
-
- const savePresetOrder = async (allPresets: ShiftPreset[]) => {
- try {
- const password = getCachedPassword(calendarId);
- const presetOrders = allPresets.map((preset, index) => ({
- id: preset.id,
- order: index,
- }));
-
- const response = await fetch("/api/presets/reorder", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- calendarId,
- presetOrders,
- password,
- }),
- });
-
- if (response.ok) {
- onPresetsChange();
- } else {
- const data = await response.json();
- toast.error(
- data.error || t("common.updateError", { item: t("preset.preset") })
- );
- // Revert order on error
- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
- }
- } catch (error) {
- console.error("Failed to reorder presets:", error);
- toast.error(t("common.updateError", { item: t("preset.preset") }));
- // Revert order on error
- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
- }
- };
-
- // 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={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")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-3 overflow-y-auto flex-1 p-6">
- {/* Primary Presets List */}
- {orderedPrimaryPresets.length > 0 &&
- !showAddForm &&
- !editingPreset && (
- <div className="space-y-2">
- <h3 className="text-sm font-medium text-muted-foreground px-1">
- {t("preset.primaryPresets")}
- </h3>
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handlePrimaryDragEnd}
- >
- <SortableContext
- items={orderedPrimaryPresets.map((p) => p.id)}
- strategy={verticalListSortingStrategy}
- >
- <div className="space-y-3">
- {orderedPrimaryPresets.map((preset) => (
- <SortablePresetItem
- key={preset.id}
- preset={preset}
- isDeleting={isDeleting === preset.id}
- onEdit={startEdit}
- onDelete={handleDelete}
- t={t}
- showDragHandle={orderedPrimaryPresets.length > 1}
- />
- ))}
- </div>
- </SortableContext>
- </DndContext>
- </div>
- )}
-
- {/* Secondary Presets List */}
- {orderedSecondaryPresets.length > 0 &&
- !showAddForm &&
- !editingPreset && (
- <div className="space-y-2">
- <h3 className="text-sm font-medium text-muted-foreground px-1">
- {t("preset.secondaryPresets")}
- </h3>
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleSecondaryDragEnd}
- >
- <SortableContext
- items={orderedSecondaryPresets.map((p) => p.id)}
- strategy={verticalListSortingStrategy}
- >
- <div className="space-y-3">
- {orderedSecondaryPresets.map((preset) => (
- <SortablePresetItem
- key={preset.id}
- preset={preset}
- isDeleting={isDeleting === preset.id}
- onEdit={startEdit}
- onDelete={handleDelete}
- t={t}
- showDragHandle={orderedSecondaryPresets.length > 1}
- />
- ))}
- </div>
- </SortableContext>
- </DndContext>
- </div>
- )}
-
- {/* Show edited preset */}
- {editingPreset && (
- <div className="space-y-3">
- <SortablePresetItem
- preset={editingPreset}
- isDeleting={isDeleting === editingPreset.id}
- onEdit={startEdit}
- onDelete={handleDelete}
- t={t}
- showDragHandle={false}
- />
- </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>
-
- {!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"
- >
- <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"
- >
- {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-manage-sheet.tsx b/components/preset-manage-sheet.tsx
new file mode 100644
index 0000000..ba7c510
--- /dev/null
+++ b/components/preset-manage-sheet.tsx
@@ -0,0 +1,879 @@
+"use client";
+
+import { useState, useEffect, memo, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { motion } from "motion/react";
+import {
+ DndContext,
+ closestCenter,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ DragEndEvent,
+} from "@dnd-kit/core";
+import {
+ arrayMove,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+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";
+import { Plus, Trash2, Edit2, Loader2, GripVertical } from "lucide-react";
+import { toast } from "sonner";
+import { getCachedPassword } from "@/lib/password-cache";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { useDirtyState } from "@/hooks/useDirtyState";
+
+interface PresetFormData {
+ title: string;
+ startTime: string;
+ endTime: string;
+ color: string;
+ notes: string;
+ isSecondary: boolean;
+ isAllDay: boolean;
+ hideFromStats: boolean;
+}
+
+interface PresetManageSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ presets: ShiftPreset[];
+ onPresetsChange: () => void;
+}
+
+// Sortable preset item component
+interface SortablePresetItemProps {
+ preset: ShiftPreset;
+ isDeleting: boolean;
+ onEdit: (preset: ShiftPreset) => void;
+ onDelete: (id: string) => void;
+ t: (key: string) => string;
+ showDragHandle?: boolean;
+}
+
+const SortablePresetItem = memo(function SortablePresetItem({
+ preset,
+ isDeleting,
+ onEdit,
+ onDelete,
+ t,
+ showDragHandle = true,
+}: SortablePresetItemProps) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: preset.id });
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition: isDragging ? undefined : transition,
+ opacity: isDragging ? 0.5 : 1,
+ zIndex: isDragging ? 1 : 0,
+ };
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className="flex flex-col gap-3 p-4 rounded-xl border border-border/50 bg-muted/20 transition-colors"
+ {...attributes}
+ >
+ <div className="flex items-start gap-2">
+ {showDragHandle && (
+ <button
+ className="cursor-grab active:cursor-grabbing p-1 hover:bg-muted/50 rounded transition-colors shrink-0"
+ {...listeners}
+ >
+ <GripVertical className="h-4 w-4 text-muted-foreground" />
+ </button>
+ )}
+ <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>
+
+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between pl-7">
+ <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={() => onEdit(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"
+ onClick={() => onDelete(preset.id)}
+ disabled={isDeleting}
+ >
+ {isDeleting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+});
+
+export function PresetManageSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ presets,
+ onPresetsChange,
+}: PresetManageSheetProps) {
+ const t = useTranslations();
+
+ const [showAddForm, setShowAddForm] = useState(false);
+ const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);
+ 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 [isLoading, setIsLoading] = useState(false);
+ const [isDeleting, setIsDeleting] = useState<string | null>(null);
+ const [orderedPrimaryPresets, setOrderedPrimaryPresets] = useState<
+ ShiftPreset[]
+ >([]);
+ const [orderedSecondaryPresets, setOrderedSecondaryPresets] = useState<
+ ShiftPreset[]
+ >([]);
+ const initialFormDataRef = useRef<PresetFormData | null>(null);
+
+ // Initialize ordered presets
+ useEffect(() => {
+ if (open) {
+ setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
+ setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
+ }
+ }, [presets, open]);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ );
+
+ const handlePrimaryDragEnd = async (event: DragEndEvent) => {
+ const { active, over } = event;
+
+ if (!over || active.id === over.id) {
+ return;
+ }
+
+ const oldIndex = orderedPrimaryPresets.findIndex((p) => p.id === active.id);
+ const newIndex = orderedPrimaryPresets.findIndex((p) => p.id === over.id);
+
+ const newOrderedPrimary = arrayMove(
+ orderedPrimaryPresets,
+ oldIndex,
+ newIndex
+ );
+ setOrderedPrimaryPresets(newOrderedPrimary);
+
+ // Save new order to backend
+ await savePresetOrder([...newOrderedPrimary, ...orderedSecondaryPresets]);
+ };
+
+ const handleSecondaryDragEnd = async (event: DragEndEvent) => {
+ const { active, over } = event;
+
+ if (!over || active.id === over.id) {
+ return;
+ }
+
+ const oldIndex = orderedSecondaryPresets.findIndex(
+ (p) => p.id === active.id
+ );
+ const newIndex = orderedSecondaryPresets.findIndex((p) => p.id === over.id);
+
+ const newOrderedSecondary = arrayMove(
+ orderedSecondaryPresets,
+ oldIndex,
+ newIndex
+ );
+ setOrderedSecondaryPresets(newOrderedSecondary);
+
+ // Save new order to backend
+ await savePresetOrder([...orderedPrimaryPresets, ...newOrderedSecondary]);
+ };
+
+ const savePresetOrder = async (allPresets: ShiftPreset[]) => {
+ try {
+ const password = getCachedPassword(calendarId);
+ const presetOrders = allPresets.map((preset, index) => ({
+ id: preset.id,
+ order: index,
+ }));
+
+ const response = await fetch("/api/presets/reorder", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ calendarId,
+ presetOrders,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ onPresetsChange();
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error || t("common.updateError", { item: t("preset.preset") })
+ );
+ // Revert order on error
+ setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
+ setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
+ }
+ } catch (error) {
+ console.error("Failed to reorder presets:", error);
+ toast.error(t("common.updateError", { item: t("preset.preset") }));
+ // Revert order on error
+ setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
+ setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
+ }
+ };
+
+ // Reset state when sheet 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);
+ }
+ }, [open]);
+
+ const handleSavePreset = async () => {
+ if (!calendarId || !formData.title.trim() || isLoading) return;
+
+ setIsLoading(true);
+ try {
+ const password = getCachedPassword(calendarId);
+
+ if (editingPreset) {
+ // Update existing preset
+ const response = await fetch(`/api/presets/${editingPreset.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...formData,
+ password,
+ }),
+ });
+
+ if (response.ok) {
+ setEditingPreset(null);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ onPresetsChange();
+ toast.success(t("common.updated", { item: t("preset.preset") }));
+ } else {
+ const data = await response.json();
+ toast.error(
+ data.error || t("common.updateError", { item: t("preset.preset") })
+ );
+ }
+ } else {
+ // Create new preset
+ 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 save preset:", error);
+ toast.error(
+ editingPreset
+ ? t("common.updateError", { item: t("preset.preset") })
+ : 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 editFormData = {
+ 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(editFormData);
+ setShowAddForm(false);
+ // Store initial data for change detection
+ initialFormDataRef.current = editFormData;
+ };
+
+ 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;
+ };
+
+ const hasChanges = () => {
+ if (editingPreset && initialFormDataRef.current) {
+ // Edit mode: check if data changed from initial
+ return (
+ JSON.stringify(formData) !== JSON.stringify(initialFormDataRef.current)
+ );
+ } else if (showAddForm) {
+ // Add mode: check if any data was entered
+ return (
+ formData.title.trim() !== "" ||
+ formData.startTime !== "09:00" ||
+ formData.endTime !== "17:00" ||
+ formData.color !== PRESET_COLORS[0].value ||
+ formData.notes.trim() !== "" ||
+ formData.isSecondary ||
+ formData.isAllDay ||
+ formData.hideFromStats
+ );
+ }
+ return false;
+ };
+
+ const resetForm = () => {
+ if (editingPreset) {
+ cancelEdit();
+ } else if (showAddForm) {
+ setShowAddForm(false);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ }
+ };
+
+ const {
+ isDirty,
+ handleClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+ } = useDirtyState({
+ open,
+ onClose: onOpenChange,
+ hasChanges: () => (editingPreset || showAddForm) && hasChanges(),
+ onConfirm: resetForm,
+ });
+
+ 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,
+ });
+ };
+
+ return (
+ <>
+ <Sheet open={open} onOpenChange={handleClose}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {t("preset.manage")}
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
+ {t("preset.manageDescription")}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-6 py-6 space-y-3">
+ {/* Primary Presets List */}
+ {orderedPrimaryPresets.length > 0 &&
+ !showAddForm &&
+ !editingPreset && (
+ <div className="space-y-2">
+ <h3 className="text-sm font-medium text-muted-foreground px-1">
+ {t("preset.primaryPresets")}
+ </h3>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handlePrimaryDragEnd}
+ >
+ <SortableContext
+ items={orderedPrimaryPresets.map((p) => p.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="space-y-3">
+ {orderedPrimaryPresets.map((preset) => (
+ <SortablePresetItem
+ key={preset.id}
+ preset={preset}
+ isDeleting={isDeleting === preset.id}
+ onEdit={startEdit}
+ onDelete={handleDelete}
+ t={t}
+ showDragHandle={orderedPrimaryPresets.length > 1}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ </div>
+ )}
+
+ {/* Secondary Presets List */}
+ {orderedSecondaryPresets.length > 0 &&
+ !showAddForm &&
+ !editingPreset && (
+ <div className="space-y-2">
+ <h3 className="text-sm font-medium text-muted-foreground px-1">
+ {t("preset.secondaryPresets")}
+ </h3>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleSecondaryDragEnd}
+ >
+ <SortableContext
+ items={orderedSecondaryPresets.map((p) => p.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="space-y-3">
+ {orderedSecondaryPresets.map((preset) => (
+ <SortablePresetItem
+ key={preset.id}
+ preset={preset}
+ isDeleting={isDeleting === preset.id}
+ onEdit={startEdit}
+ onDelete={handleDelete}
+ t={t}
+ showDragHandle={orderedSecondaryPresets.length > 1}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ </div>
+ )}
+
+ {/* Show edited preset */}
+ {editingPreset && (
+ <div className="space-y-3">
+ <SortablePresetItem
+ preset={editingPreset}
+ isDeleting={isDeleting === editingPreset.id}
+ onEdit={startEdit}
+ onDelete={handleDelete}
+ t={t}
+ showDragHandle={false}
+ />
+ </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: boolean) =>
+ setFormData({ ...formData, isAllDay: !!checked })
+ }
+ disabled={isLoading}
+ />
+ <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"
+ 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"
+ >
+ <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: boolean) =>
+ setFormData({ ...formData, isSecondary: !!checked })
+ }
+ disabled={isLoading}
+ />
+ <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: boolean) =>
+ 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>
+ </div>
+ )}
+ </div>
+
+ {/* Footer: Always visible Add or Save button */}
+ {!showAddForm && !editingPreset ? (
+ <div className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <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>
+ ) : (
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ <div className="flex gap-2.5 w-full">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ if (editingPreset) {
+ cancelEdit();
+ } else {
+ setShowAddForm(false);
+ setFormData({
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: PRESET_COLORS[0].value,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+ });
+ }
+ }}
+ disabled={isLoading}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleSavePreset}
+ disabled={
+ isLoading ||
+ !formData.title.trim() ||
+ (!!editingPreset && !isDirty)
+ }
+ 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"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ {t("common.saving")}
+ </>
+ ) : (
+ t("common.save")
+ )}
+ </Button>
+ </div>
+ </SheetFooter>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <ConfirmationDialog
+ open={showConfirmDialog}
+ onOpenChange={setShowConfirmDialog}
+ onConfirm={handleConfirmClose}
+ />
+ </>
+ );
+}
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
index 9777ac0..dbeef6d 100644
--- a/components/preset-selector.tsx
+++ b/components/preset-selector.tsx
@@ -4,7 +4,7 @@ import { ShiftPreset } from "@/lib/db/schema";
import { CalendarWithCount } from "@/lib/types";
import { useState } from "react";
import { PresetList } from "@/components/preset-list";
-import { PresetManageDialog } from "@/components/preset-manage-dialog";
+import { PresetManageSheet } from "@/components/preset-manage-sheet";
import { usePasswordProtection } from "@/hooks/usePasswordProtection";
interface PresetSelectorProps {
@@ -74,7 +74,7 @@ export function PresetSelector({
onHidePresetHeaderChange={onHidePresetHeaderChange}
/>
- <PresetManageDialog
+ <PresetManageSheet
open={showManageDialog}
onOpenChange={setShowManageDialog}
calendarId={calendarId}
diff --git a/components/shift-dialog.tsx b/components/shift-dialog.tsx
deleted file mode 100644
index dc0a427..0000000
--- a/components/shift-dialog.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-"use client";
-
-import { useEffect, useRef } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-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;
- onOpenChange: (open: boolean) => void;
- onSubmit: (shift: ShiftFormData) => void;
- selectedDate?: Date;
- shift?: ShiftWithCalendar;
- onPresetsChange?: () => void;
- calendarId?: string;
-}
-
-export interface ShiftFormData {
- date: string;
- startTime: string;
- endTime: string;
- title: string;
- color?: string;
- notes?: string;
- presetId?: string;
- isAllDay?: boolean;
-}
-
-export function ShiftDialog({
- open,
- onOpenChange,
- onSubmit,
- selectedDate,
- shift,
- onPresetsChange,
- calendarId,
-}: ShiftDialogProps) {
- const t = useTranslations();
-
- const {
- formData,
- setFormData,
- presets,
- saveAsPreset,
- setSaveAsPreset,
- presetName,
- setPresetName,
- applyPreset,
- saveAsPresetHandler,
- resetForm,
- } = useShiftForm({ open, shift, selectedDate, calendarId });
-
- 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;
-
- // If all-day, set default times for backend
- const submitData = {
- ...formData,
- startTime: formData.isAllDay ? "00:00" : formData.startTime,
- endTime: formData.isAllDay ? "23:59" : formData.endTime,
- };
-
- onSubmit(submitData);
-
- // Save as preset if enabled and it's a new shift
- if (saveAsPreset && presetName.trim()) {
- const success = await saveAsPresetHandler(submitData);
- if (success && onPresetsChange) {
- onPresetsChange();
- }
- }
-
- resetForm();
- onOpenChange(false);
- };
-
- const handlePresetSelect = async (
- preset: Parameters<typeof applyPreset>[0]
- ) => {
- applyPreset(preset);
- };
-
- return (
- <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">
- {shift ? t("shift.edit") : t("shift.create")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {shift
- ? t("shift.editDescription", {
- default: "Update the shift details",
- })
- : t("shift.createDescription", {
- default: "Add a new shift to your calendar",
- })}
- </DialogDescription>
- </DialogHeader>
- <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}
- />
- )}
-
- <ShiftFormFields
- formData={formData}
- onFormDataChange={setFormData}
- saveAsPreset={saveAsPreset}
- onSaveAsPresetChange={setSaveAsPreset}
- presetName={presetName}
- onPresetNameChange={setPresetName}
- isEditing={!!shift}
- />
- </div>
-
- <div className="border-t border-border/50 bg-muted/20 p-4 flex gap-2.5 flex-shrink-0">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="flex-1 h-11 border-border/50 hover:bg-muted/50"
- >
- {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>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index 71a6681..473cea2 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -5,7 +5,7 @@ import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { ColorPicker } from "@/components/ui/color-picker";
-import { ShiftFormData } from "@/components/shift-dialog";
+import { ShiftFormData } from "@/components/shift-sheet";
import { PRESET_COLORS } from "@/lib/constants";
interface ShiftFormFieldsProps {
diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsx
new file mode 100644
index 0000000..7d48ec9
--- /dev/null
+++ b/components/shift-sheet.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { useTranslations } from "next-intl";
+import { BaseSheet } from "@/components/ui/base-sheet";
+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 ShiftSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (shift: ShiftFormData) => void | Promise<void>;
+ selectedDate?: Date;
+ shift?: ShiftWithCalendar;
+ onPresetsChange?: () => void;
+ calendarId?: string;
+}
+
+export interface ShiftFormData {
+ date: string;
+ startTime: string;
+ endTime: string;
+ title: string;
+ color?: string;
+ notes?: string;
+ presetId?: string;
+ isAllDay?: boolean;
+}
+
+export function ShiftSheet({
+ open,
+ onOpenChange,
+ onSubmit,
+ selectedDate,
+ shift,
+ onPresetsChange,
+ calendarId,
+}: ShiftSheetProps) {
+ const t = useTranslations();
+ const [isSaving, setIsSaving] = useState(false);
+ const initialFormDataRef = useRef<string | null>(null);
+
+ const {
+ formData,
+ setFormData,
+ presets,
+ saveAsPreset,
+ setSaveAsPreset,
+ presetName,
+ setPresetName,
+ applyPreset,
+ saveAsPresetHandler,
+ resetForm,
+ } = useShiftForm({ open, shift, selectedDate, calendarId });
+
+ // Store initial form data when sheet opens
+ useEffect(() => {
+ if (open && shift) {
+ // Store initial data matching formData structure
+ const initialData: ShiftFormData = {
+ 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,
+ presetId: shift.presetId || undefined,
+ };
+ initialFormDataRef.current = JSON.stringify(initialData);
+ } else if (!open) {
+ initialFormDataRef.current = null;
+ }
+ }, [open, shift]);
+
+ const hasChanges = () => {
+ // For existing shifts, compare with initial data
+ if (shift && initialFormDataRef.current) {
+ // Create comparable version of current formData
+ const currentData: ShiftFormData = {
+ date: formData.date,
+ startTime: formData.startTime,
+ endTime: formData.endTime,
+ title: formData.title,
+ notes: formData.notes || "",
+ color: formData.color,
+ isAllDay: formData.isAllDay || false,
+ presetId: formData.presetId || undefined,
+ };
+
+ return JSON.stringify(currentData) !== initialFormDataRef.current;
+ }
+
+ // For new shifts, check if user has entered any data
+ return (
+ formData.title.trim() !== "" ||
+ formData.notes?.trim() !== "" ||
+ saveAsPreset ||
+ presetName.trim() !== ""
+ );
+ };
+
+ const handleSave = async () => {
+ if (!formData.title.trim() || isSaving) return;
+
+ setIsSaving(true);
+ try {
+ // If all-day, set default times for backend
+ const submitData = {
+ ...formData,
+ startTime: formData.isAllDay ? "00:00" : formData.startTime,
+ endTime: formData.isAllDay ? "23:59" : formData.endTime,
+ };
+
+ await onSubmit(submitData);
+
+ // Save as preset if enabled and it's a new shift
+ if (!shift && saveAsPreset && presetName.trim()) {
+ const success = await saveAsPresetHandler(submitData);
+ if (success && onPresetsChange) {
+ onPresetsChange();
+ }
+ }
+
+ if (!shift) {
+ resetForm();
+ }
+ onOpenChange(false);
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const handlePresetSelect = async (
+ preset: Parameters<typeof applyPreset>[0]
+ ) => {
+ applyPreset(preset);
+ };
+
+ return (
+ <BaseSheet
+ open={open}
+ onOpenChange={onOpenChange}
+ title={shift ? t("shift.edit") : t("shift.create")}
+ description={
+ shift ? t("shift.editDescription") : t("shift.createDescription")
+ }
+ showSaveButton
+ showCancelButton
+ onSave={handleSave}
+ isSaving={isSaving}
+ saveDisabled={!formData.title.trim() || (shift && !hasChanges())}
+ hasUnsavedChanges={hasChanges()}
+ maxWidth="md"
+ >
+ <div className="space-y-5">
+ {/* Preset Selection */}
+ {!shift && (
+ <PresetSelect presets={presets} onPresetSelect={handlePresetSelect} />
+ )}
+
+ <ShiftFormFields
+ formData={formData}
+ onFormDataChange={setFormData}
+ saveAsPreset={saveAsPreset}
+ onSaveAsPresetChange={setSaveAsPreset}
+ presetName={presetName}
+ onPresetNameChange={setPresetName}
+ isEditing={!!shift}
+ />
+ </div>
+ </BaseSheet>
+ );
+}
diff --git a/components/shifts-overview-dialog.tsx b/components/shifts-overview-dialog.tsx
new file mode 100644
index 0000000..c38ed97
--- /dev/null
+++ b/components/shifts-overview-dialog.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from "@/components/ui/dialog";
+import { ShiftWithCalendar } from "@/lib/types";
+import { useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { getDateLocale } from "@/lib/locales";
+import { useLocale } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { Trash2 } from "lucide-react";
+
+interface ShiftsOverviewDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ date: Date | null;
+ shifts: ShiftWithCalendar[];
+ onDeleteShift?: (shiftId: string) => void;
+}
+
+export function ShiftsOverviewDialog({
+ open,
+ onOpenChange,
+ date,
+ shifts,
+ onDeleteShift,
+}: ShiftsOverviewDialogProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ if (!date) return null;
+
+ const formattedDate = format(date, "EEEE, d. MMMM yyyy", {
+ locale: dateLocale,
+ });
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[500px] 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">
+ {formattedDate}
+ </DialogTitle>
+ <DialogDescription className="text-sm text-muted-foreground">
+ {shifts.length}{" "}
+ {shifts.length === 1 ? t("shift.shift_one") : t("common.shifts")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-3 overflow-y-auto flex-1 p-6">
+ {shifts.length === 0 ? (
+ <p className="text-center text-muted-foreground py-8">
+ {t("shift.noShiftsInMonth")}
+ </p>
+ ) : (
+ shifts.map((shift) => (
+ <div
+ key={shift.id}
+ className="flex items-start justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
+ style={{ borderLeftColor: shift.color, borderLeftWidth: 4 }}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="font-semibold flex items-center gap-2">
+ <div
+ className="w-1 h-4 rounded-full"
+ style={{ backgroundColor: shift.color }}
+ />
+ <span className="truncate">{shift.title}</span>
+ </div>
+ <div className="text-sm text-muted-foreground mt-1">
+ {shift.isAllDay ? (
+ <span className="font-medium">{t("shift.allDay")}</span>
+ ) : (
+ <span>
+ {shift.startTime} - {shift.endTime}
+ </span>
+ )}
+ </div>
+ {shift.notes && (
+ <p className="text-xs text-muted-foreground mt-2 line-clamp-2">
+ {shift.notes}
+ </p>
+ )}
+ </div>
+ {onDeleteShift && !shift.externalSyncId && (
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={() => onDeleteShift(shift.id)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsx
index 87ec44a..e8fd99d 100644
--- a/components/sync-notification-dialog.tsx
+++ b/components/sync-notification-dialog.tsx
@@ -317,7 +317,7 @@ export function SyncNotificationDialog({
{log.shiftsCreated > 0 && (
<div className="flex items-center gap-1.5 text-green-700">
<span className="font-medium">
- {t("syncNotifications.created", {
+ {t("common.createdCount", {
count: log.shiftsCreated,
})}
</span>
@@ -326,7 +326,7 @@ export function SyncNotificationDialog({
{log.shiftsUpdated > 0 && (
<div className="flex items-center gap-1.5 text-blue-700">
<span className="font-medium">
- {t("syncNotifications.updated", {
+ {t("common.updatedCount", {
count: log.shiftsUpdated,
})}
</span>
@@ -335,7 +335,7 @@ export function SyncNotificationDialog({
{log.shiftsDeleted > 0 && (
<div className="flex items-center gap-1.5 text-orange-700">
<span className="font-medium">
- {t("syncNotifications.deleted", {
+ {t("common.deletedCount", {
count: log.shiftsDeleted,
})}
</span>
diff --git a/components/synced-shifts-dialog.tsx b/components/synced-shifts-dialog.tsx
deleted file mode 100644
index bde5002..0000000
--- a/components/synced-shifts-dialog.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { ShiftWithCalendar } from "@/lib/types";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
-import { Clock } from "lucide-react";
-
-interface SyncedShiftsDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- date: Date | null;
- shifts: ShiftWithCalendar[];
-}
-
-export function SyncedShiftsDialog({
- open,
- onOpenChange,
- date,
- shifts,
-}: SyncedShiftsDialogProps) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
-
- const formattedDate = date
- ? format(date, "EEEE, dd. MMMM yyyy", { locale: dateLocale })
- : "";
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>
- {t("externalSync.syncedShiftsTitle", { date: formattedDate })}
- </DialogTitle>
- <DialogDescription className="sr-only">
- {t("externalSync.viewSyncedShifts")}
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-3 max-h-[60vh] overflow-y-auto">
- {shifts.length === 0 ? (
- <p className="text-center text-muted-foreground py-8">
- {t("shift.noShiftsInMonth")}
- </p>
- ) : (
- shifts.map((shift) => (
- <div
- key={shift.id}
- className="p-4 rounded-lg border transition-colors"
- style={{
- backgroundColor: shift.color
- ? `${shift.color}10`
- : "#3b82f610",
- borderLeft: `3px solid ${shift.color || "#3b82f6"}`,
- }}
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex-1 min-w-0">
- <h4
- className="font-semibold text-base mb-1 truncate"
- style={{ color: shift.color || "#3b82f6" }}
- >
- {shift.title}
- </h4>
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Clock className="h-3.5 w-3.5" />
- {shift.isAllDay ? (
- <span>{t("shift.allDay")}</span>
- ) : (
- <span>
- {shift.startTime} - {shift.endTime}
- </span>
- )}
- </div>
- {shift.notes && (
- <p className="text-sm text-muted-foreground mt-2 line-clamp-2">
- {shift.notes}
- </p>
- )}
- </div>
- </div>
- </div>
- ))
- )}
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/components/ui/alert-dialog.tsx b/components/ui/alert-dialog.tsx
new file mode 100644
index 0000000..0863e40
--- /dev/null
+++ b/components/ui/alert-dialog.tsx
@@ -0,0 +1,157 @@
+"use client"
+
+import * as React from "react"
+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
+
+import { cn } from "@/lib/utils"
+import { buttonVariants } from "@/components/ui/button"
+
+function AlertDialog({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
+ return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
+}
+
+function AlertDialogTrigger({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
+ return (
+ <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
+ )
+}
+
+function AlertDialogPortal({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
+ return (
+ <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
+ )
+}
+
+function AlertDialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
+ return (
+ <AlertDialogPrimitive.Overlay
+ data-slot="alert-dialog-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
+ return (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ data-slot="alert-dialog-content"
+ className={cn(
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
+ className
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+ )
+}
+
+function AlertDialogHeader({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-header"
+ className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogFooter({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
+ return (
+ <AlertDialogPrimitive.Title
+ data-slot="alert-dialog-title"
+ className={cn("text-lg font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
+ return (
+ <AlertDialogPrimitive.Description
+ data-slot="alert-dialog-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogAction({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
+ return (
+ <AlertDialogPrimitive.Action
+ className={cn(buttonVariants(), className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogCancel({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
+ return (
+ <AlertDialogPrimitive.Cancel
+ className={cn(buttonVariants({ variant: "outline" }), className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ AlertDialog,
+ AlertDialogPortal,
+ AlertDialogOverlay,
+ AlertDialogTrigger,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogFooter,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogAction,
+ AlertDialogCancel,
+}
diff --git a/components/ui/base-sheet.tsx b/components/ui/base-sheet.tsx
new file mode 100644
index 0000000..205c3de
--- /dev/null
+++ b/components/ui/base-sheet.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import { ReactNode } from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { Button } from "@/components/ui/button";
+import { useTranslations } from "next-intl";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { useDirtyState } from "@/hooks/useDirtyState";
+
+interface BaseSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description?: string;
+ children: ReactNode;
+ footer?: ReactNode;
+ showSaveButton?: boolean;
+ showCancelButton?: boolean;
+ onSave?: () => void | Promise<void>;
+ isSaving?: boolean;
+ saveDisabled?: boolean;
+ hasUnsavedChanges?: boolean;
+ maxWidth?: "sm" | "md" | "lg" | "xl";
+}
+
+const maxWidthClasses = {
+ sm: "sm:max-w-[480px]",
+ md: "sm:max-w-[600px]",
+ lg: "sm:max-w-[700px]",
+ xl: "sm:max-w-[800px]",
+};
+
+export function BaseSheet({
+ open,
+ onOpenChange,
+ title,
+ description,
+ children,
+ footer,
+ showSaveButton = false,
+ showCancelButton = true,
+ onSave,
+ isSaving = false,
+ saveDisabled = false,
+ hasUnsavedChanges = false,
+ maxWidth = "md",
+}: BaseSheetProps) {
+ const t = useTranslations();
+
+ const {
+ handleClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+ } = useDirtyState({
+ open,
+ onClose: onOpenChange,
+ hasChanges: () => hasUnsavedChanges,
+ });
+
+ const handleSave = async () => {
+ if (onSave) {
+ await onSave();
+ }
+ };
+
+ const handleCancelClick = () => {
+ handleClose(false);
+ };
+
+ return (
+ <>
+ <Sheet open={open} onOpenChange={handleClose}>
+ <SheetContent
+ side="right"
+ className={`w-full ${maxWidthClasses[maxWidth]} p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden`}
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
+ {title}
+ </SheetTitle>
+ {description && (
+ <SheetDescription className="text-sm text-muted-foreground">
+ {description}
+ </SheetDescription>
+ )}
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-6 py-6">{children}</div>
+
+ {(footer || showSaveButton || showCancelButton) && (
+ <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
+ {footer ? (
+ footer
+ ) : (
+ <div className="flex gap-2.5 w-full">
+ {showCancelButton && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={handleCancelClick}
+ disabled={isSaving}
+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"
+ >
+ {t("common.cancel")}
+ </Button>
+ )}
+ {showSaveButton && (
+ <Button
+ type="button"
+ onClick={handleSave}
+ disabled={saveDisabled || isSaving}
+ 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"
+ >
+ {isSaving ? t("common.saving") : t("common.save")}
+ </Button>
+ )}
+ </div>
+ )}
+ </SheetFooter>
+ )}
+ </SheetContent>
+ </Sheet>
+
+ <ConfirmationDialog
+ open={showConfirmDialog}
+ onOpenChange={setShowConfirmDialog}
+ onConfirm={handleConfirmClose}
+ />
+ </>
+ );
+}
diff --git a/components/ui/confirmation-dialog.tsx b/components/ui/confirmation-dialog.tsx
new file mode 100644
index 0000000..1f196ce
--- /dev/null
+++ b/components/ui/confirmation-dialog.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { useTranslations } from "next-intl";
+
+interface ConfirmationDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: () => void;
+ title?: string;
+ description?: string;
+}
+
+export function ConfirmationDialog({
+ open,
+ onOpenChange,
+ onConfirm,
+ title,
+ description,
+}: ConfirmationDialogProps) {
+ const t = useTranslations();
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {title || t("common.unsavedChanges")}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {description || t("common.unsavedChangesDescription")}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction onClick={onConfirm}>
+ {t("common.closeWithoutSaving")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/components/ui/sheet.tsx b/components/ui/sheet.tsx
new file mode 100644
index 0000000..84649ad
--- /dev/null
+++ b/components/ui/sheet.tsx
@@ -0,0 +1,139 @@
+"use client"
+
+import * as React from "react"
+import * as SheetPrimitive from "@radix-ui/react-dialog"
+import { XIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />
+}
+
+function SheetTrigger({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
+}
+
+function SheetClose({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Close>) {
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
+}
+
+function SheetPortal({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
+}
+
+function SheetOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
+ return (
+ <SheetPrimitive.Overlay
+ data-slot="sheet-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Content> & {
+ side?: "top" | "right" | "bottom" | "left"
+}) {
+ return (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ data-slot="sheet-content"
+ className={cn(
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
+ side === "right" &&
+ "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
+ side === "left" &&
+ "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
+ side === "top" &&
+ "data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
+ side === "bottom" &&
+ "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
+ <XIcon className="size-4" />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ </SheetPrimitive.Content>
+ </SheetPortal>
+ )
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-header"
+ className={cn("flex flex-col gap-1.5 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Title>) {
+ return (
+ <SheetPrimitive.Title
+ data-slot="sheet-title"
+ className={cn("text-foreground font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Description>) {
+ return (
+ <SheetPrimitive.Description
+ data-slot="sheet-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Sheet,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+}
diff --git a/components/view-settings-dialog.tsx b/components/view-settings-sheet.tsx
similarity index 87%
rename from components/view-settings-dialog.tsx
rename to components/view-settings-sheet.tsx
index 732145b..368cf2f 100644
--- a/components/view-settings-dialog.tsx
+++ b/components/view-settings-sheet.tsx
@@ -2,12 +2,12 @@
import { useTranslations } from "next-intl";
import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+} from "@/components/ui/sheet";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
@@ -20,7 +20,7 @@ import {
} from "@/components/ui/select";
import { Maximize2, FileText, Infinity, ArrowUpDown } from "lucide-react";
-interface ViewSettingsDialogProps {
+interface ViewSettingsSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
shiftsPerDay: number | null;
@@ -39,7 +39,7 @@ interface ViewSettingsDialogProps {
onCombinedSortModeChange: (combined: boolean) => void;
}
-export function ViewSettingsDialog({
+export function ViewSettingsSheet({
open,
onOpenChange,
shiftsPerDay,
@@ -56,22 +56,25 @@ export function ViewSettingsDialog({
onShiftSortTypeChange,
onShiftSortOrderChange,
onCombinedSortModeChange,
-}: ViewSettingsDialogProps) {
+}: ViewSettingsSheetProps) {
const t = useTranslations();
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px] 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">
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ className="w-full sm:max-w-[600px] p-0 flex flex-col gap-0 border-l border-border/50 overflow-hidden"
+ >
+ <SheetHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-6 pt-6 pb-5 space-y-1.5">
+ <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
{t("view.settingsTitle")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
+ </SheetTitle>
+ <SheetDescription className="text-sm text-muted-foreground">
{t("view.settingsDescription")}
- </DialogDescription>
- </DialogHeader>
+ </SheetDescription>
+ </SheetHeader>
- <div className="space-y-6 overflow-y-auto flex-1 px-6 py-6">
+ <div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
{/* Regular Shifts per Day */}
<div className="space-y-4">
<div className="flex items-center justify-between">
@@ -99,7 +102,7 @@ export function ViewSettingsDialog({
<div className="space-y-3">
<Slider
value={[shiftsPerDay === null ? 11 : shiftsPerDay]}
- onValueChange={(value) =>
+ onValueChange={(value: number[]) =>
onShiftsPerDayChange(value[0] === 11 ? null : value[0])
}
min={1}
@@ -146,7 +149,7 @@ export function ViewSettingsDialog({
value={[
externalShiftsPerDay === null ? 11 : externalShiftsPerDay,
]}
- onValueChange={(value) =>
+ onValueChange={(value: number[]) =>
onExternalShiftsPerDayChange(
value[0] === 11 ? null : value[0]
)
@@ -226,7 +229,9 @@ export function ViewSettingsDialog({
<Checkbox
id="combined-sort"
checked={combinedSortMode}
- onCheckedChange={onCombinedSortModeChange}
+ onCheckedChange={(checked: boolean) =>
+ onCombinedSortModeChange(checked)
+ }
className="mt-0.5"
/>
<div className="flex-1 space-y-1">
@@ -257,7 +262,9 @@ export function ViewSettingsDialog({
<Checkbox
id="show-notes"
checked={showShiftNotes}
- onCheckedChange={onShowShiftNotesChange}
+ onCheckedChange={(checked: boolean) =>
+ onShowShiftNotesChange(checked)
+ }
className="mt-0.5"
/>
<div className="flex-1 space-y-1">
@@ -278,7 +285,9 @@ export function ViewSettingsDialog({
<Checkbox
id="show-full-titles"
checked={showFullTitles}
- onCheckedChange={onShowFullTitlesChange}
+ onCheckedChange={(checked: boolean) =>
+ onShowFullTitlesChange(checked)
+ }
className="mt-0.5"
/>
<div className="flex-1 space-y-1">
@@ -296,7 +305,7 @@ export function ViewSettingsDialog({
</div>
</div>
</div>
- </DialogContent>
- </Dialog>
+ </SheetContent>
+ </Sheet>
);
}
diff --git a/hooks/useDirtyState.ts b/hooks/useDirtyState.ts
new file mode 100644
index 0000000..814bd5e
--- /dev/null
+++ b/hooks/useDirtyState.ts
@@ -0,0 +1,75 @@
+import { useState } from "react";
+
+interface UseDirtyStateOptions {
+ open: boolean;
+ onClose: (open: boolean) => void;
+ hasChanges: () => boolean;
+ onConfirm?: () => void;
+}
+
+/**
+ * Hook for managing dirty state (unsaved changes) in sheets with ConfirmationDialog.
+ *
+ * @example
+ * ```tsx
+ * const { handleClose, showConfirmDialog, setShowConfirmDialog, handleConfirmClose } =
+ * useDirtyState({
+ * open,
+ * onClose,
+ * hasChanges: () => name !== initialName,
+ * onConfirm: () => resetForm()
+ * });
+ *
+ * return (
+ * <>
+ * <Sheet open={open} onOpenChange={handleClose}>
+ * {/* Sheet content *\/}
+ * </Sheet>
+ * <ConfirmationDialog
+ * open={showConfirmDialog}
+ * onOpenChange={setShowConfirmDialog}
+ * onConfirm={handleConfirmClose}
+ * />
+ * </>
+ * );
+ * ```
+ */
+export function useDirtyState({
+ open,
+ onClose,
+ hasChanges,
+ onConfirm,
+}: UseDirtyStateOptions) {
+ const [showConfirmDialog, setShowConfirmDialog] = useState(false);
+
+ const handleClose = (open: boolean) => {
+ // If opening, just open it
+ if (open) {
+ onClose(open);
+ return;
+ }
+
+ // If closing with unsaved changes, show confirmation
+ if (hasChanges()) {
+ setShowConfirmDialog(true);
+ return;
+ }
+
+ // Otherwise close normally
+ onClose(false);
+ };
+
+ const handleConfirmClose = () => {
+ setShowConfirmDialog(false);
+ onConfirm?.();
+ onClose(false);
+ };
+
+ return {
+ isDirty: hasChanges(),
+ handleClose,
+ showConfirmDialog,
+ setShowConfirmDialog,
+ handleConfirmClose,
+ };
+}
diff --git a/hooks/usePasswordManagement.ts b/hooks/usePasswordManagement.ts
index 2cbd7d2..eaa3f4a 100644
--- a/hooks/usePasswordManagement.ts
+++ b/hooks/usePasswordManagement.ts
@@ -4,7 +4,7 @@ import {
verifyAndCachePassword,
} from "@/lib/password-cache";
import { CalendarWithCount } from "@/lib/types";
-import { ShiftFormData } from "@/components/shift-dialog";
+import { ShiftFormData } from "@/components/shift-sheet";
export interface PendingAction {
type: "delete" | "edit" | "syncNotifications";
diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.ts
index ed6a350..dc30026 100644
--- a/hooks/useShiftActions.ts
+++ b/hooks/useShiftActions.ts
@@ -2,7 +2,7 @@ import { useState, useCallback, useRef, useEffect } from "react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { isSameDay } from "date-fns";
-import { ShiftFormData } from "@/components/shift-dialog";
+import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftPreset } from "@/lib/db/schema";
import { formatDateToLocal } from "@/lib/date-utils";
diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.ts
index 0ba4995..e1ed1fe 100644
--- a/hooks/useShiftForm.ts
+++ b/hooks/useShiftForm.ts
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from "react";
-import { ShiftFormData } from "@/components/shift-dialog";
+import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftPreset } from "@/lib/db/schema";
import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 1cdd89c..74d168c 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import { ShiftWithCalendar } from "@/lib/types";
-import { ShiftFormData } from "@/components/shift-dialog";
+import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { getCachedPassword } from "@/lib/password-cache";
diff --git a/lib/types.ts b/lib/types.ts
index ab01f47..a08b6cd 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -15,6 +15,7 @@ export interface CalendarWithCount {
export interface ShiftWithCalendar {
id: string;
calendarId: string;
+ presetId?: string | null;
calendar?: {
id: string;
name: string;
diff --git a/messages/de.json b/messages/de.json
index 0aae5f6..abd544f 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -6,16 +6,17 @@
},
"common": {
"cancel": "Abbrechen",
- "close": "Schließen",
"save": "Speichern",
+ "saving": "Speichere...",
"delete": "Löschen",
- "edit": "Bearbeiten",
"create": "Erstellen",
"loading": "Lädt...",
"required": "erforderlich",
"unlock": "Entsperren",
- "manage": "Verwalten",
"add": "Hinzufügen",
+ "unsavedChanges": "Ungespeicherte Änderungen",
+ "unsavedChangesDescription": "Du hast ungespeicherte Änderungen. Möchtest du wirklich schließen, ohne zu speichern?",
+ "closeWithoutSaving": "Schließen ohne Speichern",
"created": "{item} erfolgreich erstellt",
"updated": "{item} erfolgreich aktualisiert",
"deleted": "{item} erfolgreich gelöscht",
@@ -25,6 +26,11 @@
"deleteConfirm": "{item} \"{name}\" wirklich löschen?",
"deleteConfirmWithWarning": "{item} \"{name}\" wirklich löschen? {warning}",
"shifts": "Schichten",
+ "success": "Erfolgreich",
+ "error": "Fehler",
+ "createdCount": "{count} erstellt",
+ "updatedCount": "{count} aktualisiert",
+ "deletedCount": "{count} gelöscht",
"weekday": {
"monday": "Mo",
"tuesday": "Di",
@@ -69,10 +75,11 @@
"select": "Dein BetterShift Kalender",
"deleteCalendar": "Kalender löschen",
"deleteWarning": "Alle Schichten, Presets und Notizen werden ebenfalls gelöscht.",
- "managePassword": "Passwort verwalten",
"settings": "Kalendereinstellungen für \"{name}\"",
"settingsDescription": "Passe Name, Farbe und Passwortschutz an",
- "currentlyProtected": "Dieser Kalender ist derzeit passwortgeschützt.",
+ "passwordProtected": "Kalender ist passwortgeschützt",
+ "passwordRequiredToEdit": "Bitte gib dein aktuelles Passwort ein, um Einstellungen zu ändern.",
+ "currentPasswordRequired": "Erforderlich, um Änderungen zu speichern",
"lockCalendar": "Kalender komplett sperren",
"lockCalendarHint": "Sperrt Kalender komplett - Passwort zum sehen und verwalten erforderlich",
"lockRequiresPassword": "Kalendersperre erfordert ein Passwort"
@@ -84,6 +91,7 @@
},
"password": {
"optional": "Passwortschutz (optional)",
+ "management": "Passwortverwaltung",
"currentPassword": "Aktuelles Passwort",
"currentPasswordPlaceholder": "Aktuelles Passwort eingeben",
"newPassword": "Neues Passwort",
@@ -91,7 +99,6 @@
"confirmPassword": "Passwort bestätigen",
"confirmPasswordPlaceholder": "Passwort bestätigen",
"removePassword": "Passwort entfernen",
- "manage": "Passwort für \"{name}\" verwalten",
"enter": "Passwort für \"{name}\" eingeben",
"enterCalendarPassword": "Kalenderpasswort eingeben",
"currentlyLocked": "Dieser Kalender ist derzeit gesperrt.",
@@ -103,7 +110,7 @@
"create": "Neue Notiz",
"edit": "Notiz bearbeiten",
"note": "Notiz",
- "notePlaceholder": "z.B. Frühdienst weil nachmittags Termin...",
+ "placeholder": "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."
},
@@ -123,9 +130,7 @@
"noShiftsInMonthDescription": "Füge Schichten hinzu, indem du auf Tage im Kalender oben klickst.",
"shift_one": "Schicht",
"selectPreset": "Vorlage auswählen",
- "none": "Keine",
- "addShift": "Schicht hinzufügen",
- "saveChanges": "Änderungen speichern"
+ "none": "Keine"
},
"preset": {
"preset": "Vorlage",
@@ -134,8 +139,6 @@
"edit": "Vorlage bearbeiten",
"manage": "Vorlagen verwalten",
"manageDescription": "Bearbeite oder lösche deine Schichtvorlagen",
- "createDescription": "Erstelle eine neue Vorlage für eine schnelle Schichterstellung",
- "editDescription": "Aktualisiere Vorlagendetails",
"saveAsPreset": "Als Vorlage speichern",
"presetName": "Vorlagenname",
"presetNamePlaceholder": "z.B. Frühschicht, Spätschicht...",
@@ -152,7 +155,6 @@
"hidePresets": "Vorlagen ausblenden",
"hiddenFromStats": "Aus Statistik ausgeblendet"
},
-
"view": {
"settingsTitle": "Ansichtseinstellungen",
"settingsDescription": "Passe an, wie Schichten in allen Kalendern angezeigt werden",
@@ -177,7 +179,6 @@
"showFullTitles": "Vollständige Schichttitel anzeigen",
"showFullTitlesHint": "Schichttitel vollständig ohne Kürzung anzeigen"
},
-
"stats": {
"title": "Schichtenstatistik",
"week": "Woche",
@@ -222,6 +223,7 @@
"externalSync": {
"manageTitle": "Externe Kalender verwalten",
"manageDescription": "Füge mehrere externe Kalender für diesen Kalender hinzu und verwalte sie",
+ "noSyncs": "Noch keine externen Kalender hinzugefügt",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Eigener Kalender",
@@ -237,8 +239,6 @@
"displayModeNormal": "Normal (alle Schichten anzeigen)",
"displayModeMinimal": "Minimalistisch (nur Anzahl anzeigen)",
"displayModeHint": "Wähle, wie synchronisierte Schichten im Kalender angezeigt werden sollen",
- "viewSyncedShifts": "Importierte Schichten anzeigen",
- "syncedShiftsTitle": "Importierte Schichten - {date}",
"addNewSync": "Neuen externen Kalender hinzufügen",
"editSync": "Externen Kalender bearbeiten",
"colorHint": "Wähle die Farbe für alle importierten Schichten",
@@ -249,10 +249,6 @@
"lastSynced": "Zuletzt synchronisiert",
"syncError": "Kalender konnte nicht synchronisiert werden",
"deleteConfirm": "Diesen externen Kalender löschen? Alle importierten Schichten werden entfernt.",
- "syncSuccess": "Synchronisierung erfolgreich",
- "statsCreated": "erstellt",
- "statsUpdated": "aktualisiert",
- "statsDeleted": "gelöscht",
"hintsTitle": "Kalender-URL finden",
"hintsDescription": "Wähle deinen Kalendertyp, um Anweisungen zu erhalten:",
"customCalendar": "Eigener Kalender",
@@ -272,9 +268,6 @@
"statusError": "Fehler",
"syncTypeAuto": "Automatisch",
"syncTypeManual": "Manuell",
- "created": "{count} erstellt",
- "updated": "{count} aktualisiert",
- "deleted": "{count} gelöscht",
"noChanges": "Keine Änderungen",
"errorMessage": "Fehlermeldung",
"filterAll": "Alle anzeigen",
@@ -308,9 +301,7 @@
"rangeYear": "Einzelnes Jahr",
"monthLabel": "Monat auswählen",
"yearLabel": "Jahr auswählen",
- "download": "Herunterladen",
- "success": "Export erfolgreich",
- "error": "Export fehlgeschlagen"
+ "download": "Herunterladen"
},
"update": {
"available": "Update verfügbar",
diff --git a/messages/en.json b/messages/en.json
index ad99a54..c866efa 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -6,16 +6,17 @@
},
"common": {
"cancel": "Cancel",
- "close": "Close",
"save": "Save",
+ "saving": "Saving...",
"delete": "Delete",
- "edit": "Edit",
"create": "Create",
"loading": "Loading...",
"required": "required",
"unlock": "Unlock",
- "manage": "Manage",
"add": "Add",
+ "unsavedChanges": "Unsaved Changes",
+ "unsavedChangesDescription": "You have unsaved changes. Do you really want to close without saving?",
+ "closeWithoutSaving": "Close Without Saving",
"created": "{item} created successfully",
"updated": "{item} updated successfully",
"deleted": "{item} deleted successfully",
@@ -25,6 +26,11 @@
"deleteConfirm": "Really delete {item} \"{name}\"?",
"deleteConfirmWithWarning": "Really delete {item} \"{name}\"? {warning}",
"shifts": "Shifts",
+ "success": "Success",
+ "error": "Error",
+ "createdCount": "{count} created",
+ "updatedCount": "{count} updated",
+ "deletedCount": "{count} deleted",
"weekday": {
"monday": "Mon",
"tuesday": "Tue",
@@ -69,10 +75,11 @@
"select": "Your BetterShift Calendar",
"deleteCalendar": "Delete Calendar",
"deleteWarning": "All shifts, presets and notes will also be deleted.",
- "managePassword": "Manage Password",
"settings": "Calendar Settings for \"{name}\"",
"settingsDescription": "Customize name, color and password protection",
- "currentlyProtected": "This calendar is currently password protected.",
+ "passwordProtected": "Calendar is password protected",
+ "passwordRequiredToEdit": "Please enter your current password to change settings.",
+ "currentPasswordRequired": "Required to save changes",
"lockCalendar": "Lock calendar completely",
"lockCalendarHint": "Locks calendar completely - password required to view and manage",
"lockRequiresPassword": "Locking the calendar requires a password"
@@ -84,6 +91,7 @@
},
"password": {
"optional": "Password Protection (optional)",
+ "management": "Password Management",
"currentPassword": "Current Password",
"currentPasswordPlaceholder": "Enter current password",
"newPassword": "New Password",
@@ -91,7 +99,6 @@
"confirmPassword": "Confirm Password",
"confirmPasswordPlaceholder": "Confirm password",
"removePassword": "Remove Password",
- "manage": "Manage Password for \"{name}\"",
"enter": "Enter Password for \"{name}\"",
"enterCalendarPassword": "Enter calendar password",
"currentlyLocked": "This calendar is currently locked.",
@@ -103,7 +110,7 @@
"create": "New Note",
"edit": "Edit Note",
"note": "Note",
- "notePlaceholder": "e.g., Early shift because appointment in the afternoon...",
+ "placeholder": "e.g., Early shift because appointment in the afternoon...",
"hintMobile": "Long press on a day to open notes. The note icon shows existing notes.",
"hintDesktop": "Right-click on a day to open notes. The note icon shows existing notes."
},
@@ -123,9 +130,7 @@
"noShiftsInMonthDescription": "Add shifts by clicking on days in the calendar above.",
"shift_one": "shift",
"selectPreset": "Select Preset",
- "none": "None",
- "addShift": "Add Shift",
- "saveChanges": "Save Changes"
+ "none": "None"
},
"preset": {
"preset": "Preset",
@@ -134,8 +139,6 @@
"edit": "Edit Preset",
"manage": "Manage Presets",
"manageDescription": "Edit or delete your shift presets",
- "createDescription": "Create a new preset for quick shift creation",
- "editDescription": "Update preset details",
"saveAsPreset": "Save as preset",
"presetName": "Preset name",
"presetNamePlaceholder": "e.g., Morning Shift, Evening Shift...",
@@ -152,7 +155,6 @@
"hidePresets": "Hide presets",
"hiddenFromStats": "Hidden from statistics"
},
-
"view": {
"settingsTitle": "View Settings",
"settingsDescription": "Customize how shifts are displayed in all calendars",
@@ -177,7 +179,6 @@
"showFullTitles": "Show full shift titles",
"showFullTitlesHint": "Display complete shift titles without truncation"
},
-
"stats": {
"title": "Shift Statistics",
"week": "Week",
@@ -222,6 +223,7 @@
"externalSync": {
"manageTitle": "Manage External Calendars",
"manageDescription": "Add and manage multiple external calendars for this calendar",
+ "noSyncs": "No external calendars added yet",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Custom Calendar",
@@ -237,8 +239,6 @@
"displayModeNormal": "Normal (show all shifts)",
"displayModeMinimal": "Minimal (show count only)",
"displayModeHint": "Choose how synced shifts should be displayed in the calendar",
- "viewSyncedShifts": "View Imported Shifts",
- "syncedShiftsTitle": "Imported Shifts - {date}",
"addNewSync": "Add New External Calendar",
"editSync": "Edit External Calendar",
"colorHint": "Choose the color for all imported shifts",
@@ -249,10 +249,6 @@
"lastSynced": "Last synced",
"syncError": "Failed to sync calendar",
"deleteConfirm": "Delete this external calendar? All imported shifts will be removed.",
- "syncSuccess": "Sync successful",
- "statsCreated": "created",
- "statsUpdated": "updated",
- "statsDeleted": "deleted",
"hintsTitle": "Finding Your Calendar URL",
"hintsDescription": "Select your calendar type to see instructions:",
"customCalendar": "Custom Calendar",
@@ -272,9 +268,6 @@
"statusError": "Error",
"syncTypeAuto": "Automatic",
"syncTypeManual": "Manual",
- "created": "{count} created",
- "updated": "{count} updated",
- "deleted": "{count} deleted",
"noChanges": "No changes",
"errorMessage": "Error message",
"filterAll": "Show all",
@@ -308,9 +301,7 @@
"rangeYear": "Single Year",
"monthLabel": "Select Month",
"yearLabel": "Select Year",
- "download": "Download",
- "success": "Export successful",
- "error": "Export failed"
+ "download": "Download"
},
"update": {
"available": "Update Available",
diff --git a/messages/it.json b/messages/it.json
index 7882cfc..b3a5542 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -6,16 +6,17 @@
},
"common": {
"cancel": "Annulla",
- "close": "Chiudi",
"save": "Salva",
+ "saving": "Salvataggio...",
"delete": "Elimina",
- "edit": "Modifica",
"create": "Crea",
"loading": "Caricamento...",
"required": "obbligatorio",
"unlock": "Sblocca",
- "manage": "Gestisci",
"add": "Aggiungi",
+ "unsavedChanges": "Modifiche Non Salvate",
+ "unsavedChangesDescription": "Hai modifiche non salvate. Vuoi davvero chiudere senza salvare?",
+ "closeWithoutSaving": "Chiudi Senza Salvare",
"created": "{item} creato con successo",
"updated": "{item} aggiornato con successo",
"deleted": "{item} eliminato con successo",
@@ -25,6 +26,11 @@
"deleteConfirm": "Eliminare davvero {item} \"{name}\"?",
"deleteConfirmWithWarning": "Eliminare davvero {item} \"{name}\"? {warning}",
"shifts": "Turni",
+ "success": "Successo",
+ "error": "Errore",
+ "createdCount": "{count} creati",
+ "updatedCount": "{count} aggiornati",
+ "deletedCount": "{count} eliminati",
"weekday": {
"monday": "Lun",
"tuesday": "Mar",
@@ -69,10 +75,11 @@
"select": "Il tuo Calendario BetterShift",
"deleteCalendar": "Elimina Calendario",
"deleteWarning": "Anche tutti i turni, i preset e le note verranno eliminati.",
- "managePassword": "Gestisci Password",
"settings": "Impostazioni Calendario per \"{name}\"",
"settingsDescription": "Personalizza nome, colore e protezione password",
- "currentlyProtected": "Questo calendario è attualmente protetto da password.",
+ "passwordProtected": "Il calendario è protetto da password",
+ "passwordRequiredToEdit": "Inserisci la tua password attuale per modificare le impostazioni.",
+ "currentPasswordRequired": "Richiesto per salvare le modifiche",
"lockCalendar": "Blocca calendario completamente",
"lockCalendarHint": "Blocca il calendario completamente - è necessaria la password per visualizzare e gestire",
"lockRequiresPassword": "Il blocco del calendario richiede una password"
@@ -84,6 +91,7 @@
},
"password": {
"optional": "Protezione Password (opzionale)",
+ "management": "Gestione Password",
"currentPassword": "Password Attuale",
"currentPasswordPlaceholder": "Inserisci la password attuale",
"newPassword": "Nuova Password",
@@ -91,7 +99,6 @@
"confirmPassword": "Conferma Password",
"confirmPasswordPlaceholder": "Conferma password",
"removePassword": "Rimuovi Password",
- "manage": "Gestisci Password per \"{name}\"",
"enter": "Inserisci Password per \"{name}\"",
"enterCalendarPassword": "Inserisci la password del calendario",
"currentlyLocked": "Questo calendario è attualmente bloccato.",
@@ -103,7 +110,7 @@
"create": "Nuova Nota",
"edit": "Modifica Nota",
"note": "Nota",
- "notePlaceholder": "es., Turno mattutino perché ho un appuntamento nel pomeriggio...",
+ "placeholder": "es., Turno mattutino perché ho un appuntamento nel pomeriggio...",
"hintMobile": "Premi a lungo su un giorno per aprire le note. L'icona della nota indica le note esistenti.",
"hintDesktop": "Fai clic con il pulsante destro del mouse su un giorno per aprire le note. L'icona della nota indica le note esistenti."
},
@@ -123,9 +130,7 @@
"noShiftsInMonthDescription": "Aggiungi turni cliccando sui giorni nel calendario in alto.",
"shift_one": "turno",
"selectPreset": "Seleziona Preset",
- "none": "Nessuno",
- "addShift": "Aggiungi Turno",
- "saveChanges": "Salva Modifiche"
+ "none": "Nessuno"
},
"preset": {
"preset": "Preset",
@@ -134,8 +139,6 @@
"edit": "Modifica Preset",
"manage": "Gestisci Preset",
"manageDescription": "Modifica o elimina i tuoi preset turno",
- "createDescription": "Crea un nuovo preset per la creazione rapida di turni",
- "editDescription": "Aggiorna i dettagli del preset",
"saveAsPreset": "Salva come preset",
"presetName": "Nome preset",
"presetNamePlaceholder": "es., Turno Mattutino, Turno Serale...",
@@ -148,11 +151,10 @@
"markAsSecondary": "Segna come secondario (compresso di default)",
"hideFromStats": "Nascondi dalle statistiche",
"hideFromStatsHint": "Escludi i turni da questo preset dalle statistiche",
- "hiddenFromStats": "Nascosto dalle statistiche",
"showPresets": "Mostra preset",
- "hidePresets": "Nascondi preset"
+ "hidePresets": "Nascondi preset",
+ "hiddenFromStats": "Nascosto dalle statistiche"
},
-
"view": {
"settingsTitle": "Impostazioni Vista",
"settingsDescription": "Personalizza come vengono visualizzati i turni in tutti i calendari",
@@ -221,6 +223,7 @@
"externalSync": {
"manageTitle": "Gestisci Calendari Esterni",
"manageDescription": "Aggiungi e gestisci più calendari esterni per questo calendario",
+ "noSyncs": "Nessun calendario esterno aggiunto ancora",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Calendario Personalizzato",
@@ -236,8 +239,6 @@
"displayModeNormal": "Normale (mostra tutti i turni)",
"displayModeMinimal": "Minimale (mostra solo il conteggio)",
"displayModeHint": "Scegli come visualizzare i turni sincronizzati nel calendario",
- "viewSyncedShifts": "Visualizza Turni Importati",
- "syncedShiftsTitle": "Turni Importati - {date}",
"addNewSync": "Aggiungi Nuovo Calendario Esterno",
"editSync": "Modifica Calendario Esterno",
"colorHint": "Scegli il colore per tutti i turni importati",
@@ -248,10 +249,6 @@
"lastSynced": "Ultima sincronizzazione",
"syncError": "Impossibile sincronizzare il calendario",
"deleteConfirm": "Eliminare questo calendario esterno? Tutti i turni importati verranno rimossi.",
- "syncSuccess": "Sincronizzazione riuscita",
- "statsCreated": "creati",
- "statsUpdated": "aggiornati",
- "statsDeleted": "eliminati",
"hintsTitle": "Trovare l'URL del Calendario",
"hintsDescription": "Seleziona il tipo di calendario per visualizzare le istruzioni:",
"customCalendar": "Calendario Personalizzato",
@@ -271,9 +268,6 @@
"statusError": "Errore",
"syncTypeAuto": "Automatica",
"syncTypeManual": "Manuale",
- "created": "{count} creati",
- "updated": "{count} aggiornati",
- "deleted": "{count} eliminati",
"noChanges": "Nessuna modifica",
"errorMessage": "Messaggio di errore",
"filterAll": "Mostra tutto",
@@ -307,9 +301,7 @@
"rangeYear": "Singolo anno",
"monthLabel": "Seleziona mese",
"yearLabel": "Seleziona anno",
- "download": "Scarica",
- "success": "Esportazione riuscita",
- "error": "Esportazione fallita"
+ "download": "Scarica"
},
"update": {
"available": "Aggiornamento disponibile",
diff --git a/package-lock.json b/package-lock.json
index 5dfb76d..6e3d0c2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
+ "@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
@@ -2573,6 +2574,52 @@
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
+ "node_modules/@radix-ui/react-alert-dialog": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.15.tgz",
+ "integrity": "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dialog": "1.1.15",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-slot": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
+ "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "1.1.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-arrow": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",
diff --git a/package.json b/package.json
index 2b44d0d..de175da 100644
--- a/package.json
+++ b/package.json
@@ -21,6 +21,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
+ "@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",