Skip to content

Your favorite shift management application!

feat(ui): redesign BetterShift with a new design system across the calendar, compare mode, settings, sign-in, profile and admin (#182)

panteL99693a67d48c
diff --git a/.env.example b/.env.example
index b390c1b..88e9724 100644
--- a/.env.example
+++ b/.env.example
@@ -12,12 +12,13 @@
# 1. Required -- the app is not production-ready without these
# 2. Localization -- timezone and language
# 3. Access control -- who may register, who may look without login
-# 4. OAuth providers -- optional social login
-# 5. Custom OIDC provider -- optional enterprise SSO
-# 6. Reverse proxy -- required for correct client IPs behind a proxy
-# 7. Storage -- database location
-# 8. GitHub integration -- version and release check
-# 9. Rate limiting -- all optional, defaults are sensible
+# 4. Security -- CSP fallback for reverse-proxy script injection
+# 5. OAuth providers -- optional social login
+# 6. Custom OIDC provider -- optional enterprise SSO
+# 7. Reverse proxy -- required for correct client IPs behind a proxy
+# 8. Storage -- database location
+# 9. GitHub integration -- version and release check
+# 10. Rate limiting -- all optional, defaults are sensible
# ==============================================================================
@@ -73,7 +74,22 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 4. OAUTH PROVIDERS (optional)
+# 4. SECURITY
+# ==============================================================================
+
+# script-src carries a per-request nonce plus 'strict-dynamic'. Some reverse
+# proxies rewrite the page to inject their own scripts and reconstruct your
+# existing inline scripts in the process, which drops their nonce attribute --
+# notably Cloudflare's Rocket Loader. The nonce policy then blocks the app's
+# own hydration scripts too, and the app fails to load. If that happens and
+# you cannot turn Rocket Loader (or whatever is rewriting the page) off, set
+# this to true: script-src falls back to 'self' 'unsafe-inline', the same
+# policy our other apps run without a nonce.
+# CSP_STRICT_DYNAMIC_BYPASS=false
+
+
+# ==============================================================================
+# 5. OAUTH PROVIDERS (optional)
# ==============================================================================
# A provider appears on the login page as soon as its CLIENT_ID is set; the
# matching CLIENT_SECRET is then required or startup validation complains.
@@ -95,7 +111,7 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 5. CUSTOM OIDC PROVIDER (optional)
+# 6. CUSTOM OIDC PROVIDER (optional)
# ==============================================================================
# With CUSTOM_OIDC_ENABLED=true, the ISSUER, CLIENT_ID and CLIENT_SECRET below
# all become required.
@@ -112,7 +128,7 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 6. REVERSE PROXY
+# 7. REVERSE PROXY
# ==============================================================================
# Which header carries the real client IP. Rate limits and audit-log entries
@@ -139,7 +155,7 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 7. STORAGE
+# 8. STORAGE
# ==============================================================================
# Path to the SQLite file. Defaults to <cwd>/data/sqlite.db, which is what the
@@ -149,7 +165,7 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 8. GITHUB INTEGRATION
+# 9. GITHUB INTEGRATION
# ==============================================================================
# Drives the update check on the version endpoint. The defaults point at the
# upstream repository; change them only when running a fork.
@@ -162,7 +178,7 @@ ALLOW_GUEST_ACCESS=false # Allow viewing calendars without login
# ==============================================================================
-# 9. RATE LIMITING (all optional)
+# 10. RATE LIMITING (all optional)
# ==============================================================================
# Every limit is a request count plus a window in seconds. The values shown are
# the built-in defaults.
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b68ca65..6030557 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -80,55 +80,7 @@ jobs:
echo "Generating changelog from $PREVIOUS_TAG to $GITHUB_REF_NAME"
- # Get all commits between tags, excluding the last commit (version bump)
- ALL_COMMITS=$(git log $PREVIOUS_TAG..$GITHUB_REF_NAME --pretty=format:"%s|%h" --no-merges --skip=1)
-
- # Build changelog with grouping
- CHANGELOG=""
-
- # Breaking changes: conventional commits mark these with a `!` before
- # the colon (feat!:, chore(docker)!:). Listed first and also under their
- # own type below, so an upgrade note is never buried in a long list.
- BREAKING=$(echo "$ALL_COMMITS" | grep -E "^[a-z]+(\([^)]*\))?!:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$BREAKING" ]; then
- CHANGELOG+="### ⚠️ Breaking Changes"$'\n\n'
- CHANGELOG+="$BREAKING"$'\n\n'
- fi
-
- # Features
- FEATURES=$(echo "$ALL_COMMITS" | grep -E "^feat(\([^)]*\))?!?:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$FEATURES" ]; then
- CHANGELOG+="### ✨ Features"$'\n\n'
- CHANGELOG+="$FEATURES"$'\n\n'
- fi
-
- # Bug Fixes
- FIXES=$(echo "$ALL_COMMITS" | grep -E "^fix(\([^)]*\))?!?:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$FIXES" ]; then
- CHANGELOG+="### 🐛 Bug Fixes"$'\n\n'
- CHANGELOG+="$FIXES"$'\n\n'
- fi
-
- # Documentation
- DOCS=$(echo "$ALL_COMMITS" | grep -E "^docs(\([^)]*\))?!?:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$DOCS" ]; then
- CHANGELOG+="### 📝 Documentation"$'\n\n'
- CHANGELOG+="$DOCS"$'\n\n'
- fi
-
- # Chores
- CHORES=$(echo "$ALL_COMMITS" | grep -E "^chore(\([^)]*\))?!?:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$CHORES" ]; then
- CHANGELOG+="### 🔧 Chores"$'\n\n'
- CHANGELOG+="$CHORES"$'\n\n'
- fi
-
- # Other changes (not matching conventional commits)
- OTHERS=$(echo "$ALL_COMMITS" | grep -vE "^(feat|fix|docs|chore)(\([^)]*\))?!?:" | sed 's/|/ /' | sed 's/^/- /' || true)
- if [ -n "$OTHERS" ]; then
- CHANGELOG+="### 🔀 Other Changes"$'\n\n'
- CHANGELOG+="$OTHERS"$'\n\n'
- fi
+ CHANGELOG=$(scripts/changelog.sh "$PREVIOUS_TAG" "$GITHUB_REF_NAME")
# Use heredoc for multiline output
{
diff --git a/.gitignore b/.gitignore
index 78907d5..bdb5403 100644
--- a/.gitignore
+++ b/.gitignore
@@ -80,8 +80,6 @@ public/workbox-*.js.map
# Local scripts
.LOCAL
-# Claude Code agent worktrees (nested checkouts, never commit)
-.claude/worktrees/
+.claude/
-# Playwright MCP output directory
.playwright-mcp/
diff --git a/AGENTS.md b/AGENTS.md
new file mode 120000
index 0000000..681311e
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1 @@
+CLAUDE.md
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
index ff13d24..99ff891 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,6 +26,10 @@ There is no unit-test framework here — "tests" means the lint/build/i18n pipel
`npm run release:patch|minor|major` bumps the version and pushes the tag; the release workflow builds the image from it.
+## Workflow
+
+Commits follow Conventional Commits (`type(scope): summary`, e.g. `feat(ui):`, `fix(auth):`, `chore:`, `perf:`; `!` before the colon for breaking changes). `scripts/changelog.sh`, called from `.github/workflows/release.yml`, builds the release changelog straight from `git log --pretty=%s --no-merges` between tags — grouped by that prefix, with `refactor|ci|style|test|build` dropped as internal-only. It reads commit subjects, not the PR title or body, so **multi-commit PRs must merge via "Rebase and merge", not Squash** — squashing collapses every commit into one line under the merge commit's message and the per-commit changelog entries are lost. A single-commit PR can go either way since there's nothing to collapse.
+
## Architecture
### Request flow
@@ -50,7 +54,7 @@ Anything added here affects every request, so weigh cost and check the exempt li
The product is essentially one client page. `app/page.tsx` pulls data hooks (`useCalendars`, `useShifts`, `usePresets`, `useNotes`, `useExternalSync`), pairs them with action hooks (`useShiftActions`, `useNoteActions`) and dialog state (`useDialogStates`), and renders every sheet and dialog through `components/dialog-manager.tsx` — add new dialogs there rather than inline. Real routes exist only for `/login`, `/register`, `/profile`, `/admin/*` and `/system-unavailable`.
-Purely visual preferences (shifts shown per day, note visibility, full titles) live in `localStorage` via `hooks/useViewSettings.ts`, never in the database.
+View preferences (shifts per day, sorting, note visibility, day highlighting) come from `hooks/useViewSettings.ts` and exist on two levels. The personal view is stored per account in `userPreferences` via `/api/user/view-settings`; guests and `AUTH_ENABLED=false` keep it in `localStorage`, and a signed-in account without a stored view gets the device's values once. A calendar can pin its own view in `calendars.viewSettings` (`null` = off), which replaces the personal view as a whole for everyone with access; the stamp-bar toggle always stays personal, and compare mode always uses the personal view. `lib/view-settings.ts` holds the types, defaults and the sanitiser shared by routes and client.
### Calendar access model
@@ -100,7 +104,7 @@ UI strings and log output are product text in the project's locales; code commen
## Reference
-`docs/AUTH_SETUP.md`, `docs/PERMISSIONS.md`, `docs/ADMIN_PANEL.md`, `docs/MIGRATION_AUTH_TOGGLE.md`; `.env.example` documents every environment variable with its default.
+`docs/AUTH_SETUP.md`, `docs/PERMISSIONS.md`, `docs/ADMIN_PANEL.md`, `docs/ENABLING_AUTH.md`, `docs/UPGRADING.md`; `.env.example` documents every environment variable with its default.
<!-- BEGIN:nextjs-agent-rules -->
diff --git a/README.md b/README.md
index 71b5b9b..c471b7b 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,8 @@ _BetterShift is a self-hosted shift management application for teams and individ
[Demo](https://bettershift.pantelx.com) · [Documentation](#documentation) · [Quick Start](#quick-start) · [Discord](https://discord.gg/Ma4SnagqwE)
+> **Upgrading?** Check the [Upgrade Guide](docs/UPGRADING.md) for breaking changes between versions before updating.
+
<details>
<summary>Show Screenshots</summary>
<img width="1920" height="1080" alt="calendar_page" src="https://github.com/user-attachments/assets/9b8b01b5-0a5d-4359-8024-5764866cf92a" />
@@ -44,6 +46,7 @@ _BetterShift is a self-hosted shift management application for teams and individ
docker run -d \
-p 3000:3000 \
-v ./data:/app/data \
+ -v ./uploads:/app/public/uploads \
-e BETTER_AUTH_SECRET=$(openssl rand -base64 32) \
-e BETTER_AUTH_URL=http://localhost:3000 \
-e TZ=Europe/Berlin \
@@ -78,12 +81,13 @@ npm run dev
## Documentation
-| Document | Description |
-| ------------------------------------------------ | ----------------------------------------- |
-| [Authentication Setup](docs/AUTH_SETUP.md) | Email/password, OAuth, OIDC configuration |
-| [Admin Panel](docs/ADMIN_PANEL.md) | User management, calendar administration |
-| [Permissions](docs/PERMISSIONS.md) | Sharing, access tokens, guest access |
-| [Migration Guide](docs/MIGRATION_AUTH_TOGGLE.md) | Enable auth on existing instances |
+| Document | Description |
+| -------------------------------------------------------------- | ------------------------------------------------------------------- |
+| [Authentication Setup](docs/AUTH_SETUP.md) | Email/password, OAuth, OIDC configuration |
+| [Admin Panel](docs/ADMIN_PANEL.md) | User management, calendar administration |
+| [Permissions](docs/PERMISSIONS.md) | Sharing, access tokens, guest access |
+| [Enabling Auth on an Existing Instance](docs/ENABLING_AUTH.md) | Turn on accounts for an instance that ran with `AUTH_ENABLED=false` |
+| [Upgrade Guide](docs/UPGRADING.md) | Breaking changes between versions and the steps to get through them |
## Configuration
diff --git a/app/admin/calendars/page.tsx b/app/admin/calendars/page.tsx
index 0c86fd8..dc5a54c 100644
--- a/app/admin/calendars/page.tsx
+++ b/app/admin/calendars/page.tsx
@@ -1,18 +1,22 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useTranslations } from "next-intl";
-import { Search, Filter, AlertCircle, Send, Trash2, X } from "lucide-react";
-import { Input } from "@/components/ui/input";
+import { TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { SegmentedControl } from "@/components/segmented-control";
+import { StatusBanner } from "@/components/status-banner";
+import { AdminPageHeader, AdminSearch } from "@/components/admin/admin-kit";
+import { FilterMenuButton, type SortState } from "@/components/admin/admin-table-controls";
import { CalendarTable } from "@/components/admin/calendar-table";
import { CalendarDetailsSheet } from "@/components/admin/calendar-details-sheet";
import { CalendarEditSheet } from "@/components/admin/calendar-edit-sheet";
@@ -20,52 +24,60 @@ import { CalendarTransferSheet } from "@/components/admin/calendar-transfer-shee
import { CalendarDeleteDialog } from "@/components/admin/calendar-delete-dialog";
import { CalendarBulkDeleteDialog } from "@/components/admin/calendar-bulk-delete-dialog";
import {
+ useAdminCalendarActions,
useAdminCalendars,
type AdminCalendar,
- type CalendarFilters,
- type CalendarSort,
} from "@/hooks/useAdminCalendars";
-import { useAdminLevel } from "@/hooks/useAdminAccess";
+import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";
+import {
+ ADMIN_PAGE_SIZE,
+ type CalendarContentFilter,
+ type CalendarListParams,
+ type CalendarOwnerFilter,
+ type CalendarSortField,
+} from "@/lib/admin-list";
+
+const NO_SELECTION: string[] = [];
export default function AdminCalendarsPage() {
const t = useTranslations();
- const adminLevel = useAdminLevel();
- const isSuperAdmin = adminLevel === "superadmin";
-
- // Filters & Sort
- const [searchQuery, setSearchQuery] = useState("");
- const [statusFilter, setStatusFilter] = useState<
- "all" | "orphaned" | "with-owner"
- >("all");
- const sortField = "createdAt" as const;
- const sortDirection = "desc" as const;
-
- // Build filters and sort
- const filters: CalendarFilters = {
- search: searchQuery || undefined,
- status: statusFilter,
- };
- const sort: CalendarSort = {
- field: sortField,
- direction: sortDirection,
- };
+ const search = useDebouncedSearch();
+ const [contentFilter, setContentFilter] = useState<CalendarContentFilter>("all");
+ const [ownerFilter, setOwnerFilter] = useState<CalendarOwnerFilter>("all");
+ const [sort, setSort] = useState<SortState<CalendarSortField>>({ column: "createdAt", direction: "desc" });
+
+ // Any change to search, filters or sort starts over on the first page
+ const listKey = [search.query, contentFilter, ownerFilter, sort.column, sort.direction].join("|");
+ const [requestedPage, setPage] = useResettableState(listKey, 1);
+
+ const params = useMemo<CalendarListParams>(
+ () => ({
+ search: search.query,
+ content: contentFilter,
+ owner: ownerFilter,
+ sort: sort.column,
+ order: sort.direction,
+ page: requestedPage,
+ limit: ADMIN_PAGE_SIZE,
+ }),
+ [search.query, contentFilter, ownerFilter, sort, requestedPage]
+ );
- // Use hook with filters
- const {
- calendars,
- orphanedCount,
- isLoading,
- deleteCalendar,
- bulkDeleteCalendars,
- } = useAdminCalendars(filters, sort);
+ const { calendars, total, counts, page, isLoading, isPlaceholderData } = useAdminCalendars(params);
+ const { deleteCalendar, bulkDeleteCalendars } = useAdminCalendarActions();
+ const orphanedCount = counts?.orphaned ?? 0;
- // Selection
- const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ // Selection is per page: it clears when the page, search, filters or sort change
+ const [selection, setSelection] = useResettableState(`${listKey}|${page}`, NO_SELECTION);
+ const selectedIds = useMemo(
+ () => selection.filter((id) => calendars.some((cal) => cal.id === id)),
+ [selection, calendars]
+ );
+ const selectedCalendars = calendars.filter((cal) => selectedIds.includes(cal.id));
// Dialogs & Sheets
- const [selectedCalendar, setSelectedCalendar] =
- useState<AdminCalendar | null>(null);
+ const [selectedCalendar, setSelectedCalendar] = useState<AdminCalendar | null>(null);
const [showDetailsSheet, setShowDetailsSheet] = useState(false);
const [showEditSheet, setShowEditSheet] = useState(false);
const [showTransferSheet, setShowTransferSheet] = useState(false);
@@ -74,56 +86,31 @@ export default function AdminCalendarsPage() {
// Bulk operations
const [showBulkTransferSheet, setShowBulkTransferSheet] = useState(false);
- const [calendarsForBulkTransfer, setCalendarsForBulkTransfer] = useState<
- AdminCalendar[]
- >([]);
+ const [calendarsForBulkTransfer, setCalendarsForBulkTransfer] = useState<AdminCalendar[]>([]);
- // Selection handlers
const handleToggleSelect = (calendarId: string) => {
- setSelectedIds((prev) =>
- prev.includes(calendarId)
- ? prev.filter((id) => id !== calendarId)
- : [...prev, calendarId]
+ setSelection((prev) =>
+ prev.includes(calendarId) ? prev.filter((id) => id !== calendarId) : [...prev, calendarId]
);
};
- const handleToggleSelectAll = () => {
- if (selectedIds.length === calendars.length) {
- setSelectedIds([]);
- } else {
- setSelectedIds(calendars.map((cal) => cal.id));
- }
- };
-
- const handleClearSelection = () => {
- setSelectedIds([]);
- };
-
- // Handlers
- const handleCalendarClick = (calendar: AdminCalendar) => {
- setSelectedCalendar(calendar);
- setShowDetailsSheet(true);
- };
+ const isAllSelected = calendars.length > 0 && selectedIds.length === calendars.length;
- const handleEditCalendar = (calendar: AdminCalendar) => {
- setSelectedCalendar(calendar);
- setShowEditSheet(true);
+ const handleToggleSelectAll = () => {
+ setSelection(isAllSelected ? [] : calendars.map((cal) => cal.id));
};
- const handleTransferCalendar = (calendar: AdminCalendar) => {
+ const openFor = (setter: (open: boolean) => void) => (calendar: AdminCalendar) => {
setSelectedCalendar(calendar);
- setShowTransferSheet(true);
+ setter(true);
};
- const handleDeleteCalendar = (calendar: AdminCalendar) => {
- setSelectedCalendar(calendar);
- setShowDeleteDialog(true);
+ const fromDetails = (setter: (open: boolean) => void) => () => {
+ setShowDetailsSheet(false);
+ setter(true);
};
const handleBulkTransfer = () => {
- const selectedCalendars = calendars.filter((cal) =>
- selectedIds.includes(cal.id)
- );
setCalendarsForBulkTransfer(selectedCalendars);
setShowBulkTransferSheet(true);
};
@@ -135,17 +122,12 @@ export default function AdminCalendarsPage() {
const handleBulkDeleteConfirm = async () => {
if (selectedIds.length === 0) return;
-
- const success = await bulkDeleteCalendars(selectedIds);
- if (success) {
- setSelectedIds([]);
- }
+ if (await bulkDeleteCalendars(selectedIds)) setSelection([]);
};
const handleDeleteConfirm = async () => {
if (!selectedCalendar) return;
- const success = await deleteCalendar(selectedCalendar.id);
- if (success) {
+ if (await deleteCalendar(selectedCalendar.id)) {
setShowDeleteDialog(false);
setSelectedCalendar(null);
}
@@ -157,228 +139,166 @@ export default function AdminCalendarsPage() {
setShowBulkTransferSheet(false);
setSelectedCalendar(null);
setCalendarsForBulkTransfer([]);
- setSelectedIds([]);
- };
-
- const handleEditFromDetails = () => {
- setShowDetailsSheet(false);
- setShowEditSheet(true);
- };
-
- const handleTransferFromDetails = () => {
- setShowDetailsSheet(false);
- setShowTransferSheet(true);
- };
-
- const handleDeleteFromDetails = () => {
- setShowDetailsSheet(false);
- setShowDeleteDialog(true);
+ setSelection([]);
};
- const isAllSelected =
- calendars.length > 0 && selectedIds.length === calendars.length;
- const hasOrphanedCalendars = orphanedCount > 0;
- const showOrphanedBanner =
- hasOrphanedCalendars && statusFilter !== "with-owner";
+ const showOrphanedBanner = orphanedCount > 0 && ownerFilter !== "with-owner";
- if (isLoading && calendars.length === 0) {
+ if (isLoading && !counts) {
return <FullscreenLoader />;
}
return (
<>
- <div className="space-y-6">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div>
- <h2 className="text-3xl font-bold tracking-tight">
- {t("admin.calendars.title")}
- </h2>
- <p className="text-muted-foreground mt-2">
- {t("admin.calendars.description")}
- </p>
- </div>
- </div>
+ <div className="flex flex-col gap-4">
+ <AdminPageHeader
+ title={t("admin.calendarsMenu")}
+ subtitle={
+ counts
+ ? t("adminCalendars.subtitle", { count: counts.total, shifts: counts.shifts })
+ : undefined
+ }
+ />
- {/* Orphaned Calendars Warning Banner */}
{showOrphanedBanner && (
- <div className="flex items-start gap-3 p-4 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
- <AlertCircle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
- <div className="flex-1">
- <p className="text-sm font-medium text-red-800 dark:text-red-200">
- {t("admin.calendars.orphanedWarning", { count: orphanedCount })}
- </p>
- <p className="text-xs text-red-700 dark:text-red-300 mt-1">
- {t("admin.calendars.orphanedWarningDescription")}
- </p>
- </div>
- </div>
- )}
-
- {/* Filters */}
- <div className="flex flex-col sm:flex-row gap-4">
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- type="text"
- placeholder={t("admin.calendars.searchPlaceholder")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- />
- </div>
- <Select
- value={statusFilter}
- onValueChange={(value: "all" | "orphaned" | "with-owner") =>
- setStatusFilter(value)
+ <StatusBanner
+ tone="warning"
+ icon={TriangleAlert}
+ title={t("admin.calendars.orphanedWarning", { count: orphanedCount })}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 rounded-[8px] font-semibold"
+ onClick={() => setOwnerFilter(ownerFilter === "orphaned" ? "all" : "orphaned")}
+ >
+ {ownerFilter === "orphaned" ? t("common.viewAll") : t("adminCalendars.showOrphaned")}
+ </Button>
}
>
- <SelectTrigger className="w-full sm:w-[200px]">
- <div className="flex items-center gap-2">
- <Filter className="h-4 w-4" />
- <SelectValue />
- </div>
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">
- {t("admin.calendars.allStatuses")}
- </SelectItem>
- <SelectItem value="orphaned">
- {t("admin.calendars.orphanedOnly")}
- </SelectItem>
- <SelectItem value="with-owner">
- {t("admin.calendars.withOwner")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Results Count */}
- <div className="flex items-center justify-between text-sm text-muted-foreground">
- <p>
- {t("admin.calendars.calendarsCount", { count: calendars.length })}
- </p>
- </div>
-
- {/* Bulk Actions Toolbar */}
- {selectedIds.length > 0 && (
- <div className="flex items-center justify-between p-4 rounded-lg border bg-muted/50">
- <div className="flex items-center gap-3">
- <span className="text-sm font-medium">
- {t("admin.calendars.selectedCount", {
- count: selectedIds.length,
- })}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <Button variant="outline" size="sm" onClick={handleBulkTransfer}>
- <Send className="h-4 w-4 mr-2" />
- {t("admin.calendars.transferSelected")}
- </Button>
- {isSuperAdmin && (
- <Button
- variant="outline"
- size="sm"
- onClick={handleBulkDelete}
- className="text-destructive hover:text-destructive"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("common.deleteSelected")}
- </Button>
- )}
- <Button variant="ghost" size="sm" onClick={handleClearSelection}>
- <X className="h-4 w-4 mr-2" />
- {t("admin.calendars.clearSelection")}
- </Button>
- </div>
- </div>
+ {t("admin.calendars.orphanedWarningDescription")}
+ </StatusBanner>
)}
- {/* Calendar Table */}
- {calendars.length === 0 ? (
- <div className="text-center py-12 border border-dashed rounded-lg">
- <p className="text-muted-foreground">
- {searchQuery
- ? t("admin.calendars.noSearchResults")
- : t("admin.calendars.noCalendarsFound")}
- </p>
- </div>
- ) : (
- <CalendarTable
- calendars={calendars}
- selectedIds={selectedIds}
- onToggleSelect={handleToggleSelect}
- onToggleSelectAll={handleToggleSelectAll}
- isAllSelected={isAllSelected}
- onCalendarClick={handleCalendarClick}
- onEditCalendar={handleEditCalendar}
- onTransferCalendar={handleTransferCalendar}
- onDeleteCalendar={handleDeleteCalendar}
+ <div className="flex items-center gap-[9px] max-lg:flex-wrap">
+ <AdminSearch
+ value={search.input}
+ onChange={search.setInput}
+ placeholder={t("admin.calendars.searchPlaceholder")}
+ className="lg:w-[340px]"
/>
- )}
+ <SegmentedControl
+ value={contentFilter}
+ onChange={setContentFilter}
+ label={t("adminCalendars.filterLabel")}
+ className="min-w-0 flex-1 lg:flex-none lg:[&>button]:flex-none lg:[&>button]:px-[13px]"
+ options={[
+ { value: "all", label: t("adminUsers.all") },
+ { value: "shared", label: t("adminCalendars.filterShared") },
+ { value: "synced", label: t("adminCalendars.filterSynced") },
+ ]}
+ />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <FilterMenuButton
+ label={t("adminUsers.moreFilters")}
+ active={ownerFilter !== "all"}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuLabel>{t("admin.calendars.owner")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={ownerFilter}
+ onValueChange={(value) => setOwnerFilter(value as CalendarOwnerFilter)}
+ >
+ <DropdownMenuRadioItem value="all">
+ {t("admin.calendars.allStatuses")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="orphaned">
+ {t("admin.calendars.orphanedOnly")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="with-owner">
+ {t("admin.calendars.withOwner")}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+
+ <CalendarTable
+ calendars={calendars}
+ total={total}
+ page={page}
+ pageSize={ADMIN_PAGE_SIZE}
+ onPageChange={setPage}
+ sort={sort}
+ onSortChange={setSort}
+ isStale={isPlaceholderData}
+ selectedIds={selectedIds}
+ onToggleSelect={handleToggleSelect}
+ onToggleSelectAll={handleToggleSelectAll}
+ isAllSelected={isAllSelected}
+ onCalendarClick={openFor(setShowDetailsSheet)}
+ onEditCalendar={openFor(setShowEditSheet)}
+ onTransferCalendar={openFor(setShowTransferSheet)}
+ onDeleteCalendar={openFor(setShowDeleteDialog)}
+ onBulkTransfer={handleBulkTransfer}
+ onBulkDelete={handleBulkDelete}
+ onClearSelection={() => setSelection([])}
+ emptyMessage={search.query ? t("admin.calendars.noSearchResults") : undefined}
+ />
+ </div>
- {/* Calendar Details Sheet */}
- {selectedCalendar && (
+ {selectedCalendar && (
+ <>
<CalendarDetailsSheet
+ key={`details-${selectedCalendar.id}`}
open={showDetailsSheet}
onOpenChange={setShowDetailsSheet}
calendarId={selectedCalendar.id}
- onEdit={handleEditFromDetails}
- onTransfer={handleTransferFromDetails}
- onDelete={handleDeleteFromDetails}
+ onEdit={fromDetails(setShowEditSheet)}
+ onTransfer={fromDetails(setShowTransferSheet)}
+ onDelete={fromDetails(setShowDeleteDialog)}
/>
- )}
-
- {/* Calendar Edit Sheet */}
- {selectedCalendar && (
<CalendarEditSheet
+ key={`edit-${selectedCalendar.id}`}
open={showEditSheet}
onOpenChange={setShowEditSheet}
calendar={selectedCalendar}
onSuccess={handleSuccess}
/>
- )}
-
- {/* Calendar Transfer Sheet (Single) */}
- {selectedCalendar && (
<CalendarTransferSheet
open={showTransferSheet}
onOpenChange={setShowTransferSheet}
calendars={[selectedCalendar]}
onSuccess={handleSuccess}
/>
- )}
-
- {/* Calendar Transfer Sheet (Bulk) */}
- {calendarsForBulkTransfer.length > 0 && (
- <CalendarTransferSheet
- open={showBulkTransferSheet}
- onOpenChange={setShowBulkTransferSheet}
- calendars={calendarsForBulkTransfer}
- onSuccess={handleSuccess}
- />
- )}
-
- {/* Calendar Delete Dialog */}
- {selectedCalendar && (
<CalendarDeleteDialog
open={showDeleteDialog}
onOpenChange={setShowDeleteDialog}
calendar={selectedCalendar}
onConfirm={handleDeleteConfirm}
/>
- )}
-
- {/* Calendar Bulk Delete Dialog */}
- {selectedIds.length > 0 && (
- <CalendarBulkDeleteDialog
- open={showBulkDeleteDialog}
- onOpenChange={setShowBulkDeleteDialog}
- calendars={calendars.filter((cal) => selectedIds.includes(cal.id))}
- onConfirm={handleBulkDeleteConfirm}
- />
- )}
- </div>
+ </>
+ )}
+
+ {calendarsForBulkTransfer.length > 0 && (
+ <CalendarTransferSheet
+ open={showBulkTransferSheet}
+ onOpenChange={setShowBulkTransferSheet}
+ calendars={calendarsForBulkTransfer}
+ onSuccess={handleSuccess}
+ />
+ )}
+
+ {selectedIds.length > 0 && (
+ <CalendarBulkDeleteDialog
+ open={showBulkDeleteDialog}
+ onOpenChange={setShowBulkDeleteDialog}
+ calendars={selectedCalendars}
+ onConfirm={handleBulkDeleteConfirm}
+ />
+ )}
</>
);
}
diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx
index 3c090f3..49cb8ff 100644
--- a/app/admin/layout.tsx
+++ b/app/admin/layout.tsx
@@ -1,83 +1,30 @@
"use client";
-import { useState, useEffect } from "react";
-import { AdminSidebar } from "@/components/admin/admin-sidebar";
+import { AdminSidebar, AdminMobileNav } from "@/components/admin/admin-sidebar";
import { AdminHeader } from "@/components/admin/admin-header";
import { useRequireAdmin } from "@/hooks/useAdminAccess";
import { FullscreenLoader } from "@/components/fullscreen-loader";
import { useAuth } from "@/hooks/useAuth";
-/**
- * Admin Panel Layout
- *
- * Features:
- * - Custom layout wrapper for all admin pages
- * - Includes AdminSidebar (collapsible) and AdminHeader (breadcrumbs)
- * - Access control: Redirects non-admins to home page
- * - Responsive design with sidebar + main content area
- */
-export default function AdminLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default function AdminLayout({ children }: { children: React.ReactNode }) {
const { isLoading } = useAuth();
- const [sidebarWidth, setSidebarWidth] = useState(280);
- const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
-
- // Require admin access (redirects non-admins)
useRequireAdmin("/");
- // Listen for sidebar width changes
- useEffect(() => {
- const handleResize = () => {
- // Mobile: 0px (hidden), Desktop: Check if collapsed (80px) or expanded (280px)
- if (window.innerWidth < 1024) {
- setSidebarWidth(0);
- } else {
- setSidebarWidth(280); // Default to expanded on desktop
- }
- };
-
- handleResize(); // Initial check
- window.addEventListener("resize", handleResize);
- return () => window.removeEventListener("resize", handleResize);
- }, []);
-
- // Show loader while checking auth
if (isLoading) {
return <FullscreenLoader />;
}
return (
- <div className="flex h-screen overflow-hidden">
- {/* Sidebar Navigation */}
- <AdminSidebar
- onWidthChange={setSidebarWidth}
- isMobileOpen={isMobileSidebarOpen}
- onMobileClose={() => setIsMobileSidebarOpen(false)}
- />
-
- {/* Main Content Area */}
- <div
- className="flex-1 flex flex-col overflow-hidden transition-all duration-300"
- style={{
- marginLeft:
- typeof window !== "undefined" && window.innerWidth >= 1024
- ? `${sidebarWidth}px`
- : "0",
- }}
- >
- {/* Header */}
- <AdminHeader onMenuClick={() => setIsMobileSidebarOpen(true)} />
-
- {/* Page Content */}
- <main className="flex-1 overflow-y-auto">
- <div className="container max-w-7xl mx-auto p-4 sm:p-6">
- {children}
- </div>
+ <div className="flex h-dvh flex-col overflow-hidden bg-background">
+ <AdminHeader />
+ <div className="flex min-h-0 flex-1">
+ <AdminSidebar />
+ <main className="min-w-0 flex-1 overflow-y-auto">
+ {/* Phones: no top padding, each page's AdminPageHeader is the sticky top bar */}
+ <div className="mx-auto w-full max-w-[1400px] px-4 pb-6 lg:px-[26px] lg:py-[22px]">{children}</div>
</main>
</div>
+ <AdminMobileNav />
</div>
);
}
diff --git a/app/admin/logs/page.tsx b/app/admin/logs/page.tsx
index bf0839c..d3c4386 100644
--- a/app/admin/logs/page.tsx
+++ b/app/admin/logs/page.tsx
@@ -1,725 +1,404 @@
"use client";
-import React, { useState, useEffect, useMemo } from "react";
-import { useTranslations, useLocale } from "next-intl";
-import { useAdminAuditLogs, type AuditLog } from "@/hooks/useAdminAuditLogs";
-import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { Fragment, KeyboardEvent, MouseEvent, useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { ChevronRight, SlidersHorizontal, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Badge } from "@/components/ui/badge";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
+ AdminMobileCard,
+ AdminPageHeader,
+ AdminSearch,
+ AdminTableCard,
+ AdminTableHead,
+ AdminTableRow,
+ SeverityPill,
+} from "@/components/admin/admin-kit";
+import { SortHeader, nextSort, type SortState } from "@/components/admin/admin-table-controls";
import { AuditLogDetailsDialog } from "@/components/admin/audit-log-details-dialog";
import { AuditLogDeleteDialog } from "@/components/admin/audit-log-delete-dialog";
import {
- ChevronLeft,
- ChevronRight,
- Trash2,
- Search,
- ChevronDown,
- ChevronUp,
- Filter,
- X,
-} from "lucide-react";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+ AuditFilterBar,
+ AuditFilterChips,
+ AuditFilterSheet,
+ EMPTY_AUDIT_FILTERS,
+ hasAuditFilters,
+ type AuditFilterValues,
+} from "@/components/admin/audit-log-filters";
+import { useAuditDescription } from "@/components/admin/audit-describe";
+import { useAdminAuditLogs, type AuditLog, type AuditLogFilters } from "@/hooks/useAdminAuditLogs";
import { useIsSuperAdmin } from "@/hooks/useAdminAccess";
+import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+type SortColumn = "timestamp" | "action" | "severity" | "user" | "ipAddress";
+
+const PAGE_SIZE = 25;
+// Stable identities so the resettable state falls back to the same value
+const EMPTY_ROWS: Set<string> = new Set();
+const EMPTY_IDS: string[] = [];
+const COLUMNS = "18px 160px 180px minmax(0,140px) 96px minmax(0,1fr) 118px 64px";
+
+const stop = (e: MouseEvent | KeyboardEvent) => e.stopPropagation();
-/**
- * Admin Audit Logs Page
- *
- * Features:
- * - View all audit logs (admin + superadmin)
- * - Advanced filters (action, severity, user, date range)
- * - Sortable columns
- * - Expandable rows for metadata
- * - Pagination (50 per page)
- * - Delete old logs (superadmin only)
- * - Responsive design
- */
export default function AdminAuditLogsPage() {
const t = useTranslations();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
const isSuperAdmin = useIsSuperAdmin();
-
- // Filter State
- const [page, setPage] = useState(0);
- const limit = 25;
- const [actionFilter, setActionFilter] = useState<string>("all");
- const [severityFilter, setSeverityFilter] = useState<string>("all");
- const [searchQuery, setSearchQuery] = useState("");
- const [debouncedSearch, setDebouncedSearch] = useState("");
- const [startDate, setStartDate] = useState("");
- const [endDate, setEndDate] = useState("");
-
- // Sort State
- const [sortColumn, setSortColumn] = useState<
- "timestamp" | "action" | "severity" | "user" | "ipAddress"
- >("timestamp");
- const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
-
- // Build filters and sort for hook
- const filters = useMemo(
- () => ({
- action: actionFilter !== "all" ? actionFilter : undefined,
- severity:
- severityFilter !== "all"
- ? (severityFilter as "info" | "warning" | "error" | "critical")
- : undefined,
- search: debouncedSearch || undefined,
- startDate: startDate || undefined,
- endDate: endDate || undefined,
- }),
- [actionFilter, severityFilter, debouncedSearch, startDate, endDate]
+ const describe = useAuditDescription();
+
+ const search = useDebouncedSearch(500);
+ const [filterValues, setFilterValues] = useState<AuditFilterValues>(EMPTY_AUDIT_FILTERS);
+ const [sort, setSort] = useState<SortState<SortColumn>>({ column: "timestamp", direction: "desc" });
+
+ // Any change to search or filters starts over on the first page, with nothing selected
+ const listKey = [search.query, filterValues.action, filterValues.severity, filterValues.startDate, filterValues.endDate].join("|");
+ const [page, setPage] = useResettableState(listKey, 0);
+ const [expandedRows, setExpandedRows] = useResettableState<Set<string>>(listKey, EMPTY_ROWS);
+ // Selection is per page: bulk delete is irreversible, so it must never reach rows off screen
+ const [selectedLogIds, setSelectedLogIds] = useResettableState<string[]>(
+ `${listKey}|${sort.column}|${sort.direction}|${page}`,
+ EMPTY_IDS
);
-
- const sort = useMemo(
- () => ({
- field: sortColumn,
- direction: sortDirection,
- }),
- [sortColumn, sortDirection]
- );
-
- const pagination = useMemo(
- () => ({
- limit,
- offset: page * limit,
- }),
- [page, limit]
- );
-
- // Use hook with live updates
- const { logs, total, isLoading } = useAdminAuditLogs(
- filters,
- sort,
- pagination
- );
-
- // UI State
- const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
- const [selectedLogIds, setSelectedLogIds] = useState<string[]>([]);
const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
const [showDetailsDialog, setShowDetailsDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [showFilterSheet, setShowFilterSheet] = useState(false);
- // Memoized helper functions for badge colors
- const getSeverityColor = useMemo(
- () => (severity: string) => {
- switch (severity) {
- case "info":
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- case "warning":
- return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
- case "error":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- case "critical":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- default:
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- }
- },
- []
- );
-
- const getActionColor = useMemo(
- () => (action: string) => {
- if (action.startsWith("admin.")) {
- return "bg-red-500/10 text-red-500 border-red-500/20";
- }
- if (action.startsWith("calendar.")) {
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- }
- if (action.startsWith("auth.")) {
- return "bg-green-500/10 text-green-500 border-green-500/20";
- }
- if (action.startsWith("security.")) {
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- }
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- },
- []
- );
-
- const getUserInitials = useMemo(
- () => (name: string | null) => {
- if (!name) return "?";
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- },
- []
+ const filters = useMemo<AuditLogFilters>(
+ () => ({
+ action: filterValues.action !== "all" ? filterValues.action : undefined,
+ severity:
+ filterValues.severity !== "all" ? (filterValues.severity as AuditLogFilters["severity"]) : undefined,
+ search: search.query || undefined,
+ startDate: filterValues.startDate || undefined,
+ endDate: filterValues.endDate || undefined,
+ }),
+ [filterValues, search.query]
);
+ const sortParams = useMemo(() => ({ field: sort.column, direction: sort.direction }), [sort]);
+ const pagination = useMemo(() => ({ limit: PAGE_SIZE, offset: page * PAGE_SIZE }), [page]);
- // Handler functions that combine filter changes with page reset
- const handleActionFilterChange = (value: string) => {
- setActionFilter(value);
- setPage(0);
- setSelectedLogIds([]);
- setExpandedRows(new Set());
- };
+ const { logs, total, isLoading } = useAdminAuditLogs(filters, sortParams, pagination);
- const handleSeverityFilterChange = (value: string) => {
- setSeverityFilter(value);
- setPage(0);
- setSelectedLogIds([]);
- setExpandedRows(new Set());
+ const updateFilters = (patch: Partial<AuditFilterValues>) => {
+ setFilterValues((prev) => ({ ...prev, ...patch }));
};
- const handleStartDateChange = (value: string) => {
- setStartDate(value);
- setPage(0);
- setSelectedLogIds([]);
- setExpandedRows(new Set());
- };
-
- const handleEndDateChange = (value: string) => {
- setEndDate(value);
- setPage(0);
- setSelectedLogIds([]);
- setExpandedRows(new Set());
- };
-
- const handleDebouncedSearchChange = (value: string) => {
- setDebouncedSearch(value);
- setPage(0);
- setSelectedLogIds([]);
- setExpandedRows(new Set());
+ const clearFilters = () => {
+ setFilterValues(EMPTY_AUDIT_FILTERS);
+ search.setInput("");
};
- // Debounce search query
- useEffect(() => {
- const timer = setTimeout(() => {
- handleDebouncedSearchChange(searchQuery);
- }, 500);
-
- return () => clearTimeout(timer);
- }, [searchQuery]);
-
- // Toggle row expansion
const toggleRow = (logId: string) => {
setExpandedRows((prev) => {
- const newSet = new Set(prev);
- if (newSet.has(logId)) {
- newSet.delete(logId);
- } else {
- newSet.add(logId);
- }
- return newSet;
+ const next = new Set(prev);
+ if (next.has(logId)) next.delete(logId);
+ else next.add(logId);
+ return next;
});
};
- // Handle sort column click - now triggers backend sort
- const handleSort = (
- column: "timestamp" | "action" | "severity" | "user" | "ipAddress"
- ) => {
- if (sortColumn === column) {
- setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
- } else {
- setSortColumn(column);
- setSortDirection("desc");
- }
+ const toggleLogSelection = (logId: string) => {
+ setSelectedLogIds((prev) => (prev.includes(logId) ? prev.filter((id) => id !== logId) : [...prev, logId]));
};
- // Handle pagination
- const goToNextPage = () => {
- if (page * limit + logs.length < total) {
- setPage((prev) => prev + 1);
- }
- };
+ // Guards the window between a page change and the new rows arriving
+ const selectedIds = useMemo(
+ () => selectedLogIds.filter((id) => logs.some((log) => log.id === id)),
+ [selectedLogIds, logs]
+ );
- const goToPreviousPage = () => {
- if (page > 0) {
- setPage((prev) => prev - 1);
- }
- };
+ const isAllSelected = logs.length > 0 && selectedIds.length === logs.length;
+ const toggleSelectAll = () => setSelectedLogIds(isAllSelected ? [] : logs.map((log) => log.id));
- // Clear filters
- const clearFilters = () => {
- setActionFilter("all");
- setSeverityFilter("all");
- setSearchQuery("");
- setStartDate("");
- setEndDate("");
- setPage(0);
- // Immediately clear debouncedSearch to prevent stale value
- handleDebouncedSearchChange("");
+ const openDetails = (log: AuditLog) => {
+ setSelectedLog(log);
+ setShowDetailsDialog(true);
};
- // Checkbox selection handlers
- const toggleLogSelection = (logId: string) => {
- setSelectedLogIds((prev) =>
- prev.includes(logId)
- ? prev.filter((id) => id !== logId)
- : [...prev, logId]
- );
- };
+ const hasNext = page * PAGE_SIZE + logs.length < total;
+ const template = isSuperAdmin ? `20px ${COLUMNS}` : COLUMNS;
+ const formatTimestamp = (date: Date) => format(date, "PP p", { locale: dateLocale });
+ const userLabel = (log: AuditLog) =>
+ log.userId ? log.userName || log.userEmail || t("admin.unknownUser") : t("admin.systemAction");
- const toggleSelectAll = () => {
- if (selectedLogIds.length === logs.length) {
- setSelectedLogIds([]);
- } else {
- setSelectedLogIds(logs.map((log) => log.id));
- }
- };
+ const sortHeader = (column: SortColumn, label: string) => (
+ <SortHeader column={column} label={label} sort={sort} onSort={(c) => setSort((s) => nextSort(s, c))} />
+ );
- const clearSelection = () => {
- setSelectedLogIds([]);
- };
+ const pager = (
+ <div className="flex shrink-0 gap-[7px]">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setPage((p) => Math.max(0, p - 1))}
+ disabled={page === 0}
+ className="h-[30px] rounded-lg px-[11px] text-[12.5px]"
+ >
+ {t("common.previous")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => hasNext && setPage((p) => p + 1)}
+ disabled={!hasNext}
+ className="h-[30px] rounded-lg px-[11px] text-[12.5px] font-semibold"
+ >
+ {t("common.next")}
+ </Button>
+ </div>
+ );
- const isAllSelected =
- logs.length > 0 && selectedLogIds.length === logs.length;
+ const showing =
+ total > 0
+ ? t("admin.showingLogs", {
+ from: page * PAGE_SIZE + 1,
+ to: Math.min(page * PAGE_SIZE + logs.length, total),
+ total,
+ })
+ : "";
- // Show loader only on initial load
- if (isLoading && logs.length === 0) {
- return <FullscreenLoader />;
- }
+ const emptyText = isLoading ? t("common.loading") : t("admin.noLogsFound");
return (
- <div className="space-y-6">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div>
- <h2 className="text-3xl font-bold tracking-tight">
- {t("admin.auditLogs")}
- </h2>
- <p className="text-muted-foreground mt-2">
- {t("admin.auditLogsDescription")}
- </p>
- </div>
- <div className="flex items-center gap-2">
- {isSuperAdmin && (
+ <div className="flex flex-col gap-3 lg:gap-4">
+ <AdminPageHeader
+ title={t("admin.auditLogs")}
+ subtitle={t("adminAudit.subtitle", { count: total })}
+ actions={
+ isSuperAdmin && (
<Button
variant="outline"
- size="sm"
onClick={() => setShowDeleteDialog(true)}
+ className="h-[38px] gap-2 rounded-[9px] border-warning-line bg-warning-surface px-3.5 font-semibold text-warning-title hover:bg-warning-soft hover:text-warning-title dark:border-warning-line dark:bg-warning-surface dark:hover:bg-warning-soft"
>
- <Trash2 className="h-4 w-4" />
- <span className="hidden sm:inline ml-2">
- {t("admin.deleteOldLogs")}
- </span>
+ <Trash2 className="size-4" />
+ {t("admin.deleteOldLogs")}
</Button>
- )}
- </div>
- </div>
-
- {/* Filters */}
- <div className="flex flex-col gap-4">
- <div className="flex flex-col sm:flex-row gap-4">
- {/* Search */}
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("admin.searchLogs")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- />
- </div>
-
- {/* Action Type Filter */}
- <Select value={actionFilter} onValueChange={handleActionFilterChange}>
- <SelectTrigger className="w-full sm:w-[200px]">
- <Filter className="h-4 w-4 mr-2" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t("admin.allActions")}</SelectItem>
- <SelectItem value="admin.">{t("admin.adminActions")}</SelectItem>
- <SelectItem value="calendar.">
- {t("admin.calendarActions")}
- </SelectItem>
- <SelectItem value="auth.">{t("admin.authActions")}</SelectItem>
- <SelectItem value="security.">
- {t("admin.securityActions")}
- </SelectItem>
- </SelectContent>
- </Select>
-
- {/* Severity Filter */}
- <Select
- value={severityFilter}
- onValueChange={handleSeverityFilterChange}
- >
- <SelectTrigger className="w-full sm:w-[180px]">
- <Filter className="h-4 w-4 mr-2" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">
- {t("common.filters.allSeverities")}
- </SelectItem>
- <SelectItem value="info">{t("common.severity.info")}</SelectItem>
- <SelectItem value="warning">
- {t("common.severity.warning")}
- </SelectItem>
- <SelectItem value="error">
- {t("common.severity.error")}
- </SelectItem>
- <SelectItem value="critical">
- {t("common.severity.critical")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Date Range Filters */}
- <div className="flex flex-col sm:flex-row gap-4">
- <div className="flex-1">
- <label className="text-sm font-medium mb-2 block">
- {t("common.labels.startDate")}
- </label>
- <Input
- type="date"
- value={startDate}
- onChange={(e) => handleStartDateChange(e.target.value)}
- />
- </div>
-
- <div className="flex-1">
- <label className="text-sm font-medium mb-2 block">
- {t("common.labels.endDate")}
- </label>
- <Input
- type="date"
- value={endDate}
- onChange={(e) => handleEndDateChange(e.target.value)}
- />
- </div>
+ )
+ }
+ mobileActions={
+ <>
+ {isSuperAdmin && (
+ <button
+ type="button"
+ onClick={() => setShowDeleteDialog(true)}
+ aria-label={t("admin.deleteOldLogs")}
+ className="flex size-[34px] items-center justify-center rounded-[9px] border border-warning-line bg-warning-surface text-warning-title"
+ >
+ <Trash2 className="size-[17px]" />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => setShowFilterSheet(true)}
+ aria-label={t("adminAudit.filterTitle")}
+ className={cn(
+ "relative flex size-[34px] items-center justify-center rounded-[9px] border",
+ hasAuditFilters(filterValues) ? "border-brand text-brand-ink" : "border-line text-fg-secondary"
+ )}
+ >
+ <SlidersHorizontal className="size-[17px]" />
+ {hasAuditFilters(filterValues) && (
+ <span className="absolute right-1 top-1 size-1.5 rounded-full bg-brand" />
+ )}
+ </button>
+ </>
+ }
+ />
- {/* Clear Filters Button */}
- {(actionFilter !== "all" ||
- severityFilter !== "all" ||
- searchQuery ||
- startDate ||
- endDate) && (
- <div className="flex items-end">
- <Button variant="outline" onClick={clearFilters}>
- <X className="h-4 w-4 mr-2" />
- {t("common.filters.clearFilters")}
- </Button>
- </div>
- )}
+ <div className="flex flex-wrap items-center gap-[9px]">
+ <AdminSearch
+ value={search.input}
+ onChange={search.setInput}
+ placeholder={t("admin.searchLogs")}
+ className="lg:w-[340px]"
+ />
+ <div className="hidden flex-wrap items-center gap-[9px] lg:flex">
+ <AuditFilterBar filters={filterValues} onChange={updateFilters} onClear={clearFilters} />
</div>
</div>
+ <AuditFilterChips filters={filterValues} onOpen={() => setShowFilterSheet(true)} />
- {/* Stats */}
- <div className="flex items-center justify-between text-sm text-muted-foreground">
- <p>
- {t("admin.showingLogs", {
- from: page * limit + 1,
- to: Math.min(page * limit + logs.length, total),
- total,
- })}
- </p>
- </div>
-
- {/* Bulk Actions Bar */}
- {selectedLogIds.length > 0 && isSuperAdmin && (
- <div className="flex items-center justify-between p-4 bg-muted rounded-lg border">
- <div className="flex items-center gap-3">
- <span className="text-sm font-medium">
- {t("admin.selectedLogs", { count: selectedLogIds.length })}
+ {selectedIds.length > 0 && isSuperAdmin && (
+ <div className="hidden items-center justify-between gap-3 rounded-[11px] border border-line bg-surface-panel px-3.5 py-2.5 lg:flex">
+ <div className="flex items-center gap-2">
+ <span className="text-[13px] font-semibold text-fg-strong">
+ {t("admin.selectedLogs", { count: selectedIds.length })}
</span>
- <Button variant="ghost" size="sm" onClick={clearSelection}>
- <X className="h-4 w-4 mr-2" />
+ <Button variant="ghost" size="sm" onClick={() => setSelectedLogIds([])} className="h-8 text-fg-secondary">
+ <X className="size-4" />
{t("admin.clearSelection")}
</Button>
</div>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => setShowDeleteDialog(true)}
- >
- <Trash2 className="h-4 w-4 mr-2" />
+ <Button variant="destructive" size="sm" onClick={() => setShowDeleteDialog(true)} className="h-8 font-semibold">
+ <Trash2 className="size-4" />
{t("common.deleteSelected")}
</Button>
</div>
)}
- {/* Table */}
- <div className="rounded-md border bg-card">
- <Table>
- <TableHeader>
- <TableRow>
- {isSuperAdmin && (
- <TableHead className="w-[50px]">
+ {/* Desktop table */}
+ <AdminTableCard
+ className="hidden lg:block"
+ footer={
+ total > 0 && (
+ <>
+ <span>{showing}</span>
+ {pager}
+ </>
+ )
+ }
+ >
+ <AdminTableHead
+ template={template}
+ columns={[
+ ...(isSuperAdmin
+ ? [
<Checkbox
+ key="all"
checked={isAllSelected}
onCheckedChange={toggleSelectAll}
+ aria-label={t("adminAudit.selectAll")}
+ />,
+ ]
+ : []),
+ "",
+ sortHeader("timestamp", t("admin.timestamp")),
+ sortHeader("action", t("common.labels.action")),
+ sortHeader("user", t("common.labels.user")),
+ sortHeader("severity", t("adminAudit.severityShort")),
+ t("adminAudit.whatHappened"),
+ sortHeader("ipAddress", t("common.labels.ipAddress")),
+ "",
+ ]}
+ />
+ {logs.length === 0 ? (
+ <div className="px-4 py-10 text-center text-[13px] text-fg-tertiary">{emptyText}</div>
+ ) : (
+ logs.map((log) => {
+ const expanded = expandedRows.has(log.id);
+ return (
+ <Fragment key={log.id}>
+ <AdminTableRow template={template} onClick={() => toggleRow(log.id)}>
+ {isSuperAdmin && (
+ <div onClick={stop} onKeyDown={stop} className="flex">
+ <Checkbox
+ checked={selectedIds.includes(log.id)}
+ onCheckedChange={() => toggleLogSelection(log.id)}
+ aria-label={t("adminAudit.selectEntry")}
+ />
+ </div>
+ )}
+ <ChevronRight
+ className={cn(
+ "size-[15px] transition-transform",
+ expanded ? "rotate-90 text-fg-secondary" : "text-fg-faint"
+ )}
/>
- </TableHead>
- )}
- <TableHead className="w-[50px]"></TableHead>
- <TableHead
- className="cursor-pointer select-none"
- onClick={() => handleSort("timestamp")}
- >
- <div className="flex items-center gap-2">
- {t("admin.timestamp")}
- {sortColumn === "timestamp" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer select-none"
- onClick={() => handleSort("action")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.action")}
- {sortColumn === "action" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer select-none"
- onClick={() => handleSort("user")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.user")}
- {sortColumn === "user" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer select-none"
- onClick={() => handleSort("severity")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.severity")}
- {sortColumn === "severity" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer select-none"
- onClick={() => handleSort("ipAddress")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.ipAddress")}
- {sortColumn === "ipAddress" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead className="w-[100px]"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {logs.length === 0 ? (
- <TableRow>
- <TableCell
- colSpan={isSuperAdmin ? 8 : 7}
- className="text-center py-8 text-muted-foreground"
- >
- {isLoading ? t("common.loading") : t("admin.noLogsFound")}
- </TableCell>
- </TableRow>
- ) : (
- logs.map((log) => (
- <React.Fragment key={log.id}>
- <TableRow
- className="cursor-pointer hover:bg-muted/50"
- onClick={() => toggleRow(log.id)}
+ <span className="font-mono text-[12.5px] text-fg-body">{formatTimestamp(log.timestamp)}</span>
+ <span className="max-w-full justify-self-start truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {log.action}
+ </span>
+ <span className={cn("truncate text-[13px]", log.userId ? "text-fg-body" : "text-fg-tertiary")}>
+ {userLabel(log)}
+ </span>
+ <span className="justify-self-start">
+ <SeverityPill severity={log.severity} />
+ </span>
+ <span className="truncate text-[12.5px] text-fg-tertiary">{describe(log)}</span>
+ <span className="truncate font-mono text-[12px] text-fg-tertiary">{log.ipAddress || "—"}</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ openDetails(log);
+ }}
+ onKeyDown={stop}
+ className="justify-self-end text-[12.5px] font-semibold text-brand-ink hover:underline"
>
- {isSuperAdmin && (
- <TableCell onClick={(e) => e.stopPropagation()}>
- <Checkbox
- checked={selectedLogIds.includes(log.id)}
- onCheckedChange={() => toggleLogSelection(log.id)}
- />
- </TableCell>
+ {t("adminAudit.details")}
+ </button>
+ </AdminTableRow>
+ {expanded && (
+ <div className="flex flex-col gap-2 border-b border-line-subtle bg-surface-panel px-4 py-3">
+ <div className="eyebrow">{t("admin.metadata")}</div>
+ <pre className="max-h-72 overflow-auto rounded-lg border border-line bg-background p-3 font-mono text-[12px] text-fg-body">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ {log.userAgent && (
+ <div className="text-[12px] text-fg-tertiary">
+ <span className="font-semibold text-fg-secondary">{t("admin.userAgent")}:</span>{" "}
+ {log.userAgent}
+ </div>
)}
- <TableCell>
- {expandedRows.has(log.id) ? (
- <ChevronDown className="h-4 w-4" />
- ) : (
- <ChevronRight className="h-4 w-4" />
- )}
- </TableCell>
- <TableCell className="whitespace-nowrap">
- {format(new Date(log.timestamp), "PPp", {
- locale: dateLocale,
- })}
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
- className={getActionColor(log.action)}
- >
- {log.action}
- </Badge>
- </TableCell>
- <TableCell>
- {log.userId ? (
- <div className="flex items-center gap-2">
- <Avatar className="h-6 w-6">
- {log.userImage && (
- <AvatarImage
- src={log.userImage}
- alt={log.userName || ""}
- />
- )}
- <AvatarFallback className="text-xs">
- {getUserInitials(log.userName)}
- </AvatarFallback>
- </Avatar>
- <span className="text-sm">
- {log.userName ||
- log.userEmail ||
- t("admin.unknownUser")}
- </span>
- </div>
- ) : (
- <span className="text-sm text-muted-foreground">
- {t("admin.systemAction")}
- </span>
- )}
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
- className={getSeverityColor(log.severity)}
- >
- {log.severity}
- </Badge>
- </TableCell>
- <TableCell className="text-sm text-muted-foreground">
- {log.ipAddress || "—"}
- </TableCell>
- <TableCell>
- <Button
- variant="ghost"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- setSelectedLog(log);
- setShowDetailsDialog(true);
- }}
- >
- {t("common.viewDetails")}
- </Button>
- </TableCell>
- </TableRow>
- {expandedRows.has(log.id) && (
- <TableRow>
- <TableCell
- colSpan={isSuperAdmin ? 8 : 7}
- className="bg-muted/50"
- >
- <div className="p-4 space-y-2">
- <div className="text-sm font-medium">
- {t("admin.metadata")}:
- </div>
- <pre className="text-xs bg-background p-3 rounded border overflow-x-auto">
- {JSON.stringify(log.metadata, null, 2)}
- </pre>
- {log.userAgent && (
- <div className="text-xs text-muted-foreground">
- <span className="font-medium">
- {t("admin.userAgent")}:
- </span>{" "}
- {log.userAgent}
- </div>
- )}
- </div>
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
- ))
- )}
- </TableBody>
- </Table>
- </div>
-
- {/* Pagination */}
- {total > limit && (
- <div className="flex items-center justify-between">
- <div className="text-sm text-muted-foreground">
- {t("admin.page")} {page + 1} {t("common.of")}{" "}
- {Math.ceil(total / limit)}
+ </div>
+ )}
+ </Fragment>
+ );
+ })
+ )}
+ </AdminTableCard>
+
+ {/* Phone cards */}
+ <div className="flex flex-col gap-[9px] lg:hidden">
+ {logs.length === 0 ? (
+ <div className="rounded-[11px] border border-line px-4 py-8 text-center text-[13px] text-fg-tertiary">
+ {emptyText}
</div>
- <div className="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={goToPreviousPage}
- disabled={page === 0}
- >
- <ChevronLeft className="h-4 w-4 mr-2" />
- {t("common.previous")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={goToNextPage}
- disabled={page * limit + logs.length >= total}
- >
- {t("common.next")}
- <ChevronRight className="h-4 w-4 ml-2" />
- </Button>
+ ) : (
+ logs.map((log) => (
+ <AdminMobileCard key={log.id} onClick={() => openDetails(log)}>
+ <div className="flex w-full items-center gap-2">
+ <span className="min-w-0 truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {log.action}
+ </span>
+ <span className="flex-1" />
+ <SeverityPill severity={log.severity} />
+ <ChevronRight className="size-4 shrink-0 text-fg-faint" />
+ </div>
+ <div className="text-[13.5px] leading-snug text-fg-body">{describe(log)}</div>
+ <div className="flex min-w-0 items-center gap-1.5 text-[12px] text-fg-tertiary">
+ <span className="truncate">{userLabel(log)}</span>
+ <span className="text-fg-faint">·</span>
+ <span className="shrink-0 font-mono">{formatTimestamp(log.timestamp)}</span>
+ </div>
+ </AdminMobileCard>
+ ))
+ )}
+ {total > PAGE_SIZE && (
+ <div className="flex items-center justify-between gap-3 pt-1 text-[12px] text-fg-tertiary">
+ <span className="min-w-0">{showing}</span>
+ {pager}
</div>
- </div>
- )}
+ )}
+ </div>
- {/* Dialogs */}
{selectedLog && (
- <AuditLogDetailsDialog
- open={showDetailsDialog}
- onOpenChange={setShowDetailsDialog}
- log={selectedLog}
- />
+ <AuditLogDetailsDialog open={showDetailsDialog} onOpenChange={setShowDetailsDialog} log={selectedLog} />
)}
<AuditLogDeleteDialog
open={showDeleteDialog}
onOpenChange={setShowDeleteDialog}
- selectedLogIds={selectedLogIds}
+ selectedLogIds={selectedIds}
onSuccess={() => {
setPage(0);
- clearSelection();
- // No manual refetch needed - React Query will auto-update
+ setSelectedLogIds([]);
}}
/>
+
+ <AuditFilterSheet
+ open={showFilterSheet}
+ onOpenChange={setShowFilterSheet}
+ filters={filterValues}
+ onChange={updateFilters}
+ onClear={clearFilters}
+ />
</div>
);
}
diff --git a/app/admin/page.tsx b/app/admin/page.tsx
index f9c72be..50d258a 100644
--- a/app/admin/page.tsx
+++ b/app/admin/page.tsx
@@ -1,332 +1,325 @@
"use client";
-import { useTranslations } from "next-intl";
+import { ReactNode } from "react";
+import Link from "next/link";
import { useRouter } from "next/navigation";
-import { useState, useEffect } from "react";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
+import { useLocale, useTranslations } from "next-intl";
+import { format, formatDistanceToNow } from "date-fns";
+import { ArrowUpCircle, ChevronRight, FolderClosed } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
-import { Badge } from "@/components/ui/badge";
-import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { StatsCardsGrid } from "@/components/admin/stats-cards";
+import { Pill } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { AdminPageHeader, SeverityPill } from "@/components/admin/admin-kit";
+import { useAdminSections } from "@/components/admin/admin-sidebar";
+import { useAuditDescription } from "@/components/admin/audit-describe";
import { useAdminStats } from "@/hooks/useAdminStats";
-import {
- FolderOpen,
- RefreshCw,
- Info,
- ExternalLink,
- GitCommit,
- Calendar as CalendarIcon,
- CheckCircle,
- AlertCircle,
-} from "lucide-react";
-import { formatDistanceToNow, format } from "date-fns";
+import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
+import { cn } from "@/lib/utils";
+import { useClientValue } from "@/hooks/useMediaQuery";
-interface VersionInfo {
- version: string;
- commitHash: string;
- buildDate: string;
- githubUrl: string;
- isDev: boolean;
- latestVersion?: string;
- latestUrl?: string;
- hasUpdate?: boolean;
+
+function ScaleValue({ value }: { value: number | undefined }) {
+ return (
+ <span
+ className={cn(
+ "shrink-0 font-mono text-[17px] font-medium",
+ !value ? "text-fg-faint" : "text-fg-strong"
+ )}
+ >
+ {value ?? "–"}
+ </span>
+ );
+}
+
+function SystemItem({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="flex items-center gap-[7px] whitespace-nowrap">
+ <span className="text-[11.5px] text-fg-faint">{label}</span>
+ {children}
+ </div>
+ );
}
-/**
- * Admin Dashboard Page
- *
- * Displays system statistics and quick actions.
- * Implemented in Phase 9.3
- */
export default function AdminDashboardPage() {
const t = useTranslations();
const router = useRouter();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
+ const describe = useAuditDescription();
+ const host = useClientValue(() => window.location.host, "");
- const { stats, isLoading: isLoadingStats } = useAdminStats();
- const [versionInfo, setVersionInfo] = useState<VersionInfo | null>(null);
- const [isLoadingVersion, setIsLoadingVersion] = useState(true);
-
- // Fetch version info
- useEffect(() => {
- fetchVersionInfo();
- }, []);
+ const { stats, isLoading: statsLoading } = useAdminStats();
+ const { versionInfo } = useVersionUpdateCheck();
+ const [, usersArea, calendarsArea, logsArea] = useAdminSections();
- const fetchVersionInfo = async () => {
- try {
- const response = await fetch("/api/version");
- if (!response.ok) return;
- const data = await response.json();
- setVersionInfo(data);
- } catch (error) {
- console.error("Failed to fetch version info:", error);
- } finally {
- setIsLoadingVersion(false);
- }
- };
+ // Admin actions plus security events, delivered with the stats
+ const activity = stats?.activity.logs ?? [];
+ const activityTotal = stats?.activity.total ?? 0;
- if (isLoadingStats && !stats) {
- return <FullscreenLoader />;
- }
+ const orphaned = stats?.calendars.orphaned ?? 0;
+ const hasUpdate = !!versionInfo?.hasUpdate && !versionInfo.isDev;
+ const attentionCount = (orphaned > 0 ? 1 : 0) + (hasUpdate ? 1 : 0);
- const hasOrphanedCalendars = stats && stats.calendars.orphaned > 0;
+ const buildDate =
+ versionInfo && versionInfo.buildDate !== "dev" && versionInfo.buildDate !== "unknown"
+ ? format(new Date(versionInfo.buildDate), "PPp", { locale: dateLocale })
+ : t("admin.systemInfo.unknown");
- return (
- <div className="space-y-6">
- {/* Welcome Message */}
- <div className="flex items-center justify-between">
- <div>
- <h2 className="text-3xl font-bold tracking-tight">
- {t("admin.dashboard")}
- </h2>
- <p className="text-muted-foreground mt-2">
- {t("admin.dashboardDescription")}
- </p>
- </div>
- </div>
+ const versionPill = versionInfo?.isDev ? (
+ <Pill tone="warning" className="text-[11px]">{t("admin.systemInfo.development")}</Pill>
+ ) : hasUpdate ? (
+ <Pill tone="brand" className="text-[11px]">{t("admin.systemInfo.updateAvailable")}</Pill>
+ ) : versionInfo ? (
+ <Pill tone="success" className="text-[11px]">{t("admin.systemInfo.upToDate")}</Pill>
+ ) : null;
- {/* System Information */}
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <div>
- <CardTitle className="pb-3">
- {t("admin.systemInfo.title")}
- </CardTitle>
- <CardDescription>
- {t("admin.systemInfo.description")}
- </CardDescription>
- </div>
- </div>
- {versionInfo?.hasUpdate && !versionInfo.isDev && (
- <Badge variant="default" className="gap-1">
- <AlertCircle className="h-3 w-3" />
- {t("admin.systemInfo.updateAvailable")}
- </Badge>
- )}
- {versionInfo && !versionInfo.hasUpdate && !versionInfo.isDev && (
- <Badge variant="secondary" className="gap-1">
- <CheckCircle className="h-3 w-3" />
- {t("admin.systemInfo.upToDate")}
- </Badge>
- )}
- </div>
- </CardHeader>
- <CardContent>
- {isLoadingVersion ? (
- <div className="flex items-center justify-center py-8 text-muted-foreground">
- <RefreshCw className="h-5 w-5 animate-spin mr-2" />
- {t("common.loading")}
- </div>
- ) : versionInfo ? (
- <div className="grid gap-4 md:grid-cols-2">
- {/* Version */}
- <div className="space-y-1">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Info className="h-4 w-4" />
- {t("admin.systemInfo.version")}
- </div>
- <div className="flex items-center gap-2">
- <code className="text-lg font-semibold font-mono">
- {versionInfo.version}
- </code>
- {versionInfo.isDev && (
- <Badge variant="outline">
- {t("admin.systemInfo.development")}
- </Badge>
- )}
- </div>
- </div>
+ const githubLink = versionInfo?.githubUrl && (
+ <a
+ href={versionInfo.githubUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[12.5px] font-semibold text-brand-ink hover:underline"
+ >
+ {t("admin.systemInfo.viewOnGitHub")}
+ </a>
+ );
- {/* Build Date */}
- <div className="space-y-1">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <CalendarIcon className="h-4 w-4" />
- {t("admin.systemInfo.buildDate")}
- </div>
- <div className="text-lg font-semibold">
- {versionInfo.buildDate !== "dev" &&
- versionInfo.buildDate !== "unknown"
- ? format(new Date(versionInfo.buildDate), "PPp", {
- locale: dateLocale,
- })
- : t("admin.systemInfo.unknown")}
- </div>
- </div>
+ const scaleRows = [
+ {
+ label: t("admin.usersMenu"),
+ value: stats?.users.total,
+ sub: stats
+ ? t("admin.stats.usersByRole", {
+ superadmin: stats.users.superadmin,
+ admin: stats.users.admin,
+ user: stats.users.user,
+ })
+ : "",
+ },
+ {
+ label: t("admin.calendarsMenu"),
+ value: stats ? stats.calendars.total + orphaned : undefined,
+ sub: stats
+ ? orphaned > 0
+ ? t("adminDashboard.calendarsOrphaned", { count: orphaned })
+ : t("adminDashboard.calendarsAllOwned")
+ : "",
+ },
+ { label: t("common.shifts"), value: stats?.shifts.total, sub: t("adminDashboard.acrossCalendars") },
+ {
+ label: t("common.labels.shares"),
+ value: stats?.shares.active,
+ sub: stats ? t("admin.stats.sharesDescription", { user: stats.shares.user, token: stats.shares.token }) : "",
+ },
+ { label: t("adminDashboard.events"), value: stats?.activity.recent, sub: t("admin.stats.last7Days") },
+ ];
- {/* Commit Hash */}
- <div className="space-y-1">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <GitCommit className="h-4 w-4" />
- {t("admin.systemInfo.commitHash")}
- </div>
- <div className="flex items-center gap-2">
- <code className="text-sm font-mono bg-muted px-2 py-1 rounded">
- {versionInfo.commitHash}
- </code>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 gap-1"
- asChild
- >
- <a
- href={versionInfo.githubUrl}
- target="_blank"
- rel="noopener noreferrer"
- >
- <ExternalLink className="h-3 w-3" />
- {t("admin.systemInfo.viewOnGitHub")}
- </a>
- </Button>
- </div>
- </div>
+ const areaRows = [
+ { ...usersArea, sub: stats ? t("adminDashboard.usersSub", { count: stats.users.total }) : "" },
+ {
+ ...calendarsArea,
+ sub: stats ? t("adminDashboard.calendarsSub", { count: stats.calendars.total + orphaned, orphaned }) : "",
+ },
+ { ...logsArea, sub: stats ? t("adminDashboard.logsSub", { count: stats.auditLogs.total }) : "" },
+ ];
- {/* Latest Version (if available) */}
- {versionInfo.latestVersion && !versionInfo.isDev && (
- <div className="space-y-1">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Info className="h-4 w-4" />
- {t("admin.systemInfo.latestVersion")}
- </div>
- <div className="flex items-center gap-2">
- <code className="text-lg font-semibold font-mono">
- {versionInfo.latestVersion}
- </code>
- {versionInfo.latestUrl && (
- <Button
- variant="ghost"
- size="sm"
- className="h-7 gap-1"
- asChild
- >
- <a
- href={versionInfo.latestUrl}
- target="_blank"
- rel="noopener noreferrer"
- >
- <ExternalLink className="h-3 w-3" />
- {t("admin.systemInfo.viewRelease")}
- </a>
- </Button>
- )}
- </div>
- </div>
- )}
- </div>
- ) : (
- <div className="text-center py-8 text-muted-foreground">
- {t("admin.systemInfo.unknown")}
+ return (
+ <div className="flex flex-col gap-[14px] lg:gap-[18px]">
+ <AdminPageHeader
+ title={
+ <>
+ <span className="lg:hidden">{t("admin.title")}</span>
+ <span className="hidden lg:inline">{t("adminDashboard.title")}</span>
+ </>
+ }
+ subtitle={
+ <>
+ <span className="font-mono lg:hidden">
+ {[host, versionInfo?.version, versionInfo?.commitHash].filter(Boolean).join(" · ")}
+ </span>
+ <span className="hidden lg:inline">
+ {attentionCount > 0
+ ? t("adminDashboard.attention", { count: attentionCount })
+ : t("adminDashboard.allClear")}
+ </span>
+ </>
+ }
+ actions={
+ versionInfo && (
+ <div className="flex flex-wrap items-center justify-end gap-x-5 gap-y-2">
+ <SystemItem label={t("admin.systemInfo.version")}>
+ <span className="font-mono text-[14px] font-semibold text-fg-strong">{versionInfo.version}</span>
+ {versionPill}
+ </SystemItem>
+ <SystemItem label={t("admin.systemInfo.buildDate")}>
+ <span className="text-[14px] font-semibold text-fg-strong">{buildDate}</span>
+ </SystemItem>
+ <SystemItem label={t("admin.systemInfo.commitHash")}>
+ <span className="font-mono text-[14px] font-semibold text-fg-strong">{versionInfo.commitHash}</span>
+ {githubLink}
+ </SystemItem>
</div>
- )}
- </CardContent>
- </Card>
+ )
+ }
+ />
- {/* Orphaned Calendars Warning */}
- {hasOrphanedCalendars && (
- <Card className="border-yellow-500 bg-yellow-50 dark:bg-yellow-950/20">
- <CardHeader>
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <FolderOpen className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />
- <div>
- <CardTitle className="text-yellow-900 dark:text-yellow-100">
- {t("admin.orphanedCalendarsWarning")}
- </CardTitle>
- <CardDescription className="text-yellow-700 dark:text-yellow-300">
- {t("admin.orphanedCalendarsWarningDescription", {
- count: stats!.calendars.orphaned,
- })}
- </CardDescription>
- </div>
- </div>
- <Button
- variant="outline"
- onClick={() => router.push("/admin/calendars")}
- className="border-yellow-600 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30"
- >
- {t("admin.manageOrphanedCalendars")}
+ {orphaned > 0 && (
+ <StatusBanner
+ tone="warning"
+ icon={FolderClosed}
+ title={t("admin.orphanedCalendarsWarning")}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => router.push("/admin/calendars")}
+ className="h-8 rounded-lg font-semibold"
+ >
+ {t("adminDashboard.openCalendars")}
+ </Button>
+ }
+ >
+ {t("admin.orphanedCalendarsWarningDescription", { count: orphaned })}
+ </StatusBanner>
+ )}
+
+ {hasUpdate && versionInfo?.latestVersion && (
+ <StatusBanner
+ tone="info"
+ icon={ArrowUpCircle}
+ title={t("admin.systemInfo.updateAvailable")}
+ action={
+ versionInfo.latestUrl && (
+ <Button variant="outline" size="sm" asChild className="h-8 rounded-lg font-semibold">
+ <a href={versionInfo.latestUrl} target="_blank" rel="noopener noreferrer">
+ {t("admin.systemInfo.viewRelease")}
+ </a>
</Button>
- </div>
- </CardHeader>
- </Card>
+ )
+ }
+ >
+ {t("admin.systemInfo.latestVersion")}: <span className="font-mono">{versionInfo.latestVersion}</span>
+ </StatusBanner>
)}
- {/* Stats Cards */}
- <StatsCardsGrid stats={stats} isLoading={isLoadingStats} />
+ <div className="grid gap-[14px] lg:grid-cols-[minmax(0,1fr)_320px] lg:gap-[18px]">
+ {/* Recent activity */}
+ <section className="flex min-w-0 flex-col gap-2 lg:gap-0 lg:overflow-hidden lg:rounded-[12px] lg:border lg:border-line lg:bg-surface-card">
+ <div className="flex items-center justify-between gap-3 lg:border-b lg:border-line lg:px-4 lg:py-[13px]">
+ <div className="min-w-0">
+ <h2>
+ <span className="eyebrow lg:hidden">{t("adminDashboard.recentShort")}</span>
+ <span className="hidden text-[14px] font-semibold text-fg-strong lg:inline">
+ {t("adminDashboard.recentTitle")}
+ </span>
+ </h2>
+ <p className="mt-0.5 hidden text-[12.5px] text-fg-tertiary lg:block">
+ {t("admin.recentActivityDescription")}
+ </p>
+ </div>
+ <Link href="/admin/logs" className="shrink-0 text-[12.5px] font-semibold text-brand-ink hover:underline">
+ {t("common.viewAll")}
+ </Link>
+ </div>
- {/* Recent Activity Preview */}
- {stats?.activity.logs && stats.activity.logs.length > 0 && (
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between">
- <CardTitle>{t("admin.stats.recentActivity")}</CardTitle>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => router.push("/admin/logs")}
- >
- {t("common.viewAll")}
- </Button>
+ {activity.length === 0 ? (
+ <div className="rounded-[11px] border border-line px-4 py-8 text-center text-[13px] text-fg-tertiary lg:rounded-none lg:border-0">
+ {statsLoading ? t("common.loading") : t("admin.noLogsFound")}
</div>
- <CardDescription>
- {t("admin.recentActivityDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-3">
- {stats.activity.logs.map((log, index) => (
- <div key={log.id}>
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <Badge
- variant={
- log.severity === "error"
- ? "destructive"
- : log.severity === "warning"
- ? "outline"
- : "secondary"
- }
- >
- {log.severity}
- </Badge>
- <div className="text-sm">
- <span className="font-medium">{log.action}</span>
- {log.resourceType && (
- <span className="text-muted-foreground">
- {" "}
- • {log.resourceType}
- </span>
- )}
- </div>
- </div>
- <span className="text-xs text-muted-foreground">
- {formatDistanceToNow(log.timestamp, {
- addSuffix: true,
- locale: dateLocale,
- })}
+ ) : (
+ <ul className="flex flex-col gap-2 lg:gap-0 lg:px-4 lg:pt-1">
+ {activity.map((log) => (
+ <li
+ key={log.id}
+ className="flex flex-col gap-[7px] rounded-[11px] border border-line bg-surface-card px-3 py-[11px] lg:flex-row lg:items-center lg:gap-3 lg:rounded-none lg:border-0 lg:border-b lg:border-line-subtle lg:bg-transparent lg:px-0 lg:py-3"
+ >
+ <div className="flex items-center gap-[9px] lg:contents">
+ <SeverityPill severity={log.severity} />
+ <span className="truncate font-mono text-[12px] text-fg-tertiary lg:order-2 lg:shrink-0">
+ {log.action}
+ </span>
+ <span className="ml-auto shrink-0 whitespace-nowrap text-[11.5px] text-fg-faint lg:order-3 lg:ml-0 lg:w-[100px] lg:text-right lg:text-[12.5px]">
+ {formatDistanceToNow(log.timestamp, { addSuffix: true, locale: dateLocale })}
</span>
</div>
- {index < stats.activity.logs.length - 1 && (
- <Separator className="mt-3" />
- )}
+ <span className="text-[13px] leading-[1.45] text-fg-body lg:order-1 lg:min-w-0 lg:flex-1 lg:truncate lg:text-[13.5px] lg:text-fg-strong">
+ {describe(log)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className="mt-auto hidden border-t border-line bg-surface-panel px-4 py-3 text-[12.5px] text-fg-tertiary lg:block">
+ {t("adminDashboard.activityFooter", { shown: activity.length, count: activityTotal })}
+ </div>
+ </section>
+
+ <div className="flex min-w-0 flex-col gap-[14px]">
+ {/* Scale */}
+ <section className="flex flex-col gap-2 lg:gap-0">
+ <h2 className="eyebrow lg:hidden">{t("adminDashboard.scope")}</h2>
+ <div className="overflow-hidden rounded-[11px] border border-line bg-surface-card lg:rounded-[12px]">
+ <div className="eyebrow hidden border-b border-line px-[15px] py-[11px] lg:block">
+ {t("adminDashboard.scope")}
+ </div>
+ {scaleRows.map((row) => (
+ <div
+ key={row.label}
+ className="flex items-center gap-3 border-b border-line-subtle px-3 py-[9px] last:border-b-0 lg:px-[15px] lg:py-2.5"
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-3 lg:block">
+ <div className="flex-1 text-[13px] font-semibold text-fg-body">{row.label}</div>
+ <div className="truncate text-[11.5px] text-fg-faint lg:mt-px">{row.sub}</div>
+ </div>
+ <ScaleValue value={row.value} />
</div>
))}
</div>
- </CardContent>
- </Card>
- )}
+ </section>
+
+ {/* Jump links; phones reach the areas through the tab bar */}
+ <nav className="hidden overflow-hidden rounded-[12px] border border-line bg-surface-card lg:block">
+ {areaRows.map((area) => (
+ <Link
+ key={area.href}
+ href={area.href}
+ className="flex items-center gap-[11px] border-b border-line-subtle px-[15px] py-3 transition-colors last:border-b-0 hover:bg-surface-panel"
+ >
+ <area.icon className="size-4 shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="text-[13.5px] font-semibold text-fg-strong">{area.label}</div>
+ <div className="mt-px truncate text-[11.5px] text-fg-tertiary">{area.sub}</div>
+ </div>
+ <ChevronRight className="size-4 shrink-0 text-fg-faint" />
+ </Link>
+ ))}
+ </nav>
+
+ {/* Phones: system details that the desktop header shows inline */}
+ <section className="flex flex-col gap-2 lg:hidden">
+ <h2 className="eyebrow">{t("admin.systemInfo.title")}</h2>
+ <div className="flex flex-col gap-2.5 rounded-[11px] border border-line bg-surface-card px-3 py-3">
+ <SystemItem label={t("admin.systemInfo.version")}>
+ <span className="font-mono text-[13px] font-semibold text-fg-strong">
+ {versionInfo?.version ?? "–"}
+ </span>
+ {versionPill}
+ </SystemItem>
+ <SystemItem label={t("admin.systemInfo.buildDate")}>
+ <span className="text-[13px] font-semibold text-fg-strong">{versionInfo ? buildDate : "–"}</span>
+ </SystemItem>
+ <SystemItem label={t("admin.systemInfo.commitHash")}>
+ <span className="font-mono text-[13px] font-semibold text-fg-strong">
+ {versionInfo?.commitHash ?? "–"}
+ </span>
+ {githubLink}
+ </SystemItem>
+ </div>
+ </section>
+ </div>
+ </div>
</div>
);
}
diff --git a/app/admin/users/page.tsx b/app/admin/users/page.tsx
index a866e58..96f4a09 100644
--- a/app/admin/users/page.tsx
+++ b/app/admin/users/page.tsx
@@ -1,17 +1,21 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useTranslations } from "next-intl";
-import { Search, Filter } from "lucide-react";
-import { Input } from "@/components/ui/input";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { FullscreenLoader } from "@/components/fullscreen-loader";
+import { SegmentedControl } from "@/components/segmented-control";
+import { ChoiceChips } from "@/components/form-kit";
+import { AdminPageHeader, AdminSearch } from "@/components/admin/admin-kit";
+import { FilterMenuButton, type SortState } from "@/components/admin/admin-table-controls";
import { UserTable } from "@/components/admin/user-table";
import { UserEditSheet } from "@/components/admin/user-edit-sheet";
import { UserDetailsSheet } from "@/components/admin/user-details-sheet";
@@ -19,51 +23,60 @@ import { UserBanDialog } from "@/components/admin/user-ban-dialog";
import { UserUnbanDialog } from "@/components/admin/user-unban-dialog";
import { UserDeleteDialog } from "@/components/admin/user-delete-dialog";
import { UserPasswordResetDialog } from "@/components/admin/user-password-reset-dialog";
+import { useAdminUserActions, useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";
+import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";
import {
- useAdminUsers,
- type AdminUser,
- type UserFilters,
- type UserSort,
-} from "@/hooks/useAdminUsers";
+ ADMIN_PAGE_SIZE,
+ type UserListParams,
+ type UserRoleFilter,
+ type UserSortField,
+ type UserStatusFilter,
+} from "@/lib/admin-list";
+
+type Preset = "all" | "superadmin" | "banned";
export default function AdminUsersPage() {
const t = useTranslations();
- // Filters & Sort
- const [searchQuery, setSearchQuery] = useState("");
- const [roleFilter, setRoleFilter] = useState<
- "all" | "superadmin" | "admin" | "user"
- >("all");
- const [statusFilter, setStatusFilter] = useState<"all" | "active" | "banned">(
- "all"
- );
- const sortField = "createdAt" as const;
- const sortDirection = "desc" as const;
+ const search = useDebouncedSearch();
+ const [roleFilter, setRoleFilter] = useState<UserRoleFilter>("all");
+ const [statusFilter, setStatusFilter] = useState<UserStatusFilter>("all");
+ const [sort, setSort] = useState<SortState<UserSortField>>({ column: "createdAt", direction: "desc" });
- // Build filters, sort, and pagination
- const filters: UserFilters = {
- search: searchQuery || undefined,
- role: roleFilter,
- status: statusFilter,
- };
+ // Any change to search, filters or sort starts over on the first page
+ const listKey = [search.query, roleFilter, statusFilter, sort.column, sort.direction].join("|");
+ const [requestedPage, setPage] = useResettableState(listKey, 1);
- const sort: UserSort = {
- field: sortField,
- direction: sortDirection,
- };
+ const params = useMemo<UserListParams>(
+ () => ({
+ search: search.query,
+ role: roleFilter,
+ status: statusFilter,
+ sort: sort.column,
+ order: sort.direction,
+ page: requestedPage,
+ limit: ADMIN_PAGE_SIZE,
+ }),
+ [search.query, roleFilter, statusFilter, sort, requestedPage]
+ );
+
+ const { users, total, counts, page, isLoading, isPlaceholderData } = useAdminUsers(params);
+ const { banUser, unbanUser, deleteUser, resetPassword } = useAdminUserActions();
- const pagination = { page: 1, limit: 1000 };
+ // The segments cover the common cases; anything else lives in the filter menu.
+ const preset: Preset | "custom" =
+ roleFilter === "all" && statusFilter === "all"
+ ? "all"
+ : roleFilter === "superadmin" && statusFilter === "all"
+ ? "superadmin"
+ : roleFilter === "all" && statusFilter === "banned"
+ ? "banned"
+ : "custom";
- // Use hook with filters
- const {
- users,
- total: totalUsers,
- isLoading,
- banUser,
- unbanUser,
- deleteUser,
- resetPassword,
- } = useAdminUsers(filters, sort, pagination);
+ const applyPreset = (value: Preset) => {
+ setRoleFilter(value === "superadmin" ? "superadmin" : "all");
+ setStatusFilter(value === "banned" ? "banned" : "all");
+ };
// Dialogs & Sheets
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
@@ -74,239 +87,178 @@ export default function AdminUsersPage() {
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showPasswordDialog, setShowPasswordDialog] = useState(false);
- // Handlers
- const handleUserClick = (user: AdminUser) => {
+ const openFor = (setter: (open: boolean) => void) => (user: AdminUser) => {
setSelectedUser(user);
- setShowDetailsSheet(true);
+ setter(true);
};
- const handleEditUser = (user: AdminUser) => {
- setSelectedUser(user);
- setShowEditSheet(true);
- };
-
- const handleResetPassword = (user: AdminUser) => {
- setSelectedUser(user);
- setShowPasswordDialog(true);
- };
-
- const handleBanUser = (user: AdminUser) => {
- setSelectedUser(user);
- setShowBanDialog(true);
- };
-
- const handleUnbanUser = (user: AdminUser) => {
- setSelectedUser(user);
- setShowUnbanDialog(true);
- };
-
- const handleDeleteUser = (user: AdminUser) => {
- setSelectedUser(user);
- setShowDeleteDialog(true);
+ const fromDetails = (setter: (open: boolean) => void) => () => {
+ setShowDetailsSheet(false);
+ setter(true);
};
const handleBanConfirm = async (reason: string, expiresAt?: Date) => {
if (!selectedUser) return;
- const success = await banUser(selectedUser.id, reason, expiresAt);
- if (success) {
- setShowBanDialog(false);
- }
+ if (await banUser(selectedUser.id, reason, expiresAt)) setShowBanDialog(false);
};
const handleUnbanConfirm = async () => {
if (!selectedUser) return;
- const success = await unbanUser(selectedUser.id);
- if (success) {
- setShowUnbanDialog(false);
- }
+ if (await unbanUser(selectedUser.id)) setShowUnbanDialog(false);
};
const handleDeleteConfirm = async () => {
if (!selectedUser) return;
- const success = await deleteUser(selectedUser.id);
- if (success) {
- setShowDeleteDialog(false);
- }
+ if (await deleteUser(selectedUser.id)) setShowDeleteDialog(false);
};
const handlePasswordResetConfirm = async (newPassword: string) => {
if (!selectedUser) return;
- const success = await resetPassword(selectedUser.id, newPassword);
- if (success) {
- setShowPasswordDialog(false);
- }
+ if (await resetPassword(selectedUser.id, newPassword)) setShowPasswordDialog(false);
};
- if (isLoading && users.length === 0) {
+ if (isLoading && !counts) {
return <FullscreenLoader />;
}
+ const filterMenu = (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <FilterMenuButton label={t("adminUsers.moreFilters")} active={preset === "custom"} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuLabel>{t("admin.role")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={roleFilter}
+ onValueChange={(value) => setRoleFilter(value as UserRoleFilter)}
+ >
+ <DropdownMenuRadioItem value="all">{t("admin.allRoles")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="superadmin">{t("common.roles.superadmin")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="admin">{t("common.roles.admin")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="user">{t("common.roles.user")}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{t("common.labels.status")}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={statusFilter}
+ onValueChange={(value) => setStatusFilter(value as UserStatusFilter)}
+ >
+ <DropdownMenuRadioItem value="all">{t("admin.allStatuses")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="active">{t("common.status.active")}</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="banned">{t("admin.banned")}</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+
return (
<>
- <div className="space-y-6">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div>
- <h2 className="text-3xl font-bold tracking-tight">
- {t("admin.userManagement")}
- </h2>
- <p className="text-muted-foreground mt-2">
- {t("admin.userManagementDescription")}
- </p>
- </div>
- </div>
+ <div className="flex flex-col gap-4">
+ <AdminPageHeader
+ title={t("admin.usersMenu")}
+ subtitle={
+ counts ? t("adminUsers.subtitle", { count: counts.total, banned: counts.banned }) : undefined
+ }
+ />
- {/* Filters */}
- <div className="flex flex-col sm:flex-row gap-4">
- {/* Search */}
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("admin.searchUsers")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- />
+ <div className="flex flex-col gap-[11px] lg:flex-row lg:items-center lg:gap-[9px]">
+ <AdminSearch
+ value={search.input}
+ onChange={search.setInput}
+ placeholder={t("admin.searchUsers")}
+ className="lg:w-[340px]"
+ />
+ <SegmentedControl
+ value={preset as Preset}
+ onChange={applyPreset}
+ label={t("adminUsers.filterLabel")}
+ className="hidden lg:flex [&>button]:flex-none [&>button]:px-[13px]"
+ options={[
+ { value: "all", label: t("admin.allRoles") },
+ { value: "superadmin", label: t("common.roles.superadmin") },
+ { value: "banned", label: t("admin.banned") },
+ ]}
+ />
+ <div className="flex items-center gap-[7px] lg:hidden">
+ <div className="min-w-0 flex-1 overflow-x-auto">
+ <ChoiceChips
+ value={preset === "custom" ? undefined : preset}
+ onChange={applyPreset}
+ label={t("adminUsers.filterLabel")}
+ options={[
+ { value: "all", label: `${t("adminUsers.all")} ${counts?.total ?? ""}` },
+ { value: "superadmin", label: `${t("common.roles.superadmin")} ${counts?.superadmin ?? ""}` },
+ { value: "banned", label: `${t("admin.banned")} ${counts?.banned ?? ""}` },
+ ]}
+ />
+ </div>
+ {filterMenu}
</div>
-
- {/* Role Filter */}
- <Select
- value={roleFilter}
- onValueChange={(value: "all" | "superadmin" | "admin" | "user") =>
- setRoleFilter(value)
- }
- >
- <SelectTrigger className="w-full sm:w-[180px]">
- <Filter className="h-4 w-4 mr-2" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t("admin.allRoles")}</SelectItem>
- <SelectItem value="superadmin">
- {t("common.roles.superadmin")}
- </SelectItem>
- <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>
- <SelectItem value="user">{t("common.roles.user")}</SelectItem>
- </SelectContent>
- </Select>
-
- {/* Status Filter */}
- <Select
- value={statusFilter}
- onValueChange={(value: "all" | "active" | "banned") =>
- setStatusFilter(value)
- }
- >
- <SelectTrigger className="w-full sm:w-[180px]">
- <Filter className="h-4 w-4 mr-2" />
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">{t("admin.allStatuses")}</SelectItem>
- <SelectItem value="active">
- {t("common.status.active")}
- </SelectItem>
- <SelectItem value="banned">{t("admin.banned")}</SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Results Count */}
- <div className="flex items-center justify-between text-sm text-muted-foreground">
- <p>{t("admin.usersCount", { count: totalUsers })}</p>
+ <div className="hidden lg:block">{filterMenu}</div>
</div>
- {/* Table */}
<UserTable
users={users}
- isLoading={isLoading}
- onUserClick={handleUserClick}
- onEditUser={handleEditUser}
- onResetPassword={handleResetPassword}
- onBanUser={handleBanUser}
- onUnbanUser={handleUnbanUser}
- onDeleteUser={handleDeleteUser}
+ total={total}
+ page={page}
+ pageSize={ADMIN_PAGE_SIZE}
+ onPageChange={setPage}
+ sort={sort}
+ onSortChange={setSort}
+ isStale={isPlaceholderData}
+ onUserClick={openFor(setShowDetailsSheet)}
+ onEditUser={openFor(setShowEditSheet)}
+ onResetPassword={openFor(setShowPasswordDialog)}
+ onBanUser={openFor(setShowBanDialog)}
+ onUnbanUser={openFor(setShowUnbanDialog)}
+ onDeleteUser={openFor(setShowDeleteDialog)}
/>
</div>
- {/* Edit Sheet */}
{selectedUser && (
- <UserEditSheet
- key={selectedUser.id}
- open={showEditSheet}
- onOpenChange={setShowEditSheet}
- user={selectedUser}
- onSuccess={() => {}}
- />
- )}
-
- {/* Details Sheet */}
- {selectedUser && (
- <UserDetailsSheet
- open={showDetailsSheet}
- onOpenChange={setShowDetailsSheet}
- userId={selectedUser.id}
- onEdit={() => {
- setShowDetailsSheet(false);
- setShowEditSheet(true);
- }}
- onResetPassword={() => {
- setShowDetailsSheet(false);
- setShowPasswordDialog(true);
- }}
- onBan={() => {
- setShowDetailsSheet(false);
- setShowBanDialog(true);
- }}
- onUnban={() => {
- setShowDetailsSheet(false);
- setShowUnbanDialog(true);
- }}
- onDelete={() => {
- setShowDetailsSheet(false);
- setShowDeleteDialog(true);
- }}
- />
- )}
-
- {/* Ban Dialog */}
- {selectedUser && (
- <UserBanDialog
- open={showBanDialog}
- onOpenChange={setShowBanDialog}
- user={selectedUser}
- onConfirm={handleBanConfirm}
- />
- )}
-
- {/* Unban Dialog */}
- {selectedUser && (
- <UserUnbanDialog
- open={showUnbanDialog}
- onOpenChange={setShowUnbanDialog}
- user={selectedUser}
- onConfirm={handleUnbanConfirm}
- />
- )}
-
- {/* Delete Dialog */}
- {selectedUser && (
- <UserDeleteDialog
- open={showDeleteDialog}
- onOpenChange={setShowDeleteDialog}
- user={selectedUser}
- onConfirm={handleDeleteConfirm}
- />
- )}
-
- {/* Password Reset Dialog */}
- {selectedUser && (
- <UserPasswordResetDialog
- open={showPasswordDialog}
- onOpenChange={setShowPasswordDialog}
- user={selectedUser}
- onConfirm={handlePasswordResetConfirm}
- />
+ <>
+ <UserEditSheet
+ key={`edit-${selectedUser.id}`}
+ open={showEditSheet}
+ onOpenChange={setShowEditSheet}
+ user={selectedUser}
+ />
+ <UserDetailsSheet
+ key={`details-${selectedUser.id}`}
+ open={showDetailsSheet}
+ onOpenChange={setShowDetailsSheet}
+ userId={selectedUser.id}
+ onEdit={fromDetails(setShowEditSheet)}
+ onResetPassword={fromDetails(setShowPasswordDialog)}
+ onBan={fromDetails(setShowBanDialog)}
+ onUnban={fromDetails(setShowUnbanDialog)}
+ onDelete={fromDetails(setShowDeleteDialog)}
+ />
+ <UserBanDialog
+ open={showBanDialog}
+ onOpenChange={setShowBanDialog}
+ user={selectedUser}
+ onConfirm={handleBanConfirm}
+ />
+ <UserUnbanDialog
+ open={showUnbanDialog}
+ onOpenChange={setShowUnbanDialog}
+ user={selectedUser}
+ onConfirm={handleUnbanConfirm}
+ />
+ <UserDeleteDialog
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
+ user={selectedUser}
+ onConfirm={handleDeleteConfirm}
+ />
+ <UserPasswordResetDialog
+ open={showPasswordDialog}
+ onOpenChange={setShowPasswordDialog}
+ user={selectedUser}
+ onConfirm={handlePasswordResetConfirm}
+ />
+ </>
)}
</>
);
diff --git a/app/api/activity-logs/route.ts b/app/api/activity-logs/route.ts
index 1944284..6efab09 100644
--- a/app/api/activity-logs/route.ts
+++ b/app/api/activity-logs/route.ts
@@ -7,6 +7,7 @@ import {
type CalendarPermission,
} from "@/lib/auth/permissions";
import { eq, and, desc, gte, lte, inArray, sql } from "drizzle-orm";
+import { parseLocalDate } from "@/lib/date-utils";
// Unified activity log format
interface UnifiedActivityLog {
@@ -25,8 +26,8 @@ interface UnifiedActivityLog {
*
* Query params:
* - type: Filter by action type prefix (security, calendar, sync, auth)
- * - startDate: ISO date string (inclusive)
- * - endDate: ISO date string (inclusive)
+ * - startDate: local day YYYY-MM-DD (inclusive)
+ * - endDate: local day YYYY-MM-DD (inclusive)
* - page: Page number (0-based, default: 0)
* - limit: Items per page (default: 50, max: 100)
*/
@@ -47,6 +48,18 @@ export async function GET(request: NextRequest) {
const limit = Math.min(parseInt(searchParams.get("limit") || "50", 10), 100);
const offset = parseInt(searchParams.get("offset") || "0", 10);
+ let start: Date | null = null;
+ let end: Date | null = null;
+ try {
+ if (startDate) start = parseLocalDate(startDate);
+ if (endDate) {
+ end = parseLocalDate(endDate);
+ end.setHours(23, 59, 59, 999);
+ }
+ } catch {
+ return NextResponse.json({ error: "Invalid date format" }, { status: 400 });
+ }
+
try {
// Fetch all logs and merge them before pagination
const allLogs: UnifiedActivityLog[] = [];
@@ -71,13 +84,11 @@ export async function GET(request: NextRequest) {
}
// Filter by date range
- if (startDate) {
- const start = new Date(startDate);
+ if (start) {
auditConditions.push(gte(auditLogs.timestamp, start));
}
- if (endDate) {
- const end = new Date(endDate);
+ if (end) {
auditConditions.push(lte(auditLogs.timestamp, end));
}
@@ -122,13 +133,11 @@ export async function GET(request: NextRequest) {
const syncConditions = [inArray(syncLogs.calendarId, calendarIds)];
// Filter by date range
- if (startDate) {
- const start = new Date(startDate);
+ if (start) {
syncConditions.push(gte(syncLogs.syncedAt, start));
}
- if (endDate) {
- const end = new Date(endDate);
+ if (end) {
syncConditions.push(lte(syncLogs.syncedAt, end));
}
diff --git a/app/api/admin/audit-logs/route.ts b/app/api/admin/audit-logs/route.ts
index 6a646da..975b230 100644
--- a/app/api/admin/audit-logs/route.ts
+++ b/app/api/admin/audit-logs/route.ts
@@ -1,13 +1,14 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { auditLogs, user } from "@/lib/db/schema";
-import { sql, eq, desc, and, or, lt } from "drizzle-orm";
+import { sql, eq, desc, and, or, lt, inArray } from "drizzle-orm";
import { requireAdmin } from "@/lib/auth/admin";
import {
getValidatedAdminUser,
isErrorResponse,
} from "@/lib/auth/admin-helpers";
import { logAdminAction } from "@/lib/audit-log";
+import { parseLocalDate } from "@/lib/date-utils";
/**
* Admin Audit Logs API
@@ -22,8 +23,8 @@ import { logAdminAction } from "@/lib/audit-log";
* - resourceId: Filter by specific resource ID
* - severity: Filter by severity (info, warning, error, critical)
* - search: Search in action, resourceType, or metadata (case-insensitive)
- * - startDate: Filter logs after this date (ISO string)
- * - endDate: Filter logs before this date (ISO string)
+ * - startDate: Filter logs from this local day on (YYYY-MM-DD, inclusive)
+ * - endDate: Filter logs up to this local day (YYYY-MM-DD, inclusive)
* - sortBy: Sort field (timestamp, action, severity)
* - sortOrder: Sort direction (asc, desc)
* - limit: Number of logs to return (default: 50, max: 500)
@@ -105,27 +106,32 @@ export async function GET(request: NextRequest) {
);
}
- // Date range filters
+ // Date range filters (local YYYY-MM-DD days, inclusive)
if (startDate) {
- const startTimestamp = new Date(startDate);
- if (!isNaN(startTimestamp.getTime())) {
- // Set to start of day (00:00:00)
- startTimestamp.setHours(0, 0, 0, 0);
- // Convert to Unix timestamp (seconds)
- const unixTimestamp = Math.floor(startTimestamp.getTime() / 1000);
- conditions.push(sql`${auditLogs.timestamp} >= ${unixTimestamp}`);
+ let startTimestamp: Date;
+ try {
+ startTimestamp = parseLocalDate(startDate);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid startDate" },
+ { status: 400 }
+ );
}
+ startTimestamp.setHours(0, 0, 0, 0);
+ const unixTimestamp = Math.floor(startTimestamp.getTime() / 1000);
+ conditions.push(sql`${auditLogs.timestamp} >= ${unixTimestamp}`);
}
if (endDate) {
- const endTimestamp = new Date(endDate);
- if (!isNaN(endTimestamp.getTime())) {
- // Set to end of day (23:59:59)
- endTimestamp.setHours(23, 59, 59, 999);
- // Convert to Unix timestamp (seconds)
- const unixTimestamp = Math.floor(endTimestamp.getTime() / 1000);
- conditions.push(sql`${auditLogs.timestamp} <= ${unixTimestamp}`);
+ let endTimestamp: Date;
+ try {
+ endTimestamp = parseLocalDate(endDate);
+ } catch {
+ return NextResponse.json({ error: "Invalid endDate" }, { status: 400 });
}
+ endTimestamp.setHours(23, 59, 59, 999);
+ const unixTimestamp = Math.floor(endTimestamp.getTime() / 1000);
+ conditions.push(sql`${auditLogs.timestamp} <= ${unixTimestamp}`);
}
// Apply sorting
@@ -228,7 +234,7 @@ export async function GET(request: NextRequest) {
* Delete old audit logs (bulk operation).
*
* Delete Methods:
- * 1. Query Parameter: ?before=2024-01-01 (delete logs older than date)
+ * 1. Query Parameter: ?before=2024-01-01 (delete logs before that local day)
* 2. Request Body: { logIds: [...] } (delete specific logs by ID)
*
* Permission: Superadmin only
@@ -253,9 +259,10 @@ export async function DELETE(request: NextRequest) {
// Method 1: Delete by date (query parameter)
if (beforeDate) {
- const beforeTimestamp = new Date(beforeDate);
-
- if (isNaN(beforeTimestamp.getTime())) {
+ let beforeTimestamp: Date;
+ try {
+ beforeTimestamp = parseLocalDate(beforeDate);
+ } catch {
return NextResponse.json(
{ error: "Invalid date format" },
{ status: 400 }
@@ -303,15 +310,12 @@ export async function DELETE(request: NextRequest) {
}
// Delete logs by IDs
- const deletePromises = logIds.map((id) =>
- db
- .delete(auditLogs)
- .where(eq(auditLogs.id, id))
- .returning({ id: auditLogs.id })
- );
+ const deleted = await db
+ .delete(auditLogs)
+ .where(inArray(auditLogs.id, logIds))
+ .returning({ id: auditLogs.id });
- const results = await Promise.all(deletePromises);
- deletedCount = results.filter((r) => r.length > 0).length;
+ deletedCount = deleted.length;
// Log admin action
await logAdminAction({
diff --git a/app/api/admin/calendars/route.ts b/app/api/admin/calendars/route.ts
index 466d163..6307c92 100644
--- a/app/api/admin/calendars/route.ts
+++ b/app/api/admin/calendars/route.ts
@@ -10,27 +10,64 @@ import {
calendarAccessTokens,
externalSyncs,
} from "@/lib/db/schema";
-import { sql, eq, and, isNull } from "drizzle-orm";
-import { requireAdmin } from "@/lib/auth/admin";
+import { and, asc, count, desc, eq, or, sql, type SQL } from "drizzle-orm";
+import type { SQLiteColumn, SQLiteTable } from "drizzle-orm/sqlite-core";
+import { isAdmin } from "@/lib/auth/admin";
import {
getValidatedAdminUser,
isErrorResponse,
} from "@/lib/auth/admin-helpers";
+import {
+ CALENDAR_CONTENT_FILTERS,
+ CALENDAR_OWNER_FILTERS,
+ CALENDAR_SORT_FIELDS,
+ SORT_ORDERS,
+ clampPage,
+ containsPattern,
+ parsePaging,
+ pickParam,
+ type CalendarListCounts,
+} from "@/lib/admin-list";
+
+// A calendar is orphaned when it has no owner row, whether owner_id is null or dangling
+const orphaned = sql`${user.id} is null`;
+const hasUserShares = sql`exists (select 1 from ${calendarShares} where ${calendarShares.calendarId} = ${calendars.id})`;
+const hasTokens = sql`exists (select 1 from ${calendarAccessTokens} where ${calendarAccessTokens.calendarId} = ${calendars.id})`;
+const hasSyncs = sql`exists (select 1 from ${externalSyncs} where ${externalSyncs.calendarId} = ${calendars.id})`;
+const isShared = sql`(${hasUserShares} or ${hasTokens})`;
+
+/** Timestamps defaulted by SQLite are "YYYY-MM-DD HH:MM:SS" text in UTC; app-written ones are unix seconds. */
+function toDate(value: unknown): Date {
+ if (typeof value === "number") return new Date(value * 1000);
+ if (typeof value === "string") {
+ if (/^\d+$/.test(value)) return new Date(Number(value) * 1000);
+ const utc = new Date(`${value.replace(" ", "T")}Z`);
+ return isNaN(utc.getTime()) ? new Date(value) : utc;
+ }
+ return new Date();
+}
+
+/** Per-row count as a correlated subquery, so one page is one statement. */
+function countFor(table: SQLiteTable, column: SQLiteColumn) {
+ return sql<number>`(select count(*) from ${table} where ${column} = ${calendars.id})`;
+}
/**
* Admin Calendar Management API
*
* GET /api/admin/calendars
- * Lists all calendars with filtering, sorting, and pagination.
+ * One page of calendars plus instance-wide counts. Orphaned calendars always come first.
*
* Query Parameters:
- * - status: Filter by status (all, orphaned, owned)
- * - search: Search by calendar name (case-insensitive)
- * - ownerId: Filter by specific owner ID
- * - sortBy: Sort field (name, createdAt, ownerId, shiftCount)
- * - sortOrder: Sort direction (asc, desc)
- * - limit: Number of calendars to return (default: 1000)
- * - offset: Pagination offset
+ * - search: Calendar name, owner name or owner email contains (case-insensitive)
+ * - content: all | shared | synced (default: all; shared = user shares or share links)
+ * - owner: all | orphaned | with-owner (default: all)
+ * - sort: name | createdAt | owner | shiftsCount | sharesCount | externalSyncsCount | guestPermission (default: createdAt)
+ * - order: asc | desc (default: desc)
+ * - page: 1-based page, clamped to the last page (default: 1)
+ * - limit: Page size (default: 25, max: 100)
+ *
+ * Response: { items, total, counts, page, limit } — see lib/admin-list.ts
*
* Permission: Admin or Superadmin only
*/
@@ -39,212 +76,139 @@ export async function GET(request: NextRequest) {
const currentUser = await getValidatedAdminUser(request);
if (isErrorResponse(currentUser)) return currentUser;
- requireAdmin(currentUser);
-
- // Parse query parameters
- const { searchParams } = new URL(request.url);
- const statusFilter = searchParams.get("status") || "all";
- const searchQuery = searchParams.get("search");
- const ownerIdFilter = searchParams.get("ownerId");
- const sortBy = searchParams.get("sortBy") || "createdAt";
- const sortOrder = searchParams.get("sortOrder") || "desc";
- const limit = parseInt(searchParams.get("limit") || "1000", 10);
- const offset = parseInt(searchParams.get("offset") || "0", 10);
-
- const conditions = [];
-
- // Status filter
- if (statusFilter === "orphaned") {
- conditions.push(isNull(calendars.ownerId));
- } else if (statusFilter === "with-owner") {
- conditions.push(sql`${calendars.ownerId} IS NOT NULL`);
- }
-
- // Owner filter
- if (ownerIdFilter) {
- conditions.push(eq(calendars.ownerId, ownerIdFilter));
+ if (!isAdmin(currentUser)) {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
}
- // Search filter
- if (searchQuery) {
- const searchPattern = `%${searchQuery.toLowerCase()}%`;
- conditions.push(sql`LOWER(${calendars.name}) LIKE ${searchPattern}`);
+ const { searchParams } = request.nextUrl;
+ const search = (searchParams.get("search") ?? "").trim();
+ const content = pickParam(searchParams.get("content"), CALENDAR_CONTENT_FILTERS, "all");
+ const owner = pickParam(searchParams.get("owner"), CALENDAR_OWNER_FILTERS, "all");
+ const sort = pickParam(searchParams.get("sort"), CALENDAR_SORT_FIELDS, "createdAt");
+ const order = pickParam(searchParams.get("order"), SORT_ORDERS, "desc");
+ const paging = parsePaging(searchParams);
+
+ const conditions: SQL[] = [];
+
+ if (owner === "orphaned") conditions.push(orphaned);
+ if (owner === "with-owner") conditions.push(sql`not ${orphaned}`);
+ if (content === "shared") conditions.push(isShared);
+ if (content === "synced") conditions.push(hasSyncs);
+
+ if (search) {
+ const pattern = containsPattern(search);
+ conditions.push(
+ or(
+ sql`lower(${calendars.name}) like ${pattern} escape '\\'`,
+ sql`lower(${user.name}) like ${pattern} escape '\\'`,
+ sql`lower(${user.email}) like ${pattern} escape '\\'`
+ )!
+ );
}
- // Base query with calendar data
- const baseQuery = db
+ const where = conditions.length > 0 ? and(...conditions) : undefined;
+
+ const sortExpressions: Record<typeof sort, SQL> = {
+ name: sql`lower(${calendars.name})`,
+ createdAt: sql`${calendars.createdAt}`,
+ owner: sql`lower(coalesce(${user.name}, ${user.email}, ''))`,
+ shiftsCount: sql`(select count(*) from ${shifts} where ${shifts.calendarId} = ${calendars.id})`,
+ sharesCount: sql`((select count(*) from ${calendarShares} where ${calendarShares.calendarId} = ${calendars.id}) + (select count(*) from ${calendarAccessTokens} where ${calendarAccessTokens.calendarId} = ${calendars.id}))`,
+ externalSyncsCount: sql`(select count(*) from ${externalSyncs} where ${externalSyncs.calendarId} = ${calendars.id})`,
+ guestPermission: sql`case ${calendars.guestPermission} when 'write' then 2 when 'read' then 1 else 0 end`,
+ };
+ const direction = order === "asc" ? asc : desc;
+
+ const [[{ total }], [countRow], [shiftsRow]] = await Promise.all([
+ db
+ .select({ total: count() })
+ .from(calendars)
+ .leftJoin(user, eq(calendars.ownerId, user.id))
+ .where(where),
+ db
+ .select({
+ total: count(),
+ orphaned: sql<number>`coalesce(sum(${orphaned}), 0)`,
+ shared: sql<number>`coalesce(sum(${isShared}), 0)`,
+ synced: sql<number>`coalesce(sum(${hasSyncs}), 0)`,
+ })
+ .from(calendars)
+ .leftJoin(user, eq(calendars.ownerId, user.id)),
+ db.select({ total: count() }).from(shifts),
+ ]);
+
+ const { page, offset } = clampPage(paging.page, paging.limit, total);
+
+ const rows = await db
.select({
id: calendars.id,
name: calendars.name,
color: calendars.color,
ownerId: calendars.ownerId,
guestPermission: calendars.guestPermission,
- createdAt: sql<string>`${calendars.createdAt}`,
- updatedAt: sql<string>`${calendars.updatedAt}`,
+ // Raw values: rows created with the SQL default hold text, not unix seconds
+ createdAt: sql<unknown>`${calendars.createdAt}`,
+ updatedAt: sql<unknown>`${calendars.updatedAt}`,
+ ownerUserId: user.id,
ownerName: user.name,
ownerEmail: user.email,
ownerImage: user.image,
+ shiftsCount: countFor(shifts, shifts.calendarId),
+ notesCount: countFor(calendarNotes, calendarNotes.calendarId),
+ presetsCount: countFor(shiftPresets, shiftPresets.calendarId),
+ userSharesCount: countFor(calendarShares, calendarShares.calendarId),
+ tokenSharesCount: countFor(calendarAccessTokens, calendarAccessTokens.calendarId),
+ externalSyncsCount: countFor(externalSyncs, externalSyncs.calendarId),
})
.from(calendars)
- .leftJoin(user, eq(calendars.ownerId, user.id));
-
- // Get total count
- const countQuery = db
- .select({ count: sql<number>`COUNT(*)` })
- .from(calendars);
-
- const [countResult] =
- conditions.length > 0
- ? await countQuery.where(and(...conditions))
- : await countQuery;
-
- const total = Number(countResult?.count || 0);
-
- // Get calendars with owner info
- const calendarsQuery =
- conditions.length > 0 ? baseQuery.where(and(...conditions)) : baseQuery;
-
- const calendarsData = await calendarsQuery.limit(limit).offset(offset);
-
- // Get statistics for each calendar
- const calendarIds = calendarsData.map((c) => c.id);
-
- // Get shift counts
- const shiftCounts = await db
- .select({
- calendarId: shifts.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(shifts)
- .where(sql`${shifts.calendarId} IN ${calendarIds}`)
- .groupBy(shifts.calendarId);
-
- // Get note counts
- const noteCounts = await db
- .select({
- calendarId: calendarNotes.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(calendarNotes)
- .where(sql`${calendarNotes.calendarId} IN ${calendarIds}`)
- .groupBy(calendarNotes.calendarId);
-
- // Get preset counts
- const presetCounts = await db
- .select({
- calendarId: shiftPresets.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(shiftPresets)
- .where(sql`${shiftPresets.calendarId} IN ${calendarIds}`)
- .groupBy(shiftPresets.calendarId);
-
- // Get share counts
- const shareCounts = await db
- .select({
- calendarId: calendarShares.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(calendarShares)
- .where(sql`${calendarShares.calendarId} IN ${calendarIds}`)
- .groupBy(calendarShares.calendarId);
-
- // Get share token counts
- const shareTokenCounts = await db
- .select({
- calendarId: calendarAccessTokens.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(calendarAccessTokens)
- .where(sql`${calendarAccessTokens.calendarId} IN ${calendarIds}`)
- .groupBy(calendarAccessTokens.calendarId);
-
- // Get external syncs counts
- const externalSyncsCounts = await db
- .select({
- calendarId: externalSyncs.calendarId,
- count: sql<number>`COUNT(*)`,
- })
- .from(externalSyncs)
- .where(sql`${externalSyncs.calendarId} IN ${calendarIds}`)
- .groupBy(externalSyncs.calendarId);
-
- // Build result with statistics
- const calendarsWithStats = calendarsData.map((calendar) => ({
- id: calendar.id,
- name: calendar.name,
- color: calendar.color,
- ownerId: calendar.ownerId,
- owner: calendar.ownerId
- ? {
- name: calendar.ownerName,
- email: calendar.ownerEmail,
- image: calendar.ownerImage,
- }
+ .leftJoin(user, eq(calendars.ownerId, user.id))
+ .where(where)
+ .orderBy(
+ asc(sql`case when ${orphaned} then 0 else 1 end`),
+ direction(sortExpressions[sort]),
+ direction(calendars.id)
+ )
+ .limit(paging.limit)
+ .offset(offset);
+
+ const items = rows.map((row) => ({
+ id: row.id,
+ name: row.name,
+ color: row.color,
+ ownerId: row.ownerId,
+ owner: row.ownerUserId
+ ? { name: row.ownerName, email: row.ownerEmail, image: row.ownerImage }
: null,
- guestPermission: calendar.guestPermission,
- createdAt: calendar.createdAt ? new Date(calendar.createdAt) : new Date(),
- updatedAt: calendar.updatedAt ? new Date(calendar.updatedAt) : new Date(),
- shiftsCount:
- shiftCounts.find((s) => s.calendarId === calendar.id)?.count || 0,
- notesCount:
- noteCounts.find((n) => n.calendarId === calendar.id)?.count || 0,
- presetsCount:
- presetCounts.find((p) => p.calendarId === calendar.id)?.count || 0,
- sharesCount:
- (shareCounts.find((s) => s.calendarId === calendar.id)?.count || 0) +
- (shareTokenCounts.find((t) => t.calendarId === calendar.id)?.count ||
- 0),
- externalSyncsCount:
- externalSyncsCounts.find((e) => e.calendarId === calendar.id)?.count ||
- 0,
+ guestPermission: row.guestPermission,
+ createdAt: toDate(row.createdAt),
+ updatedAt: toDate(row.updatedAt),
+ shiftsCount: Number(row.shiftsCount),
+ notesCount: Number(row.notesCount),
+ presetsCount: Number(row.presetsCount),
+ sharesCount: Number(row.userSharesCount) + Number(row.tokenSharesCount),
+ externalSyncsCount: Number(row.externalSyncsCount),
}));
- // Apply sorting
- const sortedCalendars = calendarsWithStats.sort((a, b) => {
- // Orphaned calendars always on top (when not filtering)
- if (statusFilter === "all") {
- const aOrphaned = !a.ownerId;
- const bOrphaned = !b.ownerId;
- if (aOrphaned !== bOrphaned) {
- return aOrphaned ? -1 : 1;
- }
- }
-
- // Then sort by specified field
- let comparison = 0;
- if (sortBy === "name") {
- comparison = a.name.localeCompare(b.name);
- } else if (sortBy === "createdAt") {
- comparison =
- new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
- } else if (sortBy === "ownerId") {
- const aOwner = a.owner?.name || a.owner?.email || "";
- const bOwner = b.owner?.name || b.owner?.email || "";
- comparison = aOwner.localeCompare(bOwner);
- } else if (sortBy === "shiftCount") {
- comparison = a.shiftsCount - b.shiftsCount;
- }
-
- return sortOrder === "asc" ? comparison : -comparison;
- });
+ const counts: CalendarListCounts = {
+ total: countRow.total,
+ orphaned: Number(countRow.orphaned),
+ shared: Number(countRow.shared),
+ synced: Number(countRow.synced),
+ shifts: shiftsRow.total,
+ };
return NextResponse.json({
- calendars: sortedCalendars,
+ items,
total,
- limit,
- offset,
+ counts,
+ page,
+ limit: paging.limit,
});
} catch (error) {
console.error("[Admin Calendars API] Error:", error);
-
- if (error instanceof Error && error.message === "Admin access required") {
- return NextResponse.json(
- { error: "Admin access required" },
- { status: 403 }
- );
- }
-
return NextResponse.json(
{ error: "Failed to fetch calendars" },
{ status: 500 }
diff --git a/app/api/admin/stats/route.ts b/app/api/admin/stats/route.ts
index 0ee1ee0..979ebf0 100644
--- a/app/api/admin/stats/route.ts
+++ b/app/api/admin/stats/route.ts
@@ -8,9 +8,20 @@ import {
shifts,
auditLogs,
} from "@/lib/db/schema";
-import { sql, eq, and, gte, isNull } from "drizzle-orm";
+import { sql, eq, gte, count, desc } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
-import { requireAdmin } from "@/lib/auth/admin";
+import { isAdmin } from "@/lib/auth/admin";
+
+const RECENT_LOG_LIMIT = 5;
+
+function parseMetadata(value: string | null): unknown {
+ if (!value) return null;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
/**
* Admin System Statistics API
@@ -42,7 +53,12 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
- requireAdmin(currentUser);
+ if (!isAdmin(currentUser)) {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
// Calculate date for "recent activity" (last 7 days)
const sevenDaysAgo = new Date();
@@ -77,25 +93,17 @@ export async function GET(request: NextRequest) {
usersByRole.total += count;
});
- // 2. Total calendars (exclude orphaned)
- const [totalCalendarsResult] = await db
+ // 2./3. Calendars with an owner row vs. orphaned (owner_id null or dangling)
+ const [calendarCounts] = await db
.select({
- count: sql<number>`COUNT(*)`,
+ total: count(),
+ orphaned: sql<number>`coalesce(sum(${user.id} is null), 0)`,
})
.from(calendars)
- .where(sql`${calendars.ownerId} IS NOT NULL`);
+ .leftJoin(user, eq(calendars.ownerId, user.id));
- const totalCalendars = Number(totalCalendarsResult?.count || 0);
-
- // 3. Orphaned calendars (ownerId = NULL)
- const [orphanedCalendarsResult] = await db
- .select({
- count: sql<number>`COUNT(*)`,
- })
- .from(calendars)
- .where(isNull(calendars.ownerId));
-
- const orphanedCalendars = Number(orphanedCalendarsResult?.count || 0);
+ const orphanedCalendars = Number(calendarCounts?.orphaned || 0);
+ const totalCalendars = Number(calendarCounts?.total || 0) - orphanedCalendars;
// 4. Active shares count (user shares)
const [activeSharesResult] = await db
@@ -125,17 +133,20 @@ export async function GET(request: NextRequest) {
const totalShifts = Number(totalShiftsResult?.count || 0);
- // 6. Recent activity count (last 7 days)
- const [recentActivityResult] = await db
+ // 6./7./8. One pass over the fastest-growing table: all entries, the dashboard
+ // feed's subset and the last seven days — this endpoint is polled every few seconds.
+ const feedScope = sql`(${auditLogs.action} LIKE 'admin.%' OR ${auditLogs.action} LIKE 'security.%')`;
+
+ const [logCounts] = await db
.select({
- count: sql<number>`COUNT(*)`,
+ total: count(),
+ feed: sql<number>`coalesce(sum(${feedScope}), 0)`,
+ recent: sql<number>`coalesce(sum(${gte(auditLogs.timestamp, sevenDaysAgo)}), 0)`,
})
- .from(auditLogs)
- .where(and(gte(auditLogs.timestamp, sevenDaysAgo)));
+ .from(auditLogs);
- const recentActivity = Number(recentActivityResult?.count || 0);
+ const recentActivity = Number(logCounts?.recent || 0);
- // 7. Recent audit logs preview (last 5 entries, admin-only logs + security events)
const recentLogs = await db
.select({
id: auditLogs.id,
@@ -143,15 +154,15 @@ export async function GET(request: NextRequest) {
resourceType: auditLogs.resourceType,
resourceId: auditLogs.resourceId,
userId: auditLogs.userId,
+ metadata: auditLogs.metadata,
severity: auditLogs.severity,
timestamp: auditLogs.timestamp,
})
.from(auditLogs)
- .where(
- sql`(${auditLogs.action} LIKE 'admin.%' OR ${auditLogs.action} LIKE 'security.%')` // Admin actions + security events (rate limits, etc.) - both user-visible and admin-only
- )
- .orderBy(sql`${auditLogs.timestamp} DESC`)
- .limit(5);
+ .where(feedScope)
+ // Timestamps have second precision; rowid keeps same-second entries in insert order
+ .orderBy(desc(auditLogs.timestamp), desc(sql`rowid`))
+ .limit(RECENT_LOG_LIMIT);
const stats = {
users: usersByRole,
@@ -169,24 +180,19 @@ export async function GET(request: NextRequest) {
},
activity: {
recent: recentActivity,
- logs: recentLogs,
+ total: Number(logCounts?.feed || 0),
+ logs: recentLogs.map((log) => ({
+ ...log,
+ metadata: parseMetadata(log.metadata),
+ })),
+ },
+ auditLogs: {
+ total: Number(logCounts?.total || 0),
},
};
return NextResponse.json(stats, { status: 200 });
} catch (error) {
- if (
- error &&
- typeof error === "object" &&
- "status" in error &&
- error.status === 403
- ) {
- return NextResponse.json(
- { error: "Admin access required" },
- { status: 403 }
- );
- }
-
console.error("Failed to fetch admin stats:", error);
return NextResponse.json(
{ error: "Failed to fetch statistics" },
diff --git a/app/api/admin/users/route.ts b/app/api/admin/users/route.ts
index 39bc2a9..0f3a762 100644
--- a/app/api/admin/users/route.ts
+++ b/app/api/admin/users/route.ts
@@ -1,27 +1,40 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { user, calendars, session, calendarShares } from "@/lib/db/schema";
-import { sql, eq, desc, and, or } from "drizzle-orm";
-import { requireAdmin } from "@/lib/auth/admin";
+import { and, asc, count, desc, getTableColumns, getTableName, or, sql, type SQL } from "drizzle-orm";
+import { isAdmin } from "@/lib/auth/admin";
import {
getValidatedAdminUser,
isErrorResponse,
} from "@/lib/auth/admin-helpers";
+import {
+ SORT_ORDERS,
+ USER_ROLE_FILTERS,
+ USER_SORT_FIELDS,
+ USER_STATUS_FILTERS,
+ clampPage,
+ containsPattern,
+ parsePaging,
+ pickParam,
+ type UserListCounts,
+} from "@/lib/admin-list";
/**
* Admin User Management API
*
* GET /api/admin/users
- * Lists all users with filtering, sorting, and pagination.
+ * One page of users plus instance-wide counts.
*
* Query Parameters:
- * - role: Filter by role (superadmin, admin, user)
- * - banned: Filter by ban status (true, false)
- * - search: Search by name or email (case-insensitive)
- * - sortBy: Sort field (createdAt, name, email, role)
- * - sortOrder: Sort direction (asc, desc)
- * - limit: Number of users to return (default: 1000)
- * - offset: Pagination offset
+ * - search: Name or email contains (case-insensitive)
+ * - role: all | superadmin | admin | user (default: all; "user" includes accounts without a role)
+ * - status: all | active | banned (default: all)
+ * - sort: name | email | role | status | createdAt | lastActivity | calendarCount (default: createdAt)
+ * - order: asc | desc (default: desc)
+ * - page: 1-based page, clamped to the last page (default: 1)
+ * - limit: Page size (default: 25, max: 100)
+ *
+ * Response: { items, total, counts, page, limit } — see lib/admin-list.ts
*
* Permission: Admin or Superadmin only
*/
@@ -30,121 +43,120 @@ export async function GET(request: NextRequest) {
const currentUser = await getValidatedAdminUser(request);
if (isErrorResponse(currentUser)) return currentUser;
- requireAdmin(currentUser);
-
- // Parse query parameters
- const { searchParams } = new URL(request.url);
- const roleFilter = searchParams.get("role");
- const bannedFilter = searchParams.get("banned");
- const searchQuery = searchParams.get("search");
- const sortBy = searchParams.get("sortBy") || "createdAt";
- const sortOrder = searchParams.get("sortOrder") || "desc";
- const limit = parseInt(searchParams.get("limit") || "1000", 10);
- const offset = parseInt(searchParams.get("offset") || "0", 10);
-
- const conditions = [];
+ if (!isAdmin(currentUser)) {
+ return NextResponse.json(
+ { error: "Admin access required" },
+ { status: 403 }
+ );
+ }
- if (roleFilter) {
- conditions.push(eq(user.role, roleFilter));
+ const { searchParams } = request.nextUrl;
+ const search = (searchParams.get("search") ?? "").trim();
+ const role = pickParam(searchParams.get("role"), USER_ROLE_FILTERS, "all");
+ const status = pickParam(searchParams.get("status"), USER_STATUS_FILTERS, "all");
+ const sort = pickParam(searchParams.get("sort"), USER_SORT_FIELDS, "createdAt");
+ const order = pickParam(searchParams.get("order"), SORT_ORDERS, "desc");
+ const paging = parsePaging(searchParams);
+
+ // Single-table selects render columns unqualified, so the outer row is named explicitly
+ const userId = sql`${sql.identifier(getTableName(user))}.${sql.identifier(user.id.name)}`;
+ const calendarCount = sql<number>`(select count(*) from ${calendars} where ${calendars.ownerId} = ${userId})`;
+ const sharesCount = sql<number>`(select count(*) from ${calendarShares} where ${calendarShares.userId} = ${userId})`;
+ const lastActivity = sql<number | null>`(select max(${session.updatedAt}) from ${session} where ${session.userId} = ${userId})`;
+ const isPrivileged = sql`coalesce(${user.role}, 'user') in ('admin', 'superadmin')`;
+ const roleRank = sql`case ${user.role} when 'superadmin' then 2 when 'admin' then 1 else 0 end`;
+ const bannedFlag = sql`coalesce(${user.banned}, 0)`;
+
+ const conditions: SQL[] = [];
+
+ if (role === "user") {
+ conditions.push(sql`not ${isPrivileged}`);
+ } else if (role !== "all") {
+ conditions.push(sql`${user.role} = ${role}`);
}
- if (bannedFilter !== null) {
- const isBanned = bannedFilter === "true";
- conditions.push(eq(user.banned, isBanned));
+ if (status !== "all") {
+ conditions.push(sql`${bannedFlag} = ${status === "banned" ? 1 : 0}`);
}
- if (searchQuery) {
- const searchPattern = `%${searchQuery.toLowerCase()}%`;
+ if (search) {
+ const pattern = containsPattern(search);
conditions.push(
or(
- sql`LOWER(${user.email}) LIKE ${searchPattern}`,
- sql`LOWER(${user.name}) LIKE ${searchPattern}`
- )
+ sql`lower(${user.name}) like ${pattern} escape '\\'`,
+ sql`lower(${user.email}) like ${pattern} escape '\\'`
+ )!
);
}
- // Apply sorting
- const sortField =
- sortBy === "createdAt"
- ? user.createdAt
- : sortBy === "name"
- ? user.name
- : sortBy === "email"
- ? user.email
- : sortBy === "role"
- ? user.role
- : user.createdAt;
-
- const orderByClause = sortOrder === "asc" ? sortField : desc(sortField);
-
- // Get total count (with filters)
- const countQuery = db.select({ count: sql<number>`COUNT(*)` }).from(user);
-
- const [countResult] =
- conditions.length > 0
- ? await countQuery.where(and(...conditions))
- : await countQuery;
-
- const total = Number(countResult?.count || 0);
-
- // Get users (with filters, sorting, pagination)
- const usersQuery = db
- .select()
+ const where = conditions.length > 0 ? and(...conditions) : undefined;
+
+ const sortExpressions: Record<typeof sort, SQL | typeof user.createdAt> = {
+ name: sql`lower(${user.name})`,
+ email: sql`lower(${user.email})`,
+ role: roleRank,
+ status: bannedFlag,
+ createdAt: user.createdAt,
+ lastActivity,
+ calendarCount,
+ };
+ const direction = order === "asc" ? asc : desc;
+
+ const [[{ total }], [countRow]] = await Promise.all([
+ db.select({ total: count() }).from(user).where(where),
+ db
+ .select({
+ total: count(),
+ superadmin: sql<number>`coalesce(sum(${user.role} = 'superadmin'), 0)`,
+ admin: sql<number>`coalesce(sum(${user.role} = 'admin'), 0)`,
+ banned: sql<number>`coalesce(sum(${bannedFlag} = 1), 0)`,
+ })
+ .from(user),
+ ]);
+
+ const { page, offset } = clampPage(paging.page, paging.limit, total);
+
+ const rows = await db
+ .select({
+ ...getTableColumns(user),
+ calendarCount,
+ sharesCount,
+ lastActivity,
+ })
.from(user)
- .orderBy(orderByClause)
- .limit(limit)
+ .where(where)
+ // The id tie-breaker keeps pages stable when many rows share a sort value
+ .orderBy(direction(sortExpressions[sort]), direction(user.id))
+ .limit(paging.limit)
.offset(offset);
- const users =
- conditions.length > 0
- ? await usersQuery.where(and(...conditions))
- : await usersQuery;
-
- // Enrich users with calendar count and last activity
- const enrichedUsers = await Promise.all(
- users.map(async (u) => {
- // Count owned calendars
- const [calendarCount] = await db
- .select({
- count: sql<number>`COUNT(*)`,
- })
- .from(calendars)
- .where(eq(calendars.ownerId, u.id));
-
- // Count shared calendars (via calendarShares)
- const [sharesCount] = await db
- .select({
- count: sql<number>`COUNT(*)`,
- })
- .from(calendarShares)
- .where(eq(calendarShares.userId, u.id));
-
- // Get last session (most recent activity)
- const [lastSession] = await db
- .select({
- updatedAt: session.updatedAt,
- })
- .from(session)
- .where(eq(session.userId, u.id))
- .orderBy(desc(session.updatedAt))
- .limit(1);
-
- return {
- ...u,
- role: u.role || "user",
- banned: u.banned || false,
- calendarCount: Number(calendarCount?.count || 0),
- sharesCount: Number(sharesCount?.count || 0),
- lastActivity: lastSession?.updatedAt || null,
- };
- })
- );
+ const items = rows.map((row) => ({
+ ...row,
+ role: row.role || "user",
+ banned: row.banned || false,
+ calendarCount: Number(row.calendarCount),
+ sharesCount: Number(row.sharesCount),
+ lastActivity: row.lastActivity === null ? null : new Date(Number(row.lastActivity)),
+ }));
+
+ const superadmin = Number(countRow.superadmin);
+ const admin = Number(countRow.admin);
+ const banned = Number(countRow.banned);
+ const counts: UserListCounts = {
+ total: countRow.total,
+ superadmin,
+ admin,
+ user: countRow.total - superadmin - admin,
+ banned,
+ active: countRow.total - banned,
+ };
return NextResponse.json({
- users: enrichedUsers,
+ items,
total,
- limit,
- offset,
+ counts,
+ page,
+ limit: paging.limit,
});
} catch (error) {
console.error("Failed to fetch users:", error);
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.ts
index 0ebf9f2..c2d38b9 100644
--- a/app/api/calendars/[id]/route.ts
+++ b/app/api/calendars/[id]/route.ts
@@ -13,6 +13,10 @@ import {
canManageCalendar,
canDeleteCalendar,
} from "@/lib/auth/permissions";
+import {
+ calendarViewSettingsEqual,
+ sanitizeCalendarViewSettings,
+} from "@/lib/view-settings";
import {
logUserAction,
type CalendarUpdatedMetadata,
@@ -75,7 +79,18 @@ export async function PATCH(
const { id } = await params;
const user = await getSessionUser(request.headers);
const body = await request.json();
- const { name, color, guestPermission } = body;
+ const { name, color, guestPermission, viewSettings } = body;
+
+ if (
+ viewSettings !== undefined &&
+ viewSettings !== null &&
+ (typeof viewSettings !== "object" || Array.isArray(viewSettings))
+ ) {
+ return NextResponse.json(
+ { error: "viewSettings must be an object or null" },
+ { status: 400 }
+ );
+ }
// Fetch current calendar
const [existingCalendar] = await db
@@ -103,6 +118,7 @@ export async function PATCH(
const changes: string[] = [];
let guestPermissionChanged = false;
let oldGuestPermission: string | undefined;
+ let viewSettingsChange: CalendarUpdatedMetadata["viewSettings"];
if (name && name !== existingCalendar.name) {
updateData.name = name;
@@ -124,6 +140,30 @@ export async function PATCH(
oldGuestPermission = existingCalendar.guestPermission;
}
}
+ if (viewSettings === null && existingCalendar.viewSettings !== null) {
+ updateData.viewSettings = null;
+ changes.push("viewSettings");
+ viewSettingsChange = "disabled";
+ } else if (viewSettings) {
+ const next = sanitizeCalendarViewSettings({
+ ...(existingCalendar.viewSettings ?? {}),
+ ...viewSettings,
+ });
+ if (
+ !existingCalendar.viewSettings ||
+ !calendarViewSettingsEqual(existingCalendar.viewSettings, next)
+ ) {
+ updateData.viewSettings = next;
+ changes.push("viewSettings");
+ viewSettingsChange = existingCalendar.viewSettings
+ ? "updated"
+ : "enabled";
+ }
+ }
+
+ if (changes.length === 0) {
+ return NextResponse.json(existingCalendar);
+ }
const [calendar] = await db
.update(calendars)
@@ -141,6 +181,7 @@ export async function PATCH(
metadata: {
calendarName: calendar.name,
changes,
+ ...(viewSettingsChange && { viewSettings: viewSettingsChange }),
},
request,
});
diff --git a/app/api/calendars/route.ts b/app/api/calendars/route.ts
index b5a4b9c..5fa9493 100644
--- a/app/api/calendars/route.ts
+++ b/app/api/calendars/route.ts
@@ -38,6 +38,7 @@ export async function GET(request: Request) {
color: calendars.color,
ownerId: calendars.ownerId,
guestPermission: calendars.guestPermission,
+ viewSettings: calendars.viewSettings,
createdAt: calendars.createdAt,
updatedAt: calendars.updatedAt,
_count:
diff --git a/app/api/export/ics/route.ts b/app/api/export/ics/route.ts
index 3be14c4..fc4c07d 100644
--- a/app/api/export/ics/route.ts
+++ b/app/api/export/ics/route.ts
@@ -173,7 +173,7 @@ export async function POST(request: NextRequest) {
.slice(0, 3); // Max 3 calendar names
const filename = `${calendarNamesParts.join("_")}_${
- new Date().toISOString().split("T")[0]
+ formatDateToLocal(new Date())
}.ics`;
return new NextResponse(icsContent, {
diff --git a/app/api/export/pdf/route.ts b/app/api/export/pdf/route.ts
index a499a7a..26236c4 100644
--- a/app/api/export/pdf/route.ts
+++ b/app/api/export/pdf/route.ts
@@ -6,6 +6,7 @@ import { jsPDF } from "jspdf";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar } from "@/lib/auth/permissions";
import { rateLimit } from "@/lib/rate-limiter";
+import { formatDateToLocal } from "@/lib/date-utils";
export async function POST(request: NextRequest) {
try {
@@ -296,7 +297,7 @@ export async function POST(request: NextRequest) {
.slice(0, 3); // Max 3 calendar names
const filename = `${calendarNamesParts.join("_")}_${
- new Date().toISOString().split("T")[0]
+ formatDateToLocal(new Date())
}.pdf`;
return new NextResponse(pdfBuffer, {
diff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.ts
index 74a91c0..a09e88b 100644
--- a/app/api/shifts/[id]/route.ts
+++ b/app/api/shifts/[id]/route.ts
@@ -4,6 +4,7 @@ import { calendars, shifts } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar, canEditCalendar } from "@/lib/auth/permissions";
+import { parseLocalDate } from "@/lib/date-utils";
// GET single shift
export async function GET(
@@ -140,11 +141,23 @@ export async function PUT(
);
}
+ let date = existingShift.date;
+ if (body.date) {
+ try {
+ date = parseLocalDate(body.date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+ }
+
// Update the shift
const [updatedShift] = await db
.update(shifts)
.set({
- date: body.date ? new Date(body.date) : existingShift.date,
+ date,
startTime: body.startTime ?? existingShift.startTime,
endTime: body.endTime ?? existingShift.endTime,
title: body.title ?? existingShift.title,
diff --git a/app/api/shifts/stats/route.ts b/app/api/shifts/stats/route.ts
index a06d0f3..7822d57 100644
--- a/app/api/shifts/stats/route.ts
+++ b/app/api/shifts/stats/route.ts
@@ -9,7 +9,11 @@ import {
import { eq, and, gte, lte, or, isNull } from "drizzle-orm";
import { getSessionUser } from "@/lib/auth/sessions";
import { canViewCalendar } from "@/lib/auth/permissions";
-import { calculateShiftDuration } from "@/lib/date-utils";
+import {
+ calculateShiftDuration,
+ formatDateToLocal,
+ parseLocalDate,
+} from "@/lib/date-utils";
import {
startOfWeek,
endOfWeek,
@@ -58,7 +62,17 @@ export async function GET(request: Request) {
);
}
- const referenceDate = date ? new Date(date) : new Date();
+ let referenceDate = new Date();
+ if (date) {
+ try {
+ referenceDate = parseLocalDate(date);
+ } catch {
+ return NextResponse.json(
+ { error: "Invalid date format" },
+ { status: 400 }
+ );
+ }
+ }
let startDate: Date;
let endDate: Date;
@@ -157,7 +171,7 @@ export async function GET(request: Request) {
: new Date(shiftDate);
if (!isNaN(date.getTime())) {
- const dateKey = date.toISOString().split("T")[0];
+ const dateKey = formatDateToLocal(date);
const dailyExisting = dailyStats.get(dateKey) || {
count: 0,
totalMinutes: 0,
@@ -212,8 +226,8 @@ export async function GET(request: Request) {
return NextResponse.json({
period,
- startDate: startDate.toISOString(),
- endDate: endDate.toISOString(),
+ startDate: formatDateToLocal(startDate),
+ endDate: formatDateToLocal(endDate),
stats,
totalMinutes,
totalShifts,
diff --git a/app/api/user/view-settings/route.ts b/app/api/user/view-settings/route.ts
new file mode 100644
index 0000000..c23e522
--- /dev/null
+++ b/app/api/user/view-settings/route.ts
@@ -0,0 +1,79 @@
+import { NextRequest, NextResponse } from "next/server";
+import { eq } from "drizzle-orm";
+import { db } from "@/lib/db";
+import { userPreferences } from "@/lib/db/schema";
+import { getSessionUser } from "@/lib/auth/sessions";
+import { sanitizePersonalViewSettings } from "@/lib/view-settings";
+
+// GET the signed-in user's personal view (null until first saved)
+export async function GET(request: NextRequest) {
+ try {
+ const user = await getSessionUser(request.headers);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const row = await db.query.userPreferences.findFirst({
+ where: eq(userPreferences.userId, user.id),
+ });
+ return NextResponse.json({
+ viewSettings: row?.viewSettings
+ ? sanitizePersonalViewSettings(row.viewSettings)
+ : null,
+ });
+ } catch (error) {
+ console.error("Failed to fetch view settings:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch view settings" },
+ { status: 500 }
+ );
+ }
+}
+
+// PUT merges the given keys into the stored view
+export async function PUT(request: NextRequest) {
+ try {
+ const user = await getSessionUser(request.headers);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const body = await request.json().catch(() => null);
+ const patch = body?.viewSettings;
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
+ return NextResponse.json(
+ { error: "viewSettings object is required" },
+ { status: 400 }
+ );
+ }
+
+ // Synchronous transaction so concurrent partial PUTs cannot drop each other's keys
+ const viewSettings = db.transaction((tx) => {
+ const row = tx
+ .select({ viewSettings: userPreferences.viewSettings })
+ .from(userPreferences)
+ .where(eq(userPreferences.userId, user.id))
+ .get();
+ const next = sanitizePersonalViewSettings({
+ ...(row?.viewSettings ?? {}),
+ ...patch,
+ });
+ tx.insert(userPreferences)
+ .values({ userId: user.id, viewSettings: next, updatedAt: new Date() })
+ .onConflictDoUpdate({
+ target: userPreferences.userId,
+ set: { viewSettings: next, updatedAt: new Date() },
+ })
+ .run();
+ return next;
+ });
+
+ return NextResponse.json({ viewSettings });
+ } catch (error) {
+ console.error("Failed to update view settings:", error);
+ return NextResponse.json(
+ { error: "Failed to update view settings" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/app/globals.css b/app/globals.css
index 18a9ff2..0194e8b 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -4,119 +4,419 @@
@custom-variant dark (&:is(.dark *));
@theme inline {
+ --font-sans: var(--font-plex-sans), ui-sans-serif, system-ui, sans-serif;
+ --font-mono: var(--font-plex-mono), ui-monospace, monospace;
+
--color-background: var(--background);
--color-foreground: var(--foreground);
- --font-sans: var(--font-geist-sans);
- --font-mono: var(--font-geist-mono);
- --color-sidebar-ring: var(--sidebar-ring);
- --color-sidebar-border: var(--sidebar-border);
- --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
- --color-sidebar-accent: var(--sidebar-accent);
- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
- --color-sidebar-primary: var(--sidebar-primary);
- --color-sidebar-foreground: var(--sidebar-foreground);
- --color-sidebar: var(--sidebar);
- --color-chart-5: var(--chart-5);
- --color-chart-4: var(--chart-4);
- --color-chart-3: var(--chart-3);
- --color-chart-2: var(--chart-2);
- --color-chart-1: var(--chart-1);
- --color-ring: var(--ring);
- --color-input: var(--input);
- --color-border: var(--border);
- --color-destructive: var(--destructive);
- --color-accent-foreground: var(--accent-foreground);
- --color-accent: var(--accent);
- --color-muted-foreground: var(--muted-foreground);
- --color-muted: var(--muted);
- --color-secondary-foreground: var(--secondary-foreground);
- --color-secondary: var(--secondary);
- --color-primary-foreground: var(--primary-foreground);
- --color-primary: var(--primary);
- --color-popover-foreground: var(--popover-foreground);
- --color-popover: var(--popover);
- --color-card-foreground: var(--card-foreground);
--color-card: var(--card);
- --radius-sm: calc(var(--radius) - 4px);
- --radius-md: calc(var(--radius) - 2px);
- --radius-lg: var(--radius);
- --radius-xl: calc(var(--radius) + 4px);
+ --color-card-foreground: var(--card-foreground);
+ --color-popover: var(--popover);
+ --color-popover-foreground: var(--popover-foreground);
+ --color-primary: var(--primary);
+ --color-primary-foreground: var(--primary-foreground);
+ --color-secondary: var(--secondary);
+ --color-secondary-foreground: var(--secondary-foreground);
+ --color-muted: var(--muted);
+ --color-muted-foreground: var(--muted-foreground);
+ --color-accent: var(--accent);
+ --color-accent-foreground: var(--accent-foreground);
+ --color-destructive: var(--destructive);
+ --color-border: var(--border);
+ --color-input: var(--input);
+ --color-ring: var(--ring);
+ --color-chart-1: var(--chart-1);
+ --color-chart-2: var(--chart-2);
+ --color-chart-3: var(--chart-3);
+ --color-chart-4: var(--chart-4);
+ --color-chart-5: var(--chart-5);
+ --color-sidebar: var(--sidebar);
+ --color-sidebar-foreground: var(--sidebar-foreground);
+ --color-sidebar-primary: var(--sidebar-primary);
+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
+ --color-sidebar-accent: var(--sidebar-accent);
+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
+ --color-sidebar-border: var(--sidebar-border);
+ --color-sidebar-ring: var(--sidebar-ring);
+
+ /* Text hierarchy */
+ --color-fg-strong: var(--fg-strong);
+ --color-fg-body: var(--fg-body);
+ --color-fg-secondary: var(--fg-secondary);
+ --color-fg-tertiary: var(--fg-tertiary);
+ --color-fg-faint: var(--fg-faint);
+
+ /* Surfaces and lines */
+ --color-surface-panel: var(--surface-panel);
+ --color-surface-card: var(--surface-card);
+ --color-surface-sunken: var(--surface-sunken);
+ --color-surface-cell: var(--surface-cell);
+ --color-surface-weekend: var(--surface-weekend);
+ --color-surface-today: var(--surface-today);
+ --color-line: var(--line);
+ --color-line-subtle: var(--line-subtle);
+ --color-line-grid: var(--line-grid);
+ --color-control: var(--control);
+
+ /* Month cell entries */
+ --color-cell-event: var(--cell-event);
+ --color-cell-event-line: var(--cell-event-line);
+ --color-cell-event-ink: var(--cell-event-ink);
+ --color-cell-note: var(--cell-note);
+ --color-cell-muted: var(--cell-muted);
+ --color-cell-weekend-num: var(--cell-weekend-num);
+ --color-cell-outside-num: var(--cell-outside-num);
+ --color-cell-selected: var(--cell-selected);
+
+ /* Brand accent */
+ --color-brand: var(--brand);
+ --color-brand-ink: var(--brand-ink);
+ --color-brand-soft: var(--brand-soft);
+ --color-brand-dot: var(--brand-dot);
+
+ /* Status */
+ --color-success: var(--success);
+ --color-success-soft: var(--success-soft);
+ --color-success-dot: var(--success-dot);
+ --color-warning: var(--warning);
+ --color-warning-title: var(--warning-title);
+ --color-warning-soft: var(--warning-soft);
+ --color-warning-surface: var(--warning-surface);
+ --color-warning-line: var(--warning-line);
+ --color-danger: var(--danger);
+ --color-danger-body: var(--danger-body);
+ --color-danger-soft: var(--danger-soft);
+ --color-danger-surface: var(--danger-surface);
+ --color-danger-line: var(--danger-line);
+
+ /* Stamp dock */
+ --color-dock: var(--dock);
+ --color-dock-line: var(--dock-line);
+ --color-dock-ink: var(--dock-ink);
+
+ --radius-sm: 6px;
+ --radius-md: 8px;
+ --radius-lg: 10px;
+ --radius-xl: 12px;
+ --radius-2xl: 14px;
+
+ --shadow-window: var(--elevation-window);
+ --shadow-sheet: var(--elevation-sheet);
+ --shadow-segment: var(--elevation-segment);
+ --shadow-dock: var(--elevation-dock);
}
:root {
--radius: 0.625rem;
- --background: oklch(0.96 0 0);
- --foreground: oklch(0.145 0 0);
- --card: oklch(0.985 0 0);
- --card-foreground: oklch(0.145 0 0);
- --popover: oklch(0.985 0 0);
- --popover-foreground: oklch(0.145 0 0);
- --primary: oklch(0.205 0 0);
- --primary-foreground: oklch(0.985 0 0);
- --secondary: oklch(0.95 0 0);
- --secondary-foreground: oklch(0.205 0 0);
- --muted: oklch(0.95 0 0);
- --muted-foreground: oklch(0.5 0 0);
- --accent: oklch(0.95 0 0);
- --accent-foreground: oklch(0.205 0 0);
- --destructive: oklch(0.577 0.245 27.325);
- --border: oklch(0.8 0 0);
- --input: oklch(0.8 0 0);
- --ring: oklch(0.708 0 0);
- --chart-1: oklch(0.646 0.222 41.116);
- --chart-2: oklch(0.6 0.118 184.704);
- --chart-3: oklch(0.398 0.07 227.392);
- --chart-4: oklch(0.828 0.189 84.429);
- --chart-5: oklch(0.769 0.188 70.08);
- --sidebar: oklch(0.985 0 0);
- --sidebar-foreground: oklch(0.145 0 0);
- --sidebar-primary: oklch(0.205 0 0);
- --sidebar-primary-foreground: oklch(0.985 0 0);
- --sidebar-accent: oklch(0.97 0 0);
- --sidebar-accent-foreground: oklch(0.205 0 0);
- --sidebar-border: oklch(0.922 0 0);
- --sidebar-ring: oklch(0.708 0 0);
+
+ --fg-strong: #101828;
+ --fg-body: #344054;
+ --fg-secondary: #475467;
+ --fg-tertiary: #667085;
+ --fg-faint: #98a2b3;
+
+ --surface-panel: #fafbfc;
+ --surface-card: #ffffff;
+ --surface-sunken: #f2f4f7;
+ --surface-cell: #ffffff;
+ --surface-weekend: #fbfbfc;
+ --surface-today: #f7faff;
+ --line: #e4e7ec;
+ --line-subtle: #f2f4f7;
+ --line-grid: #eef0f3;
+ --control: #d0d5dd;
+
+ --cell-event: #f3f9fd;
+ --cell-event-line: #cde6f6;
+ --cell-event-ink: #075985;
+ --cell-note: #d97706;
+ --cell-muted: #667085;
+ --cell-weekend-num: #667085;
+ --cell-outside-num: #98a2b3;
+ --cell-selected: #e4e7ec;
+
+ --brand: #2563eb;
+ --brand-ink: #1d4ed8;
+ --brand-soft: #eff4ff;
+ --brand-dot: #2563eb;
+
+ --success: #027a48;
+ --success-soft: #ecfdf3;
+ --success-dot: #12b76a;
+ --warning: #b45309;
+ --warning-title: #93370d;
+ --warning-soft: #fdf3e6;
+ --warning-surface: #fffcf5;
+ --warning-line: #fbe3b8;
+ --danger: #b42318;
+ --danger-body: #912018;
+ --danger-soft: #fef3f2;
+ --danger-surface: #fffbfa;
+ --danger-line: #fda29b;
+
+ --dock: #101828;
+ --dock-line: rgb(255 255 255 / 0.14);
+ --dock-ink: #e4e7ec;
+
+ --elevation-window: 0 12px 32px -12px rgb(16 24 40 / 0.18);
+ --elevation-sheet: 0 -14px 34px -14px rgb(16 24 40 / 0.34);
+ --elevation-segment: 0 1px 2px rgb(16 24 40 / 0.08);
+ --elevation-dock: 0 16px 32px -10px rgb(16 24 40 / 0.45);
+
+ /* shadcn semantic mapping */
+ --background: #ffffff;
+ --foreground: var(--fg-strong);
+ --card: var(--surface-card);
+ --card-foreground: var(--fg-strong);
+ --popover: #ffffff;
+ --popover-foreground: var(--fg-strong);
+ --primary: #2563eb;
+ --primary-foreground: #ffffff;
+ --secondary: var(--surface-sunken);
+ --secondary-foreground: var(--fg-body);
+ --muted: var(--surface-sunken);
+ --muted-foreground: var(--fg-tertiary);
+ --accent: var(--surface-sunken);
+ --accent-foreground: var(--fg-strong);
+ --destructive: #d92d20;
+ --border: var(--line);
+ --input: var(--control);
+ --ring: #2563eb;
+ --chart-1: #2563eb;
+ --chart-2: #7c3aed;
+ --chart-3: #059669;
+ --chart-4: #d97706;
+ --chart-5: #db2777;
+ --sidebar: var(--surface-panel);
+ --sidebar-foreground: var(--fg-body);
+ --sidebar-primary: #2563eb;
+ --sidebar-primary-foreground: #ffffff;
+ --sidebar-accent: var(--brand-soft);
+ --sidebar-accent-foreground: var(--brand-ink);
+ --sidebar-border: var(--line);
+ --sidebar-ring: #2563eb;
+
+ /* Shift chips: arbitrary DB colors, tinted per theme */
+ --shift-tint: 8%;
+ --shift-ink-mix: #101828 22%;
+
+ /* Highlighted weekdays: share of the user's colour over the cell surface */
+ --highlight-tint: 10%;
}
.dark {
- --background: oklch(0.145 0 0);
- --foreground: oklch(0.985 0 0);
- --card: oklch(0.205 0 0);
- --card-foreground: oklch(0.985 0 0);
- --popover: oklch(0.205 0 0);
- --popover-foreground: oklch(0.985 0 0);
- --primary: oklch(0.922 0 0);
- --primary-foreground: oklch(0.205 0 0);
- --secondary: oklch(0.269 0 0);
- --secondary-foreground: oklch(0.985 0 0);
- --muted: oklch(0.269 0 0);
- --muted-foreground: oklch(0.708 0 0);
- --accent: oklch(0.269 0 0);
- --accent-foreground: oklch(0.985 0 0);
- --destructive: oklch(0.704 0.191 22.216);
- --border: oklch(1 0 0 / 10%);
- --input: oklch(1 0 0 / 15%);
- --ring: oklch(0.556 0 0);
- --chart-1: oklch(0.488 0.243 264.376);
- --chart-2: oklch(0.696 0.17 162.48);
- --chart-3: oklch(0.769 0.188 70.08);
- --chart-4: oklch(0.627 0.265 303.9);
- --chart-5: oklch(0.645 0.246 16.439);
- --sidebar: oklch(0.205 0 0);
- --sidebar-foreground: oklch(0.985 0 0);
- --sidebar-primary: oklch(0.488 0.243 264.376);
- --sidebar-primary-foreground: oklch(0.985 0 0);
- --sidebar-accent: oklch(0.269 0 0);
- --sidebar-accent-foreground: oklch(0.985 0 0);
- --sidebar-border: oklch(1 0 0 / 10%);
- --sidebar-ring: oklch(0.556 0 0);
+ --fg-strong: #f2f4f7;
+ --fg-body: #e4e7ec;
+ --fg-secondary: #cdd4df;
+ --fg-tertiary: #98a2b3;
+ --fg-faint: #667085;
+
+ --surface-panel: #0e141f;
+ --surface-card: #141b28;
+ --surface-sunken: #1b2333;
+ --surface-cell: #121926;
+ --surface-weekend: #0e141f;
+ --surface-today: #13203a;
+ --line: #1e2637;
+ --line-subtle: #1a2130;
+ --line-grid: #1e2637;
+ --control: #29334a;
+
+ --cell-event: #0f1b28;
+ --cell-event-line: #1d3247;
+ --cell-event-ink: #8fd4f8;
+ --cell-note: #fbbf24;
+ --cell-muted: #7c879b;
+ --cell-weekend-num: #8c99ad;
+ --cell-outside-num: #5a6478;
+ --cell-selected: #2a3349;
+
+ --brand: #2563eb;
+ --brand-ink: #7fa8fb;
+ --brand-soft: rgb(59 130 246 / 0.16);
+ --brand-dot: #3b82f6;
+
+ --success: #6ce9a6;
+ --success-soft: rgb(18 183 106 / 0.14);
+ --success-dot: #32d583;
+ --warning: #fcd34d;
+ --warning-title: #fde68a;
+ --warning-soft: rgb(245 158 11 / 0.15);
+ --warning-surface: rgb(245 158 11 / 0.07);
+ --warning-line: rgb(245 158 11 / 0.3);
+ --danger: #fda29b;
+ --danger-body: #fecdca;
+ --danger-soft: rgb(240 68 56 / 0.15);
+ --danger-surface: rgb(240 68 56 / 0.07);
+ --danger-line: rgb(240 68 56 / 0.35);
+
+ --dock: #1b2333;
+ --dock-line: #29334a;
+ --dock-ink: #e4e7ec;
+
+ --elevation-window: 0 12px 32px -12px rgb(0 0 0 / 0.5);
+ --elevation-sheet: 0 -14px 34px -14px rgb(0 0 0 / 0.6);
+ --elevation-segment: 0 1px 2px rgb(0 0 0 / 0.3);
+ --elevation-dock: 0 16px 32px -10px rgb(0 0 0 / 0.6);
+
+ --background: #0c111b;
+ --foreground: var(--fg-strong);
+ --card: var(--surface-card);
+ --card-foreground: var(--fg-strong);
+ --popover: #141b28;
+ --popover-foreground: var(--fg-strong);
+ --primary: #2563eb;
+ --primary-foreground: #ffffff;
+ --secondary: var(--surface-sunken);
+ --secondary-foreground: var(--fg-body);
+ --muted: var(--surface-sunken);
+ --muted-foreground: var(--fg-tertiary);
+ --accent: var(--surface-sunken);
+ --accent-foreground: var(--fg-strong);
+ --destructive: #f04438;
+ --border: var(--line);
+ --input: var(--control);
+ --ring: #3b82f6;
+ --chart-1: #3b82f6;
+ --chart-2: #a78bfa;
+ --chart-3: #34d399;
+ --chart-4: #fbbf24;
+ --chart-5: #f472b6;
+ --sidebar: var(--surface-panel);
+ --sidebar-foreground: var(--fg-body);
+ --sidebar-primary: #2563eb;
+ --sidebar-primary-foreground: #ffffff;
+ --sidebar-accent: var(--brand-soft);
+ --sidebar-accent-foreground: var(--brand-ink);
+ --sidebar-border: var(--line);
+ --sidebar-ring: #3b82f6;
+
+ --shift-tint: 16%;
+ --highlight-tint: 22%;
}
@layer base {
* {
@apply border-border outline-ring/50;
}
+ html {
+ color-scheme: light;
+ }
+ html.dark {
+ color-scheme: dark;
+ }
body {
- @apply bg-background text-foreground;
+ @apply bg-background text-foreground font-sans antialiased;
+ font-feature-settings: "tnum" 1;
+ }
+ :focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+ }
+ /*
+ * iOS Safari styles date and time inputs natively and gives them an intrinsic
+ * min-width that ignores `width: 100%`, so a start/end pair overflows its
+ * column and the two fields overlap.
+ */
+ input[type="time"],
+ input[type="date"] {
+ -webkit-appearance: none;
+ appearance: none;
+ min-width: 0;
+ }
+ input[type="time"]::-webkit-date-and-time-value,
+ input[type="date"]::-webkit-date-and-time-value {
+ margin: 0;
+ text-align: left;
+ }
+}
+
+/* Scrim behind dialogs and bottom sheets; unlayered so it beats the primitives' bg utility */
+[data-slot="drawer-overlay"],
+[data-slot="dialog-overlay"],
+[data-slot="sheet-overlay"],
+[data-slot="alert-dialog-overlay"] {
+ background-color: rgb(16 24 40 / 0.34);
+}
+.dark :is(
+ [data-slot="drawer-overlay"],
+ [data-slot="dialog-overlay"],
+ [data-slot="sheet-overlay"],
+ [data-slot="alert-dialog-overlay"]
+ ) {
+ background-color: rgb(0 0 0 / 0.55);
+}
+
+/* Uppercase section label from the design system */
+@utility eyebrow {
+ font-size: 11.5px;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--fg-tertiary);
+}
+
+@layer utilities {
+ /*
+ * Shift color helpers. Set --shift on the element to the raw DB hex;
+ * dark mode lightens it because saturated colors sink on dark grounds.
+ */
+ .shift-chip,
+ .shift-rail,
+ .shift-text {
+ --shift-base: var(--shift, var(--brand));
+ }
+ .dark :is(.shift-chip, .shift-rail, .shift-text) {
+ --shift-base: color-mix(in oklch, var(--shift, var(--brand)) 72%, white);
+ }
+ .shift-chip {
+ background-color: color-mix(
+ in oklch,
+ var(--shift-base) var(--shift-tint),
+ transparent
+ );
+ color: color-mix(in oklch, var(--shift-base), var(--shift-ink-mix));
+ }
+ .dark .shift-chip {
+ color: color-mix(in oklch, var(--shift-base) 55%, white);
+ }
+ .shift-solid {
+ background-color: color-mix(in oklch, var(--shift, var(--brand)), black 8%);
+ color: #ffffff;
+ }
+ .shift-rail {
+ background-color: var(--shift-base);
+ }
+ .shift-text {
+ color: color-mix(in oklch, var(--shift-base), var(--shift-ink-mix));
+ }
+ .dark .shift-text {
+ color: color-mix(in oklch, var(--shift-base) 55%, white);
+ }
+ .shift-icon {
+ color: var(--shift, var(--brand));
+ }
+ .dark .shift-icon {
+ color: color-mix(in oklch, var(--shift, var(--brand)) 72%, white);
+ }
+ /* Phone month field: small type on a stronger fill, so the ink moves further from the hue */
+ .shift-field {
+ --shift-base: var(--shift, var(--brand));
+ background-color: color-mix(in oklch, var(--shift-base) 13%, transparent);
+ color: color-mix(in oklch, var(--shift-base), #101828 35%);
+ }
+ .dark .shift-field {
+ --shift-base: color-mix(in oklch, var(--shift, var(--brand)) 72%, white);
+ background-color: color-mix(in oklch, var(--shift-base) 19%, transparent);
+ color: color-mix(in oklch, var(--shift-base) 32%, white);
+ }
+
+ /*
+ * Weekday highlight. Set --highlight to the chosen hex. A flat layer over the cell's own
+ * background keeps weekend and hover; srgb, because oklch drags the hue toward the navy dark cell.
+ */
+ .day-highlight {
+ --highlight-layer: color-mix(in srgb, var(--highlight) var(--highlight-tint), transparent);
+ background-image: linear-gradient(var(--highlight-layer), var(--highlight-layer));
}
}
diff --git a/app/layout.tsx b/app/layout.tsx
index d2854a6..e5018d8 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,5 +1,6 @@
import type { Metadata, Viewport } from "next";
-import { Geist, Geist_Mono } from "next/font/google";
+import { IBM_Plex_Sans, IBM_Plex_Mono } from "next/font/google";
+import { headers } from "next/headers";
import { NextIntlClientProvider } from "next-intl";
import { getMessages, getLocale } from "next-intl/server";
import { ThemeProvider } from "@/components/theme-provider";
@@ -10,14 +11,15 @@ import { QueryProvider } from "@/components/query-provider";
import { getPublicConfig } from "@/lib/public-config";
import "./globals.css";
-const geistSans = Geist({
- variable: "--font-geist-sans",
- subsets: ["latin"],
+const plexSans = IBM_Plex_Sans({
+ variable: "--font-plex-sans",
+ subsets: ["latin", "latin-ext"],
});
-const geistMono = Geist_Mono({
- variable: "--font-geist-mono",
- subsets: ["latin"],
+const plexMono = IBM_Plex_Mono({
+ variable: "--font-plex-mono",
+ subsets: ["latin", "latin-ext"],
+ weight: ["400", "500", "600"],
});
export const metadata: Metadata = {
@@ -56,7 +58,10 @@ export const viewport: Viewport = {
initialScale: 1,
maximumScale: 1,
userScalable: false,
- themeColor: [{ media: "(prefers-color-scheme: dark)", color: "#0a0a0a" }],
+ themeColor: [
+ { media: "(prefers-color-scheme: light)", color: "#ffffff" },
+ { media: "(prefers-color-scheme: dark)", color: "#0c111b" },
+ ],
};
export default async function RootLayout({
@@ -67,25 +72,28 @@ export default async function RootLayout({
const locale = await getLocale();
const messages = await getMessages();
const publicConfig = getPublicConfig();
+ const nonce = (await headers()).get("x-nonce") || undefined;
return (
<html lang={locale} suppressHydrationWarning>
<head>
{/* Inject public config for immediate client-side access (zero latency) */}
<script
+ nonce={nonce}
dangerouslySetInnerHTML={{
__html: `window.__PUBLIC_CONFIG__=${JSON.stringify(publicConfig)};`,
}}
/>
</head>
<body
- className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
+ className={`${plexSans.variable} ${plexMono.variable} antialiased bg-background text-foreground`}
>
<ThemeProvider
attribute="class"
- defaultTheme="dark"
- enableSystem={false}
- disableTransitionOnChange={false}
+ defaultTheme="system"
+ enableSystem
+ disableTransitionOnChange
+ nonce={nonce}
>
<NextIntlClientProvider messages={messages} locale={locale}>
<QueryProvider>
diff --git a/app/login/page.tsx b/app/login/page.tsx
index be55220..01b54fb 100644
--- a/app/login/page.tsx
+++ b/app/login/page.tsx
@@ -2,38 +2,51 @@
import { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
-import { useTranslations } from "next-intl";
-import { useLocale } from "next-intl";
+import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { signIn } from "@/lib/auth/client";
import { useAuth } from "@/hooks/useAuth";
+import { safeReturnUrl } from "@/lib/safe-return-url";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { AuthHeader } from "@/components/auth-header";
-import { AppFooter } from "@/components/app-footer";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
-import { AlertTriangle, X } from "lucide-react";
+import {
+ AuthDivider,
+ AuthShell,
+ PasswordInput,
+ authInputClass,
+} from "@/components/auth-shell";
+import {
+ DiscordIcon,
+ GitHubIcon,
+ GoogleIcon,
+} from "@/components/auth-provider-icons";
+import { Field, InfoNote } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { Building2, Info, ShieldAlert, X } from "lucide-react";
import { format } from "date-fns";
import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
import {
isRateLimitError,
handleRateLimitError,
} from "@/lib/rate-limit-client";
+import { useMounted } from "@/hooks/useMediaQuery";
+
+type SocialProvider = "google" | "github" | "discord";
+
+const SOCIAL_ICONS = {
+ google: GoogleIcon,
+ github: GitHubIcon,
+ discord: DiscordIcon,
+} as const;
+
+const secondaryButtonClass =
+ "h-10 rounded-[9px] text-[13.5px] font-medium text-fg-body";
+
-/**
- * Login page with email/password and OIDC providers
- *
- * Features:
- * - Email/Password authentication
- * - Social login (Google, GitHub, Discord)
- * - Custom OIDC provider
- * - "Continue as Guest" for auth-disabled mode
- * - Dynamic provider list based on env config
- */
export default function LoginPage() {
const t = useTranslations();
const locale = useLocale();
@@ -46,26 +59,21 @@ export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const [mounted, setMounted] = useState(false);
+ // False during SSR and hydration, true afterwards
+ const mounted = useMounted();
const [banInfo, setBanInfo] = useState<{
reason?: string;
expiresAt?: string;
} | null>(null);
- const versionInfo = useVersionInfo();
-
- useEffect(() => {
- setMounted(true);
- }, []);
// Redirect authenticated users to home or returnUrl
useEffect(() => {
if (mounted && isAuthenticated) {
- const returnUrl = searchParams.get("returnUrl");
- router.replace(returnUrl || "/");
+ const returnUrl = safeReturnUrl(searchParams.get("returnUrl"));
+ router.replace(returnUrl);
}
}, [mounted, isAuthenticated, searchParams, router]);
- // If auth is disabled, redirect to home
useEffect(() => {
if (!isAuthEnabled) {
router.replace("/");
@@ -98,12 +106,11 @@ export default function LoginPage() {
});
if (result.error) {
- // Check if user is banned (Better Auth returns BANNED_USER code)
+ // Better Auth reports bans as BANNED_USER
if (
result.error.code === "BANNED_USER" ||
result.error.message?.toLowerCase().includes("banned")
) {
- // Fetch ban details from our API
try {
const banResponse = await fetch("/api/auth/ban-info", {
method: "POST",
@@ -118,13 +125,11 @@ export default function LoginPage() {
expiresAt: banData.banExpires,
});
} else {
- // Fallback if API fails
setBanInfo({
reason: result.error.message || t("auth.accountBanned"),
});
}
} catch {
- // Fallback if fetch fails
setBanInfo({
reason: result.error.message || t("auth.accountBanned"),
});
@@ -132,10 +137,8 @@ export default function LoginPage() {
return;
}
- // Check if the error indicates rate limiting (Better Auth wraps 429 errors)
- // The error might contain the fetch response status
+ // Better Auth hides the 429 headers; a second request exposes them for the message
if (result.error.status === 429) {
- // Make a test request to get proper rate limit headers for user-friendly message
try {
const testResponse = await fetch("/api/auth/sign-in/email", {
method: "POST",
@@ -148,7 +151,6 @@ export default function LoginPage() {
return;
}
} catch {
- // If test request fails, show generic rate limit message
toast.error(t("rateLimit.title"), {
description: t("rateLimit.fallback"),
});
@@ -161,7 +163,7 @@ export default function LoginPage() {
}
toast.success(t("auth.loginSuccess"));
- // Redirect will be handled by useEffect when isAuthenticated updates
+ // Redirect is handled by the effect once isAuthenticated updates
} catch (error) {
console.error("Login error:", error);
toast.error(t("auth.loginError"));
@@ -170,14 +172,11 @@ export default function LoginPage() {
}
};
- const handleSocialLogin = async (
- provider: "google" | "github" | "discord"
- ) => {
+ const handleSocialLogin = async (provider: SocialProvider) => {
setIsLoading(true);
try {
- // Get returnUrl from query params for OAuth callback
- const returnUrl = searchParams.get("returnUrl") || "/";
+ const returnUrl = safeReturnUrl(searchParams.get("returnUrl"));
await signIn.social({
provider,
callbackURL: returnUrl,
@@ -193,8 +192,7 @@ export default function LoginPage() {
setIsLoading(true);
try {
- // Get returnUrl from query params for OAuth callback
- const returnUrl = searchParams.get("returnUrl") || "/";
+ const returnUrl = safeReturnUrl(searchParams.get("returnUrl"));
await signIn.oauth2({
providerId: "custom-oidc",
callbackURL: returnUrl,
@@ -206,236 +204,167 @@ export default function LoginPage() {
}
};
- if (!isAuthEnabled) {
- return null;
- }
-
- // Prevent hydration mismatch by showing loader until mounted
- if (!mounted) {
- return <FullscreenLoader />;
- }
+ const socialProviders = (["google", "github", "discord"] as const).filter(
+ (provider) => providers[provider]
+ );
+ const providerLabels: Record<SocialProvider, string> = {
+ google: t("auth.provider.google"),
+ github: t("auth.provider.github"),
+ discord: t("auth.provider.discord"),
+ };
return (
- <div className="flex flex-col min-h-screen">
- <AuthHeader />
-
- <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-primary/5 px-4 py-8">
- <div className="w-full max-w-md space-y-8">
- {/* Ban Warning Banner */}
- {banInfo && (
- <div className="relative rounded-lg border-2 border-destructive bg-destructive/5 p-4 shadow-lg animate-in fade-in slide-in-from-top-4 duration-500">
- <button
- onClick={() => setBanInfo(null)}
- className="absolute top-2 right-2 p-1 rounded-md hover:bg-destructive/10 transition-colors"
+ <AuthShell title={t("auth.login")} description={t("authPage.loginSubtitle")}>
+ {banInfo && (
+ <StatusBanner
+ tone="danger"
+ icon={ShieldAlert}
+ title={t("auth.accountBanned")}
+ action={
+ <button
+ type="button"
+ onClick={() => setBanInfo(null)}
+ aria-label={t("common.close")}
+ className="flex size-7 items-center justify-center rounded-md text-danger transition-colors hover:bg-danger-soft"
+ >
+ <X className="size-4" />
+ </button>
+ }
+ >
+ {banInfo.reason && <p>{banInfo.reason}</p>}
+ <p className="mt-1 text-[12px]">
+ {banInfo.expiresAt
+ ? t("admin.bannedUntil", {
+ date: format(new Date(banInfo.expiresAt), "PPP", {
+ locale: dateLocale,
+ }),
+ })
+ : t("admin.bannedPermanently")}
+ </p>
+ </StatusBanner>
+ )}
+
+ <form onSubmit={handleEmailLogin} className="flex flex-col gap-3">
+ <Field label={t("common.labels.email")} htmlFor="email">
+ <Input
+ id="email"
+ type="email"
+ autoComplete="email"
+ placeholder={t("auth.emailPlaceholder")}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ disabled={isLoading}
+ required
+ className={authInputClass}
+ />
+ </Field>
+
+ <Field label={t("common.labels.password")} htmlFor="password">
+ <PasswordInput
+ id="password"
+ autoComplete="current-password"
+ placeholder={t("auth.passwordPlaceholder")}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ />
+ </Field>
+
+ <Button
+ type="submit"
+ className="h-11 w-full rounded-[9px] text-[15px] font-semibold"
+ disabled={isLoading}
+ >
+ {isLoading ? t("common.loading") : t("auth.login")}
+ </Button>
+ </form>
+
+ {(socialProviders.length > 0 || oidc.enabled) && (
+ <>
+ <AuthDivider>{t("common.or")}</AuthDivider>
+
+ <div className="flex flex-col gap-2">
+ {socialProviders.length > 0 && (
+ <div
+ className={cn(
+ "grid gap-2",
+ socialProviders.length === 3 && "grid-cols-3",
+ socialProviders.length === 2 && "grid-cols-2"
+ )}
>
- <X className="h-4 w-4 text-destructive" />
- </button>
- <div className="flex gap-3 pr-6">
- <AlertTriangle className="h-6 w-6 text-destructive flex-shrink-0 mt-0.5" />
- <div className="space-y-1">
- <h3 className="font-semibold text-destructive text-lg">
- {t("auth.accountBanned")}
- </h3>
- {banInfo.reason && (
- <p className="text-sm text-foreground">{banInfo.reason}</p>
- )}
- {banInfo.expiresAt ? (
- <p className="text-xs text-muted-foreground mt-2">
- {t("admin.bannedUntil", {
- date: format(new Date(banInfo.expiresAt), "PPP", {
- locale: dateLocale,
- }),
- })}
- </p>
- ) : (
- <p className="text-xs text-muted-foreground mt-2">
- {t("admin.bannedPermanently")}
- </p>
- )}
- </div>
- </div>
- </div>
- )}
-
- {/* Registration Disabled Info Banner */}
- {!allowRegistration && (
- <div className="rounded-lg border border-primary/30 bg-primary/5 p-4 shadow-sm animate-in fade-in slide-in-from-top-4 duration-500">
- <div className="flex gap-3">
- <AlertTriangle className="h-5 w-5 text-primary flex-shrink-0 mt-0.5" />
- <div className="space-y-1">
- <h3 className="font-semibold text-foreground">
- {t("auth.registrationDisabled")}
- </h3>
- <p className="text-sm text-muted-foreground">
- {t("auth.registrationDisabledDescription")}
- </p>
- </div>
- </div>
- </div>
- )}
-
- {/* Header */}
- <div className="text-center space-y-2">
- <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.loginTitle")}
- </h1>
- <p className="text-sm text-muted-foreground">
- {t("auth.loginDescription")}
- </p>
- </div>
-
- {/* Login Form */}
- <div className="rounded-xl border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 p-8 shadow-lg backdrop-blur-sm">
- <form onSubmit={handleEmailLogin} className="space-y-6">
- {/* Email */}
- <div className="space-y-2">
- <Label htmlFor="email">{t("common.labels.email")}</Label>
- <Input
- id="email"
- type="email"
- placeholder={t("auth.emailPlaceholder")}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- disabled={isLoading}
- required
- />
- </div>
-
- {/* Password */}
- <div className="space-y-2">
- <Label htmlFor="password">{t("common.labels.password")}</Label>
- <Input
- id="password"
- type="password"
- placeholder={t("auth.passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- disabled={isLoading}
- required
- />
- </div>
-
- {/* Submit Button */}
- <Button type="submit" className="w-full" disabled={isLoading}>
- {isLoading ? t("common.loading") : t("auth.login")}
- </Button>
- </form>
-
- {/* OAuth Providers */}
- {(providers.hasAny || oidc.enabled) && (
- <>
- <div className="relative my-6">
- <div className="absolute inset-0 flex items-center">
- <span className="w-full border-t border-border/50" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-card px-2 text-muted-foreground">
- {t("common.or")}
- </span>
- </div>
- </div>
-
- <div className="space-y-3">
- {providers.google && (
- <Button
- variant="outline"
- className="w-full"
- onClick={() => handleSocialLogin("google")}
- disabled={isLoading}
- >
- {t("auth.continueWith", {
- provider: t("auth.provider.google"),
- })}
- </Button>
- )}
-
- {providers.github && (
- <Button
- variant="outline"
- className="w-full"
- onClick={() => handleSocialLogin("github")}
- disabled={isLoading}
- >
- {t("auth.continueWith", {
- provider: t("auth.provider.github"),
- })}
- </Button>
- )}
-
- {providers.discord && (
+ {socialProviders.map((provider) => {
+ const Icon = SOCIAL_ICONS[provider];
+ return (
<Button
+ key={provider}
+ type="button"
variant="outline"
- className="w-full"
- onClick={() => handleSocialLogin("discord")}
+ className={cn(secondaryButtonClass, "px-2")}
+ onClick={() => handleSocialLogin(provider)}
disabled={isLoading}
>
- {t("auth.continueWith", {
- provider: t("auth.provider.discord"),
- })}
+ <Icon className="size-4" />
+ {providerLabels[provider]}
</Button>
- )}
-
- {oidc.enabled && (
- <Button
- variant="outline"
- className="w-full"
- onClick={handleCustomOidcLogin}
- disabled={isLoading}
- >
- {t("auth.continueWith", {
- provider: oidc.name || t("auth.provider.customOidc"),
- })}
- </Button>
- )}
- </div>
- </>
- )}
-
- {/* Continue as Guest */}
- {allowGuest && (
- <>
- <div className="relative my-6">
- <div className="absolute inset-0 flex items-center">
- <span className="w-full border-t border-border/50" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-card px-2 text-muted-foreground">
- {t("common.or")}
- </span>
- </div>
- </div>
- <Button
- variant="ghost"
- className="w-full border-2 border-dashed border-border/50 hover:border-primary/50 hover:bg-primary/5"
- onClick={() => {
- const returnUrl = searchParams.get("returnUrl") || "/";
- // Use replace instead of push to avoid login redirect loop
- router.replace(returnUrl);
- }}
- disabled={isLoading}
- >
- {t("auth.continueAsGuest")}
- </Button>
- </>
+ );
+ })}
+ </div>
)}
- {/* Register Link */}
- {allowRegistration && (
- <p className="mt-6 text-center text-sm text-muted-foreground">
- {t("auth.noAccountYet")}{" "}
- <Link
- href="/register"
- className="font-medium text-primary hover:underline"
- >
- {t("auth.register")}
- </Link>
- </p>
+ {oidc.enabled && (
+ <Button
+ type="button"
+ variant="outline"
+ className={secondaryButtonClass}
+ onClick={handleCustomOidcLogin}
+ disabled={isLoading}
+ >
+ <Building2 className="size-4" />
+ {t("authPage.signInWith", {
+ provider: oidc.name || t("auth.provider.customOidc"),
+ })}
+ </Button>
)}
</div>
- </div>
+ </>
+ )}
+
+ <div className="flex flex-col gap-2.5 border-t border-line pt-4">
+ {allowGuest && (
+ <button
+ type="button"
+ className="flex h-10 items-center justify-center rounded-[9px] border border-dashed border-control text-[13.5px] font-medium text-fg-secondary transition-colors hover:bg-surface-panel disabled:pointer-events-none disabled:opacity-50"
+ onClick={() => {
+ const returnUrl = safeReturnUrl(searchParams.get("returnUrl"));
+ // replace, not push, so Back does not loop into the login redirect
+ router.replace(returnUrl);
+ }}
+ disabled={isLoading}
+ >
+ {t("auth.continueAsGuest")}
+ </button>
+ )}
+
+ {allowRegistration ? (
+ <p className="text-center text-[13.5px] text-fg-secondary">
+ {t("auth.noAccountYet")}{" "}
+ <Link
+ href="/register"
+ className="font-semibold text-brand-ink hover:underline"
+ >
+ {t("auth.register")}
+ </Link>
+ </p>
+ ) : (
+ <InfoNote icon={Info}>
+ <div className="font-semibold text-fg-body">
+ {t("auth.registrationDisabled")}
+ </div>
+ {t("auth.registrationDisabledDescription")}
+ </InfoNote>
+ )}
</div>
-
- <AppFooter versionInfo={versionInfo} />
- </div>
+ </AuthShell>
);
}
diff --git a/app/page.tsx b/app/page.tsx
index 6c57879..6925c5c 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -1,20 +1,16 @@
"use client";
-import { useState, useEffect, Suspense } from "react";
+import { useState, useEffect, Suspense, useCallback, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
-import { useLocale } from "next-intl";
-import { isSameDay } from "date-fns";
-import { Button } from "@/components/ui/button";
-import { Plus } from "lucide-react";
-import { getDateLocale } from "@/lib/locales";
-import { motion, AnimatePresence } from "motion/react";
+import { useTranslations } from "next-intl";
+import { isSameMonth } from "date-fns";
import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote } from "@/lib/db/schema";
import { useCalendars } from "@/hooks/useCalendars";
import { useShifts } from "@/hooks/useShifts";
import { usePresets } from "@/hooks/usePresets";
import { useNotes } from "@/hooks/useNotes";
-import { useCompareData } from "@/hooks/useCompareData";
+import { useCompareMode } from "@/hooks/useCompareMode";
import { useViewSettings } from "@/hooks/useViewSettings";
import { useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "@/lib/query-keys";
@@ -22,35 +18,43 @@ import { useShiftActions } from "@/hooks/useShiftActions";
import { useNoteActions } from "@/hooks/useNoteActions";
import { useExternalSync } from "@/hooks/useExternalSync";
import { useDialogStates } from "@/hooks/useDialogStates";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
import { useAuth } from "@/hooks/useAuth";
+import { useConnectionStatus } from "@/hooks/useConnectionStatus";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import { EmptyCalendarState } from "@/components/empty-calendar-state";
import { GuestEmptyState } from "@/components/guest-empty-state";
import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { CalendarContent } from "@/components/calendar-content";
import { CalendarCompareSheet } from "@/components/calendar-compare-sheet";
-import { CalendarCompareView } from "@/components/calendar-compare-view";
-import { AppFooter } from "@/components/app-footer";
+import { CompareWorkspace } from "@/components/compare-workspace";
+import { CalendarWorkspace } from "@/components/calendar-workspace";
import { AppHeader } from "@/components/app-header";
import { DialogManager } from "@/components/dialog-manager";
import { ShiftFormData } from "@/components/shift-sheet";
import { getCalendarDays } from "@/lib/calendar-utils";
import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
import { findNotesForDate } from "@/lib/event-utils";
-import { toast } from "sonner";
-import { useTranslations } from "next-intl";
+import { DayLayoutOptions } from "@/lib/shift-display";
+import { CalendarViewSettings } from "@/lib/view-settings";
+
+function toDayLayout(view: CalendarViewSettings): DayLayoutOptions {
+ return {
+ maxShifts: view.shiftsPerDay ?? undefined,
+ maxExternalShifts: view.externalShiftsPerDay ?? undefined,
+ sortType: view.sortType,
+ sortOrder: view.sortOrder,
+ combinedSort: view.combinedSort,
+ };
+}
function HomeContent() {
const router = useRouter();
const searchParams = useSearchParams();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
const t = useTranslations();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
- // Auth hook
const { isGuest } = useAuth();
- // Data hooks
const {
calendars,
selectedCalendar,
@@ -59,7 +63,6 @@ function HomeContent() {
hasLoadedOnce,
createCalendar: createCalendarHook,
deleteCalendar: deleteCalendarHook,
- refetchCalendars,
} = useCalendars(searchParams.get("id"));
const {
@@ -78,34 +81,54 @@ function HomeContent() {
hasLoadedOnce: presetsLoadedOnce,
} = usePresets(selectedCalendar);
- // Local state
- const [selectedPresetId, setSelectedPresetId] = useState<
- string | undefined
- >();
+ const { canEdit } = useCalendarPermission(selectedCalendar);
+ // Toasts are owned by CalendarWorkspace; this is only the stamping gate
+ const { isOnline } = useConnectionStatus({ toasts: false });
+
+ const [selectedPresetId, setSelectedPresetId] = useState<string | undefined>();
const [currentDate, setCurrentDate] = useState(new Date());
const [selectedDate, setSelectedDate] = useState<Date | undefined>();
- const [compareNoteCalendarId, setCompareNoteCalendarId] = useState<
- string | undefined
- >();
const [editingShift, setEditingShift] = useState<ShiftWithCalendar | undefined>();
+ const [daySheetOpen, setDaySheetOpen] = useState(false);
- // Compare mode state (needs to be before useNotes hook)
- const [isCompareMode, setIsCompareMode] = useState(false);
- const [showCompareSelector, setShowCompareSelector] = useState(false);
- const [selectedCompareIds, setSelectedCompareIds] = useState<string[]>([]);
-
- // Local UI state for toggling dates in compare mode (shows spinner during API call)
- const [compareTogglingDates, setCompareTogglingDates] = useState<
- Map<string, Set<string>>
- >(new Map());
+ // Selection is tied to the calendar it was made in; switching calendars falls back to today
+ const [selection, setSelection] = useState<{ calendarId?: string; day: Date }>(
+ () => ({ day: new Date() })
+ );
+ // A fresh Date per render would invalidate every memo keyed on the selected day
+ const todayKey = formatDateToLocal(new Date());
+ const today = useMemo(() => parseLocalDate(todayKey), [todayKey]);
+ const selectedDay =
+ selection.calendarId === selectedCalendar ? selection.day : today;
+ const selectDay = useCallback(
+ (day: Date) => setSelection({ calendarId: selectedCalendar, day }),
+ [selectedCalendar]
+ );
- // Query client for cache invalidation
const queryClient = useQueryClient();
- // Compare mode data using React Query
- const compareData = useCompareData({
- calendarIds: selectedCompareIds,
- enabled: isCompareMode,
+ const {
+ isCompareMode,
+ showCompareSelector,
+ selectedCompareIds,
+ compareTogglingDates,
+ compareNoteCalendarId,
+ setCompareNoteCalendarId,
+ compareData,
+ handleToggleCompareCalendar,
+ handleExitCompare,
+ openComparePicker,
+ startCompare,
+ cancelComparePicker,
+ handleCompareDayClick,
+ } = useCompareMode({
+ calendars,
+ hasLoadedOnce,
+ selectedCalendar,
+ currentDate,
+ setCurrentDate,
+ selectDay,
+ selectedPresetId,
});
const {
@@ -114,516 +137,233 @@ function HomeContent() {
updateNote: updateNoteHook,
deleteNote: deleteNoteHook,
} = useNotes(isCompareMode ? compareNoteCalendarId : selectedCalendar);
- const { externalSyncs, hasSyncErrors } = useExternalSync(
- selectedCalendar || null
- );
+ const { externalSyncs, hasSyncErrors } = useExternalSync(selectedCalendar || null);
- // View settings
const viewSettings = useViewSettings();
-
- // Dialog states
const dialogStates = useDialogStates();
- // Note actions
const noteActions = useNoteActions({
createNote: createNoteHook,
updateNote: updateNoteHook,
deleteNote: deleteNoteHook,
});
- // Wrapper for note submit that reloads compare data
- const handleNoteSubmit = async (
- noteText: string,
- type: "note" | "event",
- color?: string,
- recurringPattern?: string,
- recurringInterval?: number
- ) => {
- await noteActions.handleNoteSubmit(
- noteText,
- type,
- color,
- recurringPattern,
- recurringInterval
- );
-
- // Invalidate notes cache for the specific calendar in compare mode
- if (isCompareMode && compareNoteCalendarId) {
- compareData.invalidateNotes(compareNoteCalendarId);
- }
- };
-
- // Wrapper for note delete that reloads compare data
- const handleNoteDelete = async () => {
- await noteActions.handleNoteDelete();
-
- // Invalidate notes cache for the specific calendar in compare mode
- if (isCompareMode && compareNoteCalendarId) {
- compareData.invalidateNotes(compareNoteCalendarId);
- }
- };
+ const shiftActions = useShiftActions({
+ shifts,
+ presets,
+ createShift: createShiftHook,
+ deleteShift: deleteShiftHook,
+ });
- // Notes list dialog handlers
const handleEditNoteFromList = (note: CalendarNote) => {
dialogStates.setShowNotesListDialog(false);
- noteActions.openNoteDialog(
- dialogStates.selectedDayDate || new Date(),
- note
- );
+ noteActions.openNoteDialog(dialogStates.selectedDayDate || new Date(), note);
};
const handleDeleteNoteFromList = async (noteId: string) => {
const success = await deleteNoteHook(noteId);
-
- if (success) {
- // Update the notes list in the dialog
- const updatedNotes = dialogStates.selectedDayNotes.filter(
- (n) => n.id !== noteId
- );
- dialogStates.setSelectedDayNotes(updatedNotes);
-
- // If no notes left, close the dialog
- if (updatedNotes.length === 0) {
- dialogStates.setShowNotesListDialog(false);
- }
-
- // Invalidate compare mode data if needed
- if (isCompareMode && compareNoteCalendarId) {
- compareData.invalidateNotes(compareNoteCalendarId);
- }
+ if (!success) return;
+ const updatedNotes = dialogStates.selectedDayNotes.filter((n) => n.id !== noteId);
+ dialogStates.setSelectedDayNotes(updatedNotes);
+ if (updatedNotes.length === 0) {
+ dialogStates.setShowNotesListDialog(false);
}
};
const handleAddNewNoteFromList = () => {
- const date = dialogStates.selectedDayDate || new Date();
- noteActions.openNoteDialog(date, undefined);
+ noteActions.openNoteDialog(dialogStates.selectedDayDate || new Date(), undefined);
};
- // Version info
- const versionInfo = useVersionInfo();
+ /** Right-click / long-press shortcut: list the day's notes, or start a new one. */
+ const openNotesForDay = (dayNotes: CalendarNote[], date: Date) => {
+ const allDayNotes = findNotesForDate(dayNotes, date);
+ if (allDayNotes.length >= 1) {
+ dialogStates.setSelectedDayDate(date);
+ dialogStates.setSelectedDayNotes(allDayNotes);
+ dialogStates.setShowNotesListDialog(true);
+ } else {
+ noteActions.openNoteDialog(date, undefined);
+ }
+ };
- // Shift actions
- const shiftActions = useShiftActions({
- shifts,
- presets,
- createShift: createShiftHook,
- deleteShift: deleteShiftHook,
- });
+ const openDayShifts = (date: Date, dayShifts: ShiftWithCalendar[]) => {
+ dialogStates.setSelectedDayDate(date);
+ dialogStates.setSelectedDayShifts(dayShifts);
+ dialogStates.setShowDayShiftsDialog(true);
+ };
- // Load compare mode from URL on initial load
- useEffect(() => {
- const compareParam = searchParams.get("compare");
- if (compareParam && !isCompareMode) {
- const calendarIds = compareParam.split(",").filter((id) => id.trim());
- if (calendarIds.length >= 2 && calendarIds.length <= 3) {
- // Verify that all calendars exist
- const validIds = calendarIds.filter((id) =>
- calendars.some((cal) => cal.id === id)
- );
- if (validIds.length >= 2) {
- setSelectedCompareIds(validIds);
- setIsCompareMode(true);
- }
- }
- } else if (!compareParam && isCompareMode) {
- // If compare param is removed from URL, exit compare mode
- setIsCompareMode(false);
- setSelectedCompareIds([]);
- setCompareTogglingDates(new Map());
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [searchParams, calendars]);
+ const openCompareNotes = (calendarId: string, date: Date) => {
+ setCompareNoteCalendarId(calendarId);
+ openNotesForDay(compareData.notesMap.get(calendarId) || [], date);
+ };
- // Update URL when calendar or compare mode changes
useEffect(() => {
if (isCompareMode && selectedCompareIds.length >= 2) {
- // In compare mode
- router.replace(`/?compare=${selectedCompareIds.join(",")}`, {
- scroll: false,
- });
+ router.replace(`/?compare=${selectedCompareIds.join(",")}`, { scroll: false });
} else if (selectedCalendar && !isCompareMode) {
- // Normal mode with selected calendar
router.replace(`/?id=${selectedCalendar}`, { scroll: false });
}
}, [selectedCalendar, isCompareMode, selectedCompareIds, router]);
- // Calendar operations
const handleDeleteCalendar = async () => {
if (!selectedCalendar) return;
await deleteCalendarHook(selectedCalendar);
dialogStates.setShowCalendarSettingsDialog(false);
};
- // External sync operations
- const handleSyncNotifications = () => {
- dialogStates.setShowSyncNotificationDialog(true);
- };
-
const handleSyncComplete = () => {
- // Invalidate caches - React Query will refetch automatically
queryClient.invalidateQueries({
queryKey: queryKeys.shifts.byCalendar(selectedCalendar!),
});
queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all });
};
- // Manual shift creation
- const handleManualShiftCreation = () => {
- setSelectedDate(new Date());
+ const openShiftSheet = (date: Date, shift?: ShiftWithCalendar) => {
+ setEditingShift(shift);
+ setSelectedDate(date);
dialogStates.setShowShiftDialog(true);
};
- // Day interaction handlers
- const handleDayClick = (date: Date | string) => {
- // Parse date to ensure it's a Date object
- const targetDate =
- typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
- ? parseLocalDate(date)
- : new Date(date);
- shiftActions.handleAddShift(targetDate, selectedPresetId);
- };
-
- const handleDayRightClick = (e: React.MouseEvent, date: Date | string) => {
- e.preventDefault();
- // Parse date to ensure it's a Date object
- const targetDate =
- typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
- ? parseLocalDate(date)
- : new Date(date);
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(notes, targetDate);
-
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- dialogStates.setSelectedDayDate(targetDate);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- noteActions.openNoteDialog(targetDate, undefined);
- }
- };
-
- const handleNoteIconClick = (e: React.MouseEvent, date: Date | string) => {
- e.stopPropagation();
- // Parse date to ensure it's a Date object
- const targetDate =
- typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
- ? parseLocalDate(date)
- : new Date(date);
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(notes, targetDate);
-
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- dialogStates.setSelectedDayDate(targetDate);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- noteActions.openNoteDialog(targetDate, undefined);
- }
- };
-
- const handleLongPressDay = (date: Date) => {
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(notes, date);
-
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- noteActions.openNoteDialog(date, undefined);
- }
- };
-
- const handleShowAllShifts = (date: Date, dayShifts: ShiftWithCalendar[]) => {
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayShifts(dayShifts);
- dialogStates.setShowDayShiftsDialog(true);
- };
-
- const handleShowSyncedShifts = (
- date: Date,
- syncedShifts: ShiftWithCalendar[]
- ) => {
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedSyncedShifts(syncedShifts);
- dialogStates.setShowSyncedShiftsDialog(true);
- };
-
- const handleDeleteShiftFromDayDialog = async (shiftId: string) => {
- dialogStates.setShowDayShiftsDialog(false);
- await shiftActions.handleDeleteShift(shiftId);
- refetchShifts();
+ const handleEditShift = (shift: ShiftWithCalendar) => {
+ openShiftSheet(shift.date as Date, shift);
};
- // Handler for editing a shift from the day shifts dialog
- const handleEditShiftFromDayDialog = (shift: ShiftWithCalendar) => {
- setEditingShift(shift);
- setSelectedDate(shift.date as Date);
- dialogStates.setShowShiftDialog(true);
- };
-
- // Clear editing state when dialog closes
const handleShiftDialogChange = (open: boolean) => {
dialogStates.setShowShiftDialog(open);
- if (!open) {
- setEditingShift(undefined);
- }
+ if (!open) setEditingShift(undefined);
};
- // Handle shift submit (create or update)
const handleShiftSubmit = async (formData: ShiftFormData) => {
if (editingShift) {
- // Update existing shift
await updateShiftHook(editingShift.id, formData);
setEditingShift(undefined);
refetchShifts();
} else {
- // Create new shift
await shiftActions.handleShiftSubmit(formData);
}
};
- // Compare mode handlers
- const handleCompareClick = () => {
- setShowCompareSelector(true);
- };
-
- const handleToggleCompareCalendar = (calendarId: string) => {
- setSelectedCompareIds((prev) =>
- prev.includes(calendarId)
- ? prev.filter((id) => id !== calendarId)
- : [...prev, calendarId]
- );
- };
-
- const handleStartCompare = () => {
- setShowCompareSelector(false);
- setIsCompareMode(true);
- };
-
- const handleExitCompare = () => {
- setIsCompareMode(false);
- setSelectedCompareIds([]);
- setCompareTogglingDates(new Map());
- // Immediately update URL to prevent re-loading from URL parameter
- if (selectedCalendar) {
- router.replace(`/?id=${selectedCalendar}`, { scroll: false });
- } else {
- router.replace(`/`, { scroll: false });
- }
+ const handleDeleteShiftFromDayDialog = async (shiftId: string) => {
+ dialogStates.setShowDayShiftsDialog(false);
+ await shiftActions.handleDeleteShift(shiftId);
+ refetchShifts();
};
- // Compare mode interaction handlers
- const handleCompareDayClick = async (
- calendarId: string,
- date: Date | string
- ) => {
- // Always parse date to ensure it's a Date object
- const targetDate =
- typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
- ? parseLocalDate(date)
- : new Date(date);
-
- if (!selectedPresetId) {
- // No preset selected, just show existing shifts if any
- const shifts = compareData.shiftsMap.get(calendarId) || [];
-
- const dayShifts = shifts.filter(
- (shift) => shift.date && isSameDay(shift.date as Date, targetDate)
- );
-
- if (dayShifts.length > 0) {
- dialogStates.setSelectedDayDate(targetDate);
- dialogStates.setSelectedDayShifts(dayShifts);
- dialogStates.setShowDayShiftsDialog(true);
- }
- return;
- }
-
- // Preset selected, add or remove shift
- const presets = compareData.presetsMap.get(calendarId) || [];
- const shifts = compareData.shiftsMap.get(calendarId) || [];
- const preset = presets.find((p) => p.id === selectedPresetId);
- if (!preset) return;
-
- const dateKey = formatDateToLocal(targetDate);
-
- // Check if already toggling
- const togglingDates = compareTogglingDates.get(calendarId) || new Set();
- if (togglingDates.has(dateKey)) return;
-
- // Mark as toggling
- setCompareTogglingDates((prev) => {
- const updated = new Map(prev);
- const current = updated.get(calendarId) || new Set();
- const newSet = new Set(current);
- newSet.add(dateKey);
- updated.set(calendarId, newSet);
- return updated;
- });
-
- try {
- // Check if shift already exists
- const existingShift = shifts.find(
- (shift) =>
- shift.date &&
- isSameDay(shift.date as Date, targetDate) &&
- shift.title === preset.title &&
- shift.startTime === preset.startTime &&
- shift.endTime === preset.endTime
- );
-
- if (existingShift) {
- // Delete existing shift using mutation
- await compareData.deleteShift({
- calendarId,
- shiftId: existingShift.id,
- });
- } else {
- // Create new shift using mutation
- const shiftData = {
- date: dateKey,
- startTime: preset.startTime,
- endTime: preset.endTime,
- title: preset.title,
- color: preset.color,
- notes: preset.notes || "",
- presetId: preset.id,
- isAllDay: preset.isAllDay || false,
- };
-
- await compareData.createShift({ calendarId, formData: shiftData });
- }
- } catch (error) {
- console.error("Failed to toggle shift:", error);
- toast.error(t("common.error"));
- } finally {
- // Remove toggling state
- setCompareTogglingDates((prev) => {
- const updated = new Map(prev);
- const current = updated.get(calendarId) || new Set();
- const newSet = new Set(current);
- newSet.delete(dateKey);
- updated.set(calendarId, newSet);
- return updated;
- });
+ // Month navigation keeps the selection inside the visible month
+ const handleDateChange = (date: Date) => {
+ setCurrentDate(date);
+ if (!isSameMonth(selectedDay, date)) {
+ selectDay(isSameMonth(new Date(), date) ? new Date() : new Date(date.getFullYear(), date.getMonth(), 1));
}
};
- const handleCompareDayRightClick = (
- calendarId: string,
- e: React.MouseEvent,
- date: Date
- ) => {
- e.preventDefault();
- const calendarNotes = compareData.notesMap.get(calendarId) || [];
-
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(calendarNotes, date);
+ // Compare mode shares one grid, so it always uses the personal view
+ const personalView = viewSettings.personal;
+ const calendarView = viewSettings.forCalendar(
+ calendars.find((c) => c.id === selectedCalendar)
+ );
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- setCompareNoteCalendarId(calendarId);
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- setCompareNoteCalendarId(calendarId);
- noteActions.openNoteDialog(date, undefined);
+ // The armed preset is page state that outlives the stamp bar: it survives a
+ // calendar switch, going offline and the personal toggle, none of which render
+ // the dock. Derived here so a day click can never stamp without it on screen.
+ const armedPresetId =
+ canEdit &&
+ isOnline &&
+ calendarView.showStampBar &&
+ presets.some((p) => p.id === selectedPresetId)
+ ? selectedPresetId
+ : undefined;
+
+ const handleDayClick = (day: Date) => {
+ selectDay(day);
+ if (!isSameMonth(day, currentDate)) setCurrentDate(day);
+ if (armedPresetId) {
+ shiftActions.handleAddShift(day, armedPresetId);
+ } else if (!desktop) {
+ setDaySheetOpen(true);
}
};
- const handleCompareNoteIconClick = (
- calendarId: string,
- e: React.MouseEvent,
- date: Date
- ) => {
- e.stopPropagation();
- const calendarNotes = compareData.notesMap.get(calendarId) || [];
-
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(calendarNotes, date);
-
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- setCompareNoteCalendarId(calendarId);
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- setCompareNoteCalendarId(calendarId);
- noteActions.openNoteDialog(date, undefined);
- }
- };
-
- const handleCompareLongPress = (calendarId: string, date: Date) => {
- const calendarNotes = compareData.notesMap.get(calendarId) || [];
-
- // Get all notes/events for this date (including recurring)
- const allDayNotes = findNotesForDate(calendarNotes, date);
-
- // Always show list dialog when notes exist (to allow adding more)
- if (allDayNotes.length >= 1) {
- setCompareNoteCalendarId(calendarId);
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayNotes(allDayNotes);
- dialogStates.setShowNotesListDialog(true);
- } else {
- // No notes - show note edit dialog to create new
- setCompareNoteCalendarId(calendarId);
- noteActions.openNoteDialog(date, undefined);
- }
- };
+ const dialogManager = (
+ <DialogManager
+ showCalendarDialog={dialogStates.showCalendarDialog}
+ onCalendarDialogChange={dialogStates.setShowCalendarDialog}
+ onCreateCalendar={createCalendarHook}
+ showShiftDialog={dialogStates.showShiftDialog}
+ onShiftDialogChange={handleShiftDialogChange}
+ onShiftSubmit={handleShiftSubmit}
+ selectedDate={selectedDate}
+ selectedCalendar={selectedCalendar || null}
+ editingShift={editingShift}
+ showSettingsDialog={dialogStates.showCalendarSettingsDialog}
+ onSettingsDialogChange={dialogStates.setShowCalendarSettingsDialog}
+ onDeleteCalendar={handleDeleteCalendar}
+ onSyncComplete={handleSyncComplete}
+ showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}
+ onSyncNotificationDialogChange={dialogStates.setShowSyncNotificationDialog}
+ showDayShiftsDialog={dialogStates.showDayShiftsDialog}
+ onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}
+ selectedDayDate={dialogStates.selectedDayDate}
+ selectedDayShifts={dialogStates.selectedDayShifts}
+ // In compare mode the day list mixes calendars the shift hooks aren't bound to
+ onDeleteShiftFromDayDialog={isCompareMode ? undefined : handleDeleteShiftFromDayDialog}
+ onEditShiftFromDayDialog={isCompareMode ? undefined : handleEditShift}
+ noteCalendarId={isCompareMode ? compareNoteCalendarId : undefined}
+ showViewSettingsDialog={dialogStates.showViewSettingsDialog}
+ onViewSettingsDialogChange={dialogStates.setShowViewSettingsDialog}
+ viewSettings={viewSettings}
+ showNoteDialog={noteActions.showNoteDialog}
+ onNoteDialogChange={noteActions.handleNoteDialogChange}
+ selectedNote={noteActions.selectedNote}
+ selectedNoteDate={noteActions.selectedDate}
+ onNoteSubmit={noteActions.handleNoteSubmit}
+ onNoteDelete={noteActions.selectedNote ? noteActions.handleNoteDelete : undefined}
+ showNotesListDialog={dialogStates.showNotesListDialog}
+ onNotesListDialogChange={dialogStates.setShowNotesListDialog}
+ selectedDayNotes={dialogStates.selectedDayNotes}
+ onEditNoteFromList={handleEditNoteFromList}
+ onDeleteNoteFromList={handleDeleteNoteFromList}
+ onAddNewNote={handleAddNewNoteFromList}
+ currentDate={currentDate}
+ shifts={shifts}
+ canEditShifts={canEdit}
+ showMonthStatsDialog={dialogStates.showMonthStatsDialog}
+ onMonthStatsDialogChange={dialogStates.setShowMonthStatsDialog}
+ showMonthShiftsDialog={dialogStates.showMonthShiftsDialog}
+ onMonthShiftsDialogChange={dialogStates.setShowMonthShiftsDialog}
+ onDeleteShift={(shift) => shiftActions.handleDeleteShift(shift.id)}
+ showPresetManageDialog={dialogStates.showPresetManageDialog}
+ onPresetManageDialogChange={dialogStates.setShowPresetManageDialog}
+ />
+ );
- const handleCompareShowAllShifts = (
- calendarId: string,
- date: Date,
- dayShifts: ShiftWithCalendar[]
- ) => {
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedDayShifts(dayShifts);
- dialogStates.setShowDayShiftsDialog(true);
- };
+ const comparePicker = (
+ <CalendarCompareSheet
+ open={showCompareSelector}
+ calendars={calendars}
+ selectedIds={selectedCompareIds}
+ onToggleCalendar={handleToggleCompareCalendar}
+ onStartCompare={startCompare}
+ onCancel={cancelComparePicker}
+ />
+ );
- const handleCompareShowSyncedShifts = (
- calendarId: string,
- date: Date,
- syncedShifts: ShiftWithCalendar[]
- ) => {
- dialogStates.setSelectedDayDate(date);
- dialogStates.setSelectedSyncedShifts(syncedShifts);
- dialogStates.setShowSyncedShiftsDialog(true);
- };
+ const calendarDays = useMemo(() => getCalendarDays(currentDate), [currentDate]);
- // Show fullscreen loader only on first load (prevents spinner on navigation)
- // Only show if at least one data source hasn't loaded yet
if (
(!hasLoadedOnce && loading) ||
(!shiftsLoadedOnce && shiftsLoading) ||
- (!presetsLoadedOnce && presetsLoading)
+ (!presetsLoadedOnce && presetsLoading) ||
+ viewSettings.loading
) {
return <FullscreenLoader message={t("common.loading")} />;
}
- // Calendar grid calculations
- const calendarDays = getCalendarDays(currentDate);
-
- // If in compare mode, render compare view
if (isCompareMode) {
- // Show loader while loading compare data
if (compareData.isLoading) {
return <FullscreenLoader message={t("common.loading")} />;
}
- // Build togglingDatesMap from local state
const togglingDatesMap = new Map<string, Set<string>>();
selectedCompareIds.forEach((id) => {
togglingDatesMap.set(id, compareTogglingDates.get(id) || new Set());
@@ -631,410 +371,120 @@ function HomeContent() {
return (
<>
- <CalendarCompareView
- calendars={calendars}
- selectedIds={selectedCompareIds}
- allCalendars={calendars}
+ <CompareWorkspace
+ calendars={calendars.filter((c) => selectedCompareIds.includes(c.id))}
calendarDays={calendarDays}
currentDate={currentDate}
- onDateChange={setCurrentDate}
+ onDateChange={handleDateChange}
+ selectedDay={selectedDay}
+ onSelectDay={selectDay}
shiftsMap={compareData.shiftsMap}
notesMap={compareData.notesMap}
externalSyncsMap={compareData.externalSyncsMap}
presetsMap={compareData.presetsMap}
+ togglingDatesMap={togglingDatesMap}
+ layout={toDayLayout(personalView)}
+ showShiftNotes={personalView.showShiftNotes}
+ highlightedWeekdays={personalView.highlightedWeekdays}
+ highlightColor={personalView.highlightColor}
selectedPresetId={selectedPresetId}
onSelectPreset={setSelectedPresetId}
- togglingDatesMap={togglingDatesMap}
- maxShiftsToShow={
- viewSettings.shiftsPerDay === null
- ? undefined
- : viewSettings.shiftsPerDay
- }
- maxExternalShiftsToShow={
- viewSettings.externalShiftsPerDay === null
- ? undefined
- : viewSettings.externalShiftsPerDay
- }
- showShiftNotes={viewSettings.showShiftNotes}
- showFullTitles={viewSettings.showFullTitles}
- shiftSortType={viewSettings.shiftSortType}
- shiftSortOrder={viewSettings.shiftSortOrder}
- combinedSortMode={viewSettings.combinedSortMode}
- highlightedWeekdays={viewSettings.highlightedWeekdays}
- highlightColor={viewSettings.highlightColor}
- locale={dateLocale}
onDayClick={handleCompareDayClick}
- onDayRightClick={handleCompareDayRightClick}
- onNoteIconClick={handleCompareNoteIconClick}
- onLongPress={handleCompareLongPress}
- onShowAllShifts={handleCompareShowAllShifts}
- onShowSyncedShifts={handleCompareShowSyncedShifts}
- onViewSettingsClick={() =>
- dialogStates.setShowViewSettingsDialog(true)
- }
- onExit={handleExitCompare}
- hidePresetHeader={viewSettings.hidePresetHeader}
- onHidePresetHeaderChange={viewSettings.handleHidePresetHeaderChange}
+ onDayContextMenu={openCompareNotes}
+ onOpenDayShifts={openDayShifts}
onPresetsChange={(calendarId: string) => {
- // Invalidate presets and shifts cache for this calendar
compareData.invalidatePresets(calendarId);
queryClient.invalidateQueries({
queryKey: queryKeys.shifts.byCalendar(calendarId),
});
}}
- onShiftsChange={() => {
- // Invalidate shifts cache for all compare calendars
- selectedCompareIds.forEach((calendarId) => {
- queryClient.invalidateQueries({
- queryKey: queryKeys.shifts.byCalendar(calendarId),
- });
- });
- }}
- presetsLoadingMap={compareData.presetsLoadingMap}
- />
-
- {/* Dialogs still work in compare mode */}
- <DialogManager
- showCalendarDialog={dialogStates.showCalendarDialog}
- onCalendarDialogChange={dialogStates.setShowCalendarDialog}
- onCreateCalendar={createCalendarHook}
- showShiftDialog={dialogStates.showShiftDialog}
- onShiftDialogChange={dialogStates.setShowShiftDialog}
- onShiftSubmit={shiftActions.handleShiftSubmit}
- selectedDate={selectedDate}
- selectedCalendar={selectedCalendar || null}
- calendars={calendars}
- showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
- onCalendarSettingsDialogChange={
- dialogStates.setShowCalendarSettingsDialog
- }
- onCalendarSettingsSuccess={refetchCalendars}
- onDeleteCalendar={handleDeleteCalendar}
- onExternalSyncFromSettings={() =>
- dialogStates.setShowExternalSyncDialog(true)
- }
- showExternalSyncDialog={dialogStates.showExternalSyncDialog}
- onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
- onSyncComplete={handleSyncComplete}
- showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}
- onSyncNotificationDialogChange={
- dialogStates.setShowSyncNotificationDialog
- }
- showDayShiftsDialog={dialogStates.showDayShiftsDialog}
- onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}
- selectedDayDate={dialogStates.selectedDayDate}
- selectedDayShifts={dialogStates.selectedDayShifts}
- locale={locale}
- onDeleteShiftFromDayDialog={handleDeleteShiftFromDayDialog}
- showSyncedShiftsDialog={dialogStates.showSyncedShiftsDialog}
- onSyncedShiftsDialogChange={dialogStates.setShowSyncedShiftsDialog}
- selectedSyncedShifts={dialogStates.selectedSyncedShifts}
- showViewSettingsDialog={dialogStates.showViewSettingsDialog}
- onViewSettingsDialogChange={dialogStates.setShowViewSettingsDialog}
- viewSettings={viewSettings}
- onViewSettingsChange={{
- handleShiftsPerDayChange: viewSettings.handleShiftsPerDayChange,
- handleExternalShiftsPerDayChange:
- viewSettings.handleExternalShiftsPerDayChange,
- handleShowShiftNotesChange: viewSettings.handleShowShiftNotesChange,
- handleShowFullTitlesChange: viewSettings.handleShowFullTitlesChange,
- handleShiftSortTypeChange: viewSettings.handleShiftSortTypeChange,
- handleShiftSortOrderChange: viewSettings.handleShiftSortOrderChange,
- handleCombinedSortModeChange:
- viewSettings.handleCombinedSortModeChange,
- handleHighlightWeekendsChange:
- viewSettings.handleHighlightWeekendsChange,
- handleHighlightedWeekdaysChange:
- viewSettings.handleHighlightedWeekdaysChange,
- handleHighlightColorChange: viewSettings.handleHighlightColorChange,
- }}
- showNoteDialog={noteActions.showNoteDialog}
- onNoteDialogChange={noteActions.handleNoteDialogChange}
- selectedNote={noteActions.selectedNote}
- selectedNoteDate={noteActions.selectedDate}
- onNoteSubmit={handleNoteSubmit}
- onNoteDelete={noteActions.selectedNote ? handleNoteDelete : undefined}
- showNotesListDialog={dialogStates.showNotesListDialog}
- onNotesListDialogChange={dialogStates.setShowNotesListDialog}
- selectedDayNotes={dialogStates.selectedDayNotes}
- onEditNoteFromList={handleEditNoteFromList}
- onDeleteNoteFromList={handleDeleteNoteFromList}
- onAddNewNote={handleAddNewNoteFromList}
+ onAddCalendar={openComparePicker}
+ onViewSettings={() => dialogStates.setShowViewSettingsDialog(true)}
+ onExit={handleExitCompare}
/>
-
- <AppFooter versionInfo={versionInfo} />
+ {comparePicker}
+ {dialogManager}
</>
);
}
- // Empty state
if (calendars.length === 0) {
- // If user is guest, show guest empty state (no create calendar option)
- if (isGuest) {
- return <GuestEmptyState />;
- }
-
- // Otherwise, show normal empty state with create calendar option
+ if (isGuest) return <GuestEmptyState />;
return (
<>
<EmptyCalendarState
onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
showUserMenu={true}
/>
- <DialogManager
- showCalendarDialog={dialogStates.showCalendarDialog}
- onCalendarDialogChange={dialogStates.setShowCalendarDialog}
- onCreateCalendar={createCalendarHook}
- showShiftDialog={dialogStates.showShiftDialog}
- onShiftDialogChange={dialogStates.setShowShiftDialog}
- onShiftSubmit={shiftActions.handleShiftSubmit}
- selectedDate={selectedDate}
- selectedCalendar={selectedCalendar || null}
- calendars={calendars}
- showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
- onCalendarSettingsDialogChange={
- dialogStates.setShowCalendarSettingsDialog
- }
- onCalendarSettingsSuccess={refetchCalendars}
- onDeleteCalendar={handleDeleteCalendar}
- onExternalSyncFromSettings={() =>
- dialogStates.setShowExternalSyncDialog(true)
- }
- showExternalSyncDialog={dialogStates.showExternalSyncDialog}
- onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
- onSyncComplete={handleSyncComplete}
- showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}
- onSyncNotificationDialogChange={
- dialogStates.setShowSyncNotificationDialog
- }
- showDayShiftsDialog={dialogStates.showDayShiftsDialog}
- onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}
- selectedDayDate={dialogStates.selectedDayDate}
- selectedDayShifts={dialogStates.selectedDayShifts}
- locale={locale}
- onDeleteShiftFromDayDialog={handleDeleteShiftFromDayDialog}
- showSyncedShiftsDialog={dialogStates.showSyncedShiftsDialog}
- onSyncedShiftsDialogChange={dialogStates.setShowSyncedShiftsDialog}
- selectedSyncedShifts={dialogStates.selectedSyncedShifts}
- showViewSettingsDialog={dialogStates.showViewSettingsDialog}
- onViewSettingsDialogChange={dialogStates.setShowViewSettingsDialog}
- viewSettings={viewSettings}
- onViewSettingsChange={{
- handleShiftsPerDayChange: viewSettings.handleShiftsPerDayChange,
- handleExternalShiftsPerDayChange:
- viewSettings.handleExternalShiftsPerDayChange,
- handleShowShiftNotesChange: viewSettings.handleShowShiftNotesChange,
- handleShowFullTitlesChange: viewSettings.handleShowFullTitlesChange,
- handleShiftSortTypeChange: viewSettings.handleShiftSortTypeChange,
- handleShiftSortOrderChange: viewSettings.handleShiftSortOrderChange,
- handleCombinedSortModeChange:
- viewSettings.handleCombinedSortModeChange,
- handleHighlightWeekendsChange:
- viewSettings.handleHighlightWeekendsChange,
- handleHighlightedWeekdaysChange:
- viewSettings.handleHighlightedWeekdaysChange,
- handleHighlightColorChange: viewSettings.handleHighlightColorChange,
- }}
- showNoteDialog={noteActions.showNoteDialog}
- onNoteDialogChange={noteActions.handleNoteDialogChange}
- selectedNote={noteActions.selectedNote}
- selectedNoteDate={noteActions.selectedDate}
- onNoteSubmit={handleNoteSubmit}
- onNoteDelete={noteActions.selectedNote ? handleNoteDelete : undefined}
- showNotesListDialog={dialogStates.showNotesListDialog}
- onNotesListDialogChange={dialogStates.setShowNotesListDialog}
- selectedDayNotes={dialogStates.selectedDayNotes}
- onEditNoteFromList={handleEditNoteFromList}
- onDeleteNoteFromList={handleDeleteNoteFromList}
- onAddNewNote={handleAddNewNoteFromList}
- />
+ {dialogManager}
</>
);
}
- return (
- <div className="min-h-screen flex flex-col">
- {/* Compare Selector Overlay */}
- <AnimatePresence>
- {showCompareSelector && (
- <CalendarCompareSheet
- calendars={calendars}
- selectedIds={selectedCompareIds}
- onToggleCalendar={handleToggleCompareCalendar}
- onStartCompare={handleStartCompare}
- onCancel={() => {
- setShowCompareSelector(false);
- setSelectedCompareIds([]);
- }}
- />
- )}
- </AnimatePresence>
+ const header = (
+ <AppHeader
+ calendars={calendars}
+ selectedCalendar={selectedCalendar}
+ currentDate={currentDate}
+ hasSyncErrors={hasSyncErrors}
+ onDateChange={handleDateChange}
+ onSelectCalendar={setSelectedCalendar}
+ onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
+ onSettings={() => dialogStates.setShowCalendarSettingsDialog(true)}
+ onSyncNotifications={() => dialogStates.setShowSyncNotificationDialog(true)}
+ onCompare={openComparePicker}
+ onViewSettings={() => dialogStates.setShowViewSettingsDialog(true)}
+ />
+ );
- <AppHeader
- calendars={calendars}
- selectedCalendar={selectedCalendar}
+ return (
+ <>
+ {comparePicker}
+
+ <CalendarWorkspace
+ header={header}
+ calendarId={selectedCalendar}
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ onDateChange={handleDateChange}
+ selectedDay={selectedDay}
+ onDayClick={handleDayClick}
+ onDayContextMenu={(date) => openNotesForDay(notes, date)}
+ shifts={shifts}
+ notes={notes}
presets={presets}
- selectedPresetId={selectedPresetId}
- showMobileCalendarDialog={dialogStates.showMobileCalendarDialog}
- hasSyncErrors={hasSyncErrors}
- onSelectCalendar={setSelectedCalendar}
+ externalSyncs={externalSyncs}
+ togglingDates={shiftActions.togglingDates}
+ layout={toDayLayout(calendarView)}
+ showShiftNotes={calendarView.showShiftNotes}
+ highlightedWeekdays={calendarView.highlightedWeekdays}
+ highlightColor={calendarView.highlightColor}
+ canEdit={canEdit}
+ showStampBar={calendarView.showStampBar}
+ selectedPresetId={armedPresetId}
onSelectPreset={setSelectedPresetId}
- onCreateCalendar={() => dialogStates.setShowCalendarDialog(true)}
- onSettings={() => dialogStates.setShowCalendarSettingsDialog(true)}
- onSyncNotifications={handleSyncNotifications}
- onCompare={handleCompareClick}
- onShiftsChange={refetchShifts}
- onManualShiftCreation={handleManualShiftCreation}
- onMobileCalendarDialogChange={dialogStates.setShowMobileCalendarDialog}
- onViewSettingsClick={() => dialogStates.setShowViewSettingsDialog(true)}
- presetsLoading={presetsLoading}
- hidePresetHeader={viewSettings.hidePresetHeader}
- onHidePresetHeaderChange={viewSettings.handleHidePresetHeaderChange}
- />
-
- <div className="container max-w-4xl mx-auto px-1 py-3 sm:p-4 flex-1">
- <CalendarContent
- calendarDays={calendarDays}
- currentDate={currentDate}
- onDateChange={setCurrentDate}
- shifts={shifts}
- notes={notes}
- selectedPresetId={selectedPresetId}
- togglingDates={shiftActions.togglingDates}
- externalSyncs={externalSyncs}
- maxShiftsToShow={
- viewSettings.shiftsPerDay === null
- ? undefined
- : viewSettings.shiftsPerDay
- }
- maxExternalShiftsToShow={
- viewSettings.externalShiftsPerDay === null
- ? undefined
- : viewSettings.externalShiftsPerDay
- }
- showShiftNotes={viewSettings.showShiftNotes}
- showFullTitles={viewSettings.showFullTitles}
- shiftSortType={viewSettings.shiftSortType}
- shiftSortOrder={viewSettings.shiftSortOrder}
- combinedSortMode={viewSettings.combinedSortMode}
- highlightedWeekdays={viewSettings.highlightedWeekdays}
- highlightColor={viewSettings.highlightColor}
- selectedCalendar={selectedCalendar || null}
- locale={dateLocale}
- onDayClick={handleDayClick}
- onDayRightClick={handleDayRightClick}
- onNoteIconClick={handleNoteIconClick}
- onLongPress={handleLongPressDay}
- onShowAllShifts={handleShowAllShifts}
- onShowSyncedShifts={handleShowSyncedShifts}
- onDeleteShift={shiftActions.handleDeleteShift}
- onEditShift={handleEditShiftFromDayDialog}
- />
- </div>
-
- {/* Floating Action Button */}
- {selectedCalendar && (
- <motion.div
- className="hidden sm:block fixed bottom-6 right-6 z-50"
- initial={{ scale: 0, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ delay: 0.5, type: "spring", stiffness: 200 }}
- >
- <Button
- size="lg"
- className="h-16 w-16 rounded-full shadow-2xl shadow-primary/30 hover:shadow-primary/50 transition-all"
- onClick={handleManualShiftCreation}
- >
- <Plus className="h-7 w-7" />
- </Button>
- </motion.div>
- )}
-
- {/* Dialogs */}
- <DialogManager
- showCalendarDialog={dialogStates.showCalendarDialog}
- onCalendarDialogChange={dialogStates.setShowCalendarDialog}
- onCreateCalendar={createCalendarHook}
- showShiftDialog={dialogStates.showShiftDialog}
- onShiftDialogChange={handleShiftDialogChange}
- onShiftSubmit={handleShiftSubmit}
- selectedDate={selectedDate}
- selectedCalendar={selectedCalendar || null}
- calendars={calendars}
- editingShift={editingShift}
- showCalendarSettingsDialog={dialogStates.showCalendarSettingsDialog}
- onCalendarSettingsDialogChange={
- dialogStates.setShowCalendarSettingsDialog
- }
- onCalendarSettingsSuccess={refetchCalendars}
- onDeleteCalendar={handleDeleteCalendar}
- onExternalSyncFromSettings={() =>
- dialogStates.setShowExternalSyncDialog(true)
- }
- showExternalSyncDialog={dialogStates.showExternalSyncDialog}
- onExternalSyncDialogChange={dialogStates.setShowExternalSyncDialog}
- onSyncComplete={handleSyncComplete}
- showSyncNotificationDialog={dialogStates.showSyncNotificationDialog}
- onSyncNotificationDialogChange={
- dialogStates.setShowSyncNotificationDialog
- }
- showDayShiftsDialog={dialogStates.showDayShiftsDialog}
- onDayShiftsDialogChange={dialogStates.setShowDayShiftsDialog}
- selectedDayDate={dialogStates.selectedDayDate}
- selectedDayShifts={dialogStates.selectedDayShifts}
- locale={locale}
- onDeleteShiftFromDayDialog={handleDeleteShiftFromDayDialog}
- onEditShiftFromDayDialog={handleEditShiftFromDayDialog}
- showSyncedShiftsDialog={dialogStates.showSyncedShiftsDialog}
- onSyncedShiftsDialogChange={dialogStates.setShowSyncedShiftsDialog}
- selectedSyncedShifts={dialogStates.selectedSyncedShifts}
- showViewSettingsDialog={dialogStates.showViewSettingsDialog}
- onViewSettingsDialogChange={dialogStates.setShowViewSettingsDialog}
- viewSettings={viewSettings}
- onViewSettingsChange={{
- handleShiftsPerDayChange: viewSettings.handleShiftsPerDayChange,
- handleExternalShiftsPerDayChange:
- viewSettings.handleExternalShiftsPerDayChange,
- handleShowShiftNotesChange: viewSettings.handleShowShiftNotesChange,
- handleShowFullTitlesChange: viewSettings.handleShowFullTitlesChange,
- handleShiftSortTypeChange: viewSettings.handleShiftSortTypeChange,
- handleShiftSortOrderChange: viewSettings.handleShiftSortOrderChange,
- handleCombinedSortModeChange:
- viewSettings.handleCombinedSortModeChange,
- handleHighlightWeekendsChange:
- viewSettings.handleHighlightWeekendsChange,
- handleHighlightedWeekdaysChange:
- viewSettings.handleHighlightedWeekdaysChange,
- handleHighlightColorChange: viewSettings.handleHighlightColorChange,
+ onManagePresets={() => dialogStates.setShowPresetManageDialog(true)}
+ sheetOpen={daySheetOpen}
+ onSheetOpenChange={setDaySheetOpen}
+ actions={{
+ onAddShift: () => openShiftSheet(selectedDay),
+ onEditShift: handleEditShift,
+ onDeleteShift: (shift) => shiftActions.handleDeleteShift(shift.id),
+ onAddNote: () => noteActions.openNoteDialog(selectedDay, undefined),
+ onOpenNote: (note) => noteActions.openNoteDialog(selectedDay, note),
+ onOpenStats: () => dialogStates.setShowMonthStatsDialog(true),
+ onOpenMonthShifts: () => dialogStates.setShowMonthShiftsDialog(true),
}}
- showNoteDialog={noteActions.showNoteDialog}
- onNoteDialogChange={noteActions.handleNoteDialogChange}
- selectedNote={noteActions.selectedNote}
- selectedNoteDate={noteActions.selectedDate}
- onNoteSubmit={handleNoteSubmit}
- onNoteDelete={noteActions.selectedNote ? handleNoteDelete : undefined}
- showNotesListDialog={dialogStates.showNotesListDialog}
- onNotesListDialogChange={dialogStates.setShowNotesListDialog}
- selectedDayNotes={dialogStates.selectedDayNotes}
- onEditNoteFromList={handleEditNoteFromList}
- onDeleteNoteFromList={handleDeleteNoteFromList}
- onAddNewNote={handleAddNewNoteFromList}
/>
- <AppFooter versionInfo={versionInfo} />
- </div>
+ {dialogManager}
+ </>
);
}
export default function Home() {
return (
- <Suspense
- fallback={
- <div className="min-h-screen flex items-center justify-center">
- <div className="text-muted-foreground">Loading...</div>
- </div>
- }
- >
+ <Suspense fallback={<FullscreenLoader message="" />}>
<HomeContent />
</Suspense>
);
diff --git a/app/profile/activity/page.tsx b/app/profile/activity/page.tsx
index 6d32885..6fecc1a 100644
--- a/app/profile/activity/page.tsx
+++ b/app/profile/activity/page.tsx
@@ -1,616 +1,6 @@
-"use client";
+import { redirect } from "next/navigation";
-import React, { useState, useEffect, useMemo, useCallback } from "react";
-import { useRouter } from "next/navigation";
-import { useTranslations, useLocale } from "next-intl";
-import { useAuth } from "@/hooks/useAuth";
-import { useActivityLogs } from "@/hooks/useActivityLogs";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
-import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Badge } from "@/components/ui/badge";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { AuthHeader } from "@/components/auth-header";
-import { AppFooter } from "@/components/app-footer";
-import {
- ChevronLeft,
- ChevronRight,
- Trash2,
- Search,
- ChevronDown,
- ChevronUp,
-} from "lucide-react";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { cn } from "@/lib/utils";
-
-/**
- * Activity Log Page - Full-screen table view for user activity logs
- *
- * Features:
- * - Merged view of auditLogs + syncLogs
- * - Advanced filters (type, date range, severity, search)
- * - Sortable columns
- * - Expandable rows for metadata
- * - Pagination
- * - Actions: Clear all, Mark all as read, Refresh
- * - Responsive design
- */
-export default function ActivityLogPage() {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const router = useRouter();
- const { isLoading: authLoading, isAuthenticated } = useAuth();
- const versionInfo = useVersionInfo();
-
- // Filter State (managed locally like admin audit log page)
- const [page, setPage] = useState(0);
- const limit = 50;
- const [typeFilter, setTypeFilter] = useState<string>("all");
- const [severityFilter, setSeverityFilter] = useState<string>("all");
- const [searchQuery, setSearchQuery] = useState("");
- const [debouncedSearch, setDebouncedSearch] = useState("");
- const [startDate, setStartDate] = useState("");
- const [endDate, setEndDate] = useState("");
-
- // Sort State
- const [sortColumn, setSortColumn] = useState<
- "timestamp" | "type" | "severity" | null
- >("timestamp");
- const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
-
- // Build filters and pagination with useMemo (like admin audit log page)
- const filters = useMemo(
- () => ({
- type:
- typeFilter !== "all"
- ? (typeFilter as "sync" | "auth" | "calendar" | "security")
- : undefined,
- severity:
- severityFilter !== "all"
- ? (severityFilter as "info" | "warning" | "error" | "critical")
- : undefined,
- search: debouncedSearch || undefined,
- startDate: startDate || undefined,
- endDate: endDate || undefined,
- }),
- [typeFilter, severityFilter, debouncedSearch, startDate, endDate]
- );
-
- const pagination = useMemo(
- () => ({
- limit,
- offset: page * limit,
- }),
- [page, limit]
- );
-
- // Use hook with filters and pagination
- const { logs, total, isLoading, error, clearLogs } = useActivityLogs(
- filters,
- pagination
- );
-
- // Calculate pagination info
- const hasMore = (page + 1) * limit < total;
-
- // UI State (must be defined before any early returns)
- const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
- const [clearDialogOpen, setClearDialogOpen] = useState(false);
-
- // Handler functions that combine filter changes with page reset
- const handleTypeFilterChange = (value: string) => {
- setTypeFilter(value);
- setPage(0);
- };
-
- const handleSeverityFilterChange = (value: string) => {
- setSeverityFilter(value);
- setPage(0);
- };
-
- const handleStartDateChange = (value: string) => {
- setStartDate(value);
- setPage(0);
- };
-
- const handleEndDateChange = (value: string) => {
- setEndDate(value);
- setPage(0);
- };
-
- const handleDebouncedSearchChange = useCallback((value: string) => {
- setDebouncedSearch(value);
- setPage(0);
- }, []);
-
- // Debounce search query
- useEffect(() => {
- const timer = setTimeout(() => {
- handleDebouncedSearchChange(searchQuery);
- }, 500);
-
- return () => clearTimeout(timer);
- }, [searchQuery, handleDebouncedSearchChange]);
-
- // Redirect to login if not authenticated
- useEffect(() => {
- if (!authLoading && !isAuthenticated) {
- router.replace("/login");
- }
- }, [authLoading, isAuthenticated, router]);
-
- // Show fullscreen loader only during initial auth check
- // Don't show loader during data refetches to prevent UI flashing
- if (authLoading) {
- return <FullscreenLoader />;
- }
-
- // Toggle row expansion
- const toggleRow = (logId: string) => {
- setExpandedRows((prev) => {
- const newSet = new Set(prev);
- if (newSet.has(logId)) {
- newSet.delete(logId);
- } else {
- newSet.add(logId);
- }
- return newSet;
- });
- };
-
- // Sort logs
- const sortedLogs = [...logs].sort((a, b) => {
- if (!sortColumn) return 0;
-
- let comparison = 0;
-
- switch (sortColumn) {
- case "timestamp":
- comparison = a.timestamp.getTime() - b.timestamp.getTime();
- break;
- case "type":
- comparison = a.type.localeCompare(b.type);
- break;
- case "severity":
- const severityOrder = { info: 0, warning: 1, error: 2, critical: 3 };
- comparison =
- (severityOrder[a.severity as keyof typeof severityOrder] ?? 0) -
- (severityOrder[b.severity as keyof typeof severityOrder] ?? 0);
- break;
- }
-
- return sortDirection === "asc" ? comparison : -comparison;
- });
-
- // Handle sort column click
- const handleSort = (column: "timestamp" | "type" | "severity") => {
- if (sortColumn === column) {
- setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
- } else {
- setSortColumn(column);
- setSortDirection("desc");
- }
- };
-
- // Severity badge color
- const getSeverityColor = (severity: string) => {
- switch (severity) {
- case "info":
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- case "warning":
- return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
- case "error":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- case "critical":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- default:
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- }
- };
-
- // Type badge color
- const getTypeColor = (type: string) => {
- switch (type) {
- case "auth":
- return "bg-purple-500/10 text-purple-500 border-purple-500/20";
- case "calendar":
- return "bg-green-500/10 text-green-500 border-green-500/20";
- case "sync":
- return "bg-cyan-500/10 text-cyan-500 border-cyan-500/20";
- case "security":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- default:
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- }
- };
-
- // Clear all logs with confirmation
- const handleClearAll = async () => {
- setClearDialogOpen(false);
- await clearLogs();
- };
-
- // Clear all filters
- const clearFilters = () => {
- setTypeFilter("all");
- setSeverityFilter("all");
- setSearchQuery("");
- setDebouncedSearch("");
- setStartDate("");
- setEndDate("");
- setPage(0);
- };
-
- // Check if any filters are active
- const hasActiveFilters =
- typeFilter !== "all" ||
- severityFilter !== "all" ||
- startDate ||
- endDate ||
- searchQuery;
-
- // Pagination handlers
- const goToNextPage = () => setPage((prev) => prev + 1);
- const goToPreviousPage = () => setPage((prev) => Math.max(0, prev - 1));
-
- return (
- <div className="flex min-h-screen flex-col">
- <AuthHeader showUserMenu />
-
- <div className="flex-1 bg-gradient-to-br from-background via-background to-primary/5">
- <main className="container py-4 sm:py-8 max-w-full sm:max-w-6xl mx-auto px-2 sm:px-4">
- {/* Header */}
- <div className="mb-6 sm:mb-8 flex items-center justify-between">
- <div>
- <h1 className="text-2xl sm:text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent mb-2">
- {t("activityLog.title")}
- </h1>
- <p className="text-sm text-muted-foreground">
- {t("activityLog.description")}
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => setClearDialogOpen(true)}
- disabled={total === 0}
- >
- <Trash2 className="h-4 w-4" />
- <span className="hidden sm:inline ml-2">
- {t("activityLog.clearAll")}
- </span>
- </Button>
- </div>
- </div>
-
- {/* Filters Bar */}
- <div className="mb-6 space-y-4">
- <div className="flex flex-col sm:flex-row gap-4">
- {/* Type Filter */}
- <Select value={typeFilter} onValueChange={handleTypeFilterChange}>
- <SelectTrigger className="w-full sm:w-[200px]">
- <SelectValue placeholder={t("activityLog.allTypes")} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">
- {t("activityLog.allTypes")}
- </SelectItem>
- <SelectItem value="auth">{t("activityLog.auth")}</SelectItem>
- <SelectItem value="calendar">
- {t("common.labels.calendar")}
- </SelectItem>
- <SelectItem value="sync">{t("activityLog.sync")}</SelectItem>
- <SelectItem value="security">
- {t("activityLog.security")}
- </SelectItem>
- </SelectContent>
- </Select>
-
- {/* Severity Filter */}
- <Select
- value={severityFilter}
- onValueChange={handleSeverityFilterChange}
- >
- <SelectTrigger className="w-full sm:w-[200px]">
- <SelectValue
- placeholder={t("common.filters.allSeverities")}
- />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">
- {t("common.filters.allSeverities")}
- </SelectItem>
- <SelectItem value="info">
- {t("common.severity.info")}
- </SelectItem>
- <SelectItem value="warning">
- {t("common.severity.warning")}
- </SelectItem>
- <SelectItem value="error">
- {t("common.severity.error")}
- </SelectItem>
- <SelectItem value="critical">
- {t("common.severity.critical")}
- </SelectItem>
- </SelectContent>
- </Select>
-
- {/* Date Range - Start Date */}
- <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
- <Input
- type="date"
- value={startDate}
- onChange={(e) => handleStartDateChange(e.target.value)}
- placeholder={t("common.labels.startDate")}
- className="w-full sm:w-[150px]"
- />
- <Input
- type="date"
- value={endDate}
- onChange={(e) => handleEndDateChange(e.target.value)}
- placeholder={t("common.labels.endDate")}
- className="w-full sm:w-[150px]"
- />
- </div>
-
- {/* Search */}
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("activityLog.searchPlaceholder")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-9"
- />
- </div>
-
- {/* Clear Filters */}
- {hasActiveFilters && (
- <Button variant="outline" onClick={clearFilters}>
- {t("common.filters.clearFilters")}
- </Button>
- )}
- </div>
-
- {/* Stats */}
- <div className="text-sm text-muted-foreground">
- {t("activityLog.totalLogs", { count: total })}
- </div>
- </div>
-
- {/* Table */}
- {isLoading && logs.length === 0 && !authLoading ? (
- <div className="text-center py-12 text-muted-foreground">
- {t("common.loading")}
- </div>
- ) : error ? (
- <div className="text-center py-12 text-red-500">
- {t("common.error")}: {error?.message || String(error)}
- </div>
- ) : logs.length === 0 ? (
- <div className="text-center py-12 text-muted-foreground">
- {t("activityLog.noLogs")}
- </div>
- ) : (
- <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
- <Table>
- <TableHeader className="bg-muted/50">
- <TableRow>
- <TableHead className="w-8"></TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("timestamp")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.time")}
- {sortColumn === "timestamp" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("type")}
- >
- <div className="flex items-center gap-2">
- {t("activityLog.eventType")}
- {sortColumn === "type" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead>{t("common.labels.action")}</TableHead>
- <TableHead>{t("activityLog.resource")}</TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("severity")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.severity")}
- {sortColumn === "severity" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {sortedLogs.map((log) => (
- <React.Fragment key={log.id}>
- <TableRow
- className="cursor-pointer"
- onClick={() => toggleRow(log.id)}
- >
- <TableCell className="text-center">
- {expandedRows.has(log.id) ? (
- <ChevronUp className="h-4 w-4 text-muted-foreground" />
- ) : (
- <ChevronDown className="h-4 w-4 text-muted-foreground" />
- )}
- </TableCell>
- <TableCell className="text-sm">
- {log.timestamp &&
- log.timestamp instanceof Date &&
- !isNaN(log.timestamp.getTime()) ? (
- <>
- {format(log.timestamp, "MMM dd, yyyy", {
- locale: dateLocale,
- })}
- <br />
- <span className="text-xs text-muted-foreground">
- {format(log.timestamp, "HH:mm:ss", {
- locale: dateLocale,
- })}
- </span>
- </>
- ) : (
- <span className="text-xs text-muted-foreground">
- Invalid date
- </span>
- )}
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
- className={cn("text-xs", getTypeColor(log.type))}
- >
- {t(`activityLog.${log.type}`)}
- </Badge>
- </TableCell>
- <TableCell className="text-sm font-mono text-xs">
- {log.action}
- </TableCell>
- <TableCell className="text-sm text-muted-foreground">
- {log.resourceType ? (
- <span>
- {log.resourceType}
- {log.resourceId && (
- <span className="text-xs block truncate max-w-[150px]">
- {log.resourceId}
- </span>
- )}
- </span>
- ) : (
- "-"
- )}
- </TableCell>
- <TableCell>
- <Badge
- variant="outline"
- className={cn(
- "text-xs",
- getSeverityColor(log.severity)
- )}
- >
- {t(`common.severity.${log.severity}`)}
- </Badge>
- </TableCell>
- </TableRow>
-
- {/* Expanded Row - Metadata */}
- {expandedRows.has(log.id) && (
- <TableRow className="bg-muted/20">
- <TableCell colSpan={6} className="p-4">
- <div className="space-y-2">
- <div className="text-sm font-semibold">
- {t("activityLog.details")}:
- </div>
- {log.metadata ? (
- <pre className="text-xs bg-background p-3 rounded border whitespace-pre-wrap break-words overflow-auto max-w-full">
- {JSON.stringify(log.metadata, null, 2)}
- </pre>
- ) : (
- <p className="text-sm text-muted-foreground">
- {t("activityLog.noMetadata")}
- </p>
- )}
- </div>
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
- ))}
- </TableBody>
- </Table>
-
- {/* Pagination */}
- <div className="flex items-center justify-between p-4 border-t bg-muted/20">
- <div className="text-sm text-muted-foreground">
- {t("activityLog.showingResults", {
- start: page * limit + 1,
- end: Math.min((page + 1) * limit, total),
- total,
- })}
- </div>
-
- <div className="flex gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={goToPreviousPage}
- disabled={page === 0}
- >
- <ChevronLeft className="h-4 w-4 mr-1" />
- {t("common.previous")}
- </Button>
-
- <Button
- variant="outline"
- size="sm"
- onClick={goToNextPage}
- disabled={!hasMore}
- >
- {t("common.next")}
- <ChevronRight className="h-4 w-4 ml-1" />
- </Button>
- </div>
- </div>
- </div>
- )}
- </main>
- </div>
-
- <AppFooter versionInfo={versionInfo} />
-
- {/* Clear All Confirmation Dialog */}
- <ConfirmationDialog
- open={clearDialogOpen}
- onOpenChange={setClearDialogOpen}
- onConfirm={handleClearAll}
- title={t("activityLog.clearAll")}
- description={t("activityLog.confirmClear")}
- confirmText={t("common.delete")}
- cancelText={t("common.cancel")}
- confirmVariant="destructive"
- />
- </div>
- );
+// Old bookmarks; the activity log is a section of the profile page now
+export default function ActivityLogRedirect() {
+ redirect("/profile?section=activity");
}
diff --git a/app/profile/page.tsx b/app/profile/page.tsx
index e740b31..273822e 100644
--- a/app/profile/page.tsx
+++ b/app/profile/page.tsx
@@ -1,96 +1,88 @@
"use client";
-import { useState, useEffect } from "react";
-import { useRouter } from "next/navigation";
+import { ReactNode, Suspense, useEffect, useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
+import {
+ ChevronRight,
+ FileText,
+ KeyRound,
+ Link2,
+ MonitorSmartphone,
+ TriangleAlert,
+ User,
+ type LucideIcon,
+} from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { useConnectedAccounts } from "@/hooks/useConnectedAccounts";
import { useSessions } from "@/hooks/useSessions";
-import { signOut } from "@/lib/auth/client";
+import { useProfileForm } from "@/hooks/useProfileForm";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { UAParser } from "ua-parser-js";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Separator } from "@/components/ui/separator";
-import { toast } from "sonner";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { AuthHeader } from "@/components/auth-header";
-import { Smartphone, Monitor, Tablet, HelpCircle, LogOut } from "lucide-react";
-import { AppFooter } from "@/components/app-footer";
import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { PanelBody } from "@/components/panel-dialog";
+import { StatusBanner } from "@/components/status-banner";
+import { UserMenu } from "@/components/user-menu";
+import {
+ accountContentClass,
+ AccountPageHeader,
+ SectionHeading,
+} from "@/components/profile/account-layout";
+import { ProfileDetailsSection } from "@/components/profile/profile-details-section";
+import { PasswordSection } from "@/components/profile/password-section";
import {
- isRateLimitError,
- handleRateLimitError,
-} from "@/lib/rate-limit-client";
+ ConnectedAccountsSection,
+ useProviderInfo,
+} from "@/components/profile/connected-accounts";
+import { SessionsSection } from "@/components/profile/sessions-section";
+import { DangerSection } from "@/components/profile/danger-section";
+import { ActivitySection } from "@/components/profile/activity-section";
+import { cn } from "@/lib/utils";
+
+type SectionId = "profile" | "password" | "accounts" | "sessions" | "activity" | "danger";
+
+interface NavItem {
+ id: SectionId;
+ icon: LucideIcon;
+ title: string;
+ description: string;
+ danger?: boolean;
+}
+
+// The URL is the source of truth, so /profile?section=<id> deep-links into a section
+const sectionHref = (id: SectionId | null) => (id ? `/profile?section=${id}` : "/profile");
-/**
- * User profile page
- *
- * Features:
- * - Display user info
- * - Change password
- * - Change email
- * - Connected OAuth accounts
- * - Delete account
- */
+/** "Mein Konto" (screens 11b/11c): section list on desktop, two-level list on phones. */
export default function ProfilePage() {
+ return (
+ <Suspense fallback={<FullscreenLoader />}>
+ <ProfileContent />
+ </Suspense>
+ );
+}
+
+function ProfileContent() {
const t = useTranslations();
const router = useRouter();
- const { user, isLoading, refetch } = useAuth();
+ const searchParams = useSearchParams();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const { user, session, isLoading, refetch } = useAuth();
const { isAuthEnabled } = useAuthFeatures();
const { accounts, isLoading: accountsLoading } = useConnectedAccounts();
const {
sessions,
isLoading: sessionsLoading,
+ error: sessionsError,
+ refetch: refetchSessions,
revokeAllSessions,
+ revokeSession,
} = useSessions();
- const [currentPassword, setCurrentPassword] = useState("");
- const [newPassword, setNewPassword] = useState("");
- const [confirmNewPassword, setConfirmNewPassword] = useState("");
- const [isChangingPassword, setIsChangingPassword] = useState(false);
- const [showDeleteDialog, setShowDeleteDialog] = useState(false);
- const [deletePassword, setDeletePassword] = useState("");
- const [isDeleting, setIsDeleting] = useState(false);
- const [mounted, setMounted] = useState(false);
- const versionInfo = useVersionInfo();
-
- // Profile editing state
- const [editName, setEditName] = useState("");
- const [editEmail, setEditEmail] = useState("");
- const [isUpdatingProfile, setIsUpdatingProfile] = useState(false);
- const [avatarFile, setAvatarFile] = useState<File | null>(null);
- const [avatarPreview, setAvatarPreview] = useState<string>("");
- const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
-
- // Check if user has password-based authentication
- const hasPasswordAuth = accounts.some(
- (account) => account.provider === "credential"
- );
-
- // Prevent hydration mismatch
- useEffect(() => {
- setMounted(true);
- }, []);
-
- // Initialize edit fields when user loads
- useEffect(() => {
- if (user) {
- setEditName(user.name || "");
- setEditEmail(user.email || "");
- setAvatarPreview(user.image || "");
- }
- }, [user]);
+ const profileForm = useProfileForm(user, refetch);
+ const providerInfo = useProviderInfo();
+ const [pendingHref, setPendingHref] = useState<string | null>(null);
- // Redirect if auth disabled or not logged in
useEffect(() => {
if (!isAuthEnabled) {
router.replace("/");
@@ -99,8 +91,8 @@ export default function ProfilePage() {
}
}, [isAuthEnabled, isLoading, user, router]);
- // Show fullscreen loader during initial data fetch
- if (isLoading || accountsLoading || sessionsLoading) {
+ // Session refetches after a revoke keep the page mounted
+ if (isLoading || accountsLoading || (sessionsLoading && sessions.length === 0)) {
return <FullscreenLoader />;
}
@@ -108,726 +100,285 @@ export default function ProfilePage() {
return null;
}
- // Don't render until mounted (prevent hydration issues)
- if (!mounted) {
- return null;
- }
-
- const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
-
- // Validate file type
- if (!file.type.startsWith("image/")) {
- toast.error(t("auth.invalidImageType"));
- return;
- }
-
- // Validate file size (max 5MB)
- if (file.size > 5 * 1024 * 1024) {
- toast.error(t("auth.imageTooLarge"));
- return;
- }
-
- setAvatarFile(file);
-
- // Create preview
- const reader = new FileReader();
- reader.onloadend = () => {
- setAvatarPreview(reader.result as string);
- };
- reader.readAsDataURL(file);
- };
-
- const handleUpdateProfile = async (e: React.FormEvent) => {
- e.preventDefault();
-
- if (!editName.trim()) {
- toast.error(t("auth.nameRequired"));
- return;
- }
-
- if (!editEmail.trim()) {
- toast.error(t("auth.emailRequired"));
- return;
- }
-
- setIsUpdatingProfile(true);
-
- try {
- // Upload avatar first if changed
- let imageUrl = user?.image;
- if (avatarFile) {
- setIsUploadingAvatar(true);
- const formData = new FormData();
- formData.append("file", avatarFile);
-
- const uploadResponse = await fetch("/api/auth/upload-avatar", {
- method: "POST",
- body: formData,
- });
-
- // Check for rate limit error
- if (isRateLimitError(uploadResponse)) {
- await handleRateLimitError(uploadResponse, t);
- return;
- }
-
- if (!uploadResponse.ok) {
- toast.error(t("auth.avatarUploadFailed"));
- return;
- }
-
- const uploadData = await uploadResponse.json();
- imageUrl = uploadData.url;
- setIsUploadingAvatar(false);
- }
-
- // Update name and image via Better Auth API
- const updateResponse = await fetch("/api/auth/update-user", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- name: editName,
- image: imageUrl,
- }),
- });
-
- if (isRateLimitError(updateResponse)) {
- await handleRateLimitError(updateResponse, t);
- return;
- }
-
- if (!updateResponse.ok) {
- const updateData = await updateResponse.json();
- toast.error(updateData.error || t("common.error"));
- return;
- }
-
- // Update email if changed (without verification)
- if (editEmail !== user?.email) {
- const emailResponse = await fetch("/api/auth/change-email", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- newEmail: editEmail,
- }),
- });
-
- if (isRateLimitError(emailResponse)) {
- await handleRateLimitError(emailResponse, t);
- return;
- }
-
- if (!emailResponse.ok) {
- const emailData = await emailResponse.json();
- toast.error(emailData.error || t("common.error"));
- return;
- }
- }
-
- toast.success(t("auth.profileUpdated"));
- setAvatarFile(null);
-
- // Reload user data without page refresh
- await refetch();
- } catch (error) {
- console.error("Profile update error:", error);
- toast.error(t("common.error"));
- } finally {
- setIsUpdatingProfile(false);
- setIsUploadingAvatar(false);
- }
- };
-
- const handleChangePassword = async (e: React.FormEvent) => {
- e.preventDefault();
-
- if (!currentPassword || !newPassword) {
- toast.error(t("validation.passwordRequired"));
- return;
- }
-
- if (newPassword.length < 8) {
- toast.error(t("validation.passwordTooShort"));
- return;
- }
-
- if (newPassword !== confirmNewPassword) {
- toast.error(t("validation.passwordsNoMatch"));
- return;
- }
-
- setIsChangingPassword(true);
-
- try {
- // Check for rate limiting first
- const response = await fetch("/api/auth/change-password", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- newPassword,
- currentPassword,
- revokeOtherSessions: false,
- }),
- });
-
- if (isRateLimitError(response)) {
- await handleRateLimitError(response, t);
- return;
- }
-
- const result = await response.json();
-
- if (!response.ok) {
- toast.error(result.error || t("common.error"));
- return;
- }
-
- toast.success(t("auth.passwordChanged"));
- setCurrentPassword("");
- setNewPassword("");
- setConfirmNewPassword("");
- } catch (error) {
- console.error("Password change error:", error);
- toast.error(t("common.error"));
- } finally {
- setIsChangingPassword(false);
- }
- };
-
- const handleDeleteAccount = async () => {
- setIsDeleting(true);
- try {
- // Use our custom delete endpoint to properly handle foreign key constraints
- const response = await fetch("/api/auth/delete-account", {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- body: hasPasswordAuth
- ? JSON.stringify({ password: deletePassword })
- : undefined,
- });
-
- // Check for rate limit error
- if (isRateLimitError(response)) {
- await handleRateLimitError(response, t);
- return;
- }
-
- const data = await response.json();
+ const hasPasswordAuth = accounts.some((account) => account.provider === "credential");
- if (!response.ok) {
- toast.error(data.error || t("common.error"));
- return;
- }
-
- toast.success(t("auth.accountDeleted"));
- setShowDeleteDialog(false);
- setDeletePassword("");
-
- // Sign out and redirect
- await signOut();
- router.replace("/");
- } catch (error) {
- console.error("Account deletion error:", error);
- toast.error(t("common.error"));
- } finally {
- setIsDeleting(false);
- }
+ // Unsaved profile edits would be lost when leaving the page
+ const leave = (href: string) => {
+ if (profileForm.isDirty) setPendingHref(href);
+ else router.push(href);
};
- const handleSignOut = async () => {
- try {
- await signOut({
- fetchOptions: {
- onSuccess: () => {
- toast.success(t("auth.logoutSuccess"));
- router.replace("/login");
+ const accountItems: NavItem[] = [
+ {
+ id: "profile",
+ icon: User,
+ title: t("auth.profile"),
+ description: t("profile.navProfileHint"),
+ },
+ ...(hasPasswordAuth
+ ? [
+ {
+ id: "password" as const,
+ icon: KeyRound,
+ title: t("common.labels.password"),
+ description: t("profile.navPasswordHint"),
},
- },
- });
- } catch (error) {
- console.error("Sign out error:", error);
- toast.error(t("common.error"));
- }
+ ]
+ : []),
+ {
+ id: "accounts",
+ icon: Link2,
+ title: t("common.auth.connectedAccounts"),
+ description:
+ accounts.map((account) => providerInfo(account.provider).label).join(", ") ||
+ t("auth.noConnectedAccounts"),
+ },
+ ];
+ const securityItems: NavItem[] = [
+ {
+ id: "sessions",
+ icon: MonitorSmartphone,
+ title: t("common.auth.activeSessions"),
+ description: t("profile.navSessionsHint", { count: sessions.length }),
+ },
+ {
+ id: "activity",
+ icon: FileText,
+ title: t("activityLog.title"),
+ description: t("profile.navActivityHint"),
+ },
+ ];
+ const dangerItem: NavItem = {
+ id: "danger",
+ icon: TriangleAlert,
+ title: t("auth.dangerZone"),
+ description: t("profile.navDangerHint"),
+ danger: true,
};
-
- const handleRevokeAllSessions = async () => {
- const result = await revokeAllSessions();
-
- if (result.success) {
- toast.success(
- t("auth.sessionsRevokedCount", { count: result.revokedCount || 0 })
- );
- } else {
- toast.error(result.error || t("common.error"));
+ const items = [...accountItems, ...securityItems, dangerItem];
+
+ const requested = searchParams.get("section");
+ const active: SectionId | null =
+ items.find((item) => item.id === requested)?.id ?? (desktop ? "profile" : null);
+ const activeItem = items.find((item) => item.id === active);
+
+ const renderSection = (id: SectionId) => {
+ switch (id) {
+ case "profile":
+ return (
+ <ProfileDetailsSection form={profileForm} canEdit={hasPasswordAuth} accounts={accounts} />
+ );
+ case "password":
+ return <PasswordSection />;
+ case "accounts":
+ return <ConnectedAccountsSection accounts={accounts} />;
+ case "sessions":
+ // A failed fetch leaves `sessions` empty, which would otherwise read as
+ // "no device is signed in anywhere" on the security screen
+ if (sessionsError) {
+ return (
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-4")}>
+ <SectionHeading
+ title={t("profile.sessionsTitle")}
+ description={t("profile.sessionsHint")}
+ />
+ <StatusBanner
+ tone="danger"
+ icon={TriangleAlert}
+ title={t("common.error")}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-9 font-semibold"
+ onClick={() => refetchSessions()}
+ >
+ {t("calendarView.retry")}
+ </Button>
+ }
+ >
+ {t("common.fetchError", { item: t("common.auth.activeSessions") })}
+ </StatusBanner>
+ </div>
+ </PanelBody>
+ );
+ }
+ return (
+ <SessionsSection
+ sessions={sessions}
+ currentSessionId={session?.session.id}
+ revokeAllSessions={revokeAllSessions}
+ revokeSession={revokeSession}
+ />
+ );
+ case "activity":
+ return <ActivitySection />;
+ case "danger":
+ return <DangerSection hasPasswordAuth={hasPasswordAuth} />;
}
};
- // Parse user agent to get device info
- const parseUserAgent = (userAgent: string | null | undefined) => {
- if (!userAgent) {
- return {
- browser: "Unknown Browser",
- os: "Unknown OS",
- deviceType: "unknown" as const,
- deviceName: "Unknown Device",
- };
- }
-
- const parser = new UAParser(userAgent);
- const result = parser.getResult();
-
- const browser = result.browser.name
- ? `${result.browser.name}${
- result.browser.version ? ` ${result.browser.version}` : ""
- }`
- : "Unknown Browser";
- const os = result.os.name
- ? `${result.os.name}${result.os.version ? ` ${result.os.version}` : ""}`
- : "Unknown OS";
-
- let deviceType: "desktop" | "mobile" | "tablet" | "unknown" = "unknown";
- if (result.device.type === "mobile") {
- deviceType = "mobile";
- } else if (result.device.type === "tablet") {
- deviceType = "tablet";
- } else if (result.device.type === undefined && result.os.name) {
- // Desktop devices typically don't have a device.type
- deviceType = "desktop";
- }
-
- return {
- browser,
- os,
- deviceType,
- deviceName: `${result.browser.name || "Unknown"} on ${
- result.os.name || "Unknown"
- }`,
- };
+ // Native replaceState syncs useSearchParams without history entries or a server round trip.
+ // Profile drafts live in this page, so switching sections needs no unsaved-changes prompt.
+ const selectSection = (id: SectionId | null) => {
+ window.history.replaceState(null, "", sectionHref(id));
};
- const getDeviceIcon = (deviceType: string) => {
- switch (deviceType) {
- case "mobile":
- return <Smartphone className="h-5 w-5" />;
- case "tablet":
- return <Tablet className="h-5 w-5" />;
- case "desktop":
- return <Monitor className="h-5 w-5" />;
- default:
- return <HelpCircle className="h-5 w-5" />;
- }
+ const renderSidebarItem = (item: NavItem) => {
+ const selected = item.id === active;
+ const content = (
+ <>
+ <item.icon
+ className={cn(
+ "mt-0.5 size-4 shrink-0",
+ item.danger ? "text-danger" : selected ? "text-brand-ink" : "text-fg-secondary"
+ )}
+ />
+ <span className="min-w-0">
+ <span
+ className={cn(
+ "block text-[13.5px] font-semibold",
+ item.danger ? "text-danger" : selected ? "text-brand-ink" : "text-fg-body"
+ )}
+ >
+ {item.title}
+ </span>
+ <span
+ className={cn(
+ "block text-[12px]",
+ item.danger ? "text-danger" : selected ? "text-brand-ink/80" : "text-fg-tertiary"
+ )}
+ >
+ {item.description}
+ </span>
+ </span>
+ </>
+ );
+ const className = cn(
+ "flex items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",
+ selected
+ ? item.danger
+ ? "bg-danger-surface shadow-[inset_2px_0_0_var(--danger)]"
+ : "bg-brand-soft shadow-[inset_2px_0_0_var(--brand)]"
+ : "hover:bg-surface-sunken"
+ );
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => selectSection(item.id)}
+ aria-current={selected ? "page" : undefined}
+ className={className}
+ >
+ {content}
+ </button>
+ );
};
- return (
- <div className="flex flex-col min-h-screen">
- <AuthHeader showUserMenu />
-
- <div className="flex-1 bg-gradient-to-br from-background via-background to-primary/5">
- <div className="container mx-auto max-w-4xl px-4 py-8">
- {/* Header */}
- <div className="mb-8 space-y-2">
- <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.profileTitle")}
- </h1>
- <p className="text-muted-foreground">
- {t("auth.profileDescription")}
- </p>
- </div>
-
- <div className="space-y-6">
- {/* User Info */}
- <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.profile")}
- </CardTitle>
- <CardDescription>
- {t("auth.profileBasicInfoDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center gap-4">
- {user?.image && (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={user.image}
- alt={user.name || "User"}
- className="w-16 h-16 rounded-full object-cover border-2 border-border"
- />
- )}
- <div className="flex-1">
- <div className="mb-3">
- <Label>{t("common.labels.name")}</Label>
- <p className="mt-1 text-sm">{user?.name || "—"}</p>
- </div>
- <div>
- <Label>{t("common.labels.email")}</Label>
- <p className="mt-1 text-sm">{user?.email || "—"}</p>
- </div>
- </div>
- </div>
- </CardContent>
- </Card>
-
- {/* Edit Profile - Only for email/password users */}
- {hasPasswordAuth && (
- <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.editProfile")}
- </CardTitle>
- <CardDescription>
- {t("auth.editProfileDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <form onSubmit={handleUpdateProfile} className="space-y-4">
- {/* Avatar Upload */}
- <div className="space-y-2">
- <Label htmlFor="avatar">{t("auth.profilePicture")}</Label>
- <div className="flex items-center gap-4">
- {avatarPreview && (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={avatarPreview}
- alt="Avatar preview"
- className="w-20 h-20 rounded-full object-cover border-2 border-border"
- />
- )}
- <div className="flex-1">
- <Input
- id="avatar"
- type="file"
- accept="image/*"
- onChange={handleAvatarChange}
- disabled={isUpdatingProfile || isUploadingAvatar}
- />
- <p className="text-xs text-muted-foreground mt-1">
- {t("auth.avatarHint")}
- </p>
- </div>
- </div>
- </div>
-
- {/* Name */}
- <div className="space-y-2">
- <Label htmlFor="editName">
- {t("common.labels.name")}
- </Label>
- <Input
- id="editName"
- type="text"
- value={editName}
- onChange={(e) => setEditName(e.target.value)}
- disabled={isUpdatingProfile || isUploadingAvatar}
- required
- />
- </div>
-
- {/* Email */}
- <div className="space-y-2">
- <Label htmlFor="editEmail">
- {t("common.labels.email")}
- </Label>
- <Input
- id="editEmail"
- type="email"
- value={editEmail}
- onChange={(e) => setEditEmail(e.target.value)}
- disabled={isUpdatingProfile || isUploadingAvatar}
- required
- />
- </div>
-
- <Button
- type="submit"
- disabled={isUpdatingProfile || isUploadingAvatar}
- >
- {isUploadingAvatar
- ? t("auth.uploadingImage")
- : isUpdatingProfile
- ? t("common.saving")
- : t("common.save")}
- </Button>
- </form>
- </CardContent>
- </Card>
+ const renderListRow = (item: NavItem) => {
+ const content = (
+ <>
+ <item.icon
+ className={cn("size-[18px] shrink-0", item.danger ? "text-danger" : "text-fg-secondary")}
+ />
+ <span className="min-w-0 flex-1">
+ <span
+ className={cn(
+ "block truncate text-[14.5px]",
+ item.danger ? "font-semibold text-danger" : "text-fg-strong"
)}
-
- {/* Change Password - Only for email/password users */}
- {hasPasswordAuth && (
- <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.changePassword")}
- </CardTitle>
- <CardDescription>
- {t("auth.changePasswordDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <form onSubmit={handleChangePassword} className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="currentPassword">
- {t("auth.currentPassword")}
- </Label>
- <Input
- id="currentPassword"
- type="password"
- value={currentPassword}
- onChange={(e) => setCurrentPassword(e.target.value)}
- disabled={isChangingPassword}
- />
- </div>
-
- <div className="space-y-2">
- <Label htmlFor="newPassword">
- {t("common.labels.newPassword")}
- </Label>
- <Input
- id="newPassword"
- type="password"
- value={newPassword}
- onChange={(e) => setNewPassword(e.target.value)}
- disabled={isChangingPassword}
- minLength={8}
- />
- </div>
-
- <div className="space-y-2">
- <Label htmlFor="confirmNewPassword">
- {t("common.labels.confirmPassword")}
- </Label>
- <Input
- id="confirmNewPassword"
- type="password"
- value={confirmNewPassword}
- onChange={(e) => setConfirmNewPassword(e.target.value)}
- disabled={isChangingPassword}
- minLength={8}
- />
- </div>
-
- <Button type="submit" disabled={isChangingPassword}>
- {isChangingPassword
- ? t("common.saving")
- : t("auth.changePassword")}
- </Button>
- </form>
- </CardContent>
- </Card>
+ >
+ {item.title}
+ </span>
+ <span
+ className={cn(
+ "block truncate text-[12px]",
+ item.danger ? "text-danger-body" : "text-fg-tertiary"
)}
+ >
+ {item.description}
+ </span>
+ </span>
+ <ChevronRight className="size-4 shrink-0 text-fg-tertiary" />
+ </>
+ );
+ const className = "flex w-full items-center gap-3 px-3.5 py-3 text-left";
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => selectSection(item.id)}
+ className={className}
+ >
+ {content}
+ </button>
+ );
+ };
- {/* Connected Accounts */}
- <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("common.auth.connectedAccounts")}
- </CardTitle>
- <CardDescription>
- {t("auth.connectedAccountsDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent>
- {accountsLoading ? (
- <p className="text-sm text-muted-foreground">
- {t("common.loading")}
- </p>
- ) : accounts.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- {t("auth.noConnectedAccounts")}
- </p>
- ) : (
- <div className="space-y-3">
- {accounts.map((account) => (
- <div
- key={account.id}
- className="flex items-center justify-between rounded-lg border border-border/50 p-3"
- >
- <div>
- <p className="font-medium capitalize">
- {account.provider === "credential"
- ? t("auth.emailPasswordAuth")
- : account.provider}
- </p>
- <p className="text-sm text-muted-foreground">
- {account.accountId || "—"}
- </p>
- </div>
- </div>
- ))}
- </div>
- )}
- </CardContent>
- </Card>
-
- {/* Active Sessions */}
- <Card className="border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
- <div>
- <CardTitle className="bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("common.auth.activeSessions")}
- </CardTitle>
- <CardDescription>
- {t("auth.activeSessionsDescription")}
- </CardDescription>
- </div>
- {sessions.length > 1 && !sessionsLoading && (
- <Button
- variant="outline"
- size="sm"
- onClick={handleRevokeAllSessions}
- className="text-destructive hover:text-destructive"
- >
- <LogOut className="h-4 w-4 mr-2" />
- {t("auth.logoutAllDevices")}
- </Button>
- )}
- </div>
- </CardHeader>
- <CardContent>
- {sessionsLoading ? (
- <p className="text-sm text-muted-foreground">
- {t("common.loading")}
- </p>
- ) : sessions.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- {t("auth.noActiveSessions")}
- </p>
- ) : (
- <div className="space-y-3">
- {sessions.map((session) => {
- const deviceInfo = parseUserAgent(session.userAgent);
-
- return (
- <div
- key={session.id}
- className="flex items-start gap-3 rounded-lg border border-border/50 p-3 transition-colors"
- >
- <div className="mt-0.5 text-muted-foreground">
- {getDeviceIcon(deviceInfo.deviceType)}
- </div>
- <div className="flex-1 min-w-0 space-y-1">
- <div className="flex items-center gap-2 flex-wrap">
- <p className="font-medium truncate">
- {deviceInfo.deviceName}
- </p>
- </div>
- <div className="text-xs text-muted-foreground space-y-0.5">
- <p className="truncate">
- {t("auth.browser")}: {deviceInfo.browser}
- </p>
- <p className="truncate">
- {t("auth.operatingSystem")}: {deviceInfo.os}
- </p>
- {session.ipAddress && (
- <p className="truncate">
- {t("common.labels.ipAddress")}:{" "}
- {session.ipAddress}
- </p>
- )}
- <p>
- {t("common.time.lastActive")}:{" "}
- {new Intl.DateTimeFormat(undefined, {
- dateStyle: "medium",
- timeStyle: "short",
- }).format(new Date(session.updatedAt))}
- </p>
- </div>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </CardContent>
- </Card>
-
- <Separator />
-
- {/* Danger Zone */}
- <Card className="border-destructive/30 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm">
- <CardHeader>
- <CardTitle className="bg-gradient-to-r from-destructive to-destructive/70 bg-clip-text text-transparent">
- {t("auth.dangerZone")}
- </CardTitle>
- <CardDescription>
- {t("auth.dangerZoneDescription")}
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <p className="font-medium">{t("auth.logout")}</p>
- <p className="text-sm text-muted-foreground">
- {t("auth.logoutDescription")}
- </p>
- </div>
- <Button variant="outline" onClick={handleSignOut}>
- {t("auth.logout")}
- </Button>
- </div>
-
- <Separator />
+ const renderGroup = (label: string | null, groupItems: NavItem[], danger = false): ReactNode => (
+ <section key={label ?? "danger"}>
+ {label && <div className="eyebrow mb-2 px-1">{label}</div>}
+ <div
+ className={cn(
+ "divide-y overflow-hidden rounded-[12px] border",
+ danger
+ ? "divide-danger-line border-danger-line bg-danger-surface"
+ : "divide-line-subtle border-line bg-surface-card"
+ )}
+ >
+ {groupItems.map(renderListRow)}
+ </div>
+ </section>
+ );
- <div className="flex items-center justify-between">
- <div>
- <p className="font-medium">{t("auth.deleteAccount")}</p>
- <p className="text-sm text-muted-foreground">
- {t("auth.deleteAccountDescription")}
- </p>
- </div>
- <Button
- variant="destructive"
- onClick={() => setShowDeleteDialog(true)}
- >
- {t("auth.deleteAccount")}
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
+ const inSection = !desktop && !!active;
- {/* Delete Confirmation Dialog */}
- <ConfirmationDialog
- open={showDeleteDialog}
- onOpenChange={(open) => {
- setShowDeleteDialog(open);
- if (!open) setDeletePassword("");
- }}
- onConfirm={handleDeleteAccount}
- title={t("auth.deleteAccount")}
- description={t("auth.deleteAccountConfirm")}
- confirmText={
- isDeleting ? t("common.loading") : t("auth.deleteAccount")
- }
- confirmDisabled={isDeleting || (hasPasswordAuth && !deletePassword)}
- >
- {hasPasswordAuth && (
- <div className="space-y-2 pt-4">
- <Label htmlFor="deletePassword">
- {t("auth.confirmPasswordLabel")}
- </Label>
- <Input
- id="deletePassword"
- type="password"
- value={deletePassword}
- onChange={(e) => setDeletePassword(e.target.value)}
- disabled={isDeleting}
- placeholder={t("auth.enterPassword")}
- />
+ return (
+ <div className="flex h-dvh flex-col bg-background">
+ <AccountPageHeader
+ title={inSection && activeItem ? activeItem.title : t("profile.title")}
+ subtitle={inSection && activeItem ? activeItem.description : user.email}
+ onBack={inSection ? () => selectSection(null) : () => leave("/")}
+ actions={<UserMenu />}
+ />
+
+ <div className="flex min-h-0 flex-1">
+ {desktop && (
+ <nav className="flex w-[278px] shrink-0 flex-col gap-1 overflow-y-auto border-r border-line bg-surface-panel p-2.5">
+ {items.map(renderSidebarItem)}
+ </nav>
+ )}
+
+ <main className="flex min-w-0 flex-1 flex-col">
+ {active ? (
+ <div key={active} className="flex min-h-0 flex-1 flex-col">
+ {renderSection(active)}
+ </div>
+ ) : (
+ <PanelBody className="bg-surface-panel px-4">
+ <div className="flex flex-col gap-5">
+ {renderGroup(t("profile.groupAccount"), accountItems)}
+ {renderGroup(t("profile.groupSecurity"), securityItems)}
+ {renderGroup(null, [dangerItem], true)}
</div>
- )}
- </ConfirmationDialog>
- </div>
+ </PanelBody>
+ )}
+ </main>
</div>
- <AppFooter versionInfo={versionInfo} />
+ <ConfirmationDialog
+ open={!!pendingHref}
+ onOpenChange={(open) => !open && setPendingHref(null)}
+ onConfirm={() => {
+ const href = pendingHref;
+ setPendingHref(null);
+ profileForm.discard();
+ if (href) router.push(href);
+ }}
+ />
</div>
);
}
diff --git a/app/register/page.tsx b/app/register/page.tsx
index 70758c2..e059842 100644
--- a/app/register/page.tsx
+++ b/app/register/page.tsx
@@ -9,27 +9,23 @@ import { useAuth } from "@/hooks/useAuth";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { FullscreenLoader } from "@/components/fullscreen-loader";
-import { AuthHeader } from "@/components/auth-header";
-import { AppFooter } from "@/components/app-footer";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
+import {
+ AuthShell,
+ PasswordInput,
+ authInputClass,
+} from "@/components/auth-shell";
+import { Field } from "@/components/form-kit";
+import { Check } from "lucide-react";
+import { cn } from "@/lib/utils";
import {
isRateLimitError,
handleRateLimitError,
} from "@/lib/rate-limit-client";
+import { useMounted } from "@/hooks/useMediaQuery";
+
-/**
- * Registration page for new users
- *
- * Features:
- * - Email/Password registration
- * - Name field
- * - Password confirmation
- * - Validation
- * - Redirect to dashboard after success
- */
export default function RegisterPage() {
const t = useTranslations();
const router = useRouter();
@@ -40,13 +36,12 @@ export default function RegisterPage() {
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const [mounted, setMounted] = useState(false);
- const versionInfo = useVersionInfo();
+ // False during SSR and hydration, true afterwards
+ const mounted = useMounted();
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
- // Validation
if (!name) {
toast.error(t("auth.nameRequired"));
return;
@@ -82,9 +77,8 @@ export default function RegisterPage() {
});
if (result.error) {
- // Check if the error indicates rate limiting
+ // Better Auth hides the 429 headers; a second request exposes them for the message
if (result.error.status === 429) {
- // Make a test request to get proper rate limit headers
try {
const testResponse = await fetch("/api/auth/sign-up/email", {
method: "POST",
@@ -97,7 +91,6 @@ export default function RegisterPage() {
return;
}
} catch {
- // If test request fails, show generic rate limit message
toast.error(t("rateLimit.title"), {
description: t("rateLimit.fallback"),
});
@@ -115,9 +108,8 @@ export default function RegisterPage() {
return;
}
- // Better Auth automatically signs in the user after signup
+ // Better Auth signs the user in after sign-up; the session update navigates away
toast.success(t("auth.registerSuccess"));
- // Session update triggers automatic navigation via AuthProvider
} catch (error) {
console.error("Registration error:", error);
toast.error(t("auth.registerError"));
@@ -126,19 +118,12 @@ export default function RegisterPage() {
}
};
- // Prevent hydration mismatch
- useEffect(() => {
- setMounted(true);
- }, []);
-
- // Redirect authenticated users to home
useEffect(() => {
if (mounted && isAuthenticated) {
router.replace("/");
}
}, [mounted, isAuthenticated, router]);
- // Redirect if auth disabled or registration not allowed
useEffect(() => {
if (!isAuthEnabled) {
router.replace("/");
@@ -151,115 +136,101 @@ export default function RegisterPage() {
return null;
}
- // Prevent hydration mismatch by showing loader until mounted
- // Also show loader while redirecting authenticated users
+ // Also covers the moment between sign-up and the redirect
if (!mounted || isAuthenticated) {
return <FullscreenLoader />;
}
- return (
- <div className="flex flex-col min-h-screen">
- <AuthHeader />
-
- <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-primary/5 px-4 py-8">
- <div className="w-full max-w-md space-y-8">
- {/* Header */}
- <div className="text-center space-y-2">
- <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("auth.registerTitle")}
- </h1>
- <p className="text-sm text-muted-foreground">
- {t("auth.registerDescription")}
- </p>
- </div>
-
- {/* Registration Form */}
- <div className="rounded-xl border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 p-8 shadow-lg backdrop-blur-sm">
- <form onSubmit={handleRegister} className="space-y-6">
- {/* Name */}
- <div className="space-y-2">
- <Label htmlFor="name">{t("common.labels.name")}</Label>
- <Input
- id="name"
- type="text"
- placeholder={t("auth.namePlaceholder")}
- value={name}
- onChange={(e) => setName(e.target.value)}
- disabled={isLoading}
- required
- />
- </div>
-
- {/* Email */}
- <div className="space-y-2">
- <Label htmlFor="email">{t("common.labels.email")}</Label>
- <Input
- id="email"
- type="email"
- placeholder={t("auth.emailPlaceholder")}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- disabled={isLoading}
- required
- />
- </div>
-
- {/* Password */}
- <div className="space-y-2">
- <Label htmlFor="password">{t("common.labels.password")}</Label>
- <Input
- id="password"
- type="password"
- placeholder={t("auth.passwordPlaceholder")}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- disabled={isLoading}
- required
- minLength={8}
- />
- <p className="text-xs text-muted-foreground">
- {t("validation.passwordTooShort")}
- </p>
- </div>
-
- {/* Confirm Password */}
- <div className="space-y-2">
- <Label htmlFor="confirmPassword">
- {t("common.labels.confirmPassword")}
- </Label>
- <Input
- id="confirmPassword"
- type="password"
- placeholder={t("common.labels.confirmPassword")}
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- disabled={isLoading}
- required
- minLength={8}
- />
- </div>
+ const passwordsMatch = confirmPassword.length > 0 && password === confirmPassword;
- {/* Submit Button */}
- <Button type="submit" className="w-full" disabled={isLoading}>
- {isLoading ? t("common.loading") : t("auth.register")}
- </Button>
- </form>
-
- {/* Login Link */}
- <p className="mt-6 text-center text-sm text-muted-foreground">
- {t("auth.alreadyHaveAccount")}{" "}
- <Link
- href="/login"
- className="font-medium text-primary hover:underline"
- >
- {t("auth.login")}
- </Link>
- </p>
+ return (
+ <AuthShell
+ title={t("authPage.registerTitle")}
+ description={t("authPage.registerSubtitle")}
+ >
+ <form onSubmit={handleRegister} className="flex flex-col gap-3">
+ <Field label={t("common.labels.name")} htmlFor="name">
+ <Input
+ id="name"
+ type="text"
+ autoComplete="name"
+ placeholder={t("auth.namePlaceholder")}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ disabled={isLoading}
+ required
+ className={authInputClass}
+ />
+ </Field>
+
+ <Field label={t("common.labels.email")} htmlFor="email">
+ <Input
+ id="email"
+ type="email"
+ autoComplete="email"
+ placeholder={t("auth.emailPlaceholder")}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ disabled={isLoading}
+ required
+ className={authInputClass}
+ />
+ </Field>
+
+ <Field
+ label={t("common.labels.password")}
+ htmlFor="password"
+ hint={t("authPage.passwordHint")}
+ >
+ <PasswordInput
+ id="password"
+ autoComplete="new-password"
+ placeholder={t("auth.passwordPlaceholder")}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ minLength={8}
+ />
+ </Field>
+
+ <Field label={t("authPage.repeatPassword")} htmlFor="confirmPassword">
+ <div className="relative">
+ <Input
+ id="confirmPassword"
+ type="password"
+ autoComplete="new-password"
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ disabled={isLoading}
+ required
+ minLength={8}
+ className={cn(authInputClass, "pr-11")}
+ />
+ {passwordsMatch && (
+ <span className="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-success">
+ <Check className="size-[17px]" aria-hidden="true" />
+ <span className="sr-only">{t("authPage.passwordsMatch")}</span>
+ </span>
+ )}
</div>
- </div>
- </div>
-
- <AppFooter versionInfo={versionInfo} />
- </div>
+ </Field>
+
+ <Button
+ type="submit"
+ className="h-11 w-full rounded-[9px] text-[15px] font-semibold"
+ disabled={isLoading}
+ >
+ {isLoading ? t("common.loading") : t("authPage.registerTitle")}
+ </Button>
+ </form>
+
+ <p className="border-t border-line pt-4 text-center text-[13.5px] text-fg-secondary">
+ {t("authPage.haveAccount")}{" "}
+ <Link href="/login" className="font-semibold text-brand-ink hover:underline">
+ {t("auth.login")}
+ </Link>
+ </p>
+ </AuthShell>
);
}
diff --git a/app/system-unavailable/page.tsx b/app/system-unavailable/page.tsx
index 2e278b8..1ca209b 100644
--- a/app/system-unavailable/page.tsx
+++ b/app/system-unavailable/page.tsx
@@ -1,42 +1,24 @@
import { getTranslations } from "next-intl/server";
-import { AlertTriangle } from "lucide-react";
-import { AppFooter } from "@/components/app-footer";
+import { DatabaseZap } from "lucide-react";
import { AuthHeader } from "@/components/auth-header";
-import { getVersionInfo } from "@/lib/version";
+import { EmptyStateBlock } from "@/components/empty-state-block";
+import { RetryButton } from "./retry-button";
export default async function SystemUnavailablePage() {
const t = await getTranslations();
- const versionInfo = await getVersionInfo();
return (
- <div className="flex flex-col min-h-screen">
+ <div className="flex min-h-dvh flex-col bg-background">
<AuthHeader />
-
- <div className="flex flex-1 items-center justify-center bg-gradient-to-br from-background via-background to-destructive/5 px-4 py-8">
- <div className="w-full max-w-2xl">
- {/* Error Banner */}
- <div className="rounded-lg border-2 border-destructive bg-destructive/10 p-8 shadow-lg animate-in fade-in slide-in-from-top-4 duration-500">
- <div className="flex gap-4 items-start">
- <AlertTriangle className="h-12 w-12 text-destructive flex-shrink-0 mt-1" />
- <div className="space-y-3 flex-1">
- <h1 className="text-3xl font-semibold text-destructive">
- {t("system.unavailable")}
- </h1>
- <p className="text-sm text-muted-foreground mt-4">
- {t("system.unavailableDescription")}
- </p>
- <div className="pt-4 border-t border-destructive/20 mt-6">
- <p className="text-xs text-muted-foreground">
- {t("system.unavailableRetry")}
- </p>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <AppFooter versionInfo={versionInfo} />
+ <main className="flex flex-1 items-center justify-center px-4 py-10 sm:p-10">
+ <EmptyStateBlock
+ icon={DatabaseZap}
+ tone="danger"
+ title={t("system.unavailable")}
+ description={t("system.unavailableDescription")}
+ actions={<RetryButton label={t("calendarView.retry")} />}
+ />
+ </main>
</div>
);
}
diff --git a/app/system-unavailable/retry-button.tsx b/app/system-unavailable/retry-button.tsx
new file mode 100644
index 0000000..2d73fed
--- /dev/null
+++ b/app/system-unavailable/retry-button.tsx
@@ -0,0 +1,15 @@
+"use client";
+
+import { RotateCw } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { stateActionClass } from "@/components/empty-state-block";
+
+// The proxy sends a reload of this page back to "/" once the DB is healthy again
+export function RetryButton({ label }: { label: string }) {
+ return (
+ <Button onClick={() => window.location.reload()} className={stateActionClass}>
+ <RotateCw className="size-[17px]" />
+ {label}
+ </Button>
+ );
+}
diff --git a/components/admin/admin-detail-panel.tsx b/components/admin/admin-detail-panel.tsx
new file mode 100644
index 0000000..8e1369d
--- /dev/null
+++ b/components/admin/admin-detail-panel.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { ReactNode } from "react";
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { PanelCloseButton, PanelDialog } from "@/components/panel-dialog";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+
+export interface AdminDetailPanelProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: ReactNode;
+ subtitle?: ReactNode;
+ /** Stacked with an 18px gap, like the sections in 13c/13e */
+ children: ReactNode;
+ footer?: ReactNode;
+}
+
+/** Admin detail view: a 440px side panel over the list on desktop, a bottom sheet on phones. */
+export function AdminDetailPanel({ open, onOpenChange, title, subtitle, children, footer }: AdminDetailPanelProps) {
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+
+ if (!desktop) {
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={title}
+ description={subtitle}
+ footer={footer}
+ bodyClassName="flex flex-col gap-[18px]"
+ >
+ {children}
+ </PanelDialog>
+ );
+ }
+
+ return (
+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/20 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0" />
+ <DialogPrimitive.Content className="fixed bottom-3 right-3 top-3 z-50 flex w-[440px] max-w-[calc(100vw-24px)] flex-col overflow-hidden rounded-[14px] border border-control bg-background shadow-window outline-none duration-200 data-[state=closed]:animate-out data-[state=closed]:slide-out-to-right-8 data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:slide-in-from-right-8 data-[state=open]:fade-in-0 dark:bg-surface-panel">
+ <div className="flex shrink-0 items-start gap-3 border-b border-line px-[18px] py-4">
+ <div className="min-w-0 flex-1">
+ <DialogPrimitive.Title className="truncate text-[17px] font-semibold leading-tight tracking-[-0.01em] text-fg-strong">
+ {title}
+ </DialogPrimitive.Title>
+ <DialogPrimitive.Description
+ className={subtitle ? "mt-1 truncate text-[12.5px] text-fg-tertiary" : "sr-only"}
+ >
+ {subtitle ?? title}
+ </DialogPrimitive.Description>
+ </div>
+ <PanelCloseButton onClick={() => onOpenChange(false)} />
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col gap-[18px] overflow-y-auto px-[18px] py-4">{children}</div>
+ {footer && (
+ <div className="flex shrink-0 items-center gap-2.5 border-t border-line px-[18px] py-4">{footer}</div>
+ )}
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+}
diff --git a/components/admin/admin-form-panel.tsx b/components/admin/admin-form-panel.tsx
new file mode 100644
index 0000000..e95dfaf
--- /dev/null
+++ b/components/admin/admin-form-panel.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import { ReactNode } from "react";
+import { useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";
+import { useDirtyState } from "@/hooks/useDirtyState";
+
+interface AdminFormPanelProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: ReactNode;
+ subtitle?: ReactNode;
+ children: ReactNode;
+ onSave: () => void | Promise<void>;
+ isSaving?: boolean;
+ saveDisabled?: boolean;
+ saveLabel?: string;
+ hasUnsavedChanges?: boolean;
+}
+
+/** Admin side panel with a Cancel/Save footer and the unsaved-changes guard of BaseSheet. */
+export function AdminFormPanel({
+ open,
+ onOpenChange,
+ title,
+ subtitle,
+ children,
+ onSave,
+ isSaving = false,
+ saveDisabled = false,
+ saveLabel,
+ hasUnsavedChanges = false,
+}: AdminFormPanelProps) {
+ const t = useTranslations();
+ const { handleClose, showConfirmDialog, setShowConfirmDialog, handleConfirmClose } =
+ useDirtyState({ onClose: onOpenChange, hasChanges: () => hasUnsavedChanges });
+
+ return (
+ <>
+ <AdminDetailPanel
+ open={open}
+ onOpenChange={(next) => (next ? onOpenChange(true) : handleClose())}
+ title={title}
+ subtitle={subtitle}
+ footer={
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => handleClose()}
+ disabled={isSaving}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ onClick={() => onSave()}
+ disabled={saveDisabled || isSaving}
+ className="h-10 flex-1 font-semibold"
+ >
+ {isSaving ? t("common.saving") : saveLabel || t("common.save")}
+ </Button>
+ </>
+ }
+ >
+ {children}
+ </AdminDetailPanel>
+
+ <ConfirmationDialog
+ open={showConfirmDialog}
+ onOpenChange={setShowConfirmDialog}
+ onConfirm={handleConfirmClose}
+ />
+ </>
+ );
+}
diff --git a/components/admin/admin-header.tsx b/components/admin/admin-header.tsx
index 31b2537..4c32c7c 100644
--- a/components/admin/admin-header.tsx
+++ b/components/admin/admin-header.tsx
@@ -1,150 +1,35 @@
"use client";
-import { useTranslations } from "next-intl";
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { Menu } from "lucide-react";
-import { useConnectionStatus } from "@/hooks/useConnectionStatus";
-import {
- Breadcrumb,
- BreadcrumbItem,
- BreadcrumbLink,
- BreadcrumbList,
- BreadcrumbPage,
- BreadcrumbSeparator,
-} from "@/components/ui/breadcrumb";
-import { Button } from "@/components/ui/button";
-import { ThemeSwitcher } from "@/components/theme-switcher";
-import { LanguageSwitcher } from "@/components/language-switcher";
-
-interface BreadcrumbSegment {
- label: string;
- href?: string;
-}
-
-interface AdminHeaderProps {
- onMenuClick?: () => void;
-}
+import { useTranslations } from "next-intl";
+import { ChevronRight } from "lucide-react";
+import { UserMenu } from "@/components/user-menu";
+import { isActiveSection, useAdminSections } from "@/components/admin/admin-sidebar";
-/**
- * Admin Panel Header
- *
- * Features:
- * - Automatic breadcrumb navigation from URL
- * - Theme + Language switchers
- * - Mobile menu toggle
- */
-export function AdminHeader({ onMenuClick }: AdminHeaderProps) {
+/** Desktop top bar: breadcrumb and account menu (which also holds appearance and language). */
+export function AdminHeader() {
const t = useTranslations();
const pathname = usePathname();
- const { isOnline } = useConnectionStatus();
-
- // Generate breadcrumbs from pathname
- const generateBreadcrumbs = (): BreadcrumbSegment[] => {
- const segments: BreadcrumbSegment[] = [
- { label: t("admin.title"), href: "/admin" },
- ];
-
- // Parse pathname segments
- const pathParts = pathname.split("/").filter(Boolean);
-
- // Remove "admin" prefix (already in first segment)
- const adminIndex = pathParts.indexOf("admin");
- if (adminIndex !== -1) {
- pathParts.splice(adminIndex, 1);
- }
-
- // Map path segments to breadcrumb items
- let currentPath = "/admin";
- for (let i = 0; i < pathParts.length; i++) {
- const part = pathParts[i];
- currentPath += `/${part}`;
-
- // Check if it's the last segment (current page - no link)
- const isLast = i === pathParts.length - 1;
-
- // Map known segments to translations
- let label = part;
- if (part === "users") {
- label = t("admin.usersMenu");
- } else if (part === "calendars") {
- label = t("admin.calendarsMenu");
- } else if (part === "orphaned") {
- label = t("admin.orphanedCalendars");
- } else if (part === "logs") {
- label = t("admin.auditLogs");
- }
-
- segments.push({
- label,
- href: isLast ? undefined : currentPath,
- });
- }
-
- return segments;
- };
-
- const breadcrumbs = generateBreadcrumbs();
+ const sections = useAdminSections();
+ const current = sections.find((section) => isActiveSection(pathname, section.href));
return (
- <header className="sticky top-0 z-20 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
- <div className="p-4 space-y-3">
- {/* Top row: Breadcrumbs + Controls */}
- <div className="flex items-center justify-between gap-4">
- {/* Mobile Menu Button */}
- <Button
- variant="ghost"
- size="icon"
- onClick={onMenuClick}
- className="lg:hidden flex-shrink-0"
- aria-label="Toggle menu"
- >
- <Menu className="h-5 w-5" />
- </Button>
-
- {/* Breadcrumbs */}
- <Breadcrumb className="flex-1 min-w-0">
- <BreadcrumbList>
- {breadcrumbs.map((segment, index) => {
- const isLast = index === breadcrumbs.length - 1;
-
- return (
- <div key={segment.href || segment.label} className="contents">
- <BreadcrumbItem>
- {segment.href ? (
- <BreadcrumbLink asChild>
- <Link href={segment.href}>{segment.label}</Link>
- </BreadcrumbLink>
- ) : (
- <BreadcrumbPage>{segment.label}</BreadcrumbPage>
- )}
- </BreadcrumbItem>
- {!isLast && <BreadcrumbSeparator />}
- </div>
- );
- })}
- </BreadcrumbList>
- </Breadcrumb>
-
- {/* Controls: Connection Status + Theme + Language */}
- <div className="flex items-center gap-2">
- {/* Connection Status Indicator */}
- <div
- title={isOnline ? t("sync.connected") : t("sync.disconnected")}
- >
- <div
- className={`w-2.5 h-2.5 rounded-full transition-all ${
- isOnline
- ? "bg-green-500 animate-pulse shadow-[0_0_8px_rgba(34,197,94,0.6)]"
- : "bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.6)]"
- }`}
- ></div>
- </div>
- <LanguageSwitcher />
- <ThemeSwitcher />
- </div>
- </div>
- </div>
+ <header className="hidden h-14 shrink-0 items-center gap-2.5 border-b border-line bg-background px-[18px] lg:flex">
+ <nav aria-label={t("adminShell.breadcrumb")} className="flex min-w-0 flex-1 items-center gap-2.5">
+ <Link href="/admin" className="text-[13.5px] text-fg-tertiary transition-colors hover:text-fg-body">
+ {t("admin.title")}
+ </Link>
+ {current && (
+ <>
+ <ChevronRight className="size-[15px] shrink-0 text-fg-faint" />
+ <span aria-current="page" className="truncate text-[13.5px] font-semibold text-fg-strong">
+ {current.label}
+ </span>
+ </>
+ )}
+ </nav>
+ <UserMenu />
</header>
);
}
diff --git a/components/admin/admin-kit.tsx b/components/admin/admin-kit.tsx
new file mode 100644
index 0000000..12c5904
--- /dev/null
+++ b/components/admin/admin-kit.tsx
@@ -0,0 +1,266 @@
+"use client";
+
+import { ReactNode } from "react";
+import { useTranslations } from "next-intl";
+import Link from "next/link";
+import { ArrowLeft, Search } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Pill, SectionLabel } from "@/components/form-kit";
+import { UserMenu } from "@/components/user-menu";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { cn, getUserInitials } from "@/lib/utils";
+
+/*
+ * Shared admin building blocks (screens 13a–13k). Pages compose these; data
+ * fetching and permission checks stay in the pages and hooks.
+ */
+
+/**
+ * Page title row. On phones it doubles as the sticky top bar (back to the app,
+ * title, subtitle, `mobileActions`, avatar), so it must be the first child of the page.
+ */
+export function AdminPageHeader({
+ title,
+ subtitle,
+ actions,
+ mobileActions,
+}: {
+ title: ReactNode;
+ subtitle?: ReactNode;
+ /** Desktop only */
+ actions?: ReactNode;
+ /** Phones, shown before the avatar; typically 34px icon buttons */
+ mobileActions?: ReactNode;
+}) {
+ const t = useTranslations();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ return (
+ <div className="sticky top-0 z-20 -mx-4 flex items-center gap-2.5 border-b border-line bg-background px-4 pb-3 pt-[max(12px,env(safe-area-inset-top))] lg:static lg:mx-0 lg:flex-wrap lg:items-end lg:justify-between lg:gap-4 lg:border-0 lg:bg-transparent lg:p-0">
+ <Link
+ href="/"
+ aria-label={t("admin.backToApp")}
+ className="flex size-[34px] shrink-0 items-center justify-center rounded-[9px] border border-line text-fg-secondary lg:hidden"
+ >
+ <ArrowLeft className="size-[17px]" />
+ </Link>
+ <div className="min-w-0 flex-1 lg:flex-none">
+ <h1 className="truncate text-[16px] font-semibold tracking-[-0.01em] text-fg-strong lg:text-[21px]">{title}</h1>
+ {subtitle && (
+ <p className="truncate text-[11.5px] text-fg-tertiary lg:mt-1 lg:text-[13.5px] lg:text-fg-secondary">
+ {subtitle}
+ </p>
+ )}
+ </div>
+ {actions && <div className="hidden flex-wrap items-center gap-2 lg:flex">{actions}</div>}
+ {!desktop && (
+ <div className="flex shrink-0 items-center gap-2 lg:hidden">
+ {mobileActions}
+ <UserMenu />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function AdminSearch({
+ value,
+ onChange,
+ placeholder,
+ className,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder: string;
+ className?: string;
+}) {
+ return (
+ <div className={cn("relative w-full sm:w-[366px]", className)}>
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <Input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ className="h-[38px] rounded-[9px] pl-9 text-[13.5px]"
+ />
+ </div>
+ );
+}
+
+/** Bordered card that holds a table (desktop) or card list (phones) plus an optional footer. */
+export function AdminTableCard({
+ children,
+ footer,
+ className,
+}: {
+ children: ReactNode;
+ footer?: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div className={cn("overflow-hidden rounded-[12px] border border-line bg-surface-card", className)}>
+ {children}
+ {footer && (
+ <div className="flex items-center justify-between gap-3 border-t border-line bg-surface-panel px-4 py-3 text-[12.5px] text-fg-secondary">
+ {footer}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Uppercase column header row; pass a grid template shared with the rows. */
+export function AdminTableHead({ columns, template }: { columns: ReactNode[]; template: string }) {
+ return (
+ <div
+ className="hidden items-center gap-3.5 border-b border-line bg-surface-panel px-4 py-2.5 lg:grid"
+ style={{ gridTemplateColumns: template }}
+ >
+ {columns.map((column, i) => (
+ <div key={i} className="eyebrow truncate text-[11px]">
+ {column}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export function AdminTableRow({
+ template,
+ children,
+ muted,
+ onClick,
+}: {
+ template: string;
+ children: ReactNode;
+ muted?: "danger" | "panel";
+ onClick?: () => void;
+}) {
+ return (
+ <div
+ role={onClick ? "button" : undefined}
+ tabIndex={onClick ? 0 : undefined}
+ onClick={onClick}
+ onKeyDown={(e) => onClick && (e.key === "Enter" || e.key === " ") && onClick()}
+ className={cn(
+ "hidden items-center gap-3.5 border-b border-line-subtle px-4 py-3 last:border-b-0 lg:grid",
+ onClick && "cursor-pointer hover:bg-surface-panel",
+ muted === "danger" && "bg-danger-surface",
+ muted === "panel" && "bg-surface-panel"
+ )}
+ style={{ gridTemplateColumns: template }}
+ >
+ {children}
+ </div>
+ );
+}
+
+/** Phone replacement for a table row (13h–13k). */
+export function AdminMobileCard({
+ children,
+ onClick,
+ muted,
+}: {
+ children: ReactNode;
+ onClick?: () => void;
+ muted?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "flex w-full flex-col gap-2 rounded-[11px] border border-line px-3.5 py-3 text-left lg:hidden",
+ muted ? "bg-surface-panel" : "bg-surface-card"
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+export function UserAvatar({
+ name,
+ image,
+ size = 32,
+ tone = "neutral",
+ color,
+}: {
+ name?: string | null;
+ image?: string | null;
+ size?: number;
+ tone?: "neutral" | "brand";
+ /** Solid background, e.g. a calendar owner's avatar */
+ color?: string;
+}) {
+ const style = { width: size, height: size, fontSize: size * 0.36 };
+ if (image) {
+ // eslint-disable-next-line @next/next/no-img-element
+ return <img src={image} alt="" className="shrink-0 rounded-full object-cover" style={style} />;
+ }
+ return (
+ <span
+ className={cn(
+ "flex shrink-0 items-center justify-center rounded-full font-semibold",
+ color ? "text-white" : tone === "brand" ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken text-fg-secondary"
+ )}
+ style={{ ...style, backgroundColor: color }}
+ >
+ {name ? getUserInitials({ name }) : "?"}
+ </span>
+ );
+}
+
+export function RolePill({ role }: { role: string | null | undefined }) {
+ const t = useTranslations();
+ if (role === "superadmin") return <Pill tone="brand">{t("common.roles.superadmin")}</Pill>;
+ if (role === "admin") return <Pill tone="violet">{t("common.roles.admin")}</Pill>;
+ return <Pill>{t("common.roles.user")}</Pill>;
+}
+
+export function StatusPill({ banned }: { banned: boolean | null | undefined }) {
+ const t = useTranslations();
+ return banned ? (
+ <Pill tone="danger">{t("adminKit.banned")}</Pill>
+ ) : (
+ <Pill tone="success">{t("adminKit.active")}</Pill>
+ );
+}
+
+export function SeverityPill({ severity }: { severity: string | null | undefined }) {
+ const t = useTranslations();
+ if (severity === "critical") return <Pill tone="danger">{t("adminKit.severityCritical")}</Pill>;
+ if (severity === "error") return <Pill tone="danger">{t("adminKit.severityError")}</Pill>;
+ if (severity === "warning") return <Pill tone="warning">{t("adminKit.severityWarning")}</Pill>;
+ return <Pill>{t("adminKit.severityInfo")}</Pill>;
+}
+
+/** Monospace count; zero renders faint as in the handoff. */
+export function Count({ value, className }: { value: number; className?: string }) {
+ return (
+ <span className={cn("font-mono text-[13px]", value === 0 ? "text-fg-faint" : "text-fg-strong", className)}>
+ {value}
+ </span>
+ );
+}
+
+/** Labelled numbers used in mobile cards and detail panels. */
+/** Labelled block inside a detail side panel. */
+export function DetailSection({ label, children }: { label: ReactNode; children: ReactNode }) {
+ return (
+ <section>
+ <SectionLabel>{label}</SectionLabel>
+ <div className="flex flex-col gap-2">{children}</div>
+ </section>
+ );
+}
+
+export function StatTile({ label, value }: { label: ReactNode; value: number }) {
+ return (
+ <div className="rounded-[10px] border border-line bg-surface-card px-3 py-2.5">
+ <div className={cn("font-mono text-[19px] font-medium", value === 0 ? "text-fg-faint" : "text-fg-strong")}>
+ {value}
+ </div>
+ <div className="text-[11.5px] text-fg-tertiary">{label}</div>
+ </div>
+ );
+}
diff --git a/components/admin/admin-pagination.tsx b/components/admin/admin-pagination.tsx
new file mode 100644
index 0000000..ec8247e
--- /dev/null
+++ b/components/admin/admin-pagination.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { ReactNode } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+/**
+ * "26–50 of 120" plus previous/next for a server-paginated admin list. Fills its
+ * row, so it works as a table footer and below the phone cards alike.
+ */
+export function AdminPagination({
+ page,
+ pageSize,
+ shown,
+ total,
+ onPageChange,
+ extra,
+ className,
+}: {
+ /** 1-based page the rows belong to */
+ page: number;
+ pageSize: number;
+ /** Rows on this page */
+ shown: number;
+ total: number;
+ onPageChange: (page: number) => void;
+ /** Shown before the buttons, e.g. bulk actions */
+ extra?: ReactNode;
+ className?: string;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
+ const to = Math.min((page - 1) * pageSize + shown, total);
+ const hasPrevious = page > 1;
+ const hasNext = page * pageSize < total;
+ const number = (value: number) => value.toLocaleString(locale);
+ const buttonClass = "h-11 rounded-lg px-4 text-[13px] lg:h-[30px] lg:px-[11px] lg:text-[12.5px]";
+
+ return (
+ <div className={cn("flex w-full min-w-0 items-center justify-between gap-3", className)}>
+ <span className="min-w-0 truncate">
+ {t("adminPagination.range", { from: number(from), to: number(to), total: number(total) })}
+ </span>
+ <div className="flex shrink-0 items-center gap-[7px]">
+ {extra}
+ {(hasPrevious || hasNext) && (
+ <nav aria-label={t("adminPagination.label")} className="flex gap-[7px]">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => onPageChange(page - 1)}
+ disabled={!hasPrevious}
+ className={buttonClass}
+ >
+ {t("common.previous")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => onPageChange(page + 1)}
+ disabled={!hasNext}
+ className={cn(buttonClass, "font-semibold")}
+ >
+ {t("common.next")}
+ </Button>
+ </nav>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/components/admin/admin-sidebar.tsx b/components/admin/admin-sidebar.tsx
index b3190cc..569498e 100644
--- a/components/admin/admin-sidebar.tsx
+++ b/components/admin/admin-sidebar.tsx
@@ -1,284 +1,191 @@
"use client";
-import { useState, useEffect } from "react";
-import { usePathname, useRouter } from "next/navigation";
-import { useTranslations } from "next-intl";
-import { motion, AnimatePresence } from "motion/react";
-import { cn } from "@/lib/utils";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
+import { useState } from "react";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { useLocale, useTranslations } from "next-intl";
import {
- LayoutDashboard,
- Users,
- FolderOpen,
- ScrollText,
+ ArrowLeft,
ChevronLeft,
ChevronRight,
- ArrowLeft,
Crown,
+ FolderClosed,
+ LayoutDashboard,
+ ScrollText,
+ Users,
+ type LucideIcon,
} from "lucide-react";
+import { Pill } from "@/components/form-kit";
+import { UserAvatar } from "@/components/admin/admin-kit";
import { useAdminLevel } from "@/hooks/useAdminAccess";
+import { useAdminStats } from "@/hooks/useAdminStats";
import { useAuth } from "@/hooks/useAuth";
+import { cn } from "@/lib/utils";
-interface NavItem {
- label: string;
+export interface AdminSection {
href: string;
- icon: React.ElementType;
- adminOnly?: boolean; // Only visible for superadmin
-}
-
-interface AdminSidebarProps {
- onWidthChange?: (width: number) => void;
- isMobileOpen?: boolean;
- onMobileClose?: () => void;
+ label: string;
+ shortLabel: string;
+ icon: LucideIcon;
}
-/**
- * Admin Panel Sidebar Navigation
- *
- * Features:
- * - Collapsible (Icons only ↔ Icons + Text)
- * - Active route highlighting
- * - Role-based menu items (superadmin badge)
- * - Mobile responsive
- * - "Back to App" link at bottom
- */
-export function AdminSidebar({
- onWidthChange,
- isMobileOpen,
- onMobileClose,
-}: AdminSidebarProps) {
+/** The four admin areas, shared by sidebar, tab bar, breadcrumb and dashboard. */
+export function useAdminSections(): AdminSection[] {
const t = useTranslations();
- const router = useRouter();
- const pathname = usePathname();
- const { user } = useAuth();
- const adminLevel = useAdminLevel();
- const [isCollapsed, setIsCollapsed] = useState(false);
-
- const isSuperAdmin = adminLevel === "superadmin";
- // Notify parent of width changes
- useEffect(() => {
- onWidthChange?.(isCollapsed ? 80 : 280);
- }, [isCollapsed, onWidthChange]);
- // Navigation items
- const navItems: NavItem[] = [
- {
- label: t("admin.dashboard"),
- href: "/admin",
- icon: LayoutDashboard,
- },
+ return [
+ { href: "/admin", label: t("admin.dashboard"), shortLabel: t("admin.dashboard"), icon: LayoutDashboard },
+ { href: "/admin/users", label: t("admin.usersMenu"), shortLabel: t("admin.usersMenu"), icon: Users },
{
- label: t("admin.usersMenu"),
- href: "/admin/users",
- icon: Users,
- },
- {
- label: t("admin.calendarsMenu"),
href: "/admin/calendars",
- icon: FolderOpen,
- },
- {
- label: t("admin.auditLogs"),
- href: "/admin/logs",
- icon: ScrollText,
+ label: t("admin.calendarsMenu"),
+ shortLabel: t("admin.calendarsMenu"),
+ icon: FolderClosed,
},
+ { href: "/admin/logs", label: t("admin.auditLogs"), shortLabel: t("adminShell.logsShort"), icon: ScrollText },
];
+}
- const handleNavigation = (href: string) => {
- router.push(href);
- // Close mobile menu after navigation
- if (typeof window !== "undefined" && window.innerWidth < 1024) {
- onMobileClose?.();
- }
- };
-
- const handleBackToApp = () => {
- router.push("/");
- // Close mobile menu after navigation
- if (typeof window !== "undefined" && window.innerWidth < 1024) {
- onMobileClose?.();
- }
- };
+export function isActiveSection(pathname: string, href: string) {
+ return href === "/admin" ? pathname === "/admin" : pathname.startsWith(href);
+}
- // Get user initials for avatar
- const getInitials = (name: string | undefined | null) => {
- if (!name) return "?";
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
+/** Desktop area list (13a–13f): account row, the four areas, back to the app. */
+export function AdminSidebar() {
+ const t = useTranslations();
+ const locale = useLocale();
+ const pathname = usePathname();
+ const { user } = useAuth();
+ const adminLevel = useAdminLevel();
+ const sections = useAdminSections();
+ const [collapsed, setCollapsed] = useState(false);
+ const { stats } = useAdminStats();
+ const counts: Record<string, number | undefined> = {
+ "/admin/users": stats?.users.total,
+ "/admin/calendars": stats ? stats.calendars.total + stats.calendars.orphaned : undefined,
+ "/admin/logs": stats?.auditLogs.total,
};
return (
- <>
- {/* Backdrop for mobile */}
- {isMobileOpen && (
- <div
- className="fixed inset-0 bg-black/50 z-40 lg:hidden"
- onClick={onMobileClose}
- />
+ <aside
+ className={cn(
+ "hidden shrink-0 flex-col border-r border-line bg-surface-panel lg:flex",
+ collapsed ? "w-16" : "w-[248px]"
)}
-
- {/* Sidebar */}
- <motion.aside
- initial={false}
- animate={{
- width: isCollapsed ? "80px" : "280px",
- }}
- style={{
- x:
- typeof window !== "undefined" && window.innerWidth < 1024
- ? isMobileOpen
- ? 0
- : -280
- : 0,
- }}
- transition={{ duration: 0.3, ease: "easeInOut" }}
+ >
+ <div
className={cn(
- "fixed left-0 top-0 h-screen",
- "border-r border-border bg-background",
- "flex flex-col",
- "z-50 lg:z-30"
+ "flex items-center gap-2.5 border-b border-line py-[13px]",
+ collapsed ? "flex-col px-2" : "px-3.5"
)}
>
- {/* Header: User Info + Collapse Toggle */}
- <div className="p-4 flex items-center justify-between gap-2 min-h-[72px]">
- <AnimatePresence mode="wait">
- {!isCollapsed && (
- <motion.div
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -10 }}
- transition={{ duration: 0.2 }}
- className="flex items-center gap-3 min-w-0 flex-1"
- >
- {/* User Avatar */}
- <Avatar className="h-10 w-10 flex-shrink-0">
- <AvatarImage
- src={user?.image || undefined}
- alt={user?.name || ""}
- />
- <AvatarFallback className="bg-primary/10 text-primary text-sm font-semibold">
- {getInitials(user?.name)}
- </AvatarFallback>
- </Avatar>
- {/* User Info */}
- <div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">{user?.name}</p>
- {isSuperAdmin && (
- <Badge
- variant="default"
- className="text-xs mt-1 bg-amber-500 hover:bg-amber-600"
- >
- <Crown className="w-3 h-3 mr-1" />
- {t("admin.superadminBadge")}
- </Badge>
- )}
- {!isSuperAdmin && (
- <Badge
- variant="secondary"
- className="text-xs mt-1 bg-orange-500/10 text-orange-500 border-orange-500/20"
- >
- {t("common.roles.admin")}
- </Badge>
- )}
- </div>
- </motion.div>
- )}
- </AnimatePresence>
-
- {/* Collapse Toggle Button */}
- <Button
- variant="ghost"
- size="icon"
- onClick={() => setIsCollapsed(!isCollapsed)}
- className="flex-shrink-0"
- aria-label={
- isCollapsed
- ? t("admin.expandSidebar")
- : t("admin.collapseSidebar")
- }
- >
- {isCollapsed ? (
- <ChevronRight className="h-4 w-4" />
+ <UserAvatar name={user?.name} image={user?.image} size={34} tone="brand" />
+ {!collapsed && (
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{user?.name}</div>
+ {adminLevel === "superadmin" ? (
+ <Pill tone="warning" className="mt-[3px] px-[7px] text-[10.5px]">
+ <Crown className="size-[11px]" />
+ {t("admin.superadminBadge")}
+ </Pill>
) : (
- <ChevronLeft className="h-4 w-4" />
+ <Pill tone="violet" className="mt-[3px] px-[7px] text-[10.5px]">
+ {t("common.roles.admin")}
+ </Pill>
)}
- </Button>
- </div>
-
- <Separator />
-
- {/* Navigation Items */}
- <nav className="flex-1 p-2 space-y-1 overflow-y-auto">
- {navItems.map((item) => {
- const Icon = item.icon;
- const isActive = pathname === item.href;
-
- return (
- <Button
- key={item.href}
- variant={isActive ? "secondary" : "ghost"}
- className={cn(
- "w-full justify-start gap-3",
- isCollapsed && "justify-center px-0"
- )}
- onClick={() => handleNavigation(item.href)}
- title={isCollapsed ? item.label : undefined}
- >
- <Icon className="h-5 w-5 flex-shrink-0" />
- <AnimatePresence mode="wait">
- {!isCollapsed && (
- <motion.span
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -10 }}
- transition={{ duration: 0.2 }}
- className="truncate"
- >
- {item.label}
- </motion.span>
+ </div>
+ )}
+ <button
+ type="button"
+ onClick={() => setCollapsed((value) => !value)}
+ aria-label={collapsed ? t("admin.expandSidebar") : t("admin.collapseSidebar")}
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-fg-faint transition-colors hover:bg-surface-sunken hover:text-fg-secondary"
+ >
+ {collapsed ? <ChevronRight className="size-4" /> : <ChevronLeft className="size-4" />}
+ </button>
+ </div>
+
+ <nav className="flex min-h-0 flex-1 flex-col gap-[3px] overflow-y-auto p-3">
+ {sections.map((section) => {
+ const active = isActiveSection(pathname, section.href);
+ const count = counts[section.href];
+ return (
+ <Link
+ key={section.href}
+ href={section.href}
+ aria-current={active ? "page" : undefined}
+ title={collapsed ? section.label : undefined}
+ className={cn(
+ "flex items-center gap-2.5 rounded-lg px-2.5 py-2 transition-colors",
+ collapsed && "justify-center",
+ active ? "bg-brand-soft shadow-[inset_2px_0_0_var(--brand)]" : "hover:bg-surface-sunken"
+ )}
+ >
+ <section.icon className={cn("size-4 shrink-0", active ? "text-brand-ink" : "text-fg-secondary")} />
+ {!collapsed && (
+ <>
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate text-[13.5px]",
+ active ? "font-semibold text-brand-ink" : "font-medium text-fg-body"
+ )}
+ >
+ {section.label}
+ </span>
+ {count !== undefined && (
+ <span className={cn("font-mono text-[11.5px]", active ? "text-brand-ink" : "text-fg-tertiary")}>
+ {count.toLocaleString(locale)}
+ </span>
)}
- </AnimatePresence>
- </Button>
- );
- })}
- </nav>
+ </>
+ )}
+ </Link>
+ );
+ })}
+ </nav>
+
+ <div className="border-t border-line p-3">
+ <Link
+ href="/"
+ title={collapsed ? t("admin.backToApp") : undefined}
+ className={cn(
+ "flex items-center gap-[9px] rounded-lg px-2.5 py-2 text-[13.5px] font-medium text-fg-body transition-colors hover:bg-surface-sunken",
+ collapsed && "justify-center"
+ )}
+ >
+ <ArrowLeft className="size-4 shrink-0 text-fg-secondary" />
+ {!collapsed && t("admin.backToApp")}
+ </Link>
+ </div>
+ </aside>
+ );
+}
- <Separator />
+/** Phone tab bar replacing the sidebar (13g–13k). */
+export function AdminMobileNav() {
+ const pathname = usePathname();
+ const sections = useAdminSections();
- {/* Back to App Link */}
- <div className="p-2">
- <Button
- variant="ghost"
+ return (
+ <nav className="grid shrink-0 grid-cols-4 gap-1 border-t border-line bg-background px-3 pb-[max(8px,env(safe-area-inset-bottom))] pt-2 lg:hidden">
+ {sections.map((section) => {
+ const active = isActiveSection(pathname, section.href);
+ return (
+ <Link
+ key={section.href}
+ href={section.href}
+ aria-current={active ? "page" : undefined}
className={cn(
- "w-full justify-start gap-3",
- isCollapsed && "justify-center px-0"
+ "flex h-12 flex-col items-center justify-center gap-[3px] rounded-[10px]",
+ active ? "bg-brand-soft text-brand-ink" : "text-fg-tertiary"
)}
- onClick={handleBackToApp}
- title={isCollapsed ? t("admin.backToApp") : undefined}
>
- <ArrowLeft className="h-5 w-5 flex-shrink-0" />
- <AnimatePresence mode="wait">
- {!isCollapsed && (
- <motion.span
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -10 }}
- transition={{ duration: 0.2 }}
- className="truncate"
- >
- {t("admin.backToApp")}
- </motion.span>
- )}
- </AnimatePresence>
- </Button>
- </div>
- </motion.aside>
- </>
+ <section.icon className="size-[19px]" />
+ <span className={cn("text-[10.5px]", active ? "font-semibold" : "font-medium")}>
+ {section.shortLabel}
+ </span>
+ </Link>
+ );
+ })}
+ </nav>
);
}
diff --git a/components/admin/admin-table-controls.tsx b/components/admin/admin-table-controls.tsx
new file mode 100644
index 0000000..f11a2ab
--- /dev/null
+++ b/components/admin/admin-table-controls.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { ComponentProps, ReactNode } from "react";
+import { ChevronDown, ChevronUp, SlidersHorizontal, type LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/** 30px outline icon button used in the actions column of admin tables. */
+export function RowActionButton({
+ icon: Icon,
+ label,
+ className,
+ ...props
+}: { icon: LucideIcon; label: string } & ComponentProps<"button">) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ className={cn(
+ "flex size-[30px] shrink-0 items-center justify-center rounded-[7px] border border-line bg-surface-card text-fg-secondary transition-colors hover:bg-surface-panel disabled:pointer-events-none disabled:opacity-40",
+ className
+ )}
+ {...props}
+ >
+ <Icon className="size-[15px]" />
+ </button>
+ );
+}
+
+/** Clickable column header; shows the direction only on the active column. */
+export function SortHeader<T extends string>({
+ column,
+ label,
+ sort,
+ onSort,
+}: {
+ column: T;
+ label: ReactNode;
+ sort: { column: T; direction: "asc" | "desc" };
+ onSort: (column: T) => void;
+}) {
+ const active = sort.column === column;
+ const Icon = sort.direction === "asc" ? ChevronUp : ChevronDown;
+ return (
+ <button
+ type="button"
+ onClick={() => onSort(column)}
+ className={cn(
+ "inline-flex max-w-full items-center gap-1 uppercase hover:text-fg-strong",
+ active && "text-fg-body"
+ )}
+ >
+ <span className="truncate">{label}</span>
+ {active && <Icon className="size-3.5 shrink-0" />}
+ </button>
+ );
+}
+
+/** Square outline trigger for the secondary filter menu; the dot marks a non-default filter. */
+export function FilterMenuButton({
+ label,
+ active,
+ ...props
+}: { label: string; active: boolean } & ComponentProps<"button">) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ className={cn(
+ "relative flex size-[38px] shrink-0 items-center justify-center rounded-[9px] border bg-surface-card transition-colors hover:bg-surface-panel",
+ active ? "border-brand text-brand-ink" : "border-line text-fg-secondary"
+ )}
+ {...props}
+ >
+ <SlidersHorizontal className="size-4" />
+ {active && <span className="absolute right-1.5 top-1.5 size-1.5 rounded-full bg-brand" />}
+ </button>
+ );
+}
+
+export type SortState<T extends string> = { column: T; direction: "asc" | "desc" };
+
+export function nextSort<T extends string>(sort: SortState<T>, column: T): SortState<T> {
+ return sort.column === column
+ ? { column, direction: sort.direction === "asc" ? "desc" : "asc" }
+ : { column, direction: "desc" };
+}
diff --git a/components/admin/audit-describe.ts b/components/admin/audit-describe.ts
new file mode 100644
index 0000000..921c753
--- /dev/null
+++ b/components/admin/audit-describe.ts
@@ -0,0 +1,152 @@
+"use client";
+
+import { useCallback } from "react";
+import { useTranslations } from "next-intl";
+
+interface DescribableLog {
+ action: string;
+ metadata?: unknown;
+}
+
+function field(metadata: unknown, key: string): unknown {
+ return metadata && typeof metadata === "object" ? (metadata as Record<string, unknown>)[key] : undefined;
+}
+
+function text(metadata: unknown, key: string): string {
+ const value = field(metadata, key);
+ return typeof value === "string" || typeof value === "number" ? String(value) : "";
+}
+
+function count(metadata: unknown, key: string): number {
+ const value = Number(field(metadata, key));
+ return Number.isFinite(value) ? value : 0;
+}
+
+/**
+ * Plain-language summary of an audit entry, built from its action and metadata.
+ * Falls back to the raw action name when the metadata lacks what a sentence needs.
+ */
+export function useAuditDescription() {
+ const t = useTranslations();
+
+ return useCallback(
+ (log: DescribableLog): string => {
+ const m = log.metadata;
+ const target = text(m, "targetUser") || text(m, "deletedUser");
+ const calendar = text(m, "calendarName");
+ const sync = text(m, "syncName");
+
+ switch (log.action) {
+ case "admin.user.ban":
+ if (!target) break;
+ return text(m, "expiresAt") === "permanent"
+ ? t("adminAudit.describe.userBannedPermanently", { user: target })
+ : t("adminAudit.describe.userBanned", { user: target });
+ case "admin.user.unban":
+ if (target) return t("adminAudit.describe.userUnbanned", { user: target });
+ break;
+ case "admin.user.password_reset":
+ if (target) return t("adminAudit.describe.passwordReset", { user: target });
+ break;
+ case "admin.user.delete":
+ if (target) return t("adminAudit.describe.userDeleted", { user: target });
+ break;
+ case "admin.user.update":
+ if (target) return t("adminAudit.describe.userUpdated", { user: target });
+ break;
+ case "admin.calendar.transfer":
+ if (calendar && text(m, "newOwnerEmail")) {
+ return t("adminAudit.describe.calendarTransferred", {
+ calendar,
+ user: text(m, "newOwnerEmail"),
+ });
+ }
+ break;
+ case "admin.calendar.bulk_transfer":
+ if (text(m, "newOwnerEmail")) {
+ return t("adminAudit.describe.calendarsTransferred", {
+ count: count(m, "count"),
+ user: text(m, "newOwnerEmail"),
+ });
+ }
+ break;
+ case "admin.calendar.bulk_delete":
+ return t("adminAudit.describe.calendarsDeleted", { count: count(m, "count") });
+ case "admin.audit_log.delete_by_ids":
+ case "admin.audit_log.delete_by_date":
+ return t("adminAudit.describe.logsDeleted", { count: count(m, "deletedCount") });
+ case "admin.calendar.update":
+ case "calendar.updated":
+ if (calendar) return t("adminAudit.describe.calendarUpdated", { calendar });
+ break;
+ case "admin.calendar.delete":
+ case "calendar.deleted":
+ if (calendar) return t("adminAudit.describe.calendarDeleted", { calendar });
+ break;
+ case "calendar.created":
+ if (calendar) return t("adminAudit.describe.calendarCreated", { calendar });
+ break;
+ case "calendar.shared":
+ if (calendar && text(m, "sharedWith")) {
+ return t("adminAudit.describe.calendarShared", { calendar, user: text(m, "sharedWith") });
+ }
+ break;
+ case "calendar.share.removed":
+ if (calendar && text(m, "removedUser")) {
+ return t("adminAudit.describe.shareRemoved", { calendar, user: text(m, "removedUser") });
+ }
+ break;
+ case "calendar.permission.changed":
+ if (calendar && text(m, "user")) {
+ return t("adminAudit.describe.permissionChanged", { calendar, user: text(m, "user") });
+ }
+ break;
+ case "calendar.guest_permission.changed":
+ if (calendar) return t("adminAudit.describe.guestPermissionChanged", { calendar });
+ break;
+ case "sync.created":
+ if (sync) return t("adminAudit.describe.syncCreated", { sync });
+ break;
+ case "sync.deleted":
+ if (sync) return t("adminAudit.describe.syncDeleted", { sync });
+ break;
+ case "sync.orphaned.disabled":
+ if (sync) return t("adminAudit.describe.syncDisabled", { sync });
+ break;
+ case "sync.executed":
+ if (!sync) break;
+ return field(m, "success") === false
+ ? t("adminAudit.describe.syncFailed", { sync })
+ : t("adminAudit.describe.syncExecuted", {
+ sync,
+ added: count(m, "shiftsAdded"),
+ updated: count(m, "shiftsUpdated"),
+ deleted: count(m, "shiftsDeleted"),
+ });
+ case "security.rate_limit.hit":
+ if (text(m, "endpoint")) return t("adminAudit.describe.rateLimit", { endpoint: text(m, "endpoint") });
+ break;
+ case "auth.login.success":
+ return text(m, "provider")
+ ? t("adminAudit.describe.loginProvider", { provider: text(m, "provider") })
+ : t("adminAudit.describe.loginEmail");
+ case "auth.login.failed":
+ if (text(m, "email")) return t("adminAudit.describe.loginFailed", { email: text(m, "email") });
+ break;
+ case "auth.user.registered":
+ if (text(m, "email")) return t("adminAudit.describe.registered", { email: text(m, "email") });
+ break;
+ case "auth.profile.updated":
+ return t("adminAudit.describe.profileUpdated");
+ case "auth.password.changed":
+ return t("adminAudit.describe.passwordChanged");
+ case "auth.account.deleted":
+ return t("adminAudit.describe.accountDeleted");
+ case "auth.session.revoked":
+ return t("adminAudit.describe.sessionsRevoked", { count: count(m, "count") || 1 });
+ }
+ return log.action;
+ },
+ [t]
+ );
+}
diff --git a/components/admin/audit-log-delete-dialog.tsx b/components/admin/audit-log-delete-dialog.tsx
index 4b2f462..94c78c9 100644
--- a/components/admin/audit-log-delete-dialog.tsx
+++ b/components/admin/audit-log-delete-dialog.tsx
@@ -1,21 +1,19 @@
"use client";
import { useState } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
-} from "@/components/ui/dialog";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { TriangleAlert } from "lucide-react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
-import { AlertTriangle, Trash2, X } from "lucide-react";
+import { Field, inputClass } from "@/components/form-kit";
+import { PanelDialog } from "@/components/panel-dialog";
+import { StatusBanner } from "@/components/status-banner";
import { useAdminAuditLogs } from "@/hooks/useAdminAuditLogs";
-import { toast } from "sonner";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
+import { getDateLocale } from "@/lib/locales";
interface AuditLogDeleteDialogProps {
open: boolean;
@@ -31,27 +29,36 @@ export function AuditLogDeleteDialog({
onSuccess,
}: AuditLogDeleteDialogProps) {
const t = useTranslations();
- const { deleteLogsByDate, deleteLogsByIds, isLoading } = useAdminAuditLogs();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const { deleteLogsByDate, deleteLogsByIds, isLoading } = useAdminAuditLogs(
+ undefined,
+ undefined,
+ undefined,
+ { listEnabled: false }
+ );
const [beforeDate, setBeforeDate] = useState("");
const [confirmed, setConfirmed] = useState(false);
- // Determine mode: by IDs (if provided) or by date
+ // Selected rows take precedence over the date cut-off
const deleteByIds = selectedLogIds.length > 0;
+ const reset = () => {
+ setBeforeDate("");
+ setConfirmed(false);
+ };
+
const handleDelete = async () => {
if (!confirmed) {
toast.error(t("admin.pleaseConfirmDeletion"));
return;
}
- let success = false;
-
+ let success: boolean;
if (deleteByIds) {
- // Delete by IDs
success = await deleteLogsByIds(selectedLogIds);
} else {
- // Delete by date
if (!beforeDate) {
toast.error(t("admin.pleaseSelectDate"));
return;
@@ -61,132 +68,96 @@ export function AuditLogDeleteDialog({
if (success) {
onOpenChange(false);
- setBeforeDate("");
- setConfirmed(false);
+ reset();
onSuccess?.();
}
};
- const handleClose = () => {
- if (!isLoading) {
+ const handleOpenChange = (next: boolean) => {
+ if (next) {
+ onOpenChange(true);
+ } else if (!isLoading) {
onOpenChange(false);
- setBeforeDate("");
- setConfirmed(false);
+ reset();
}
};
- return (
- <Dialog open={open} onOpenChange={handleClose}>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <div className="flex items-center gap-2 text-destructive">
- <AlertTriangle className="h-5 w-5" />
- <DialogTitle>
- {deleteByIds
- ? t("common.deleteSelected")
- : t("admin.deleteOldLogs")}
- </DialogTitle>
- </div>
- <DialogDescription className="pt-2">
- {deleteByIds
- ? t("admin.deleteSelectedLogsDescription", {
- count: selectedLogIds.length,
- })
- : t("admin.deleteLogsDescription")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4">
- {!deleteByIds && (
- <>
- {/* Date Picker */}
- <div>
- <label className="text-sm font-medium mb-2 block">
- {t("admin.deleteLogsBefore")}
- </label>
- <Input
- type="date"
- value={beforeDate}
- onChange={(e) => setBeforeDate(e.target.value)}
- max={new Date().toISOString().split("T")[0]}
- disabled={isLoading}
- />
- <p className="text-xs text-muted-foreground mt-1">
- {t("admin.deleteLogsBeforeHint")}
- </p>
- </div>
-
- {/* Preview */}
- {beforeDate && (
- <div className="p-3 bg-muted rounded-lg text-sm">
- <div className="font-medium mb-1">{t("admin.preview")}:</div>
- <div className="text-muted-foreground">
- {t("admin.willDeleteLogsOlderThan", {
- date: new Date(beforeDate).toLocaleDateString(),
- })}
- </div>
- </div>
- )}
- </>
- )}
-
- {deleteByIds && (
- <div className="p-3 bg-muted rounded-lg text-sm">
- <div className="font-medium mb-1">{t("admin.preview")}:</div>
- <div className="text-muted-foreground">
- {t("admin.willDeleteSelectedLogs", {
- count: selectedLogIds.length,
- })}
- </div>
- </div>
- )}
-
- {/* Warning */}
- <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-3">
- <div className="flex gap-2">
- <AlertTriangle className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
- <div className="text-sm text-destructive">
- {t("admin.deleteLogsWarning")}
- </div>
- </div>
- </div>
+ const title = deleteByIds ? t("common.deleteSelected") : t("admin.deleteOldLogs");
- {/* Confirmation Checkbox */}
- <div className="flex items-start gap-3">
- <Checkbox
- id="confirm-delete"
- checked={confirmed}
- onCheckedChange={(checked) => setConfirmed(checked === true)}
- disabled={isLoading}
- />
- <label
- htmlFor="confirm-delete"
- className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
- >
- {t("admin.confirmPermanentDeletion")}
- </label>
- </div>
- </div>
-
- <DialogFooter>
- <Button variant="outline" onClick={handleClose} disabled={isLoading}>
- <X className="h-4 w-4 mr-2" />
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={handleOpenChange}
+ width="sm"
+ title={title}
+ description={
+ deleteByIds
+ ? t("admin.deleteSelectedLogsDescription", { count: selectedLogIds.length })
+ : t("admin.deleteLogsDescription")
+ }
+ bodyClassName="flex flex-col gap-4"
+ footer={
+ <>
+ <Button
+ variant="outline"
+ onClick={() => handleOpenChange(false)}
+ disabled={isLoading}
+ className="h-10 flex-1 font-semibold"
+ >
{t("common.cancel")}
</Button>
<Button
variant="destructive"
onClick={handleDelete}
disabled={isLoading || (!deleteByIds && !beforeDate) || !confirmed}
+ className="h-10 flex-1 font-semibold"
>
- <Trash2 className="h-4 w-4 mr-2" />
- {isLoading
- ? t("common.loading")
- : deleteByIds
- ? t("common.deleteSelected")
- : t("admin.deleteOldLogs")}
+ {isLoading ? t("common.loading") : title}
</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ {deleteByIds ? (
+ <div className="rounded-[10px] border border-line bg-surface-panel px-3 py-2.5 text-[13px] text-fg-secondary">
+ {t("admin.willDeleteSelectedLogs", { count: selectedLogIds.length })}
+ </div>
+ ) : (
+ <>
+ <Field label={t("admin.deleteLogsBefore")} htmlFor="audit-delete-before" hint={t("admin.deleteLogsBeforeHint")}>
+ <Input
+ id="audit-delete-before"
+ type="date"
+ value={beforeDate}
+ onChange={(e) => setBeforeDate(e.target.value)}
+ max={formatDateToLocal(new Date())}
+ disabled={isLoading}
+ className={inputClass}
+ />
+ </Field>
+ {beforeDate && (
+ <div className="rounded-[10px] border border-line bg-surface-panel px-3 py-2.5 text-[13px] text-fg-secondary">
+ {t("admin.willDeleteLogsOlderThan", {
+ date: format(parseLocalDate(beforeDate), "PP", { locale: dateLocale }),
+ })}
+ </div>
+ )}
+ </>
+ )}
+
+ <StatusBanner tone="danger" icon={TriangleAlert}>
+ {t("admin.deleteLogsWarning")}
+ </StatusBanner>
+
+ <label htmlFor="confirm-delete" className="flex cursor-pointer items-start gap-3 text-[13px] text-fg-body">
+ <Checkbox
+ id="confirm-delete"
+ checked={confirmed}
+ onCheckedChange={(checked) => setConfirmed(checked === true)}
+ disabled={isLoading}
+ className="mt-px"
+ />
+ {t("admin.confirmPermanentDeletion")}
+ </label>
+ </PanelDialog>
);
}
diff --git a/components/admin/audit-log-details-dialog.tsx b/components/admin/audit-log-details-dialog.tsx
index 0476f73..d3b8695 100644
--- a/components/admin/audit-log-details-dialog.tsx
+++ b/components/admin/audit-log-details-dialog.tsx
@@ -1,20 +1,17 @@
"use client";
-import { useTranslations, useLocale } from "next-intl";
+import { ReactNode } from "react";
+import { useLocale, useTranslations } from "next-intl";
import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogFooter,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import { Copy, X } from "lucide-react";
+import { Copy } from "lucide-react";
import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { SectionLabel } from "@/components/form-kit";
+import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";
+import { SeverityPill, UserAvatar } from "@/components/admin/admin-kit";
+import { useAuditDescription } from "@/components/admin/audit-describe";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
import type { AuditLog } from "@/hooks/useAdminAuditLogs";
interface AuditLogDetailsDialogProps {
@@ -23,60 +20,28 @@ interface AuditLogDetailsDialogProps {
log: AuditLog;
}
-export function AuditLogDetailsDialog({
- open,
- onOpenChange,
- log,
-}: AuditLogDetailsDialogProps) {
+function DetailRow({ label, children, mono }: { label: string; children: ReactNode; mono?: boolean }) {
+ return (
+ <div className="flex items-start justify-between gap-4 border-b border-line-subtle px-3.5 py-2.5 last:border-b-0">
+ <span className="shrink-0 text-[12.5px] text-fg-tertiary">{label}</span>
+ <span
+ className={cn(
+ "min-w-0 break-all text-right text-fg-body",
+ mono ? "font-mono text-[12px]" : "text-[13px]"
+ )}
+ >
+ {children}
+ </span>
+ </div>
+ );
+}
+
+export function AuditLogDetailsDialog({ open, onOpenChange, log }: AuditLogDetailsDialogProps) {
const t = useTranslations();
const locale = useLocale();
const dateLocale = getDateLocale(locale);
+ const describe = useAuditDescription();
- // Get user initials
- const getUserInitials = (name: string | null) => {
- if (!name) return "?";
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- };
-
- // Severity badge color
- const getSeverityColor = (severity: string) => {
- switch (severity) {
- case "info":
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- case "warning":
- return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";
- case "error":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- case "critical":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- default:
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- }
- };
-
- // Action category badge color
- const getActionColor = (action: string) => {
- if (action.startsWith("admin.")) {
- return "bg-red-500/10 text-red-500 border-red-500/20";
- }
- if (action.startsWith("calendar")) {
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- }
- if (action.startsWith("auth")) {
- return "bg-green-500/10 text-green-500 border-green-500/20";
- }
- if (action.startsWith("security")) {
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- }
- return "bg-gray-500/10 text-gray-500 border-gray-500/20";
- };
-
- // Copy JSON to clipboard
const copyToClipboard = () => {
const jsonString = JSON.stringify(
{
@@ -103,164 +68,88 @@ export function AuditLogDetailsDialog({
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
- <DialogHeader>
- <DialogTitle>{t("admin.auditLogDetails")}</DialogTitle>
- </DialogHeader>
-
- <div className="space-y-6">
- {/* Action & Severity */}
- <div className="grid grid-cols-2 gap-4">
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("common.labels.action")}
- </div>
- <Badge variant="outline" className={getActionColor(log.action)}>
- {log.action}
- </Badge>
- </div>
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("common.labels.severity")}
+ <AdminDetailPanel
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.auditLogDetails")}
+ subtitle={format(new Date(log.timestamp), "PPpp", { locale: dateLocale })}
+ footer={
+ <Button variant="outline" onClick={() => onOpenChange(false)} className="h-10 flex-1 font-semibold">
+ {t("common.close")}
+ </Button>
+ }
+ >
+ <div className="flex flex-col gap-2.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {log.action}
+ </span>
+ <SeverityPill severity={log.severity} />
+ </div>
+ <p className="text-[14px] leading-snug text-fg-strong">{describe(log)}</p>
+ </div>
+
+ <div>
+ <SectionLabel>{t("common.labels.user")}</SectionLabel>
+ {log.userId != null ? (
+ <div className="flex items-center gap-3 rounded-[11px] border border-line px-3.5 py-3">
+ <UserAvatar name={log.userName} image={log.userImage} size={36} />
+ <div className="min-w-0">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">
+ {log.userName || t("admin.unknownUser")}
</div>
- <Badge
- variant="outline"
- className={getSeverityColor(log.severity)}
- >
- {log.severity}
- </Badge>
+ <div className="truncate text-[12.5px] text-fg-tertiary">{log.userEmail || "—"}</div>
</div>
</div>
-
- {/* Timestamp */}
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.timestamp")}
- </div>
- <div className="text-sm">
- {format(new Date(log.timestamp), "PPpp", { locale: dateLocale })}
- </div>
+ ) : (
+ <div className="rounded-[11px] border border-line px-3.5 py-3 text-[13px] text-fg-secondary">
+ {t("admin.systemAction")}
</div>
+ )}
+ </div>
- {/* User Details */}
- {log.userId != null && (
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("common.labels.user")}
- </div>
- <div className="flex items-center gap-3 p-3 border rounded-lg">
- <Avatar className="h-10 w-10">
- {log.userImage && (
- <AvatarImage src={log.userImage} alt={log.userName || ""} />
- )}
- <AvatarFallback>
- {getUserInitials(log.userName)}
- </AvatarFallback>
- </Avatar>
- <div>
- <div className="text-sm font-medium">
- {log.userName || t("admin.unknownUser")}
- </div>
- <div className="text-xs text-muted-foreground">
- {log.userEmail || "—"}
- </div>
- </div>
- </div>
- </div>
- )}
-
- {/* Resource */}
+ <div>
+ <SectionLabel>{t("adminAudit.details")}</SectionLabel>
+ <div className="overflow-hidden rounded-[11px] border border-line">
{log.resourceType != null && (
- <div className="grid grid-cols-2 gap-4">
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.resourceType")}
- </div>
- <div className="text-sm">{log.resourceType}</div>
- </div>
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.resourceId")}
- </div>
- <div className="text-sm font-mono text-xs">
- {log.resourceId || "—"}
- </div>
- </div>
- </div>
+ <>
+ <DetailRow label={t("admin.resourceType")}>{log.resourceType}</DetailRow>
+ <DetailRow label={t("admin.resourceId")} mono>
+ {log.resourceId || "—"}
+ </DetailRow>
+ </>
)}
-
- {/* IP Address */}
{log.ipAddress != null && (
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("common.labels.ipAddress")}
- </div>
- <div className="text-sm font-mono">{log.ipAddress}</div>
- </div>
- )}
-
- {/* User Agent */}
- {log.userAgent != null && (
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.userAgent")}
- </div>
- <div className="text-xs text-muted-foreground break-all">
- {log.userAgent}
- </div>
- </div>
+ <DetailRow label={t("common.labels.ipAddress")} mono>
+ {log.ipAddress}
+ </DetailRow>
)}
-
- {/* Metadata */}
- {log.metadata != null && (
- <div>
- <div className="flex items-center justify-between mb-2">
- <div className="text-sm font-medium text-muted-foreground">
- {t("admin.metadata")}
- </div>
- <Button
- variant="ghost"
- size="sm"
- onClick={copyToClipboard}
- className="h-7"
- >
- <Copy className="h-3 w-3 mr-1" />
- {t("common.copy")}
- </Button>
- </div>
- <pre className="text-xs bg-muted p-4 rounded-lg border overflow-x-auto">
- {JSON.stringify(log.metadata, null, 2)}
- </pre>
- </div>
- )}
-
- {/* Additional Info */}
- <div className="grid grid-cols-2 gap-4 pt-4 border-t">
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.logId")}
- </div>
- <div className="text-xs font-mono">{log.id}</div>
- </div>
- <div>
- <div className="text-sm font-medium text-muted-foreground mb-2">
- {t("admin.userVisible")}
- </div>
- <div className="text-sm">
- {log.isUserVisible ? t("common.yes") : t("common.no")}
- </div>
- </div>
+ <DetailRow label={t("admin.userVisible")}>{log.isUserVisible ? t("common.yes") : t("common.no")}</DetailRow>
+ <DetailRow label={t("admin.logId")} mono>
+ {log.id}
+ </DetailRow>
+ </div>
+ {log.userAgent != null && (
+ <p className="mt-2 break-all text-[12px] leading-relaxed text-fg-tertiary">
+ <span className="font-semibold text-fg-secondary">{t("admin.userAgent")}:</span> {log.userAgent}
+ </p>
+ )}
+ </div>
+
+ {log.metadata != null && (
+ <div>
+ <div className="mb-2 flex items-center justify-between">
+ <SectionLabel className="mb-0">{t("admin.metadata")}</SectionLabel>
+ <Button variant="ghost" size="sm" onClick={copyToClipboard} className="h-7 gap-1.5 px-2 text-fg-secondary">
+ <Copy className="size-3.5" />
+ {t("common.copy")}
+ </Button>
</div>
+ <pre className="overflow-x-auto rounded-[10px] border border-line bg-surface-panel p-3 font-mono text-[12px] leading-relaxed text-fg-body">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
</div>
-
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- <X className="h-4 w-4 mr-2" />
- {t("common.close")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ )}
+ </AdminDetailPanel>
);
}
diff --git a/components/admin/audit-log-filters.tsx b/components/admin/audit-log-filters.tsx
new file mode 100644
index 0000000..41aed16
--- /dev/null
+++ b/components/admin/audit-log-filters.tsx
@@ -0,0 +1,286 @@
+"use client";
+
+import { ReactNode } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { CalendarDays, Filter, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { ChoiceChips, Field, inputClass } from "@/components/form-kit";
+import { PanelDialog } from "@/components/panel-dialog";
+import { parseLocalDate } from "@/lib/date-utils";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+export interface AuditFilterValues {
+ action: string;
+ severity: string;
+ startDate: string;
+ endDate: string;
+}
+
+export const EMPTY_AUDIT_FILTERS: AuditFilterValues = { action: "all", severity: "all", startDate: "", endDate: "" };
+
+export function hasAuditFilters(filters: AuditFilterValues) {
+ return (
+ filters.action !== "all" || filters.severity !== "all" || !!filters.startDate || !!filters.endDate
+ );
+}
+
+function useFilterOptions() {
+ const t = useTranslations();
+ return {
+ actions: [
+ { value: "all", label: t("admin.allActions") },
+ { value: "admin.", label: t("admin.adminActions") },
+ { value: "calendar.", label: t("admin.calendarActions") },
+ { value: "auth.", label: t("admin.authActions") },
+ { value: "security.", label: t("admin.securityActions") },
+ ],
+ severities: [
+ { value: "all", label: t("common.filters.allSeverities") },
+ { value: "info", label: t("common.severity.info") },
+ { value: "warning", label: t("common.severity.warning") },
+ { value: "error", label: t("common.severity.error") },
+ { value: "critical", label: t("common.severity.critical") },
+ ],
+ };
+}
+
+function useRangeLabel(filters: AuditFilterValues) {
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const fmt = (value: string) => format(parseLocalDate(value), "P", { locale: dateLocale });
+ if (!filters.startDate && !filters.endDate) return null;
+ return `${filters.startDate ? fmt(filters.startDate) : "…"} – ${filters.endDate ? fmt(filters.endDate) : "…"}`;
+}
+
+const triggerClass =
+ "h-9 gap-2 rounded-[9px] border-line bg-surface-card px-3 text-[13.5px] text-fg-body shadow-none data-[size=default]:h-9";
+
+function DateInputs({
+ filters,
+ onChange,
+}: {
+ filters: AuditFilterValues;
+ onChange: (patch: Partial<AuditFilterValues>) => void;
+}) {
+ const t = useTranslations();
+ return (
+ <div className="grid grid-cols-2 gap-3">
+ <Field label={t("common.labels.startDate")} htmlFor="audit-start">
+ <Input
+ id="audit-start"
+ type="date"
+ value={filters.startDate}
+ max={filters.endDate || undefined}
+ onChange={(e) => onChange({ startDate: e.target.value })}
+ className={inputClass}
+ />
+ </Field>
+ <Field label={t("common.labels.endDate")} htmlFor="audit-end">
+ <Input
+ id="audit-end"
+ type="date"
+ value={filters.endDate}
+ min={filters.startDate || undefined}
+ onChange={(e) => onChange({ endDate: e.target.value })}
+ className={inputClass}
+ />
+ </Field>
+ </div>
+ );
+}
+
+/** Desktop filter row next to the search (13f). */
+export function AuditFilterBar({
+ filters,
+ onChange,
+ onClear,
+}: {
+ filters: AuditFilterValues;
+ onChange: (patch: Partial<AuditFilterValues>) => void;
+ onClear: () => void;
+}) {
+ const t = useTranslations();
+ const { actions, severities } = useFilterOptions();
+ const rangeLabel = useRangeLabel(filters);
+
+ return (
+ <>
+ <Select value={filters.action} onValueChange={(action) => onChange({ action })}>
+ <SelectTrigger aria-label={t("common.labels.action")} className={triggerClass}>
+ <Filter className="size-[15px] text-fg-tertiary" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {actions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Select value={filters.severity} onValueChange={(severity) => onChange({ severity })}>
+ <SelectTrigger aria-label={t("common.labels.severity")} className={triggerClass}>
+ <Filter className="size-[15px] text-fg-tertiary" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {severities.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ "flex h-9 items-center gap-2 rounded-[9px] border px-3 text-[13.5px] transition-colors hover:bg-surface-panel",
+ rangeLabel ? "border-brand bg-brand-soft text-brand-ink" : "border-line bg-surface-card text-fg-body"
+ )}
+ >
+ <CalendarDays className={cn("size-[15px]", rangeLabel ? "text-brand-ink" : "text-fg-tertiary")} />
+ {rangeLabel ? (
+ <span className="font-mono text-[12.5px]">{rangeLabel}</span>
+ ) : (
+ t("adminAudit.dateRange")
+ )}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[340px] rounded-[12px] border-line bg-background p-4">
+ <DateInputs filters={filters} onChange={onChange} />
+ {rangeLabel && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onChange({ startDate: "", endDate: "" })}
+ className="mt-3 h-8 px-2 text-fg-secondary"
+ >
+ <X className="size-4" />
+ {t("adminAudit.clearRange")}
+ </Button>
+ )}
+ </PopoverContent>
+ </Popover>
+
+ {hasAuditFilters(filters) && (
+ <Button variant="ghost" onClick={onClear} className="h-9 gap-1.5 px-2.5 text-[13px] text-fg-secondary">
+ <X className="size-4" />
+ {t("common.filters.clearFilters")}
+ </Button>
+ )}
+ </>
+ );
+}
+
+function SummaryChip({ active, onClick, children }: { active: boolean; onClick: () => void; children: ReactNode }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "flex h-8 shrink-0 items-center whitespace-nowrap rounded-full border px-3 text-[12.5px]",
+ active
+ ? "border-brand bg-brand-soft font-semibold text-brand-ink"
+ : "border-line bg-surface-card font-medium text-fg-body"
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+/** Phone filter summary: one chip per filter, each opening the filter sheet. */
+export function AuditFilterChips({
+ filters,
+ onOpen,
+}: {
+ filters: AuditFilterValues;
+ onOpen: () => void;
+}) {
+ const { actions, severities } = useFilterOptions();
+ const rangeLabel = useRangeLabel(filters);
+ const t = useTranslations();
+
+ return (
+ <div className="-mx-4 flex gap-[7px] overflow-x-auto px-4 lg:hidden">
+ <SummaryChip active={filters.action !== "all"} onClick={onOpen}>
+ {actions.find((option) => option.value === filters.action)?.label}
+ </SummaryChip>
+ <SummaryChip active={filters.severity !== "all"} onClick={onOpen}>
+ {severities.find((option) => option.value === filters.severity)?.label}
+ </SummaryChip>
+ <SummaryChip active={!!rangeLabel} onClick={onOpen}>
+ {rangeLabel ? <span className="font-mono">{rangeLabel}</span> : t("adminAudit.dateRange")}
+ </SummaryChip>
+ </div>
+ );
+}
+
+/** Phone filter sheet (13k); changes apply immediately like the desktop controls. */
+export function AuditFilterSheet({
+ open,
+ onOpenChange,
+ filters,
+ onChange,
+ onClear,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ filters: AuditFilterValues;
+ onChange: (patch: Partial<AuditFilterValues>) => void;
+ onClear: () => void;
+}) {
+ const t = useTranslations();
+ const { actions, severities } = useFilterOptions();
+
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("adminAudit.filterTitle")}
+ bodyClassName="flex flex-col gap-5"
+ footer={
+ <>
+ <Button
+ variant="outline"
+ onClick={onClear}
+ disabled={!hasAuditFilters(filters)}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.filters.clearFilters")}
+ </Button>
+ <Button onClick={() => onOpenChange(false)} className="h-10 flex-1 font-semibold">
+ {t("adminAudit.done")}
+ </Button>
+ </>
+ }
+ >
+ <Field label={t("common.labels.action")}>
+ <ChoiceChips
+ value={filters.action}
+ onChange={(action) => onChange({ action })}
+ options={actions}
+ label={t("common.labels.action")}
+ />
+ </Field>
+ <Field label={t("common.labels.severity")}>
+ <ChoiceChips
+ value={filters.severity}
+ onChange={(severity) => onChange({ severity })}
+ options={severities}
+ label={t("common.labels.severity")}
+ />
+ </Field>
+ <DateInputs filters={filters} onChange={onChange} />
+ </PanelDialog>
+ );
+}
diff --git a/components/admin/calendar-bulk-delete-dialog.tsx b/components/admin/calendar-bulk-delete-dialog.tsx
index 38ca147..d62c784 100644
--- a/components/admin/calendar-bulk-delete-dialog.tsx
+++ b/components/admin/calendar-bulk-delete-dialog.tsx
@@ -2,19 +2,15 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { AlertTriangle } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
+import { PanelDialog } from "@/components/panel-dialog";
+import { SectionLabel } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
import type { AdminCalendar } from "@/hooks/useAdminCalendars";
+import { shiftVars } from "@/lib/shift-display";
interface CalendarBulkDeleteDialogProps {
open: boolean;
@@ -23,6 +19,8 @@ interface CalendarBulkDeleteDialogProps {
onConfirm: () => Promise<void>;
}
+const PREVIEW_LIMIT = 5;
+
export function CalendarBulkDeleteDialog({
open,
onOpenChange,
@@ -39,7 +37,6 @@ export function CalendarBulkDeleteDialog({
setIsSubmitting(true);
try {
await onConfirm();
- // Reset form
setUnderstood(false);
onOpenChange(false);
} finally {
@@ -48,79 +45,25 @@ export function CalendarBulkDeleteDialog({
};
const handleCancel = () => {
- // Reset form
setUnderstood(false);
onOpenChange(false);
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("common.deleteSelected")}</DialogTitle>
- <DialogDescription>
- {t("admin.calendars.bulkDeleteConfirm", {
- count: calendars.length,
- })}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
- <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
- <p className="text-sm text-red-800 dark:text-red-200">
- {t("admin.calendars.bulkDeleteWarning")}
- </p>
- </div>
-
- {/* Calendar List (max 5 shown) */}
- <div className="space-y-2">
- <Label>{t("admin.calendars.calendarsToDelete")}:</Label>
- <div className="p-3 rounded-lg border bg-muted/20 max-h-[150px] overflow-y-auto">
- <ul className="space-y-1 text-sm">
- {calendars.slice(0, 5).map((calendar) => (
- <li key={calendar.id} className="flex items-center gap-2">
- <div
- className="w-3 h-3 rounded-full shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <span className="truncate">{calendar.name}</span>
- </li>
- ))}
- {calendars.length > 5 && (
- <li className="text-muted-foreground italic">
- {t("admin.calendars.andMore", {
- count: calendars.length - 5,
- })}
- </li>
- )}
- </ul>
- </div>
- </div>
-
- {/* Checkbox Confirmation */}
- <div className="flex items-start space-x-3">
- <Checkbox
- id="understood"
- checked={understood}
- onCheckedChange={(checked) => setUnderstood(checked === true)}
- className="mt-1"
- />
- <Label
- htmlFor="understood"
- className="text-sm font-medium leading-normal cursor-pointer"
- >
- {t("admin.calendars.deleteUnderstood")}
- </Label>
- </div>
- </div>
-
- <DialogFooter>
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("common.deleteSelected")}
+ description={t("admin.calendars.bulkDeleteConfirm", { count: calendars.length })}
+ width="sm"
+ bodyClassName="flex flex-col gap-4"
+ footer={
+ <>
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
{t("common.cancel")}
</Button>
@@ -128,13 +71,51 @@ export function CalendarBulkDeleteDialog({
variant="destructive"
onClick={handleConfirm}
disabled={!understood || isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
- {isSubmitting
- ? t("common.saving")
- : t("admin.calendars.confirmDelete")}
+ {isSubmitting ? t("common.saving") : t("admin.calendars.confirmDelete")}
</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ <StatusBanner tone="danger" icon={TriangleAlert}>
+ {t("admin.calendars.bulkDeleteWarning")}
+ </StatusBanner>
+
+ <section>
+ <SectionLabel>{t("admin.calendars.calendarsToDelete")}</SectionLabel>
+ <ul className="flex flex-col divide-y divide-line-subtle rounded-[11px] border border-line bg-surface-card">
+ {calendars.slice(0, PREVIEW_LIMIT).map((calendar) => (
+ <li key={calendar.id} className="flex items-center gap-2.5 px-3.5 py-2.5">
+ <span
+ className="shift-rail size-2.5 shrink-0 rounded-full"
+ style={shiftVars(calendar.color)}
+ />
+ <span className="truncate text-[13.5px] font-semibold text-fg-strong">{calendar.name}</span>
+ </li>
+ ))}
+ {calendars.length > PREVIEW_LIMIT && (
+ <li className="px-3.5 py-2.5 text-[12.5px] text-fg-tertiary">
+ {t("admin.calendars.andMore", { count: calendars.length - PREVIEW_LIMIT })}
+ </li>
+ )}
+ </ul>
+ </section>
+
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="bulk-delete-understood"
+ checked={understood}
+ onCheckedChange={(checked) => setUnderstood(checked === true)}
+ className="mt-0.5"
+ />
+ <Label
+ htmlFor="bulk-delete-understood"
+ className="cursor-pointer text-[13.5px] font-medium leading-snug text-fg-body"
+ >
+ {t("admin.calendars.deleteUnderstood")}
+ </Label>
+ </div>
+ </PanelDialog>
);
}
diff --git a/components/admin/calendar-delete-dialog.tsx b/components/admin/calendar-delete-dialog.tsx
index 513e1a3..928705f 100644
--- a/components/admin/calendar-delete-dialog.tsx
+++ b/components/admin/calendar-delete-dialog.tsx
@@ -1,20 +1,7 @@
"use client";
-import { useState } from "react";
import { useTranslations } from "next-intl";
-import { AlertTriangle } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
-import { Input } from "@/components/ui/input";
-import { Checkbox } from "@/components/ui/checkbox";
+import { ConfirmNameDeleteDialog } from "@/components/admin/confirm-name-delete-dialog";
import type { AdminCalendar } from "@/hooks/useAdminCalendars";
interface CalendarDeleteDialogProps {
@@ -31,108 +18,21 @@ export function CalendarDeleteDialog({
onConfirm,
}: CalendarDeleteDialogProps) {
const t = useTranslations();
- const [confirmation, setConfirmation] = useState("");
- const [understood, setUnderstood] = useState(false);
- const [isSubmitting, setIsSubmitting] = useState(false);
-
- const isConfirmed = confirmation === calendar.name && understood;
-
- const handleConfirm = async () => {
- if (!isConfirmed) return;
-
- setIsSubmitting(true);
- try {
- await onConfirm();
- // Reset form
- setConfirmation("");
- setUnderstood(false);
- onOpenChange(false);
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const handleCancel = () => {
- // Reset form
- setConfirmation("");
- setUnderstood(false);
- onOpenChange(false);
- };
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("admin.calendars.deleteCalendar")}</DialogTitle>
- <DialogDescription>
- {t("admin.calendars.deleteCalendarConfirm", {
- name: calendar.name,
- })}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
- <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
- <p className="text-sm text-red-800 dark:text-red-200">
- {t("admin.calendars.deleteWarning")}
- </p>
- </div>
-
- {/* Checkbox Confirmation */}
- <div className="flex items-start space-x-3">
- <Checkbox
- id="understood"
- checked={understood}
- onCheckedChange={(checked) => setUnderstood(checked === true)}
- className="mt-1"
- />
- <Label
- htmlFor="understood"
- className="text-sm font-medium leading-normal cursor-pointer"
- >
- {t("admin.calendars.deleteUnderstood")}
- </Label>
- </div>
-
- {/* Name Confirmation */}
- <div className="space-y-2">
- <Label htmlFor="confirmation">
- {t("admin.calendars.deleteConfirmation", { name: calendar.name })}
- </Label>
- <Input
- id="confirmation"
- value={confirmation}
- onChange={(e) => setConfirmation(e.target.value)}
- placeholder={calendar.name}
- className="font-mono"
- />
- <p className="text-xs text-muted-foreground">
- {t("admin.calendars.deleteConfirmationHint")}
- </p>
- </div>
- </div>
-
- <DialogFooter>
- <Button
- variant="outline"
- onClick={handleCancel}
- disabled={isSubmitting}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="destructive"
- onClick={handleConfirm}
- disabled={!isConfirmed || isSubmitting}
- >
- {isSubmitting
- ? t("common.saving")
- : t("admin.calendars.confirmDelete")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <ConfirmNameDeleteDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ name={calendar.name}
+ idPrefix="delete-calendar"
+ title={t("admin.calendars.deleteCalendar")}
+ description={t("admin.calendars.deleteCalendarConfirm", { name: calendar.name })}
+ warning={t("admin.calendars.deleteWarning")}
+ understoodLabel={t("admin.calendars.deleteUnderstood")}
+ confirmationLabel={t("admin.calendars.deleteConfirmation", { name: calendar.name })}
+ confirmationHint={t("admin.calendars.deleteConfirmationHint")}
+ confirmLabel={t("admin.calendars.confirmDelete")}
+ onConfirm={onConfirm}
+ />
);
}
diff --git a/components/admin/calendar-details-sheet.tsx b/components/admin/calendar-details-sheet.tsx
index 93ed362..591e8ca 100644
--- a/components/admin/calendar-details-sheet.tsx
+++ b/components/admin/calendar-details-sheet.tsx
@@ -1,35 +1,23 @@
"use client";
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
-import { useLocale } from "next-intl";
+import { useQuery } from "@tanstack/react-query";
+import { useLocale, useTranslations } from "next-intl";
import { format } from "date-fns";
-import {
- Edit,
- Send,
- Trash2,
- Calendar,
- StickyNote,
- Bookmark,
- Share2,
- CloudDownload,
- Link,
-} from "lucide-react";
-import { BaseSheet } from "@/components/ui/base-sheet";
+import { CloudDownload, Eye, EyeOff, Link2, Pencil, Send, SquarePen, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import {
- useAdminCalendars,
- type CalendarDetails,
-} from "@/hooks/useAdminCalendars";
+import { ListRow, Pill } from "@/components/form-kit";
+import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";
+import { DetailSection, StatTile, UserAvatar } from "@/components/admin/admin-kit";
+import { isOrphaned, ownerColor } from "@/components/admin/calendar-table";
+import { fetchAdminCalendarDetails } from "@/hooks/useAdminCalendars";
import {
useCanEditCalendar,
useCanDeleteCalendar,
useCanTransferCalendar,
} from "@/hooks/useAdminAccess";
import { getDateLocale } from "@/lib/locales";
+import { queryKeys } from "@/lib/query-keys";
+import { shiftVars } from "@/lib/shift-display";
interface CalendarDetailsSheetProps {
open: boolean;
@@ -40,6 +28,13 @@ interface CalendarDetailsSheetProps {
onDelete: () => void;
}
+function PermissionPill({ permission }: { permission: string }) {
+ const t = useTranslations();
+ if (permission === "admin") return <Pill tone="violet">{t("common.labels.permissions.admin")}</Pill>;
+ if (permission === "write") return <Pill tone="brand">{t("common.labels.permissions.write")}</Pill>;
+ return <Pill>{t("common.labels.permissions.read")}</Pill>;
+}
+
export function CalendarDetailsSheet({
open,
onOpenChange,
@@ -49,391 +44,201 @@ export function CalendarDetailsSheet({
onDelete,
}: CalendarDetailsSheetProps) {
const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const { fetchCalendarDetails, isLoading } = useAdminCalendars();
- const [calendarDetails, setCalendarDetails] =
- useState<CalendarDetails | null>(null);
+ const dateLocale = getDateLocale(useLocale());
+ const { data: calendar = null, isError: loadFailed } = useQuery({
+ queryKey: queryKeys.admin.calendars.detail(calendarId),
+ queryFn: () => fetchAdminCalendarDetails(calendarId),
+ enabled: open,
+ retry: false,
+ });
const canEdit = useCanEditCalendar();
const canDelete = useCanDeleteCalendar();
const canTransfer = useCanTransferCalendar();
- useEffect(() => {
- if (!open) return;
-
- const loadDetails = async () => {
- const details = await fetchCalendarDetails(calendarId);
- if (details) {
- setCalendarDetails(details);
- }
- };
-
- loadDetails();
- }, [open, calendarId, fetchCalendarDetails]);
-
- const isOrphaned = !calendarDetails?.ownerId || !calendarDetails?.owner;
-
- const getOwnerInitials = () => {
- if (!calendarDetails?.owner) return "?";
- const name = calendarDetails.owner.name;
- if (!name) return "?";
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- };
-
- const getUserInitials = (name: string, email: string) => {
- if (name) {
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- }
- return email.slice(0, 2).toUpperCase();
- };
-
- const getGuestPermissionBadge = () => {
- if (!calendarDetails) return null;
-
- const permission = calendarDetails.guestPermission;
- if (permission === "none") {
- return (
- <Badge variant="secondary" className="text-xs">
- {t("common.labels.permissions.none")}
- </Badge>
- );
- } else if (permission === "read") {
- return (
- <Badge variant="outline" className="text-xs">
- {t("common.labels.permissions.read")}
- </Badge>
- );
- } else {
- return (
- <Badge variant="default" className="text-xs">
- {t("common.labels.permissions.write")}
- </Badge>
- );
- }
- };
+ const date = (value: Date) => format(value, "PP", { locale: dateLocale });
+ const orphaned = calendar ? isOrphaned(calendar) : false;
+
+ const guest = calendar?.guestPermission;
+ const GuestIcon = guest === "write" ? SquarePen : guest === "read" ? Eye : EyeOff;
+ const guestLabel =
+ guest === "write"
+ ? t("common.labels.permissions.write")
+ : guest === "read"
+ ? t("common.labels.permissions.read")
+ : t("common.labels.permissions.none");
+ const guestHint =
+ guest === "write"
+ ? t("adminCalendars.guestWriteHint")
+ : guest === "read"
+ ? t("adminCalendars.guestReadHint")
+ : t("adminCalendars.guestNoneHint");
+
+ const footer = (canEdit || canTransfer || canDelete) && calendar && (
+ <>
+ {canEdit && (
+ <Button variant="outline" onClick={onEdit} className="h-10 min-w-0 flex-1 font-semibold">
+ <Pencil className="size-[15px] text-fg-secondary" />
+ <span className="truncate">{t("adminUsers.edit")}</span>
+ </Button>
+ )}
+ {canTransfer && (
+ <Button variant="outline" onClick={onTransfer} className="h-10 min-w-0 flex-1 font-semibold">
+ <Send className="size-[15px] text-fg-secondary" />
+ <span className="truncate">{t("admin.calendars.transferOwnership")}</span>
+ </Button>
+ )}
+ {canDelete && (
+ <Button
+ variant="outline"
+ onClick={onDelete}
+ aria-label={t("admin.calendars.deleteCalendar")}
+ title={t("admin.calendars.deleteCalendar")}
+ className="h-10 w-11 shrink-0 border-danger-line p-0 text-danger hover:bg-danger-surface hover:text-danger"
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ )}
+ </>
+ );
return (
- <BaseSheet
+ <AdminDetailPanel
open={open}
onOpenChange={onOpenChange}
title={t("admin.calendars.calendarDetails")}
- description={t("admin.calendars.calendarDetailsDescription")}
- maxWidth="lg"
+ subtitle={calendar?.name}
+ footer={footer || undefined}
>
- {isLoading && !calendarDetails ? (
- <div className="text-center py-12 text-muted-foreground">
- {t("common.loading")}
- </div>
- ) : calendarDetails ? (
- <div className="space-y-6">
- {/* Calendar Info & Owner Cards */}
- <div className="flex items-stretch gap-4">
- {/* Calendar Name Card */}
- <div className="flex-1 p-4 rounded-lg border bg-muted/30">
- <h3 className="text-lg font-semibold mb-2 truncate">
- {calendarDetails.name}
- </h3>
- <div className="flex flex-wrap gap-2 mb-3">
- {isOrphaned && (
- <Badge
- variant="outline"
- className="bg-red-500/10 text-red-500 border-red-500/20"
- >
- {t("admin.calendars.orphaned")}
- </Badge>
- )}
- {getGuestPermissionBadge()}
+ {!calendar ? (
+ <p className="py-12 text-center text-[13px] text-fg-tertiary">
+ {loadFailed ? t("admin.calendars.noCalendarsFound") : t("common.loading")}
+ </p>
+ ) : (
+ <>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div className="min-w-0 rounded-[11px] border border-line bg-surface-card px-3.5 py-[13px]">
+ <div className="flex min-w-0 items-center gap-[9px]">
+ <span
+ className="shift-rail size-2.5 shrink-0 rounded-full"
+ style={shiftVars(calendar.color)}
+ />
+ <span className="truncate text-[15px] font-semibold text-fg-strong">{calendar.name}</span>
</div>
- <div className="space-y-1 text-xs text-muted-foreground">
- <p>
- {t("common.stats.created")}{" "}
- {format(calendarDetails.createdAt, "PP", {
- locale: dateLocale,
- })}
- </p>
- <p>
- {t("admin.calendars.updated")}{" "}
- {format(calendarDetails.updatedAt, "PP", {
- locale: dateLocale,
- })}
- </p>
+ <div className="mt-[9px] text-[11.5px] leading-relaxed text-fg-tertiary">
+ <div>
+ {t("common.stats.created")} {date(calendar.createdAt)}
+ </div>
+ <div>
+ {t("admin.calendars.updated")} {date(calendar.updatedAt)}
+ </div>
</div>
</div>
- {/* Separator */}
- <div className="w-px bg-border self-stretch" />
-
- {/* Owner Info Card */}
- <div className="flex-1 p-4 rounded-lg border bg-muted/30">
- <h4 className="text-sm font-medium mb-3">
- {t("admin.calendars.owner")}
- </h4>
- {isOrphaned ? (
- <div className="flex items-center justify-center h-20">
- <p className="text-sm text-red-600 dark:text-red-400">
- {t("admin.calendars.noOwner")}
- </p>
+ <div className="min-w-0 rounded-[11px] border border-line bg-surface-card px-3.5 py-[13px]">
+ <div className="eyebrow">{t("admin.calendars.owner")}</div>
+ {orphaned ? (
+ <div className="mt-[9px] flex flex-col items-start gap-1.5">
+ <Pill tone="warning">{t("admin.calendars.orphaned")}</Pill>
+ <span className="text-[12px] text-fg-tertiary">{t("admin.calendars.noOwner")}</span>
</div>
) : (
- <div className="flex items-center gap-3">
- <Avatar className="h-12 w-12">
- {calendarDetails.owner?.image && (
- <AvatarImage src={calendarDetails.owner.image} />
- )}
- <AvatarFallback className="text-sm">
- {getOwnerInitials()}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {calendarDetails.owner?.name}
- </p>
- <p className="text-xs text-muted-foreground truncate">
- {calendarDetails.owner?.email}
- </p>
+ <div className="mt-[9px] flex min-w-0 items-center gap-2.5">
+ <UserAvatar
+ name={calendar.owner?.name || calendar.owner?.email}
+ image={calendar.owner?.image}
+ size={30}
+ color={ownerColor(calendar.ownerId)}
+ />
+ <div className="min-w-0">
+ <div className="truncate text-[13px] font-semibold text-fg-strong">
+ {calendar.owner?.name}
+ </div>
+ <div className="truncate text-[11.5px] text-fg-tertiary">{calendar.owner?.email}</div>
</div>
</div>
)}
</div>
</div>
- <Separator />
-
- {/* Statistics */}
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("common.stats.statistics")}
- </h4>
- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
- <div className="p-3 rounded-lg border bg-muted/20">
- <div className="flex items-center gap-2 mb-1">
- <Calendar className="h-4 w-4 text-muted-foreground" />
- <span className="text-xs text-muted-foreground">
- {t("common.labels.shifts")}
- </span>
- </div>
- <p className="text-xl font-semibold">
- {calendarDetails.shiftsCount}
- </p>
- </div>
- <div className="p-3 rounded-lg border bg-muted/20">
- <div className="flex items-center gap-2 mb-1">
- <StickyNote className="h-4 w-4 text-muted-foreground" />
- <span className="text-xs text-muted-foreground">
- {t("common.labels.notes")}
- </span>
- </div>
- <p className="text-xl font-semibold">
- {calendarDetails.notesCount}
- </p>
- </div>
- <div className="p-3 rounded-lg border bg-muted/20">
- <div className="flex items-center gap-2 mb-1">
- <Bookmark className="h-4 w-4 text-muted-foreground" />
- <span className="text-xs text-muted-foreground">
- {t("common.labels.presets")}
- </span>
- </div>
- <p className="text-xl font-semibold">
- {calendarDetails.presetsCount}
- </p>
- </div>
- <div className="p-3 rounded-lg border bg-muted/20">
- <div className="flex items-center gap-2 mb-1">
- <Share2 className="h-4 w-4 text-muted-foreground" />
- <span className="text-xs text-muted-foreground">
- {t("common.labels.shares")}
- </span>
- </div>
- <p className="text-xl font-semibold">
- {calendarDetails.sharesCount}
- </p>
- <p className="text-xs text-muted-foreground mt-1">
- {calendarDetails.shares.length}{" "}
- {t("admin.calendars.userShares")},{" "}
- {calendarDetails.shareTokens?.length || 0}{" "}
- {t("admin.calendars.tokenShares")}
- </p>
- </div>
+ <DetailSection label={t("adminCalendars.content")}>
+ <div className="grid grid-cols-2 gap-2.5">
+ <StatTile label={t("common.labels.shifts")} value={calendar.shiftsCount} />
+ <StatTile label={t("common.labels.presets")} value={calendar.presetsCount} />
+ <StatTile label={t("common.labels.notes")} value={calendar.notesCount} />
+ <StatTile
+ label={t("adminCalendars.sharesAndLinks", {
+ links: calendar.shareTokens?.length || 0,
+ })}
+ value={calendar.shares.length}
+ />
</div>
- </div>
-
- {/* User Shares List */}
- {calendarDetails.shares.length > 0 && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
- <Share2 className="h-4 w-4" />
- {t("admin.calendars.userSharesList")} (
- {calendarDetails.shares.length})
- </h4>
- <div className="space-y-2 max-h-64 overflow-y-auto">
- {calendarDetails.shares.map((share) => (
- <div
- key={share.userId}
- className="flex items-center gap-3 p-2 rounded-lg border bg-muted/20"
- >
- <Avatar className="h-8 w-8">
- {share.userImage && (
- <AvatarImage src={share.userImage} />
- )}
- <AvatarFallback className="text-xs">
- {getUserInitials(share.userName, share.userEmail)}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {share.userName}
- </p>
- <p className="text-xs text-muted-foreground truncate">
- {share.userEmail}
- </p>
- </div>
- <Badge variant="secondary" className="text-xs">
- {t(`common.labels.permissions.${share.permission}`)}
- </Badge>
- </div>
- ))}
+ </DetailSection>
+
+ <DetailSection label={t("adminCalendars.publicAccess")}>
+ <ListRow className="py-[11px]">
+ <GuestIcon className="size-4 shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="text-[13.5px] font-semibold text-fg-strong">
+ {t("adminCalendars.guestPermissionValue", { permission: guestLabel })}
</div>
+ <div className="mt-0.5 text-[11.5px] text-fg-tertiary">{guestHint}</div>
</div>
- </>
+ </ListRow>
+ </DetailSection>
+
+ {calendar.shares.length > 0 && (
+ <DetailSection label={t("admin.calendars.userSharesList")}>
+ {calendar.shares.map((share) => (
+ <ListRow key={share.userId} className="py-2.5">
+ <UserAvatar name={share.userName || share.userEmail} image={share.userImage} size={30} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{share.userName}</div>
+ <div className="truncate text-[12px] text-fg-tertiary">{share.userEmail}</div>
+ </div>
+ <PermissionPill permission={share.permission} />
+ </ListRow>
+ ))}
+ </DetailSection>
)}
- {/* Share Tokens */}
- {calendarDetails.shareTokens &&
- calendarDetails.shareTokens.length > 0 && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
- <Link className="h-4 w-4" />
- {t("admin.calendars.tokenSharesList")} (
- {calendarDetails.shareTokens.length})
- </h4>
- <div className="space-y-2 max-h-64 overflow-y-auto">
- {calendarDetails.shareTokens.map((token) => (
- <div
- key={token.id}
- className="flex items-center gap-3 p-2 rounded-lg border bg-muted/20"
- >
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {token.name}
- </p>
- <p className="text-xs text-muted-foreground">
- {t("common.stats.created")}{" "}
- {format(token.createdAt, "PP", {
- locale: dateLocale,
- })}
- </p>
- </div>
- <Badge variant="secondary" className="text-xs">
- {t(`common.labels.permissions.${token.permission}`)}
- </Badge>
- </div>
- ))}
+ {calendar.shareTokens?.length > 0 && (
+ <DetailSection label={t("admin.calendars.tokenSharesList")}>
+ {calendar.shareTokens.map((token) => (
+ <ListRow key={token.id} className="py-2.5">
+ <Link2 className="size-4 shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{token.name}</div>
+ <div className="text-[12px] text-fg-tertiary">
+ {t("common.stats.created")} {date(new Date(token.createdAt))}
+ </div>
</div>
- </div>
- </>
- )}
+ <PermissionPill permission={token.permission} />
+ </ListRow>
+ ))}
+ </DetailSection>
+ )}
- {/* External Syncs */}
- {calendarDetails.externalSyncs &&
- calendarDetails.externalSyncs.length > 0 && (
- <>
- {(calendarDetails.shares.length > 0 ||
- (calendarDetails.shareTokens &&
- calendarDetails.shareTokens.length > 0)) && <Separator />}
- <div>
- <h4 className="text-sm font-medium flex items-center gap-2 mb-3">
- <CloudDownload className="h-4 w-4" />
- {t("admin.calendars.externalSyncs")} (
- {calendarDetails.externalSyncs.length})
- </h4>
- <div className="space-y-2 max-h-48 overflow-y-auto">
- {calendarDetails.externalSyncs.map((sync) => (
- <div
- key={sync.id}
- className="p-2 rounded-lg border bg-muted/20"
- >
- <p className="text-sm font-medium truncate">
- {sync.name}
- </p>
- <p className="text-xs text-muted-foreground truncate">
- {sync.url}
- </p>
- {sync.lastSyncedAt && (
- <p className="text-xs text-muted-foreground mt-1">
- {t("admin.calendars.lastSynced")}{" "}
- {format(sync.lastSyncedAt, "PP", {
- locale: dateLocale,
- })}
- </p>
- )}
+ {calendar.externalSyncs?.length > 0 && (
+ <DetailSection label={t("admin.calendars.externalSyncs")}>
+ {calendar.externalSyncs.map((sync) => (
+ <ListRow key={sync.id} className="items-start py-2.5">
+ <CloudDownload className="mt-0.5 size-4 shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{sync.name}</div>
+ <div className="truncate font-mono text-[11.5px] text-fg-tertiary">{sync.url}</div>
+ {sync.lastSyncedAt && (
+ <div className="mt-0.5 text-[12px] text-fg-tertiary">
+ {t("admin.calendars.lastSynced")} {date(sync.lastSyncedAt)}
</div>
- ))}
+ )}
</div>
- </div>
- </>
- )}
-
- {/* Quick Actions */}
- {(canEdit || canTransfer || canDelete) && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("admin.calendars.quickActions")}
- </h4>
- <div className="flex flex-col sm:flex-row gap-2">
- {canEdit && (
- <Button
- variant="outline"
- className="flex-1"
- onClick={onEdit}
- >
- <Edit className="h-4 w-4 mr-2" />
- {t("admin.calendars.editCalendar")}
- </Button>
- )}
- {canTransfer && (
- <Button
- variant="outline"
- className="flex-1"
- onClick={onTransfer}
- >
- <Send className="h-4 w-4 mr-2" />
- {t("admin.calendars.transferOwnership")}
- </Button>
- )}
- {canDelete && (
- <Button
- variant="outline"
- className="flex-1 text-destructive hover:text-destructive"
- onClick={onDelete}
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("admin.calendars.deleteCalendar")}
- </Button>
- )}
- </div>
- </div>
- </>
+ </ListRow>
+ ))}
+ </DetailSection>
)}
- </div>
- ) : null}
- </BaseSheet>
+ </>
+ )}
+ </AdminDetailPanel>
);
}
diff --git a/components/admin/calendar-edit-sheet.tsx b/components/admin/calendar-edit-sheet.tsx
index 88d2010..e4683a8 100644
--- a/components/admin/calendar-edit-sheet.tsx
+++ b/components/admin/calendar-edit-sheet.tsx
@@ -1,23 +1,12 @@
"use client";
-import { useState, useEffect } from "react";
+import { useState } from "react";
import { useTranslations } from "next-intl";
-import { BaseSheet } from "@/components/ui/base-sheet";
-import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { ColorPicker } from "@/components/ui/color-picker";
-import { PRESET_COLORS } from "@/lib/constants";
-import {
- useAdminCalendars,
- type AdminCalendar,
-} from "@/hooks/useAdminCalendars";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { ColorSwatches, Field, inputClass } from "@/components/form-kit";
+import { AdminFormPanel } from "@/components/admin/admin-form-panel";
+import { useAdminCalendarActions, type AdminCalendar } from "@/hooks/useAdminCalendars";
import { useCanEditCalendar } from "@/hooks/useAdminAccess";
interface CalendarEditSheetProps {
@@ -27,30 +16,16 @@ interface CalendarEditSheetProps {
onSuccess: () => void;
}
-export function CalendarEditSheet({
- open,
- onOpenChange,
- calendar,
- onSuccess,
-}: CalendarEditSheetProps) {
+export function CalendarEditSheet({ open, onOpenChange, calendar, onSuccess }: CalendarEditSheetProps) {
const t = useTranslations();
- const { updateCalendar, isLoading } = useAdminCalendars();
+ const { updateCalendar, isUpdating } = useAdminCalendarActions();
const canEdit = useCanEditCalendar();
+ // Resets when the parent remounts this component via its key
const [name, setName] = useState(calendar.name);
const [color, setColor] = useState(calendar.color);
- const [guestPermission, setGuestPermission] = useState(
- calendar.guestPermission
- );
-
- // Reset state when calendar changes
- useEffect(() => {
- setName(calendar.name);
- setColor(calendar.color);
- setGuestPermission(calendar.guestPermission);
- }, [calendar]);
+ const [guestPermission, setGuestPermission] = useState(calendar.guestPermission);
- // Track if form has changes
const hasChanges =
name !== calendar.name ||
color !== calendar.color ||
@@ -60,115 +35,82 @@ export function CalendarEditSheet({
return null;
}
- const handleOpenChange = (newOpen: boolean) => {
- onOpenChange(newOpen);
- };
-
const handleSave = async () => {
- const updates: {
- name?: string;
- color?: string;
- guestPermission?: string;
- } = {};
+ const updates: Parameters<typeof updateCalendar>[1] = {};
if (name !== calendar.name) updates.name = name;
if (color !== calendar.color) updates.color = color;
- if (guestPermission !== calendar.guestPermission)
- updates.guestPermission = guestPermission;
+ if (guestPermission !== calendar.guestPermission) updates.guestPermission = guestPermission;
const success = await updateCalendar(calendar.id, updates);
if (success) {
onSuccess();
- handleOpenChange(false);
+ onOpenChange(false);
}
};
return (
- <BaseSheet
+ <AdminFormPanel
open={open}
- onOpenChange={handleOpenChange}
+ onOpenChange={onOpenChange}
title={t("admin.calendars.editCalendar")}
- description={t("admin.calendars.editCalendarDescription")}
- showSaveButton
+ subtitle={calendar.name}
onSave={handleSave}
- isSaving={isLoading}
+ isSaving={isUpdating}
saveDisabled={!hasChanges || !name.trim()}
hasUnsavedChanges={hasChanges}
- maxWidth="md"
>
- <div className="space-y-6">
- {/* Calendar Name */}
- <div className="space-y-2">
- <Label htmlFor="name">
- {t("common.labels.name")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <Input
- id="name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder={t("admin.calendars.namePlaceholder")}
- />
- </div>
-
- {/* Calendar Color */}
- <ColorPicker
- color={color}
- onChange={setColor}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
+ <Field label={t("common.labels.name")} htmlFor="admin-calendar-name">
+ <Input
+ id="admin-calendar-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("admin.calendars.namePlaceholder")}
+ className={inputClass}
/>
+ </Field>
- {/* Guest Permission */}
- <div className="space-y-2">
- <Label htmlFor="guestPermission">
- {t("admin.calendars.guestPermission")}
- </Label>
- <Select
- value={guestPermission}
- onValueChange={(value) =>
- setGuestPermission(value as "none" | "read" | "write")
- }
+ <Field label={t("form.colorLabel")}>
+ <ColorSwatches value={color} onChange={setColor} allowCustom />
+ </Field>
+
+ <Field
+ label={t("admin.calendars.guestPermission")}
+ htmlFor="admin-calendar-guest"
+ hint={t("admin.calendars.guestPermissionHint")}
+ >
+ <Select
+ value={guestPermission}
+ onValueChange={(value) => setGuestPermission(value as AdminCalendar["guestPermission"])}
+ >
+ <SelectTrigger
+ id="admin-calendar-guest"
+ className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10"
>
- <SelectTrigger id="guestPermission">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="none">
- {t("common.labels.permissions.none")}
- </SelectItem>
- <SelectItem value="read">
- {t("common.labels.permissions.read")}
- </SelectItem>
- <SelectItem value="write">
- {t("common.labels.permissions.write")}
- </SelectItem>
- </SelectContent>
- </Select>
- <p className="text-xs text-muted-foreground">
- {t("admin.calendars.guestPermissionHint")}
- </p>
- </div>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{t("common.labels.permissions.none")}</SelectItem>
+ <SelectItem value="read">{t("common.labels.permissions.read")}</SelectItem>
+ <SelectItem value="write">{t("common.labels.permissions.write")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
- {/* Current Owner */}
- <div className="space-y-2">
- <Label>{t("admin.calendars.currentOwner")}</Label>
- <div className="p-3 rounded-lg border bg-muted/20">
- {calendar.ownerId ? (
- <div className="flex flex-col gap-1">
- <p className="text-sm font-medium">{calendar.owner!.name}</p>
- <p className="text-xs text-muted-foreground">
- {calendar.owner!.email}
- </p>
+ <Field label={t("admin.calendars.currentOwner")}>
+ <div className="rounded-[9px] border border-line bg-surface-panel px-[13px] py-[11px]">
+ {calendar.ownerId && calendar.owner ? (
+ <>
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">
+ {calendar.owner.name}
</div>
- ) : (
- <p className="text-sm text-muted-foreground">
- {t("admin.calendars.noOwner")}
- </p>
- )}
- </div>
+ <div className="mt-0.5 truncate text-[12px] text-fg-tertiary">{calendar.owner.email}</div>
+ </>
+ ) : (
+ <div className="text-[13px] text-fg-tertiary">{t("admin.calendars.noOwner")}</div>
+ )}
</div>
- </div>
- </BaseSheet>
+ </Field>
+ </AdminFormPanel>
);
}
diff --git a/components/admin/calendar-table.tsx b/components/admin/calendar-table.tsx
index 663b030..65919c2 100644
--- a/components/admin/calendar-table.tsx
+++ b/components/admin/calendar-table.tsx
@@ -1,28 +1,8 @@
"use client";
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { useLocale } from "next-intl";
+import { useLocale, useTranslations } from "next-intl";
import { format } from "date-fns";
-import {
- MoreVertical,
- Edit,
- Trash2,
- Eye,
- Send,
- ChevronUp,
- ChevronDown,
-} from "lucide-react";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import { Badge } from "@/components/ui/badge";
+import { ChevronRight, Ellipsis, Eye, Pencil, Send, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -32,16 +12,44 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Pill } from "@/components/form-kit";
+import {
+ AdminTableCard,
+ AdminTableHead,
+ AdminTableRow,
+ Count,
+ UserAvatar,
+} from "@/components/admin/admin-kit";
+import {
+ RowActionButton,
+ SortHeader,
+ nextSort,
+ type SortState,
+} from "@/components/admin/admin-table-controls";
+import { AdminPagination } from "@/components/admin/admin-pagination";
import { getDateLocale } from "@/lib/locales";
+import type { CalendarSortField } from "@/lib/admin-list";
import type { AdminCalendar } from "@/hooks/useAdminCalendars";
import {
useCanEditCalendar,
useCanDeleteCalendar,
useCanTransferCalendar,
} from "@/hooks/useAdminAccess";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
interface CalendarTableProps {
+ /** One page of calendars, already sorted by the API */
calendars: AdminCalendar[];
+ /** Calendars matching the current search and filters */
+ total: number;
+ page: number;
+ pageSize: number;
+ onPageChange: (page: number) => void;
+ sort: SortState<CalendarSortField>;
+ onSortChange: (sort: SortState<CalendarSortField>) => void;
+ /** Dims the rows while the next page loads */
+ isStale?: boolean;
selectedIds: string[];
onToggleSelect: (calendarId: string) => void;
onToggleSelectAll: () => void;
@@ -50,19 +58,78 @@ interface CalendarTableProps {
onEditCalendar: (calendar: AdminCalendar) => void;
onTransferCalendar: (calendar: AdminCalendar) => void;
onDeleteCalendar: (calendar: AdminCalendar) => void;
+ onBulkTransfer: () => void;
+ onBulkDelete: () => void;
+ onClearSelection: () => void;
+ emptyMessage?: string;
+}
+
+const TEMPLATE =
+ "18px minmax(0,1.2fr) minmax(0,2fr) 110px 90px 90px 70px 120px 102px";
+
+// Dark enough for white initials in both themes
+const OWNER_COLORS = ["#0f766e", "#6d28d9", "#344054", "#b45309", "#1d4ed8", "#be185d", "#15803d"];
+
+/** Stable avatar color per owner, as in 13d. */
+export function ownerColor(key: string | null | undefined) {
+ if (!key) return OWNER_COLORS[2];
+ let hash = 0;
+ for (let i = 0; i < key.length; i++) hash = (hash * 31 + key.charCodeAt(i)) | 0;
+ return OWNER_COLORS[Math.abs(hash) % OWNER_COLORS.length];
+}
+
+export function isOrphaned(calendar: Pick<AdminCalendar, "ownerId" | "owner">) {
+ return !calendar.ownerId || !calendar.owner;
+}
+
+function GuestPermissionPill({ permission }: { permission: AdminCalendar["guestPermission"] }) {
+ const t = useTranslations();
+ if (permission === "write") return <Pill tone="brand">{t("common.labels.permissions.write")}</Pill>;
+ if (permission === "read") return <Pill>{t("common.labels.permissions.read")}</Pill>;
+ return <Pill className="text-fg-tertiary">{t("common.labels.permissions.none")}</Pill>;
+}
+
+function CalendarDot({ color, className }: { color: string; className?: string }) {
+ return (
+ <span
+ className={cn("shift-rail size-2 shrink-0 rounded-full", className)}
+ style={shiftVars(color)}
+ />
+ );
}
-type SortColumn =
- | "name"
- | "createdAt"
- | "owner"
- | "shiftsCount"
- | "sharesCount"
- | "externalSyncsCount"
- | "guestPermission";
-type SortDirection = "asc" | "desc";
+function OwnerCell({ calendar, compact }: { calendar: AdminCalendar; compact?: boolean }) {
+ const t = useTranslations();
+ if (isOrphaned(calendar)) {
+ return <Pill tone="warning">{t("admin.calendars.orphaned")}</Pill>;
+ }
+ const owner = calendar.owner!;
+ return (
+ <div className="flex min-w-0 items-center gap-2.5">
+ <UserAvatar
+ name={owner.name || owner.email}
+ image={owner.image}
+ size={compact ? 28 : 30}
+ color={ownerColor(calendar.ownerId)}
+ />
+ <div className="min-w-0">
+ <div
+ className={cn(
+ "truncate font-semibold",
+ compact ? "text-[12.5px] text-fg-body" : "text-[13px] text-fg-strong"
+ )}
+ >
+ {owner.name}
+ </div>
+ <div className={cn("truncate text-fg-tertiary", compact ? "text-[11.5px]" : "text-[12px]")}>
+ {owner.email}
+ </div>
+ </div>
+ </div>
+ );
+}
-function CalendarTableRow({
+function CalendarRow({
calendar,
isSelected,
onToggleSelect,
@@ -73,382 +140,326 @@ function CalendarTableRow({
}: {
calendar: AdminCalendar;
isSelected: boolean;
- onToggleSelect: (calendarId: string) => void;
- onCalendarClick: (calendar: AdminCalendar) => void;
- onEditCalendar: (calendar: AdminCalendar) => void;
- onTransferCalendar: (calendar: AdminCalendar) => void;
- onDeleteCalendar: (calendar: AdminCalendar) => void;
-}) {
+} & Pick<
+ CalendarTableProps,
+ "onToggleSelect" | "onCalendarClick" | "onEditCalendar" | "onTransferCalendar" | "onDeleteCalendar"
+>) {
const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
-
+ const dateLocale = getDateLocale(useLocale());
const canEdit = useCanEditCalendar();
const canDelete = useCanDeleteCalendar();
const canTransfer = useCanTransferCalendar();
- const isOrphaned = !calendar.ownerId || !calendar.owner;
- const hasActions = canEdit || canTransfer || canDelete;
-
return (
- <TableRow
- className="cursor-pointer"
+ <AdminTableRow
+ template={TEMPLATE}
+ muted={isSelected ? "panel" : undefined}
onClick={() => onCalendarClick(calendar)}
>
- {/* Checkbox */}
- <TableCell onClick={(e) => e.stopPropagation()}>
+ {/* Stop clicks and Enter/Space from also opening the details panel */}
+ <div
+ className="flex items-center"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
<Checkbox
checked={isSelected}
onCheckedChange={() => onToggleSelect(calendar.id)}
+ aria-label={calendar.name}
/>
- </TableCell>
+ </div>
+ <div className="flex min-w-0 items-center gap-2.5">
+ <CalendarDot color={calendar.color} />
+ <span className="truncate text-[13.5px] font-semibold text-fg-strong">{calendar.name}</span>
+ </div>
+ <OwnerCell calendar={calendar} />
+ <span className="truncate text-[12.5px] text-fg-secondary">
+ {format(calendar.createdAt, "PP", { locale: dateLocale })}
+ </span>
+ <Count value={calendar.shiftsCount} />
+ <Count value={calendar.sharesCount} />
+ <Count value={calendar.externalSyncsCount || 0} />
+ <div>
+ <GuestPermissionPill permission={calendar.guestPermission} />
+ </div>
+ <div
+ className="flex items-center justify-end gap-1.5"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <RowActionButton
+ icon={Pencil}
+ label={t("admin.calendars.editCalendar")}
+ disabled={!canEdit}
+ onClick={() => onEditCalendar(calendar)}
+ />
+ <RowActionButton
+ icon={Send}
+ label={t("admin.calendars.transferOwnership")}
+ disabled={!canTransfer}
+ onClick={() => onTransferCalendar(calendar)}
+ />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <RowActionButton icon={Ellipsis} label={t("adminUsers.moreActions")} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-48">
+ <DropdownMenuItem onClick={() => onCalendarClick(calendar)}>
+ <Eye />
+ {t("common.viewDetails")}
+ </DropdownMenuItem>
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => onDeleteCalendar(calendar)}
+ className="text-danger focus:text-danger"
+ >
+ <Trash2 />
+ {t("admin.calendars.deleteCalendar")}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </AdminTableRow>
+ );
+}
- {/* Calendar Name + Color */}
- <TableCell>
- <div className="flex items-center gap-3">
- <div
- className="w-4 h-4 rounded-full shrink-0 ring-2 ring-background"
- style={{ backgroundColor: calendar.color }}
- />
- <div className="min-w-0">
- <p className="text-sm font-medium truncate">{calendar.name}</p>
- </div>
- </div>
- </TableCell>
+function CalendarCard({
+ calendar,
+ isSelected,
+ onToggleSelect,
+ onClick,
+}: {
+ calendar: AdminCalendar;
+ isSelected: boolean;
+ onToggleSelect: () => void;
+ onClick: () => void;
+}) {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const stat = (label: string, value: number) => (
+ <div>
+ <div className="text-[11px] text-fg-tertiary">{label}</div>
+ <div
+ className={cn(
+ "font-mono text-[15px] font-medium",
+ value === 0 ? "text-fg-faint" : "text-fg-strong"
+ )}
+ >
+ {value}
+ </div>
+ </div>
+ );
- {/* Owner */}
- <TableCell>
- {isOrphaned ? (
- <Badge
- variant="outline"
- className="bg-red-500/10 text-red-500 border-red-500/20"
- >
- {t("admin.calendars.orphaned")}
- </Badge>
- ) : (
- <div className="flex items-center gap-3">
- <Avatar className="h-8 w-8">
- {calendar.owner?.image && (
- <AvatarImage src={calendar.owner.image} />
- )}
- <AvatarFallback className="text-xs">
- {calendar.owner?.name
- ? calendar.owner.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2)
- : (calendar.owner?.email || "").slice(0, 2).toUpperCase()}
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0">
- <p className="text-sm truncate">{calendar.owner?.name}</p>
- <p className="text-xs text-muted-foreground truncate">
- {calendar.owner?.email}
- </p>
+ return (
+ <div
+ className={cn(
+ "flex items-start gap-2.5 rounded-[11px] border py-3 pl-[13px]",
+ isSelected ? "border-brand bg-brand-soft" : "border-line bg-surface-card"
+ )}
+ >
+ <Checkbox
+ checked={isSelected}
+ onCheckedChange={onToggleSelect}
+ aria-label={calendar.name}
+ className="mt-[3px]"
+ />
+ <button
+ type="button"
+ onClick={onClick}
+ className="flex min-w-0 flex-1 flex-col gap-2.5 pr-[13px] text-left"
+ >
+ <div className="flex w-full items-center gap-2.5">
+ <CalendarDot color={calendar.color} />
+ <span className="min-w-0 flex-1 truncate text-[15px] font-semibold text-fg-strong">
+ {calendar.name}
+ </span>
+ <GuestPermissionPill permission={calendar.guestPermission} />
+ <ChevronRight className="size-[17px] shrink-0 text-fg-faint" />
+ </div>
+ <OwnerCell calendar={calendar} compact />
+ <div className="flex w-full gap-4 border-t border-line-subtle pt-[9px]">
+ {stat(t("common.labels.shifts"), calendar.shiftsCount)}
+ {stat(t("common.labels.shares"), calendar.sharesCount)}
+ {stat(t("admin.calendars.externalSyncsShort"), calendar.externalSyncsCount || 0)}
+ <div>
+ <div className="text-[11px] text-fg-tertiary">{t("common.stats.created")}</div>
+ <div className="mt-px text-[13px] font-medium text-fg-strong">
+ {format(calendar.createdAt, "PP", { locale: dateLocale })}
</div>
</div>
- )}
- </TableCell>
-
- {/* Created */}
- <TableCell>
- <span className="text-sm text-muted-foreground">
- {format(calendar.createdAt, "PP", { locale: dateLocale })}
- </span>
- </TableCell>
-
- {/* Shifts Count */}
- <TableCell>
- <span className="text-sm">{calendar.shiftsCount}</span>
- </TableCell>
-
- {/* Shares Count */}
- <TableCell>
- <span className="text-sm">{calendar.sharesCount}</span>
- </TableCell>
+ </div>
+ </button>
+ </div>
+ );
+}
- {/* External Syncs Count */}
- <TableCell>
- <span className="text-sm">{calendar.externalSyncsCount || 0}</span>
- </TableCell>
+function BulkActions({
+ count,
+ onBulkTransfer,
+ onBulkDelete,
+ onClearSelection,
+}: {
+ count: number;
+} & Pick<CalendarTableProps, "onBulkTransfer" | "onBulkDelete" | "onClearSelection">) {
+ const t = useTranslations();
+ const canTransfer = useCanTransferCalendar();
+ const canDelete = useCanDeleteCalendar();
- {/* Guest Permission */}
- <TableCell>
- {calendar.guestPermission === "none" ? (
- <Badge variant="secondary" className="text-xs">
- {t("common.labels.permissions.none")}
- </Badge>
- ) : calendar.guestPermission === "read" ? (
- <Badge variant="outline" className="text-xs">
- {t("common.labels.permissions.read")}
- </Badge>
- ) : (
- <Badge variant="default" className="text-xs">
- {t("common.labels.permissions.write")}
- </Badge>
- )}
- </TableCell>
+ if (count === 0) {
+ return <span>{t("adminCalendars.selectedNone")}</span>;
+ }
- {/* Actions */}
- <TableCell onClick={(e) => e.stopPropagation()}>
- {hasActions && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => onCalendarClick(calendar)}>
- <Eye className="h-4 w-4 mr-2" />
- {t("common.viewDetails")}
- </DropdownMenuItem>
- {canEdit && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => onEditCalendar(calendar)}>
- <Edit className="h-4 w-4 mr-2" />
- {t("admin.calendars.editCalendar")}
- </DropdownMenuItem>
- </>
- )}
- {canTransfer && (
- <DropdownMenuItem onClick={() => onTransferCalendar(calendar)}>
- <Send className="h-4 w-4 mr-2" />
- {t("admin.calendars.transferOwnership")}
- </DropdownMenuItem>
- )}
- {canDelete && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => onDeleteCalendar(calendar)}
- className="text-destructive"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("admin.calendars.deleteCalendar")}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </TableCell>
- </TableRow>
+ return (
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <span className="font-semibold text-fg-body">{t("adminCalendars.selectedCount", { count })}</span>
+ {canTransfer && (
+ <Button variant="outline" size="sm" onClick={onBulkTransfer} className="h-8 rounded-[8px]">
+ <Send className="size-3.5 text-fg-secondary" />
+ {t("admin.calendars.transferSelected")}
+ </Button>
+ )}
+ {canDelete && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onBulkDelete}
+ className="h-8 rounded-[8px] border-danger-line text-danger hover:bg-danger-surface hover:text-danger"
+ >
+ <Trash2 className="size-3.5" />
+ {t("common.deleteSelected")}
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onClearSelection}
+ aria-label={t("admin.calendars.clearSelection")}
+ title={t("admin.calendars.clearSelection")}
+ className="size-8 p-0 text-fg-secondary"
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
);
}
export function CalendarTable({
calendars,
+ total,
+ page,
+ pageSize,
+ onPageChange,
+ sort,
+ onSortChange,
+ isStale,
selectedIds,
onToggleSelect,
onToggleSelectAll,
isAllSelected,
- onCalendarClick,
- onEditCalendar,
- onTransferCalendar,
- onDeleteCalendar,
+ onBulkTransfer,
+ onBulkDelete,
+ onClearSelection,
+ emptyMessage,
+ ...rowHandlers
}: CalendarTableProps) {
const t = useTranslations();
- const [sortColumn, setSortColumn] = useState<SortColumn | null>("createdAt");
- const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
-
- // Sort calendars (orphaned always first, then by selected column)
- const sortedCalendars = [...calendars].sort((a, b) => {
- // Orphaned calendars always on top
- const aOrphaned = !a.ownerId;
- const bOrphaned = !b.ownerId;
- if (aOrphaned !== bOrphaned) {
- return aOrphaned ? -1 : 1;
- }
-
- // Then sort by selected column
- if (!sortColumn) return 0;
-
- let comparison = 0;
-
- switch (sortColumn) {
- case "name":
- comparison = a.name.localeCompare(b.name);
- break;
- case "createdAt":
- comparison = a.createdAt.getTime() - b.createdAt.getTime();
- break;
- case "owner":
- const aOwner = a.owner?.name || "";
- const bOwner = b.owner?.name || "";
- comparison = aOwner.localeCompare(bOwner);
- break;
- case "shiftsCount":
- comparison = a.shiftsCount - b.shiftsCount;
- break;
- case "sharesCount":
- comparison = a.sharesCount - b.sharesCount;
- break;
- case "externalSyncsCount":
- comparison = (a.externalSyncsCount || 0) - (b.externalSyncsCount || 0);
- break;
- case "guestPermission":
- const permissionOrder = { none: 0, read: 1, write: 2 };
- comparison =
- permissionOrder[a.guestPermission] -
- permissionOrder[b.guestPermission];
- break;
- }
-
- return sortDirection === "asc" ? comparison : -comparison;
- });
-
- // Handle sort column click
- const handleSort = (column: SortColumn) => {
- if (sortColumn === column) {
- setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
- } else {
- setSortColumn(column);
- setSortDirection("desc");
- }
- };
+ const header = (column: CalendarSortField, label: string) => (
+ <SortHeader
+ column={column}
+ label={label}
+ sort={sort}
+ onSort={(next) => onSortChange(nextSort(sort, next))}
+ />
+ );
+ const bulk = (
+ <BulkActions
+ count={selectedIds.length}
+ onBulkTransfer={onBulkTransfer}
+ onBulkDelete={onBulkDelete}
+ onClearSelection={onClearSelection}
+ />
+ );
+ const empty = (
+ <p className="px-4 py-10 text-center text-[13px] text-fg-tertiary">
+ {emptyMessage ?? t("admin.calendars.noCalendarsFound")}
+ </p>
+ );
+ const pagination = (className?: string, extra?: React.ReactNode) => (
+ <AdminPagination
+ page={page}
+ pageSize={pageSize}
+ shown={calendars.length}
+ total={total}
+ onPageChange={onPageChange}
+ extra={extra}
+ className={className}
+ />
+ );
return (
- <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
- <Table>
- <TableHeader className="bg-muted/50">
- <TableRow>
- <TableHead className="w-[50px]">
- <Checkbox
- checked={isAllSelected}
- onCheckedChange={onToggleSelectAll}
- />
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("name")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.name")}
- {sortColumn === "name" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("owner")}
- >
- <div className="flex items-center gap-2">
- {t("admin.calendars.owner")}
- {sortColumn === "owner" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("createdAt")}
- >
- <div className="flex items-center gap-2">
- {t("common.stats.created")}
- {sortColumn === "createdAt" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("shiftsCount")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.shifts")}
- {sortColumn === "shiftsCount" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("sharesCount")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.shares")}
- {sortColumn === "sharesCount" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("externalSyncsCount")}
- >
- <div className="flex items-center gap-2">
- {t("admin.calendars.externalSyncsShort")}
- {sortColumn === "externalSyncsCount" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("guestPermission")}
- >
- <div className="flex items-center gap-2">
- {t("admin.calendars.guestPermission")}
- {sortColumn === "guestPermission" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead className="w-[50px]"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {sortedCalendars.length === 0 ? (
- <TableRow>
- <TableCell colSpan={9} className="text-center py-8">
- <p className="text-muted-foreground">
- {t("admin.calendars.noCalendarsFound")}
- </p>
- </TableCell>
- </TableRow>
- ) : (
- sortedCalendars.map((calendar) => (
- <CalendarTableRow
+ <div aria-busy={isStale || undefined} className={cn(isStale && "opacity-60")}>
+ <AdminTableCard className="hidden lg:block" footer={total > 0 && pagination(undefined, bulk)}>
+ <AdminTableHead
+ template={TEMPLATE}
+ columns={[
+ <Checkbox
+ key="select-all"
+ checked={isAllSelected}
+ onCheckedChange={onToggleSelectAll}
+ disabled={calendars.length === 0}
+ aria-label={t("adminCalendars.selectAll")}
+ />,
+ header("name", t("common.labels.name")),
+ header("owner", t("admin.calendars.owner")),
+ header("createdAt", t("common.stats.created")),
+ header("shiftsCount", t("common.labels.shifts")),
+ header("sharesCount", t("common.labels.shares")),
+ header("externalSyncsCount", t("admin.calendars.externalSyncsShort")),
+ header("guestPermission", t("adminCalendars.guestColumn")),
+ <span key="actions" className="block text-right">
+ {t("adminUsers.actions")}
+ </span>,
+ ]}
+ />
+ {calendars.length === 0
+ ? empty
+ : calendars.map((calendar) => (
+ <CalendarRow
key={calendar.id}
calendar={calendar}
isSelected={selectedIds.includes(calendar.id)}
onToggleSelect={onToggleSelect}
- onCalendarClick={onCalendarClick}
- onEditCalendar={onEditCalendar}
- onTransferCalendar={onTransferCalendar}
- onDeleteCalendar={onDeleteCalendar}
+ {...rowHandlers}
/>
- ))
- )}
- </TableBody>
- </Table>
+ ))}
+ </AdminTableCard>
+
+ <div className="flex flex-col gap-[9px] lg:hidden">
+ {selectedIds.length > 0 && (
+ <div className="rounded-[11px] border border-line bg-surface-panel px-3.5 py-2.5 text-[12.5px] text-fg-secondary">
+ {bulk}
+ </div>
+ )}
+ {calendars.length === 0 ? (
+ <div className="rounded-[11px] border border-line">{empty}</div>
+ ) : (
+ calendars.map((calendar) => (
+ <CalendarCard
+ key={calendar.id}
+ calendar={calendar}
+ isSelected={selectedIds.includes(calendar.id)}
+ onToggleSelect={() => onToggleSelect(calendar.id)}
+ onClick={() => rowHandlers.onCalendarClick(calendar)}
+ />
+ ))
+ )}
+ {total > pageSize && pagination("pt-1 text-[12px] text-fg-tertiary")}
+ </div>
</div>
);
}
diff --git a/components/admin/calendar-transfer-sheet.tsx b/components/admin/calendar-transfer-sheet.tsx
index 95c53e0..bcb83b4 100644
--- a/components/admin/calendar-transfer-sheet.tsx
+++ b/components/admin/calendar-transfer-sheet.tsx
@@ -1,19 +1,18 @@
"use client";
-import { useState, useCallback, useMemo } from "react";
+import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
-import { Search, X } from "lucide-react";
-import { BaseSheet } from "@/components/ui/base-sheet";
+import { Check, Search, X } from "lucide-react";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import { Badge } from "@/components/ui/badge";
-import {
- useAdminCalendars,
- type AdminCalendar,
-} from "@/hooks/useAdminCalendars";
-import { useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";
+import { Field, ListRow, Pill, SectionLabel, inputClass } from "@/components/form-kit";
+import { AdminFormPanel } from "@/components/admin/admin-form-panel";
+import { RolePill, UserAvatar } from "@/components/admin/admin-kit";
+import { isOrphaned } from "@/components/admin/calendar-table";
+import { useAdminCalendarActions, type AdminCalendar } from "@/hooks/useAdminCalendars";
+import { fetchAdminUsers } from "@/hooks/useAdminUsers";
import { useCanTransferCalendar } from "@/hooks/useAdminAccess";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
interface CalendarTransferSheetProps {
open: boolean;
@@ -30,6 +29,20 @@ interface SearchUser {
role: string;
}
+function UserRow({ user, selected }: { user: SearchUser; selected?: boolean }) {
+ return (
+ <>
+ <UserAvatar name={user.name || user.email} image={user.image} size={32} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{user.name}</div>
+ <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>
+ </div>
+ <RolePill role={user.role} />
+ {selected && <Check className="size-4 shrink-0 text-brand-ink" />}
+ </>
+ );
+}
+
export function CalendarTransferSheet({
open,
onOpenChange,
@@ -37,300 +50,194 @@ export function CalendarTransferSheet({
onSuccess,
}: CalendarTransferSheetProps) {
const t = useTranslations();
- const { transferCalendar, bulkTransferCalendars, isLoading } =
- useAdminCalendars();
- const { fetchUsers } = useAdminUsers();
+ const { transferCalendar, bulkTransferCalendars, isTransferring } = useAdminCalendarActions();
const canTransfer = useCanTransferCalendar();
const [query, setQuery] = useState("");
const [selectedUser, setSelectedUser] = useState<SearchUser | null>(null);
const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
const [searchLoading, setSearchLoading] = useState(false);
+ const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const isBulk = calendars.length > 1;
- // Debounced search
- const handleSearch = useCallback(
- (value: string) => {
- setQuery(value);
- setSelectedUser(null);
+ useEffect(() => () => clearTimeout(searchTimeout.current ?? undefined), []);
- if (value.length < 2) {
- setSearchResults([]);
- return;
- }
+ const handleSearch = (value: string) => {
+ setQuery(value);
+ setSelectedUser(null);
+ clearTimeout(searchTimeout.current ?? undefined);
- setSearchLoading(true);
+ if (value.length < 2) {
+ setSearchResults([]);
+ setSearchLoading(false);
+ return;
+ }
- // Debounce search
- const timeoutId = setTimeout(async () => {
- const result = await fetchUsers(
- { search: value, status: "active" },
- { field: "name", direction: "asc" },
- { page: 1, limit: 50 }
+ setSearchLoading(true);
+ searchTimeout.current = setTimeout(async () => {
+ try {
+ const result = await fetchAdminUsers({
+ search: value,
+ status: "active",
+ sort: "name",
+ order: "asc",
+ limit: 50,
+ });
+ setSearchResults(
+ result.items.map((user) => ({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ image: user.image || null,
+ role: user.role || "user",
+ }))
);
-
- if (result) {
- setSearchResults(
- result.users.map((user: AdminUser) => ({
- id: user.id,
- name: user.name,
- email: user.email,
- image: user.image || null,
- role: user.role || "user",
- }))
- );
- }
- setSearchLoading(false);
- }, 300);
-
- return () => clearTimeout(timeoutId);
- },
- [fetchUsers]
- );
+ } catch {
+ setSearchResults([]);
+ }
+ setSearchLoading(false);
+ }, 300);
+ };
const handleSelectUser = (user: SearchUser) => {
setSelectedUser(user);
setQuery(user.name || user.email);
};
- const handleTransfer = async () => {
- if (!selectedUser) return;
-
- let success = false;
-
- if (isBulk) {
- // Bulk transfer
- const calendarIds = calendars.map((cal) => cal.id);
- success = await bulkTransferCalendars(calendarIds, selectedUser.id);
- } else {
- // Single transfer
- success = await transferCalendar(calendars[0].id, selectedUser.id);
- }
-
- if (success) {
- handleClose();
- onSuccess();
- }
- };
-
const handleClose = () => {
+ clearTimeout(searchTimeout.current ?? undefined);
setQuery("");
setSelectedUser(null);
setSearchResults([]);
+ setSearchLoading(false);
onOpenChange(false);
};
- const getUserInitials = (user: SearchUser) => {
- if (user.name) {
- return user.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- }
- return user.email.slice(0, 2).toUpperCase();
- };
+ const handleTransfer = async () => {
+ if (!selectedUser) return;
+
+ const success = isBulk
+ ? await bulkTransferCalendars(
+ calendars.map((cal) => cal.id),
+ selectedUser.id
+ )
+ : await transferCalendar(calendars[0].id, selectedUser.id);
- const getRoleBadgeClass = (role: string) => {
- switch (role) {
- case "superadmin":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- case "admin":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- default:
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
+ if (success) {
+ handleClose();
+ onSuccess();
}
};
- const showResults = useMemo(
- () => query.length >= 2 && !selectedUser && searchResults.length > 0,
- [query, selectedUser, searchResults]
- );
-
if (!canTransfer) {
return null;
}
+ const showResults = query.length >= 2 && !selectedUser && searchResults.length > 0;
+
return (
- <BaseSheet
+ <AdminFormPanel
open={open}
- onOpenChange={handleClose}
+ onOpenChange={(next) => (next ? onOpenChange(true) : handleClose())}
title={t("admin.calendars.transferOwnership")}
- description={
+ subtitle={
isBulk
- ? t("admin.calendars.transferMultipleDescription", {
- count: calendars.length,
- })
- : t("admin.calendars.transferSingleDescription", {
- name: calendars[0]?.name,
- })
+ ? t("admin.calendars.transferMultipleDescription", { count: calendars.length })
+ : calendars[0]?.name
}
- showSaveButton
onSave={handleTransfer}
- isSaving={isLoading}
+ isSaving={isTransferring}
saveDisabled={!selectedUser}
saveLabel={t("admin.calendars.transferButton")}
- maxWidth="md"
>
- <div className="space-y-6">
- {/* Calendar(s) Preview */}
- <div className="space-y-2">
- <Label>
- {isBulk
- ? t("admin.calendars.calendarsToTransfer")
- : t("admin.calendars.calendarToTransfer")}
- </Label>
- <div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-3 bg-muted/20">
- {calendars.map((calendar) => (
- <div
- key={calendar.id}
- className="flex items-center gap-3 p-2 rounded-md bg-background"
- >
- <div
- className="w-3 h-3 rounded-full shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {calendar.name}
- </p>
- {calendar.ownerId ? (
- <p className="text-xs text-muted-foreground truncate">
- {t("admin.calendars.currentOwner")}:{" "}
- {calendar.owner!.name}
- </p>
- ) : (
- <Badge
- variant="outline"
- className="bg-red-500/10 text-red-500 border-red-500/20 text-xs"
- >
- {t("admin.calendars.orphaned")}
- </Badge>
- )}
- </div>
+ <section>
+ <SectionLabel>
+ {isBulk
+ ? t("admin.calendars.calendarsToTransfer")
+ : t("admin.calendars.calendarToTransfer")}
+ </SectionLabel>
+ <div className="flex max-h-56 flex-col gap-2 overflow-y-auto">
+ {calendars.map((calendar) => (
+ <ListRow key={calendar.id} className="py-2.5">
+ <span
+ className="shift-rail size-2.5 shrink-0 rounded-full"
+ style={shiftVars(calendar.color)}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{calendar.name}</div>
+ {!isOrphaned(calendar) && (
+ <div className="truncate text-[12px] text-fg-tertiary">
+ {t("admin.calendars.currentOwner")}: {calendar.owner!.name}
+ </div>
+ )}
</div>
- ))}
- </div>
+ {isOrphaned(calendar) && <Pill tone="warning">{t("admin.calendars.orphaned")}</Pill>}
+ </ListRow>
+ ))}
+ </div>
+ </section>
+
+ <Field
+ label={t("admin.calendars.selectNewOwner")}
+ htmlFor="transfer-user-search"
+ hint={query.length < 2 ? t("admin.calendars.searchUserHint") : undefined}
+ >
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <Input
+ id="transfer-user-search"
+ type="text"
+ value={query}
+ onChange={(e) => handleSearch(e.target.value)}
+ placeholder={t("admin.calendars.searchUserPlaceholder")}
+ className={cn(inputClass, "pl-9 pr-10")}
+ autoComplete="off"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => handleSearch("")}
+ aria-label={t("admin.calendars.clearSelection")}
+ className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary hover:text-fg-strong"
+ >
+ <X className="size-4" />
+ </button>
+ )}
</div>
- {/* User Search */}
- <div className="space-y-2">
- <Label htmlFor="user-search">
- {t("admin.calendars.selectNewOwner")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- id="user-search"
- type="text"
- value={query}
- onChange={(e) => handleSearch(e.target.value)}
- placeholder={t("admin.calendars.searchUserPlaceholder")}
- className="pl-10 pr-10"
- autoComplete="off"
- />
- {query && (
+ {showResults && (
+ <div className="flex max-h-64 flex-col overflow-y-auto rounded-[11px] border border-line bg-surface-card">
+ {searchResults.map((user) => (
<button
+ key={user.id}
type="button"
- onClick={() => {
- setQuery("");
- setSelectedUser(null);
- }}
- className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ onClick={() => handleSelectUser(user)}
+ className="flex items-center gap-3 border-b border-line-subtle px-3.5 py-2.5 text-left transition-colors last:border-b-0 hover:bg-surface-panel"
>
- <X className="h-4 w-4" />
+ <UserRow user={user} />
</button>
- )}
+ ))}
</div>
+ )}
- {/* Search Results */}
- {showResults && (
- <div className="border rounded-lg divide-y max-h-64 overflow-y-auto bg-card">
- {searchResults.map((user) => (
- <button
- key={user.id}
- type="button"
- onClick={() => handleSelectUser(user)}
- className="w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors text-left"
- >
- <Avatar className="h-8 w-8">
- {user.image && <AvatarImage src={user.image} />}
- <AvatarFallback className="text-xs">
- {getUserInitials(user)}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">{user.name}</p>
- <p className="text-xs text-muted-foreground truncate">
- {user.email}
- </p>
- </div>
- <Badge
- variant="outline"
- className={getRoleBadgeClass(user.role)}
- >
- {t(`common.roles.${user.role}`)}
- </Badge>
- </button>
- ))}
- </div>
- )}
-
- {/* No Results */}
- {query.length >= 2 &&
- !selectedUser &&
- searchResults.length === 0 &&
- !searchLoading && (
- <p className="text-sm text-muted-foreground text-center py-4">
- {t("common.empty.noUsersFound")}
- </p>
- )}
-
- {/* Loading */}
- {searchLoading && (
- <p className="text-sm text-muted-foreground text-center py-4">
- {t("common.loading")}
- </p>
- )}
-
- {/* Hint */}
- {query.length < 2 && (
- <p className="text-xs text-muted-foreground">
- {t("admin.calendars.searchUserHint")}
- </p>
- )}
- </div>
+ {searchLoading && (
+ <p className="py-3 text-center text-[13px] text-fg-tertiary">{t("common.loading")}</p>
+ )}
- {/* Selected User Preview */}
- {selectedUser && (
- <div className="space-y-2">
- <Label>{t("admin.calendars.newOwner")}</Label>
- <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/20">
- <Avatar className="h-10 w-10">
- {selectedUser.image && <AvatarImage src={selectedUser.image} />}
- <AvatarFallback>{getUserInitials(selectedUser)}</AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {selectedUser.name}
- </p>
- <p className="text-xs text-muted-foreground truncate">
- {selectedUser.email}
- </p>
- </div>
- <Badge
- variant="outline"
- className={getRoleBadgeClass(selectedUser.role)}
- >
- {t(`common.roles.${selectedUser.role}`)}
- </Badge>
- </div>
- </div>
+ {query.length >= 2 && !selectedUser && searchResults.length === 0 && !searchLoading && (
+ <p className="py-3 text-center text-[13px] text-fg-tertiary">{t("common.empty.noUsersFound")}</p>
)}
- </div>
- </BaseSheet>
+ </Field>
+
+ {selectedUser && (
+ <section>
+ <SectionLabel>{t("admin.calendars.newOwner")}</SectionLabel>
+ <ListRow highlighted className="bg-brand-soft">
+ <UserRow user={selectedUser} selected />
+ </ListRow>
+ </section>
+ )}
+ </AdminFormPanel>
);
}
diff --git a/components/admin/confirm-name-delete-dialog.tsx b/components/admin/confirm-name-delete-dialog.tsx
new file mode 100644
index 0000000..6ac7a98
--- /dev/null
+++ b/components/admin/confirm-name-delete-dialog.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { TriangleAlert } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { PanelDialog } from "@/components/panel-dialog";
+import { Field, inputClass } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { cn } from "@/lib/utils";
+
+interface ConfirmNameDeleteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Typed back by the admin before the delete button unlocks */
+ name: string;
+ idPrefix: string;
+ title: string;
+ description: string;
+ warning: string;
+ understoodLabel: string;
+ confirmationLabel: string;
+ confirmationHint: string;
+ confirmLabel: string;
+ onConfirm: () => Promise<void>;
+}
+
+/** Irreversible admin delete: tick "understood" and type the name to unlock. */
+export function ConfirmNameDeleteDialog({
+ open,
+ onOpenChange,
+ name,
+ idPrefix,
+ title,
+ description,
+ warning,
+ understoodLabel,
+ confirmationLabel,
+ confirmationHint,
+ confirmLabel,
+ onConfirm,
+}: ConfirmNameDeleteDialogProps) {
+ const t = useTranslations();
+ const [confirmation, setConfirmation] = useState("");
+ const [understood, setUnderstood] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const isConfirmed = confirmation === name && understood;
+
+ const reset = () => {
+ setConfirmation("");
+ setUnderstood(false);
+ };
+
+ const handleConfirm = async () => {
+ if (!isConfirmed) return;
+
+ setIsSubmitting(true);
+ try {
+ await onConfirm();
+ reset();
+ onOpenChange(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleCancel = () => {
+ reset();
+ onOpenChange(false);
+ };
+
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={title}
+ description={description}
+ width="sm"
+ bodyClassName="flex flex-col gap-4"
+ footer={
+ <>
+ <Button
+ variant="outline"
+ onClick={handleCancel}
+ disabled={isSubmitting}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleConfirm}
+ disabled={!isConfirmed || isSubmitting}
+ className="h-10 flex-1 font-semibold"
+ >
+ {isSubmitting ? t("common.saving") : confirmLabel}
+ </Button>
+ </>
+ }
+ >
+ <StatusBanner tone="danger" icon={TriangleAlert}>
+ {warning}
+ </StatusBanner>
+
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id={`${idPrefix}-understood`}
+ checked={understood}
+ onCheckedChange={(checked) => setUnderstood(checked === true)}
+ className="mt-0.5"
+ />
+ <Label
+ htmlFor={`${idPrefix}-understood`}
+ className="cursor-pointer text-[13.5px] font-medium leading-snug text-fg-body"
+ >
+ {understoodLabel}
+ </Label>
+ </div>
+
+ <Field
+ label={confirmationLabel}
+ htmlFor={`${idPrefix}-confirmation`}
+ hint={confirmationHint}
+ >
+ <Input
+ id={`${idPrefix}-confirmation`}
+ value={confirmation}
+ onChange={(e) => setConfirmation(e.target.value)}
+ placeholder={name}
+ autoComplete="off"
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ </PanelDialog>
+ );
+}
diff --git a/components/admin/stats-cards.tsx b/components/admin/stats-cards.tsx
deleted file mode 100644
index 40e2056..0000000
--- a/components/admin/stats-cards.tsx
+++ /dev/null
@@ -1,214 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { useTranslations } from "next-intl";
-import {
- Users,
- Calendar,
- Share2,
- FolderOpen,
- Clock,
- Activity,
- LucideIcon,
-} from "lucide-react";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { cn } from "@/lib/utils";
-import type { AdminStats } from "@/hooks/useAdminStats";
-
-interface StatsCardProps {
- title: string;
- value: number | string;
- description?: string;
- icon: LucideIcon;
- variant?: "default" | "warning" | "success" | "info";
- href?: string;
- badge?: {
- text: string;
- variant: "default" | "secondary" | "destructive" | "outline";
- };
- isLoading?: boolean;
-}
-
-/**
- * Individual Stats Card Component
- *
- * Displays a single statistic with optional click navigation.
- */
-function StatsCard({
- title,
- value,
- description,
- icon: Icon,
- variant = "default",
- href,
- badge,
- isLoading = false,
-}: StatsCardProps) {
- const router = useRouter();
-
- const variantColors = {
- default: "text-blue-600 dark:text-blue-400",
- warning: "text-yellow-600 dark:text-yellow-400",
- success: "text-green-600 dark:text-green-400",
- info: "text-cyan-600 dark:text-cyan-400",
- };
-
- const handleClick = () => {
- if (href) {
- router.push(href);
- }
- };
-
- return (
- <Card
- className={cn(
- "transition-all",
- href && "cursor-pointer hover:shadow-md hover:scale-[1.02]"
- )}
- onClick={handleClick}
- >
- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
- <CardTitle className="text-sm font-medium">{title}</CardTitle>
- <Icon className={cn("h-4 w-4", variantColors[variant])} />
- </CardHeader>
- <CardContent>
- {isLoading ? (
- <div className="text-muted-foreground">-</div>
- ) : (
- <>
- <div className="flex items-center gap-2">
- <div className="text-2xl font-bold">{value}</div>
- {badge && (
- <Badge variant={badge.variant} className="text-xs">
- {badge.text}
- </Badge>
- )}
- </div>
- {description && (
- <p className="text-xs text-muted-foreground mt-1">
- {description}
- </p>
- )}
- </>
- )}
- </CardContent>
- </Card>
- );
-}
-
-interface StatsCardsGridProps {
- stats: AdminStats | null;
- isLoading: boolean;
-}
-
-/**
- * Admin Stats Cards Grid
- *
- * Displays system statistics in a responsive grid layout.
- *
- * Features:
- * - Responsive layout (1 col mobile, 2-3 cols desktop)
- * - Color-coded by importance/type
- * - Clickable cards navigate to relevant pages
- * - Loading skeleton states
- * - Warning indicators (e.g., orphaned calendars)
- */
-export function StatsCardsGrid({ stats, isLoading }: StatsCardsGridProps) {
- const t = useTranslations();
-
- return (
- <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
- {/* Total Users */}
- <StatsCard
- title={t("admin.stats.totalUsers")}
- value={isLoading ? "-" : stats?.users.total || 0}
- description={
- isLoading
- ? undefined
- : t("admin.stats.usersByRole", {
- superadmin: stats?.users.superadmin || 0,
- admin: stats?.users.admin || 0,
- user: stats?.users.user || 0,
- })
- }
- icon={Users}
- variant="info"
- href="/admin/users"
- isLoading={isLoading}
- />
-
- {/* Total Calendars */}
- <StatsCard
- title={t("admin.stats.totalCalendars")}
- value={isLoading ? "-" : stats?.calendars.total || 0}
- description={t("admin.stats.calendarsDescription")}
- icon={Calendar}
- variant="default"
- href="/admin/calendars"
- isLoading={isLoading}
- />
-
- {/* Active Shares */}
- <StatsCard
- title={t("admin.stats.activeShares")}
- value={isLoading ? "-" : stats?.shares.active || 0}
- description={
- isLoading
- ? undefined
- : t("admin.stats.sharesDescription", {
- user: stats?.shares.user || 0,
- token: stats?.shares.token || 0,
- })
- }
- icon={Share2}
- variant="success"
- isLoading={isLoading}
- />
-
- {/* Orphaned Calendars */}
- <StatsCard
- title={t("admin.stats.orphanedCalendars")}
- value={isLoading ? "-" : stats?.calendars.orphaned || 0}
- description={t("admin.stats.orphanedDescription")}
- icon={FolderOpen}
- variant={
- !isLoading && stats && stats.calendars.orphaned > 0
- ? "warning"
- : "default"
- }
- href="/admin/calendars"
- badge={
- !isLoading && stats && stats.calendars.orphaned > 0
- ? {
- text: t("admin.stats.needsAttention"),
- variant: "destructive",
- }
- : undefined
- }
- isLoading={isLoading}
- />
-
- {/* Total Shifts */}
- <StatsCard
- title={t("admin.stats.totalShifts")}
- value={isLoading ? "-" : stats?.shifts.total || 0}
- description={t("admin.stats.shiftsDescription")}
- icon={Clock}
- variant="default"
- isLoading={isLoading}
- />
-
- {/* Recent Activity */}
- <StatsCard
- title={t("admin.stats.recentActivity")}
- value={isLoading ? "-" : stats?.activity.recent || 0}
- description={t("admin.stats.last7Days")}
- icon={Activity}
- variant="info"
- href="/admin/logs"
- isLoading={isLoading}
- />
- </div>
- );
-}
diff --git a/components/admin/user-ban-dialog.tsx b/components/admin/user-ban-dialog.tsx
index ba2ed34..bbe1538 100644
--- a/components/admin/user-ban-dialog.tsx
+++ b/components/admin/user-ban-dialog.tsx
@@ -2,20 +2,14 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { AlertTriangle } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { PanelDialog } from "@/components/panel-dialog";
+import { Field, ToggleRow, inputClass } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
import type { AdminUser } from "@/hooks/useAdminUsers";
interface UserBanDialogProps {
@@ -25,30 +19,27 @@ interface UserBanDialogProps {
onConfirm: (reason: string, expiresAt?: Date) => Promise<void>;
}
-export function UserBanDialog({
- open,
- onOpenChange,
- user,
- onConfirm,
-}: UserBanDialogProps) {
+export function UserBanDialog({ open, onOpenChange, user, onConfirm }: UserBanDialogProps) {
const t = useTranslations();
const [reason, setReason] = useState("");
const [isPermanent, setIsPermanent] = useState(true);
const [expiresAt, setExpiresAt] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
+ const reset = () => {
+ setReason("");
+ setIsPermanent(true);
+ setExpiresAt("");
+ };
+
const handleConfirm = async () => {
if (!reason.trim()) return;
setIsSubmitting(true);
try {
- const expirationDate =
- isPermanent || !expiresAt ? undefined : new Date(expiresAt);
+ const expirationDate = isPermanent || !expiresAt ? undefined : parseLocalDate(expiresAt);
await onConfirm(reason.trim(), expirationDate);
- // Reset form
- setReason("");
- setIsPermanent(true);
- setExpiresAt("");
+ reset();
onOpenChange(false);
} finally {
setIsSubmitting(false);
@@ -56,84 +47,25 @@ export function UserBanDialog({
};
const handleCancel = () => {
- // Reset form
- setReason("");
- setIsPermanent(true);
- setExpiresAt("");
+ reset();
onOpenChange(false);
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("admin.banUser")}</DialogTitle>
- <DialogDescription>
- {t("admin.banUserConfirm", {
- name: user.name || user.email,
- })}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <div className="flex gap-3 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
- <AlertTriangle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" />
- <p className="text-sm text-yellow-800 dark:text-yellow-200">
- {t("admin.banWarning")}
- </p>
- </div>
-
- {/* Reason */}
- <div className="space-y-2">
- <Label htmlFor="reason">
- {t("admin.banReason")} <span className="text-destructive">*</span>
- </Label>
- <Textarea
- id="reason"
- value={reason}
- onChange={(e) => setReason(e.target.value)}
- placeholder={t("admin.banReasonPlaceholder")}
- rows={4}
- className="resize-none"
- />
- </div>
-
- {/* Permanent Ban Checkbox */}
- <div className="flex items-center space-x-2">
- <Checkbox
- id="permanent"
- checked={isPermanent}
- onCheckedChange={(checked) => setIsPermanent(checked === true)}
- />
- <Label
- htmlFor="permanent"
- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
- >
- {t("admin.permanentBan")}
- </Label>
- </div>
-
- {/* Expiration Date */}
- {!isPermanent && (
- <div className="space-y-2">
- <Label htmlFor="expires">{t("admin.banExpires")}</Label>
- <Input
- id="expires"
- type="date"
- value={expiresAt}
- onChange={(e) => setExpiresAt(e.target.value)}
- min={new Date().toISOString().split("T")[0]}
- />
- </div>
- )}
- </div>
-
- <DialogFooter>
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.banUser")}
+ description={t("admin.banUserConfirm", { name: user.name || user.email })}
+ width="sm"
+ bodyClassName="flex flex-col gap-4"
+ footer={
+ <>
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
{t("common.cancel")}
</Button>
@@ -141,11 +73,47 @@ export function UserBanDialog({
variant="destructive"
onClick={handleConfirm}
disabled={!reason.trim() || isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
{isSubmitting ? t("common.saving") : t("admin.confirmBan")}
</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ <StatusBanner tone="warning" icon={TriangleAlert}>
+ {t("admin.banWarning")}
+ </StatusBanner>
+
+ <Field label={t("admin.banReason")} htmlFor="ban-reason">
+ <Textarea
+ id="ban-reason"
+ value={reason}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder={t("admin.banReasonPlaceholder")}
+ rows={3}
+ className="resize-none rounded-[9px] px-3 text-[14px]"
+ />
+ </Field>
+
+ <ToggleRow
+ id="ban-permanent"
+ title={t("admin.permanentBan")}
+ checked={isPermanent}
+ onCheckedChange={setIsPermanent}
+ />
+
+ {!isPermanent && (
+ <Field label={t("admin.banExpires")} htmlFor="ban-expires">
+ <Input
+ id="ban-expires"
+ type="date"
+ value={expiresAt}
+ onChange={(e) => setExpiresAt(e.target.value)}
+ min={formatDateToLocal(new Date())}
+ className={inputClass}
+ />
+ </Field>
+ )}
+ </PanelDialog>
);
}
diff --git a/components/admin/user-delete-dialog.tsx b/components/admin/user-delete-dialog.tsx
index c910937..a3f18f9 100644
--- a/components/admin/user-delete-dialog.tsx
+++ b/components/admin/user-delete-dialog.tsx
@@ -1,20 +1,7 @@
"use client";
-import { useState } from "react";
import { useTranslations } from "next-intl";
-import { AlertTriangle } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
-import { Input } from "@/components/ui/input";
-import { Checkbox } from "@/components/ui/checkbox";
+import { ConfirmNameDeleteDialog } from "@/components/admin/confirm-name-delete-dialog";
import type { AdminUser } from "@/hooks/useAdminUsers";
interface UserDeleteDialogProps {
@@ -24,113 +11,23 @@ interface UserDeleteDialogProps {
onConfirm: () => Promise<void>;
}
-export function UserDeleteDialog({
- open,
- onOpenChange,
- user,
- onConfirm,
-}: UserDeleteDialogProps) {
+export function UserDeleteDialog({ open, onOpenChange, user, onConfirm }: UserDeleteDialogProps) {
const t = useTranslations();
- const [confirmation, setConfirmation] = useState("");
- const [understood, setUnderstood] = useState(false);
- const [isSubmitting, setIsSubmitting] = useState(false);
-
- const isConfirmed = confirmation === user.name && understood;
-
- const handleConfirm = async () => {
- if (!isConfirmed) return;
-
- setIsSubmitting(true);
- try {
- await onConfirm();
- // Reset form
- setConfirmation("");
- setUnderstood(false);
- onOpenChange(false);
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const handleCancel = () => {
- // Reset form
- setConfirmation("");
- setUnderstood(false);
- onOpenChange(false);
- };
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("admin.deleteUser")}</DialogTitle>
- <DialogDescription>
- {t("admin.deleteUserConfirm", {
- name: user.name || user.email,
- })}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <div className="flex gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-900">
- <AlertTriangle className="h-5 w-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
- <p className="text-sm text-red-800 dark:text-red-200">
- {t("admin.deleteWarning")}
- </p>
- </div>
-
- {/* Checkbox Confirmation */}
- <div className="flex items-start space-x-3">
- <Checkbox
- id="understood"
- checked={understood}
- onCheckedChange={(checked) => setUnderstood(checked === true)}
- className="mt-1"
- />
- <Label
- htmlFor="understood"
- className="text-sm font-medium leading-normal cursor-pointer"
- >
- {t("admin.deleteUnderstood")}
- </Label>
- </div>
-
- {/* Name Confirmation */}
- <div className="space-y-2">
- <Label htmlFor="confirmation">
- {t("admin.deleteConfirmation", { name: user.name })}
- </Label>
- <Input
- id="confirmation"
- value={confirmation}
- onChange={(e) => setConfirmation(e.target.value)}
- placeholder={user.name}
- className="font-mono"
- />
- <p className="text-xs text-muted-foreground">
- {t("admin.deleteConfirmationHint")}
- </p>
- </div>
- </div>
-
- <DialogFooter>
- <Button
- variant="outline"
- onClick={handleCancel}
- disabled={isSubmitting}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="destructive"
- onClick={handleConfirm}
- disabled={!isConfirmed || isSubmitting}
- >
- {isSubmitting ? t("common.saving") : t("admin.confirmDelete")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <ConfirmNameDeleteDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ name={user.name}
+ idPrefix="delete-user"
+ title={t("admin.deleteUser")}
+ description={t("admin.deleteUserConfirm", { name: user.name || user.email })}
+ warning={t("admin.deleteWarning")}
+ understoodLabel={t("admin.deleteUnderstood")}
+ confirmationLabel={t("admin.deleteConfirmation", { name: user.name })}
+ confirmationHint={t("admin.deleteConfirmationHint")}
+ confirmLabel={t("admin.confirmDelete")}
+ onConfirm={onConfirm}
+ />
);
}
diff --git a/components/admin/user-details-sheet.tsx b/components/admin/user-details-sheet.tsx
index 3272833..19d8f34 100644
--- a/components/admin/user-details-sheet.tsx
+++ b/components/admin/user-details-sheet.tsx
@@ -1,32 +1,21 @@
"use client";
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
-import { useLocale } from "next-intl";
-import { format, formatDistanceToNow } from "date-fns";
-import {
- Edit,
- Key,
- Ban,
- ShieldOff,
- Trash2,
- Calendar,
- Share2,
- Monitor,
-} from "lucide-react";
-import { BaseSheet } from "@/components/ui/base-sheet";
+import { useQuery } from "@tanstack/react-query";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { ChevronRight, KeyRound, Lock, LockOpen, Pencil, Trash2, type LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import { useAdminUsers, type UserDetails } from "@/hooks/useAdminUsers";
-import {
- useCanEditUser,
- useCanBanUser,
- useCanDeleteUser,
- useCanResetPassword,
-} from "@/hooks/useAdminAccess";
+import { ListRow, Pill } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { AdminDetailPanel } from "@/components/admin/admin-detail-panel";
+import { DetailSection, RolePill, StatTile, StatusPill, UserAvatar } from "@/components/admin/admin-kit";
+import { fetchAdminUserDetails } from "@/hooks/useAdminUsers";
+import { useUserPermissions } from "@/hooks/useAdminAccess";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import { getDateLocale } from "@/lib/locales";
+import { queryKeys } from "@/lib/query-keys";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
interface UserDetailsSheetProps {
open: boolean;
@@ -39,6 +28,51 @@ interface UserDetailsSheetProps {
onDelete: () => void;
}
+function ActionButton({
+ icon: Icon,
+ label,
+ onClick,
+ danger,
+ className,
+}: {
+ icon: LucideIcon;
+ label: string;
+ onClick: () => void;
+ danger?: boolean;
+ className?: string;
+}) {
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={onClick}
+ className={cn(
+ "h-[38px] gap-2 rounded-[9px] px-2 text-[13.5px] font-semibold text-fg-body",
+ danger && "border-danger-line text-danger hover:bg-danger-surface hover:text-danger",
+ className
+ )}
+ >
+ <Icon className={cn("size-[15px]", !danger && "text-fg-secondary")} />
+ <span className="truncate">{label}</span>
+ </Button>
+ );
+}
+
+/** Phone variant of a secondary action: a full-width row with a chevron (13i). */
+function ActionRow({ icon: Icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="flex h-[46px] w-full items-center gap-2.5 rounded-[10px] border border-line bg-surface-card px-[13px] text-left transition-colors hover:bg-surface-panel"
+ >
+ <Icon className="size-[17px] text-fg-secondary" />
+ <span className="flex-1 truncate text-[14px] font-semibold text-fg-body">{label}</span>
+ <ChevronRight className="size-4 text-fg-faint" />
+ </button>
+ );
+}
+
export function UserDetailsSheet({
open,
onOpenChange,
@@ -50,304 +84,187 @@ export function UserDetailsSheet({
onDelete,
}: UserDetailsSheetProps) {
const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const { fetchUserDetails, isLoading } = useAdminUsers();
- const [userDetails, setUserDetails] = useState<UserDetails | null>(null);
-
- const canEdit = useCanEditUser(userDetails);
- const canBan = useCanBanUser(userDetails);
- const canDelete = useCanDeleteUser(userDetails);
- const canResetPassword = useCanResetPassword(userDetails);
+ const dateLocale = getDateLocale(useLocale());
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const { data: userDetails = null, isError: loadFailed } = useQuery({
+ queryKey: queryKeys.admin.users.detail(userId),
+ queryFn: () => fetchAdminUserDetails(userId),
+ enabled: open,
+ retry: false,
+ });
- useEffect(() => {
- if (!open) return;
+ const { canEdit, canBan, canDelete, canResetPassword } = useUserPermissions(userDetails);
- const loadDetails = async () => {
- const details = await fetchUserDetails(userId);
- if (details) {
- setUserDetails(details);
- }
- };
+ const user = userDetails;
+ const date = (value: Date, pattern = "PP") => format(value, pattern, { locale: dateLocale });
+ const hasActions = canEdit || canResetPassword || canBan || canDelete;
- loadDetails();
- }, [open, userId, fetchUserDetails]);
+ const banAction =
+ user && canBan
+ ? user.banned
+ ? { icon: LockOpen, label: t("admin.unbanUser"), onClick: onUnban }
+ : { icon: Lock, label: t("adminUsers.ban"), onClick: onBan }
+ : null;
- const getUserInitials = () => {
- if (!userDetails) return "?";
- if (userDetails.name) {
- return userDetails.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- }
- if (userDetails.email) {
- return userDetails.email.slice(0, 2).toUpperCase();
- }
- return "?";
- };
+ const phoneFooter = user && hasActions && (
+ <div className="flex w-full flex-col gap-2">
+ {banAction && <ActionRow {...banAction} />}
+ {canResetPassword && (
+ <ActionRow icon={KeyRound} label={t("admin.resetPassword")} onClick={onResetPassword} />
+ )}
+ {(canEdit || canDelete) && (
+ <div className="flex gap-2">
+ {canEdit && (
+ <ActionButton
+ icon={Pencil}
+ label={t("adminUsers.edit")}
+ onClick={onEdit}
+ className="h-[46px] flex-1 text-[14px]"
+ />
+ )}
+ {canDelete && (
+ <ActionButton
+ icon={Trash2}
+ label={t("common.delete")}
+ onClick={onDelete}
+ danger
+ className="h-[46px] flex-1 text-[14px]"
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
- const getRoleBadgeClass = (role: string) => {
- switch (role) {
- case "superadmin":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- case "admin":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- default:
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- }
- };
+ const desktopFooter = (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.close")}
+ </Button>
+ );
return (
- <BaseSheet
+ <AdminDetailPanel
open={open}
onOpenChange={onOpenChange}
title={t("admin.userDetails")}
- description={t("admin.userDetailsDescription")}
- maxWidth="lg"
+ subtitle={user?.name || user?.email}
+ footer={desktop ? desktopFooter : phoneFooter || undefined}
>
- {isLoading && !userDetails ? (
- <div className="text-center py-12 text-muted-foreground">
- {t("common.loading")}
- </div>
- ) : userDetails ? (
- <div className="space-y-6">
- {/* User Info Card */}
- <div className="flex items-start gap-4 p-4 rounded-lg border bg-muted/30">
- <Avatar className="h-16 w-16">
- {userDetails.image && <AvatarImage src={userDetails.image} />}
- <AvatarFallback className="text-lg">
- {getUserInitials()}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
- <h3 className="text-lg font-semibold truncate">
- {userDetails.name}
- </h3>
- <span
- className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getRoleBadgeClass(
- userDetails.role || "user"
- )}`}
- >
- {t(`common.roles.${userDetails.role}`)}
+ {!user ? (
+ <p className="py-12 text-center text-[13px] text-fg-tertiary">
+ {loadFailed ? t("admin.userNotFound") : t("common.loading")}
+ </p>
+ ) : (
+ <>
+ <div className="flex items-center gap-[13px]">
+ <UserAvatar name={user.name || user.email} image={user.image} size={44} />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="truncate text-[17px] font-semibold tracking-[-0.01em] text-fg-strong">
+ {user.name}
</span>
- {userDetails.banned && (
- <Badge variant="destructive">{t("admin.banned")}</Badge>
- )}
+ <RolePill role={user.role} />
+ <StatusPill banned={user.banned} />
</div>
- <p className="text-sm text-muted-foreground truncate">
- {userDetails.email}
- </p>
- <div className="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
- <span>
- {t("admin.joined")}{" "}
- {format(userDetails.createdAt, "PP", {
- locale: dateLocale,
- })}
- </span>
- {userDetails.lastActivity && (
- <span>
- {t("common.time.lastActive")}{" "}
- {formatDistanceToNow(userDetails.lastActivity, {
- addSuffix: true,
- locale: dateLocale,
- })}
- </span>
- )}
+ <div className="mt-0.5 truncate text-[13px] text-fg-secondary">{user.email}</div>
+ <div className="mt-0.5 text-[12px] text-fg-faint">
+ {t("adminUsers.joinedOn", { date: date(user.createdAt, "PPP") })}
</div>
</div>
</div>
- {/* Ban Information */}
- {userDetails.banned && (
- <div className="p-4 rounded-lg border bg-destructive/5 border-destructive/20">
- <h4 className="text-sm font-semibold text-destructive mb-2">
- {t("admin.banned")}
- </h4>
- {userDetails.banReason && (
- <p className="text-sm mb-2">{userDetails.banReason}</p>
- )}
- <p className="text-xs text-muted-foreground">
- {userDetails.banExpires
- ? t("admin.bannedUntil", {
- date: format(userDetails.banExpires, "PPP", {
- locale: dateLocale,
- }),
- })
- : t("admin.bannedPermanently")}
- </p>
- </div>
+ {user.banned && (
+ <StatusBanner
+ tone="danger"
+ icon={Lock}
+ title={
+ user.banExpires
+ ? t("admin.bannedUntil", { date: date(user.banExpires, "PPP") })
+ : t("admin.bannedPermanently")
+ }
+ >
+ {user.banReason && t("adminUsers.banReasonQuoted", { reason: user.banReason })}
+ </StatusBanner>
)}
- {/* Quick Actions */}
- <div className="flex flex-wrap gap-2">
- {canEdit && (
- <Button size="sm" variant="outline" onClick={onEdit}>
- <Edit className="h-4 w-4 mr-2" />
- {t("admin.editUser")}
- </Button>
- )}
- {canResetPassword && (
- <Button size="sm" variant="outline" onClick={onResetPassword}>
- <Key className="h-4 w-4 mr-2" />
- {t("admin.resetPassword")}
- </Button>
- )}
- {canBan && !userDetails.banned && (
- <Button size="sm" variant="outline" onClick={onBan}>
- <Ban className="h-4 w-4 mr-2" />
- {t("admin.banUser")}
- </Button>
- )}
- {canBan && userDetails.banned && (
- <Button size="sm" variant="outline" onClick={onUnban}>
- <ShieldOff className="h-4 w-4 mr-2" />
- {t("admin.unbanUser")}
- </Button>
- )}
- {canDelete && (
- <Button size="sm" variant="destructive" onClick={onDelete}>
- <Trash2 className="h-4 w-4 mr-2" />
- {t("admin.deleteUser")}
- </Button>
- )}
- </div>
-
- <Separator />
-
- {/* Statistics */}
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("common.stats.statistics")}
- </h4>
- <div className="grid grid-cols-3 gap-4">
- <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
- <Calendar className="h-5 w-5 text-primary" />
- <div>
- <p className="text-2xl font-bold">
- {userDetails.ownedCalendars.length}
- </p>
- <p className="text-xs text-muted-foreground">
- {t("admin.ownedCalendars")}
- </p>
- </div>
- </div>
- <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
- <Share2 className="h-5 w-5 text-primary" />
- <div>
- <p className="text-2xl font-bold">
- {userDetails.sharedCalendars.length}
- </p>
- <p className="text-xs text-muted-foreground">
- {t("common.labels.sharedCalendars")}
- </p>
- </div>
- </div>
- <div className="flex items-center gap-3 p-3 rounded-lg border bg-muted/30">
- <Monitor className="h-5 w-5 text-primary" />
- <div>
- <p className="text-2xl font-bold">
- {userDetails.sessionsCount}
- </p>
- <p className="text-xs text-muted-foreground">
- {t("common.auth.activeSessions")}
- </p>
- </div>
- </div>
+ <DetailSection label={t("adminUsers.numbers")}>
+ <div className="grid grid-cols-3 gap-2.5">
+ <StatTile label={t("admin.ownedCalendars")} value={user.ownedCalendars.length} />
+ <StatTile label={t("common.labels.sharedCalendars")} value={user.sharedCalendars.length} />
+ <StatTile label={t("common.auth.activeSessions")} value={user.sessionsCount} />
</div>
- </div>
+ </DetailSection>
- {/* Owned Calendars */}
- {userDetails.ownedCalendars.length > 0 && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("admin.ownedCalendars")} (
- {userDetails.ownedCalendars.length})
- </h4>
- <div className="space-y-2">
- {userDetails.ownedCalendars.map((calendar) => (
- <div
- key={calendar.id}
- className="flex items-center gap-3 p-3 rounded-lg border bg-muted/20"
- >
- <div
- className="h-4 w-4 rounded-full flex-shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <span className="text-sm truncate">{calendar.name}</span>
- </div>
- ))}
- </div>
- </div>
- </>
+ {user.ownedCalendars.length > 0 && (
+ <DetailSection label={t("admin.ownedCalendars")}>
+ {user.ownedCalendars.map((calendar) => (
+ <ListRow key={calendar.id} className="py-2.5">
+ <span
+ className="shift-rail size-2.5 shrink-0 rounded-full"
+ style={shiftVars(calendar.color)}
+ />
+ <span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold text-fg-strong">
+ {calendar.name}
+ </span>
+ </ListRow>
+ ))}
+ </DetailSection>
)}
- {/* Shared Calendars */}
- {userDetails.sharedCalendars.length > 0 && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("common.labels.sharedCalendars")} (
- {userDetails.sharedCalendars.length})
- </h4>
- <div className="space-y-2">
- {userDetails.sharedCalendars.map((share) => (
- <div
- key={share.id}
- className="flex items-center justify-between gap-3 p-3 rounded-lg border bg-muted/20"
- >
- <span className="text-sm truncate">{share.name}</span>
- <Badge variant="outline" className="text-xs">
- {t(`common.labels.permissions.${share.permission}`)}
- </Badge>
- </div>
- ))}
- </div>
- </div>
- </>
+ {user.sharedCalendars.length > 0 && (
+ <DetailSection label={t("common.labels.sharedCalendars")}>
+ {user.sharedCalendars.map((share) => (
+ <ListRow key={share.id} className="py-2.5">
+ <span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold text-fg-strong">
+ {share.name}
+ </span>
+ <Pill>
+ {share.permission === "admin"
+ ? t("common.labels.permissions.admin")
+ : share.permission === "write"
+ ? t("common.labels.permissions.write")
+ : t("common.labels.permissions.read")}
+ </Pill>
+ </ListRow>
+ ))}
+ </DetailSection>
+ )}
+
+ {user.accounts.length > 0 && (
+ <DetailSection label={t("common.auth.connectedAccounts")}>
+ {user.accounts.map((account) => (
+ <ListRow key={account.id} className="py-[11px]">
+ <KeyRound className="size-4 shrink-0 text-fg-secondary" />
+ <span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold capitalize text-fg-strong">
+ {account.providerId}
+ </span>
+ <span className="font-mono text-[12px] text-fg-tertiary">{date(account.createdAt)}</span>
+ </ListRow>
+ ))}
+ </DetailSection>
)}
- {/* Connected Accounts */}
- {userDetails.accounts.length > 0 && (
- <>
- <Separator />
- <div>
- <h4 className="text-sm font-medium mb-3">
- {t("common.auth.connectedAccounts")} (
- {userDetails.accounts.length})
- </h4>
- <div className="space-y-2">
- {userDetails.accounts.map((account) => (
- <div
- key={account.id}
- className="flex items-center justify-between gap-3 p-3 rounded-lg border bg-muted/20"
- >
- <span className="text-sm font-medium capitalize">
- {account.providerId}
- </span>
- <span className="text-xs text-muted-foreground">
- {format(account.createdAt, "PP", {
- locale: dateLocale,
- })}
- </span>
- </div>
- ))}
- </div>
+ {desktop && hasActions && (
+ <DetailSection label={t("adminUsers.actions")}>
+ <div className="grid grid-cols-2 gap-2">
+ {canEdit && <ActionButton icon={Pencil} label={t("adminUsers.edit")} onClick={onEdit} />}
+ {canResetPassword && (
+ <ActionButton icon={KeyRound} label={t("admin.resetPassword")} onClick={onResetPassword} />
+ )}
+ {banAction && <ActionButton {...banAction} />}
+ {canDelete && (
+ <ActionButton icon={Trash2} label={t("common.delete")} onClick={onDelete} danger />
+ )}
</div>
- </>
+ </DetailSection>
)}
- </div>
- ) : (
- <div className="text-center py-8 text-muted-foreground">
- {t("admin.userNotFound")}
- </div>
+ </>
)}
- </BaseSheet>
+ </AdminDetailPanel>
);
}
diff --git a/components/admin/user-edit-sheet.tsx b/components/admin/user-edit-sheet.tsx
index 447aa39..64a6aa2 100644
--- a/components/admin/user-edit-sheet.tsx
+++ b/components/admin/user-edit-sheet.tsx
@@ -2,54 +2,36 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { BaseSheet } from "@/components/ui/base-sheet";
-import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { useAdminUsers, type AdminUser } from "@/hooks/useAdminUsers";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Field, inputClass } from "@/components/form-kit";
+import { AdminFormPanel } from "@/components/admin/admin-form-panel";
+import { useAdminUserActions, type AdminUser } from "@/hooks/useAdminUsers";
import { useCanEditUser, useCanChangeUserRole } from "@/hooks/useAdminAccess";
interface UserEditSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
user: AdminUser;
- onSuccess: () => void;
}
-export function UserEditSheet({
- open,
- onOpenChange,
- user,
- onSuccess,
-}: UserEditSheetProps) {
+export function UserEditSheet({ open, onOpenChange, user }: UserEditSheetProps) {
const t = useTranslations();
- const { updateUser, isLoading } = useAdminUsers();
+ const { updateUser, isUpdating } = useAdminUserActions();
const canEdit = useCanEditUser(user);
const canChangeRole = useCanChangeUserRole(user);
- // State will reset when component remounts (via key prop)
+ // Resets when the parent remounts this component via its key
const [name, setName] = useState(user.name);
const [email, setEmail] = useState(user.email);
const [role, setRole] = useState(user.role || "user");
- // Track if form has changes
- const hasChanges =
- name !== user.name || email !== user.email || role !== user.role;
+ const hasChanges = name !== user.name || email !== user.email || role !== user.role;
if (!canEdit) {
return null;
}
- const handleOpenChange = (newOpen: boolean) => {
- onOpenChange(newOpen);
- };
-
const handleSave = async () => {
const updates: { name?: string; email?: string; role?: string } = {};
@@ -58,77 +40,55 @@ export function UserEditSheet({
if (canChangeRole && role !== user.role) updates.role = role;
const success = await updateUser(user.id, updates);
- if (success) {
- onSuccess();
- handleOpenChange(false);
- }
+ if (success) onOpenChange(false);
};
return (
- <BaseSheet
+ <AdminFormPanel
open={open}
- onOpenChange={handleOpenChange}
+ onOpenChange={onOpenChange}
title={t("admin.editUser")}
- description={t("admin.editUserDescription")}
- showSaveButton
+ subtitle={user.name || user.email}
onSave={handleSave}
- isSaving={isLoading}
+ isSaving={isUpdating}
saveDisabled={!hasChanges}
hasUnsavedChanges={hasChanges}
- maxWidth="md"
>
- <div className="space-y-6">
- {/* Name */}
- <div className="space-y-2">
- <Label htmlFor="name">
- {t("common.labels.name")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <Input
- id="name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder={t("admin.namePlaceholder")}
- />
- </div>
+ <Field label={t("common.labels.name")} htmlFor="admin-user-name">
+ <Input
+ id="admin-user-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("admin.namePlaceholder")}
+ className={inputClass}
+ />
+ </Field>
- {/* Email */}
- <div className="space-y-2">
- <Label htmlFor="email">
- {t("common.labels.email")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <Input
- id="email"
- type="email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- placeholder={t("admin.emailPlaceholder")}
- />
- </div>
+ <Field label={t("common.labels.email")} htmlFor="admin-user-email">
+ <Input
+ id="admin-user-email"
+ type="email"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ placeholder={t("admin.emailPlaceholder")}
+ className={inputClass}
+ />
+ </Field>
- {/* Role */}
- {canChangeRole && (
- <div className="space-y-2">
- <Label htmlFor="role">{t("admin.role")}</Label>
- <Select value={role} onValueChange={setRole}>
- <SelectTrigger id="role">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="user">{t("common.roles.user")}</SelectItem>
- <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>
- <SelectItem value="superadmin">
- {t("common.roles.superadmin")}
- </SelectItem>
- </SelectContent>
- </Select>
- <p className="text-xs text-muted-foreground">
- {t("admin.roleChangeWarning")}
- </p>
- </div>
- )}
- </div>
- </BaseSheet>
+ {canChangeRole && (
+ <Field label={t("admin.role")} htmlFor="admin-user-role" hint={t("admin.roleChangeWarning")}>
+ <Select value={role} onValueChange={setRole}>
+ <SelectTrigger id="admin-user-role" className="h-10 w-full rounded-[9px] px-3 text-[14px] data-[size=default]:h-10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="user">{t("common.roles.user")}</SelectItem>
+ <SelectItem value="admin">{t("common.roles.admin")}</SelectItem>
+ <SelectItem value="superadmin">{t("common.roles.superadmin")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+ )}
+ </AdminFormPanel>
);
}
diff --git a/components/admin/user-password-reset-dialog.tsx b/components/admin/user-password-reset-dialog.tsx
index 8913c39..e4c38d6 100644
--- a/components/admin/user-password-reset-dialog.tsx
+++ b/components/admin/user-password-reset-dialog.tsx
@@ -2,19 +2,14 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { Eye, EyeOff, Copy, RefreshCw, AlertCircle } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { Copy, Eye, EyeOff, RefreshCw, TriangleAlert } from "lucide-react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
-import { toast } from "sonner";
+import { PanelDialog } from "@/components/panel-dialog";
+import { Field, inputClass } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import { cn } from "@/lib/utils";
import type { AdminUser } from "@/hooks/useAdminUsers";
interface UserPasswordResetDialogProps {
@@ -24,6 +19,53 @@ interface UserPasswordResetDialogProps {
onConfirm: (newPassword: string) => Promise<void>;
}
+const CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
+
+function randomPassword(length = 16) {
+ const values = crypto.getRandomValues(new Uint32Array(length));
+ return Array.from(values, (v) => CHARSET[v % CHARSET.length]).join("");
+}
+
+function PasswordInput({
+ id,
+ value,
+ onChange,
+ visible,
+ onToggle,
+ placeholder,
+}: {
+ id: string;
+ value: string;
+ onChange: (value: string) => void;
+ visible: boolean;
+ onToggle: () => void;
+ placeholder: string;
+}) {
+ const t = useTranslations();
+ const Icon = visible ? EyeOff : Eye;
+ return (
+ <div className="relative">
+ <Input
+ id={id}
+ type={visible ? "text" : "password"}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ autoComplete="new-password"
+ className={cn(inputClass, "pr-10", visible && value && "font-mono")}
+ />
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-label={visible ? t("adminUsers.hidePassword") : t("adminUsers.showPassword")}
+ className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:text-fg-strong"
+ >
+ <Icon className="size-4" />
+ </button>
+ </div>
+ );
+}
+
export function UserPasswordResetDialog({
open,
onOpenChange,
@@ -41,13 +83,7 @@ export function UserPasswordResetDialog({
const isValid = password.length >= 8 && passwordsMatch;
const generateRandomPassword = () => {
- const length = 16;
- const charset =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
- let newPassword = "";
- for (let i = 0; i < length; i++) {
- newPassword += charset.charAt(Math.floor(Math.random() * charset.length));
- }
+ const newPassword = randomPassword();
setPassword(newPassword);
setConfirmPassword(newPassword);
setShowPassword(true);
@@ -59,17 +95,20 @@ export function UserPasswordResetDialog({
toast.success(t("common.copied", { item: t("common.labels.password") }));
};
+ const reset = () => {
+ setPassword("");
+ setConfirmPassword("");
+ setShowPassword(false);
+ setShowConfirmPassword(false);
+ };
+
const handleConfirm = async () => {
if (!isValid) return;
setIsSubmitting(true);
try {
await onConfirm(password);
- // Reset form
- setPassword("");
- setConfirmPassword("");
- setShowPassword(false);
- setShowConfirmPassword(false);
+ reset();
onOpenChange(false);
} finally {
setIsSubmitting(false);
@@ -77,142 +116,91 @@ export function UserPasswordResetDialog({
};
const handleCancel = () => {
- // Reset form
- setPassword("");
- setConfirmPassword("");
- setShowPassword(false);
- setShowConfirmPassword(false);
+ reset();
onOpenChange(false);
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("admin.resetPassword")}</DialogTitle>
- <DialogDescription>
- {t("admin.resetPasswordFor", {
- name: user.name || user.email,
- })}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <div className="flex gap-3 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-900">
- <AlertCircle className="h-5 w-5 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" />
- <div className="text-sm text-yellow-800 dark:text-yellow-200 space-y-1">
- <p className="font-medium">{t("admin.passwordResetWarning")}</p>
- <p>{t("admin.passwordResetSecurityNote")}</p>
- </div>
- </div>
-
- {/* Generate Button */}
- <Button
- type="button"
- variant="outline"
- onClick={generateRandomPassword}
- className="w-full"
- >
- <RefreshCw className="h-4 w-4 mr-2" />
- {t("admin.generatePassword")}
- </Button>
-
- {/* New Password */}
- <div className="space-y-2">
- <Label htmlFor="password">
- {t("common.labels.newPassword")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <div className="relative">
- <Input
- id="password"
- type={showPassword ? "text" : "password"}
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder={t("admin.passwordPlaceholder")}
- className="pr-10"
- />
- <button
- type="button"
- onClick={() => setShowPassword(!showPassword)}
- className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- >
- {showPassword ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </button>
- </div>
- {password && password.length < 8 && (
- <p className="text-xs text-destructive">
- {t("validation.passwordTooShort")}
- </p>
- )}
- </div>
-
- {/* Confirm Password */}
- <div className="space-y-2">
- <Label htmlFor="confirmPassword">
- {t("common.labels.confirmPassword")}{" "}
- <span className="text-destructive">*</span>
- </Label>
- <div className="relative">
- <Input
- id="confirmPassword"
- type={showConfirmPassword ? "text" : "password"}
- value={confirmPassword}
- onChange={(e) => setConfirmPassword(e.target.value)}
- placeholder={t("admin.confirmPasswordPlaceholder")}
- className="pr-10"
- />
- <button
- type="button"
- onClick={() => setShowConfirmPassword(!showConfirmPassword)}
- className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- >
- {showConfirmPassword ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </button>
- </div>
- {confirmPassword && !passwordsMatch && (
- <p className="text-xs text-destructive">
- {t("validation.passwordsNoMatch")}
- </p>
- )}
- </div>
-
- {/* Copy Password Button */}
- {password && isValid && (
- <Button
- type="button"
- variant="secondary"
- onClick={copyPassword}
- className="w-full"
- >
- <Copy className="h-4 w-4 mr-2" />
- {t("admin.copyPassword")}
- </Button>
- )}
- </div>
-
- <DialogFooter>
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.resetPassword")}
+ description={t("admin.resetPasswordFor", { name: user.name || user.email })}
+ width="sm"
+ bodyClassName="flex flex-col gap-4"
+ footer={
+ <>
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
{t("common.cancel")}
</Button>
- <Button onClick={handleConfirm} disabled={!isValid || isSubmitting}>
+ <Button
+ onClick={handleConfirm}
+ disabled={!isValid || isSubmitting}
+ className="h-10 flex-1 font-semibold"
+ >
{isSubmitting ? t("common.saving") : t("admin.setPassword")}
</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ <StatusBanner tone="warning" icon={TriangleAlert} title={t("admin.passwordResetWarning")}>
+ {t("admin.passwordResetSecurityNote")}
+ </StatusBanner>
+
+ <Button
+ type="button"
+ variant="outline"
+ onClick={generateRandomPassword}
+ className="h-10 w-full rounded-[9px] font-semibold"
+ >
+ <RefreshCw className="size-4 text-fg-secondary" />
+ {t("admin.generatePassword")}
+ </Button>
+
+ <Field label={t("common.labels.newPassword")} htmlFor="reset-password">
+ <PasswordInput
+ id="reset-password"
+ value={password}
+ onChange={setPassword}
+ visible={showPassword}
+ onToggle={() => setShowPassword(!showPassword)}
+ placeholder={t("admin.passwordPlaceholder")}
+ />
+ {password && password.length < 8 && (
+ <p className="text-[12px] text-danger">{t("validation.passwordTooShort")}</p>
+ )}
+ </Field>
+
+ <Field label={t("common.labels.confirmPassword")} htmlFor="reset-password-confirm">
+ <PasswordInput
+ id="reset-password-confirm"
+ value={confirmPassword}
+ onChange={setConfirmPassword}
+ visible={showConfirmPassword}
+ onToggle={() => setShowConfirmPassword(!showConfirmPassword)}
+ placeholder={t("admin.confirmPasswordPlaceholder")}
+ />
+ {confirmPassword && !passwordsMatch && (
+ <p className="text-[12px] text-danger">{t("validation.passwordsNoMatch")}</p>
+ )}
+ </Field>
+
+ {isValid && (
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={copyPassword}
+ className="h-10 w-full rounded-[9px] font-semibold"
+ >
+ <Copy className="size-4" />
+ {t("admin.copyPassword")}
+ </Button>
+ )}
+ </PanelDialog>
);
}
diff --git a/components/admin/user-table.tsx b/components/admin/user-table.tsx
index 355ac4c..70fce2d 100644
--- a/components/admin/user-table.tsx
+++ b/components/admin/user-table.tsx
@@ -1,30 +1,17 @@
"use client";
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { useLocale } from "next-intl";
+import { useLocale, useTranslations } from "next-intl";
import { format, formatDistanceToNow } from "date-fns";
import {
- MoreVertical,
- Edit,
- Key,
- Ban,
- ShieldOff,
+ ChevronRight,
+ Ellipsis,
+ Eye,
+ KeyRound,
+ Lock,
+ LockOpen,
+ Pencil,
Trash2,
- ChevronUp,
- ChevronDown,
} from "lucide-react";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
@@ -32,24 +19,42 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ AdminMobileCard,
+ AdminTableCard,
+ AdminTableHead,
+ AdminTableRow,
+ Count,
+ RolePill,
+ StatusPill,
+ UserAvatar,
+} from "@/components/admin/admin-kit";
import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
+ RowActionButton,
+ SortHeader,
+ nextSort,
+ type SortState,
+} from "@/components/admin/admin-table-controls";
+import { AdminPagination } from "@/components/admin/admin-pagination";
import { getDateLocale } from "@/lib/locales";
+import type { UserSortField } from "@/lib/admin-list";
import type { AdminUser } from "@/hooks/useAdminUsers";
-import {
- useCanEditUser,
- useCanBanUser,
- useCanDeleteUser,
- useCanResetPassword,
-} from "@/hooks/useAdminAccess";
+import { useUserPermissions } from "@/hooks/useAdminAccess";
+import { cn } from "@/lib/utils";
interface UserTableProps {
+ /** One page of users, already sorted by the API */
users: AdminUser[];
- isLoading?: boolean;
+ /** Accounts matching the current search and filters */
+ total: number;
+ page: number;
+ pageSize: number;
+ onPageChange: (page: number) => void;
+ sort: SortState<UserSortField>;
+ onSortChange: (sort: SortState<UserSortField>) => void;
+ /** Dims the rows while the next page loads */
+ isStale?: boolean;
onUserClick: (user: AdminUser) => void;
onEditUser: (user: AdminUser) => void;
onResetPassword: (user: AdminUser) => void;
@@ -58,420 +63,232 @@ interface UserTableProps {
onDeleteUser: (user: AdminUser) => void;
}
-type SortColumn =
- | "name"
- | "email"
- | "role"
- | "status"
- | "createdAt"
- | "lastActivity"
- | "calendarCount"
- | "sharesCount";
-type SortDirection = "asc" | "desc";
+type RowHandlers = Pick<
+ UserTableProps,
+ "onUserClick" | "onEditUser" | "onResetPassword" | "onBanUser" | "onUnbanUser" | "onDeleteUser"
+>;
-function UserTableRow({
- user,
- onUserClick,
- onEditUser,
- onResetPassword,
- onBanUser,
- onUnbanUser,
- onDeleteUser,
-}: {
- user: AdminUser;
- onUserClick: (user: AdminUser) => void;
- onEditUser: (user: AdminUser) => void;
- onResetPassword: (user: AdminUser) => void;
- onBanUser: (user: AdminUser) => void;
- onUnbanUser: (user: AdminUser) => void;
- onDeleteUser: (user: AdminUser) => void;
-}) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
+const TEMPLATE = "minmax(0,2.4fr) 120px 110px 130px 150px 90px 102px";
- const canEdit = useCanEditUser(user);
- const canBan = useCanBanUser(user);
- const canDelete = useCanDeleteUser(user);
- const canResetPassword = useCanResetPassword(user);
-
- const getUserInitials = () => {
- if (user.name) {
- return user.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- }
- return user.email.slice(0, 2).toUpperCase();
+function useDateFormatters() {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ return {
+ created: (date: Date) => format(date, "PP", { locale: dateLocale }),
+ lastActive: (date: Date | null) =>
+ date
+ ? formatDistanceToNow(date, { addSuffix: true, locale: dateLocale })
+ : t("admin.neverActive"),
+ until: (date: Date) => format(date, "PPP", { locale: dateLocale }),
};
+}
- const getRoleBadgeClass = () => {
- switch (user.role) {
- case "superadmin":
- return "bg-red-500/10 text-red-500 border-red-500/20";
- case "admin":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- default:
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- }
- };
+function BannedPill({ user }: { user: AdminUser }) {
+ const t = useTranslations();
+ const dates = useDateFormatters();
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-help">
+ <StatusPill banned />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ {user.banReason && <p className="text-xs font-medium">{user.banReason}</p>}
+ <p className="text-xs opacity-80">
+ {user.banExpires
+ ? t("admin.bannedUntil", { date: dates.until(user.banExpires) })
+ : t("admin.bannedPermanently")}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
- const hasActions = canEdit || canResetPassword || canBan || canDelete;
+function UserRow({ user, ...handlers }: { user: AdminUser } & RowHandlers) {
+ const t = useTranslations();
+ const dates = useDateFormatters();
+ const { canEdit, canBan, canDelete, canResetPassword } = useUserPermissions(user);
return (
- <TableRow className="cursor-pointer" onClick={() => onUserClick(user)}>
- {/* Avatar + Name + Email */}
- <TableCell>
- <div className="flex items-center gap-3">
- <Avatar className="h-8 w-8">
- {user.image && <AvatarImage src={user.image} />}
- <AvatarFallback className="text-xs">
- {getUserInitials()}
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0">
- <p className="text-sm font-medium truncate">{user.name}</p>
- <p className="text-xs text-muted-foreground truncate">
- {user.email}
- </p>
- </div>
+ <AdminTableRow
+ template={TEMPLATE}
+ muted={user.banned ? "danger" : undefined}
+ onClick={() => handlers.onUserClick(user)}
+ >
+ <div className="flex min-w-0 items-center gap-[11px]">
+ <UserAvatar name={user.name || user.email} image={user.image} size={32} />
+ <div className="min-w-0">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">{user.name}</div>
+ <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>
</div>
- </TableCell>
-
- {/* Role */}
- <TableCell>
- <span
- className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getRoleBadgeClass()}`}
- >
- {t(`common.roles.${user.role}`)}
- </span>
- </TableCell>
-
- {/* Status */}
- <TableCell>
+ </div>
+ <div>
+ <RolePill role={user.role} />
+ </div>
+ <div>{user.banned ? <BannedPill user={user} /> : <StatusPill banned={false} />}</div>
+ <span className="truncate text-[12.5px] text-fg-secondary">{dates.created(user.createdAt)}</span>
+ <span className="truncate text-[12.5px] text-fg-secondary">
+ {dates.lastActive(user.lastActivity)}
+ </span>
+ <Count value={user.calendarCount} />
+ {/* Stop clicks and Enter/Space from also opening the details panel */}
+ <div
+ className="flex items-center justify-end gap-1.5"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <RowActionButton
+ icon={Pencil}
+ label={t("admin.editUser")}
+ disabled={!canEdit}
+ onClick={() => handlers.onEditUser(user)}
+ />
{user.banned ? (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <Badge variant="destructive" className="cursor-help">
- {t("admin.banned")}
- </Badge>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- <div className="space-y-1">
- {user.banReason && (
- <p className="text-xs font-medium">{user.banReason}</p>
- )}
- {user.banExpires ? (
- <p className="text-xs text-muted-foreground">
- {t("admin.bannedUntil", {
- date: format(user.banExpires, "PPP", {
- locale: dateLocale,
- }),
- })}
- </p>
- ) : (
- <p className="text-xs text-muted-foreground">
- {t("admin.bannedPermanently")}
- </p>
- )}
- </div>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <Badge variant="secondary">{t("common.status.active")}</Badge>
- )}
- </TableCell>
-
- {/* Created */}
- <TableCell>
- <span className="text-sm text-muted-foreground">
- {format(user.createdAt, "PP", { locale: dateLocale })}
- </span>
- </TableCell>
-
- {/* Last Activity */}
- <TableCell>
- {user.lastActivity ? (
- <span className="text-sm text-muted-foreground">
- {formatDistanceToNow(user.lastActivity, {
- addSuffix: true,
- locale: dateLocale,
- })}
- </span>
+ <RowActionButton
+ icon={LockOpen}
+ label={t("admin.unbanUser")}
+ disabled={!canBan}
+ onClick={() => handlers.onUnbanUser(user)}
+ />
) : (
- <span className="text-sm text-muted-foreground">
- {t("admin.neverActive")}
- </span>
+ <RowActionButton
+ icon={Lock}
+ label={t("admin.banUser")}
+ disabled={!canBan}
+ onClick={() => handlers.onBanUser(user)}
+ />
)}
- </TableCell>
-
- {/* Calendar Count */}
- <TableCell>
- <span className="text-sm">{user.calendarCount}</span>
- </TableCell>
-
- {/* Shares Count */}
- <TableCell>
- <span className="text-sm">{user.sharesCount}</span>
- </TableCell>
-
- {/* Actions */}
- <TableCell onClick={(e) => e.stopPropagation()}>
- {hasActions && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {canEdit && (
- <DropdownMenuItem onClick={() => onEditUser(user)}>
- <Edit className="h-4 w-4 mr-2" />
- {t("admin.editUser")}
- </DropdownMenuItem>
- )}
- {canResetPassword && (
- <DropdownMenuItem onClick={() => onResetPassword(user)}>
- <Key className="h-4 w-4 mr-2" />
- {t("admin.resetPassword")}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <RowActionButton icon={Ellipsis} label={t("adminUsers.moreActions")} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-52">
+ <DropdownMenuItem onClick={() => handlers.onUserClick(user)}>
+ <Eye />
+ {t("common.viewDetails")}
+ </DropdownMenuItem>
+ {canResetPassword && (
+ <DropdownMenuItem onClick={() => handlers.onResetPassword(user)}>
+ <KeyRound />
+ {t("admin.resetPassword")}
+ </DropdownMenuItem>
+ )}
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => handlers.onDeleteUser(user)}
+ className="text-danger focus:text-danger"
+ >
+ <Trash2 />
+ {t("admin.deleteUser")}
</DropdownMenuItem>
- )}
- {canBan && (
- <>
- {(canEdit || canResetPassword) && <DropdownMenuSeparator />}
- {!user.banned ? (
- <DropdownMenuItem onClick={() => onBanUser(user)}>
- <Ban className="h-4 w-4 mr-2" />
- {t("admin.banUser")}
- </DropdownMenuItem>
- ) : (
- <DropdownMenuItem onClick={() => onUnbanUser(user)}>
- <ShieldOff className="h-4 w-4 mr-2" />
- {t("admin.unbanUser")}
- </DropdownMenuItem>
- )}
- </>
- )}
- {canDelete && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => onDeleteUser(user)}
- className="text-destructive"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("admin.deleteUser")}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </TableCell>
- </TableRow>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </AdminTableRow>
+ );
+}
+
+function UserCard({ user, onClick }: { user: AdminUser; onClick: () => void }) {
+ const t = useTranslations();
+ const dates = useDateFormatters();
+ return (
+ <AdminMobileCard onClick={onClick}>
+ <div className="flex items-start gap-[11px]">
+ <UserAvatar name={user.name || user.email} image={user.image} size={36} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">{user.name}</div>
+ <div className="mt-px truncate text-[12.5px] text-fg-tertiary">{user.email}</div>
+ <div className="mt-2 flex flex-wrap items-center gap-1.5">
+ <RolePill role={user.role} />
+ <StatusPill banned={user.banned} />
+ <span className="font-mono text-[11.5px] text-fg-faint">
+ {t("adminUsers.calendarCount", { count: user.calendarCount })} ·{" "}
+ {dates.lastActive(user.lastActivity)}
+ </span>
+ </div>
+ </div>
+ <ChevronRight className="mt-[3px] size-[17px] shrink-0 text-fg-faint" />
+ </div>
+ </AdminMobileCard>
);
}
export function UserTable({
users,
- onUserClick,
- onEditUser,
- onResetPassword,
- onBanUser,
- onUnbanUser,
- onDeleteUser,
+ total,
+ page,
+ pageSize,
+ onPageChange,
+ sort,
+ onSortChange,
+ isStale,
+ ...handlers
}: UserTableProps) {
const t = useTranslations();
- const [sortColumn, setSortColumn] = useState<SortColumn | null>("createdAt");
- const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
-
- // Sort users
- const sortedUsers = [...users].sort((a, b) => {
- if (!sortColumn) return 0;
-
- let comparison = 0;
- switch (sortColumn) {
- case "name":
- comparison = (a.name || "").localeCompare(b.name || "");
- break;
- case "email":
- comparison = a.email.localeCompare(b.email);
- break;
- case "role":
- const roleOrder = { user: 0, admin: 1, superadmin: 2 };
- comparison =
- (roleOrder[a.role as keyof typeof roleOrder] ?? 0) -
- (roleOrder[b.role as keyof typeof roleOrder] ?? 0);
- break;
- case "status":
- comparison = (a.banned ? 1 : 0) - (b.banned ? 1 : 0);
- break;
- case "createdAt":
- comparison = a.createdAt.getTime() - b.createdAt.getTime();
- break;
- case "lastActivity":
- const aTime = a.lastActivity?.getTime() ?? 0;
- const bTime = b.lastActivity?.getTime() ?? 0;
- comparison = aTime - bTime;
- break;
- case "calendarCount":
- comparison = a.calendarCount - b.calendarCount;
- break;
- case "sharesCount":
- comparison = a.sharesCount - b.sharesCount;
- break;
- }
-
- return sortDirection === "asc" ? comparison : -comparison;
- });
-
- // Handle sort column click
- const handleSort = (column: SortColumn) => {
- if (sortColumn === column) {
- setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
- } else {
- setSortColumn(column);
- setSortDirection("desc");
- }
- };
+ const header = (column: UserSortField, label: string) => (
+ <SortHeader
+ column={column}
+ label={label}
+ sort={sort}
+ onSort={(next) => onSortChange(nextSort(sort, next))}
+ />
+ );
+ const empty = (
+ <p className="px-4 py-10 text-center text-[13px] text-fg-tertiary">
+ {t("common.empty.noUsersFound")}
+ </p>
+ );
+ const pagination = (className?: string) => (
+ <AdminPagination
+ page={page}
+ pageSize={pageSize}
+ shown={users.length}
+ total={total}
+ onPageChange={onPageChange}
+ className={className}
+ />
+ );
return (
- <div className="border border-border/50 bg-gradient-to-br from-card/95 via-card to-card/80 backdrop-blur-sm rounded-lg overflow-hidden shadow-sm">
- <Table>
- <TableHeader className="bg-muted/50">
- <TableRow>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("name")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.user")}
- {sortColumn === "name" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("role")}
- >
- <div className="flex items-center gap-2">
- {t("admin.role")}
- {sortColumn === "role" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("status")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.status")}
- {sortColumn === "status" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("createdAt")}
- >
- <div className="flex items-center gap-2">
- {t("common.stats.created")}
- {sortColumn === "createdAt" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("lastActivity")}
- >
- <div className="flex items-center gap-2">
- {t("common.time.lastActive")}
- {sortColumn === "lastActivity" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("calendarCount")}
- >
- <div className="flex items-center gap-2">
- {t("admin.calendarsCount")}
- {sortColumn === "calendarCount" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead
- className="cursor-pointer hover:bg-muted/80 transition-colors"
- onClick={() => handleSort("sharesCount")}
- >
- <div className="flex items-center gap-2">
- {t("common.labels.shares")}
- {sortColumn === "sharesCount" &&
- (sortDirection === "asc" ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- ))}
- </div>
- </TableHead>
- <TableHead className="w-[50px]"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {users.length === 0 ? (
- <TableRow>
- <TableCell colSpan={8} className="text-center py-8">
- <p className="text-sm text-muted-foreground">
- {t("common.empty.noUsersFound")}
- </p>
- </TableCell>
- </TableRow>
- ) : (
- sortedUsers.map((user) => (
- <UserTableRow
- key={user.id}
- user={user}
- onUserClick={onUserClick}
- onEditUser={onEditUser}
- onResetPassword={onResetPassword}
- onBanUser={onBanUser}
- onUnbanUser={onUnbanUser}
- onDeleteUser={onDeleteUser}
- />
- ))
- )}
- </TableBody>
- </Table>
+ <div aria-busy={isStale || undefined} className={cn(isStale && "opacity-60")}>
+ <AdminTableCard className="hidden lg:block" footer={total > 0 && pagination()}>
+ <AdminTableHead
+ template={TEMPLATE}
+ columns={[
+ header("name", t("common.labels.user")),
+ header("role", t("admin.role")),
+ header("status", t("common.labels.status")),
+ header("createdAt", t("common.stats.created")),
+ header("lastActivity", t("common.time.lastActive")),
+ header("calendarCount", t("admin.calendarsCount")),
+ <span key="actions" className="block text-right">
+ {t("adminUsers.actions")}
+ </span>,
+ ]}
+ />
+ {users.length === 0
+ ? empty
+ : users.map((user) => <UserRow key={user.id} user={user} {...handlers} />)}
+ </AdminTableCard>
+
+ <div className="flex flex-col gap-[9px] lg:hidden">
+ {users.length === 0 ? (
+ <div className="rounded-[11px] border border-line">{empty}</div>
+ ) : (
+ users.map((user) => (
+ <UserCard key={user.id} user={user} onClick={() => handlers.onUserClick(user)} />
+ ))
+ )}
+ {total > pageSize && pagination("pt-1 text-[12px] text-fg-tertiary")}
+ </div>
</div>
);
}
diff --git a/components/admin/user-unban-dialog.tsx b/components/admin/user-unban-dialog.tsx
index 4f0a069..36c0b2e 100644
--- a/components/admin/user-unban-dialog.tsx
+++ b/components/admin/user-unban-dialog.tsx
@@ -1,17 +1,12 @@
"use client";
import { useState } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
+import { PanelDialog } from "@/components/panel-dialog";
+import { SectionLabel } from "@/components/form-kit";
+import { getDateLocale } from "@/lib/locales";
import type { AdminUser } from "@/hooks/useAdminUsers";
interface UserUnbanDialogProps {
@@ -21,13 +16,9 @@ interface UserUnbanDialogProps {
onConfirm: () => Promise<void>;
}
-export function UserUnbanDialog({
- open,
- onOpenChange,
- user,
- onConfirm,
-}: UserUnbanDialogProps) {
+export function UserUnbanDialog({ open, onOpenChange, user, onConfirm }: UserUnbanDialogProps) {
const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
const [isSubmitting, setIsSubmitting] = useState(false);
const handleConfirm = async () => {
@@ -41,41 +32,42 @@ export function UserUnbanDialog({
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[450px]">
- <DialogHeader>
- <DialogTitle>{t("admin.unbanUser")}</DialogTitle>
- <DialogDescription>
- {t("admin.unbanUserConfirm", {
- name: user.name || user.email,
- })}
- </DialogDescription>
- </DialogHeader>
-
- {user.banReason && (
- <div className="py-4">
- <Label className="text-sm font-medium">
- {t("admin.originalBanReason")}
- </Label>
- <div className="mt-2 p-3 rounded-lg bg-muted text-sm">
- {user.banReason}
- </div>
- </div>
- )}
-
- <DialogFooter>
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("admin.unbanUser")}
+ description={t("admin.unbanUserConfirm", { name: user.name || user.email })}
+ width="sm"
+ bodyClassName="flex flex-col gap-3"
+ footer={
+ <>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSubmitting}
+ className="h-10 flex-1 font-semibold"
>
{t("common.cancel")}
</Button>
- <Button onClick={handleConfirm} disabled={isSubmitting}>
+ <Button onClick={handleConfirm} disabled={isSubmitting} className="h-10 flex-1 font-semibold">
{isSubmitting ? t("common.saving") : t("admin.confirmUnban")}
</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ {user.banReason && (
+ <div>
+ <SectionLabel>{t("admin.originalBanReason")}</SectionLabel>
+ <div className="rounded-[10px] border border-line bg-surface-panel px-3 py-2.5 text-[13.5px] text-fg-body">
+ {user.banReason}
+ </div>
+ </div>
+ )}
+ <p className="text-[12.5px] text-fg-tertiary">
+ {user.banExpires
+ ? t("admin.bannedUntil", { date: format(user.banExpires, "PPP", { locale: dateLocale }) })
+ : t("admin.bannedPermanently")}
+ </p>
+ </PanelDialog>
);
}
diff --git a/components/app-footer.tsx b/components/app-footer.tsx
deleted file mode 100644
index 175c229..0000000
--- a/components/app-footer.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { Heart, ExternalLink, FileText } from "lucide-react";
-import { LanguageSwitcher } from "./language-switcher";
-import { ThemeSwitcher } from "./theme-switcher";
-import { useState } from "react";
-import { ChangelogDialog } from "./changelog-dialog";
-import { useLocale } from "next-intl";
-
-interface VersionInfo {
- version: string;
- githubUrl: string;
- commitHash?: string;
-}
-
-interface AppFooterProps {
- versionInfo: VersionInfo | null;
-}
-
-export function AppFooter({ versionInfo }: AppFooterProps) {
- const t = useTranslations();
- const locale = useLocale();
- const [showChangelog, setShowChangelog] = useState(false);
-
- // Format version display based on version type
- const displayVersion =
- versionInfo?.version === "dev" && versionInfo?.commitHash
- ? `dev (${versionInfo.commitHash})`
- : versionInfo?.version;
-
- return (
- <>
- <footer className="border-t bg-background mt-auto">
- <div className="container max-w-4xl mx-auto p-3 sm:p-4">
- {/* Mobile: Two rows (language + links), Desktop: One row */}
- <div className="flex flex-col gap-2 sm:flex-row sm:justify-between sm:items-center sm:gap-4">
- {/* Language and theme switcher */}
- <div className="flex justify-center sm:justify-start items-center gap-2">
- <LanguageSwitcher />
- <ThemeSwitcher />
- </div>
-
- {/* Links row - horizontal on all screen sizes */}
- <div className="flex flex-row items-center justify-center sm:justify-end gap-3 sm:gap-4 text-xs">
- {/* Version info */}
- {versionInfo && (
- <a
- href={versionInfo.githubUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="text-muted-foreground hover:text-foreground transition-colors font-mono whitespace-nowrap"
- title={
- versionInfo.commitHash
- ? `${t("footer.version")}: ${versionInfo.version} (${
- versionInfo.commitHash
- })`
- : `${t("footer.version")}: ${versionInfo.version}`
- }
- >
- {t("footer.version")}: {displayVersion}
- </a>
- )}
- {/* Changelog link */}
- <button
- onClick={() => setShowChangelog(true)}
- className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- title={t("changelog.title")}
- >
- <FileText className="w-4 h-4" />
- <span className="hidden sm:inline">{t("changelog.title")}</span>
- </button>
- {/* GitHub repo link */}
- <a
- href="https://github.com/panteLx/BetterShift"
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground transition-colors"
- title={t("footer.github")}
- >
- <ExternalLink className="w-4 h-4" />
- <span className="hidden sm:inline">{t("footer.github")}</span>
- </a>
- {/* Buy Me a Coffee link */}
- <a
- href="https://buymeacoffee.com/pantel"
- target="_blank"
- rel="noopener noreferrer"
- className="flex items-center gap-1.5 text-muted-foreground hover:text-amber-500 transition-colors"
- title={t("footer.support")}
- >
- <Heart className="w-4 h-4" />
- <span className="hidden sm:inline">{t("footer.support")}</span>
- </a>
- </div>
- </div>
- </div>
- </footer>
-
- {/* Changelog Dialog */}
- <ChangelogDialog
- open={showChangelog}
- onOpenChange={setShowChangelog}
- locale={locale}
- />
- </>
- );
-}
diff --git a/components/app-header.tsx b/components/app-header.tsx
index 5a61303..77b1fb3 100644
--- a/components/app-header.tsx
+++ b/components/app-header.tsx
@@ -1,383 +1,285 @@
-import { motion } from "motion/react";
-import { useTranslations } from "next-intl";
+"use client";
+
import { useState } from "react";
import Link from "next/link";
-import { CalendarWithCount } from "@/lib/types";
-import { CalendarSelector } from "@/components/calendar-selector";
-import { PresetSelector } from "@/components/preset-selector";
-import { UserMenu } from "@/components/user-menu";
-import { useAuth } from "@/hooks/useAuth";
-import { useAuthFeatures } from "@/hooks/useAuthFeatures";
-import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
+import { useLocale, useTranslations } from "next-intl";
+import { addMonths, format, subMonths } from "date-fns";
import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import {
- Calendar as CalendarIcon,
- Plus,
Bell,
- ExternalLink,
+ CalendarDays,
+ ChevronLeft,
+ ChevronRight,
+ Settings,
+ TriangleAlert,
} from "lucide-react";
-import { ShiftPreset } from "@/lib/db/schema";
-import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
-import { useConnectionStatus } from "@/hooks/useConnectionStatus";
+import { CalendarWithCount } from "@/lib/types";
+import { CalendarSwitcher } from "@/components/calendar-switcher";
+import { GuestMenu, UserMenu } from "@/components/user-menu";
import { ChangelogDialog } from "@/components/changelog-dialog";
-import { useLocale } from "next-intl";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
interface AppHeaderProps {
calendars: CalendarWithCount[];
selectedCalendar: string | undefined;
- presets: ShiftPreset[];
- selectedPresetId: string | undefined;
- showMobileCalendarDialog: boolean;
+ currentDate: Date;
hasSyncErrors?: boolean;
+ onDateChange: (date: Date) => void;
onSelectCalendar: (id: string) => void;
- onSelectPreset: (id: string | undefined) => void;
onCreateCalendar: () => void;
onSettings: () => void;
onSyncNotifications: () => void;
onCompare?: () => void;
- onPresetsChange?: () => void;
- onShiftsChange: () => void;
- onManualShiftCreation: () => void;
- onMobileCalendarDialogChange: (open: boolean) => void;
- onViewSettingsClick: () => void;
- presetsLoading?: boolean;
- hidePresetHeader?: boolean;
- onHidePresetHeaderChange?: (hide: boolean) => void;
+ onViewSettings?: () => void;
+}
+
+export function HeaderIconButton({
+ label,
+ onClick,
+ children,
+ className,
+}: {
+ label: string;
+ onClick: () => void;
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={label}
+ aria-label={label}
+ className={cn(
+ "relative flex size-9 shrink-0 items-center justify-center rounded-lg border border-line text-fg-secondary transition-colors hover:bg-surface-panel lg:size-8",
+ className
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+/** The phone month arrows: one bordered group, used by both workspaces. */
+export function MonthArrows({
+ currentDate,
+ onDateChange,
+}: {
+ currentDate: Date;
+ onDateChange: (date: Date) => void;
+}) {
+ const t = useTranslations();
+ const stepClass =
+ "flex size-9 items-center justify-center text-fg-secondary transition-colors hover:bg-surface-panel";
+
+ return (
+ <div className="flex overflow-hidden rounded-[9px] border border-line">
+ <button
+ type="button"
+ className={stepClass}
+ onClick={() => onDateChange(subMonths(currentDate, 1))}
+ aria-label={t("calendarView.previousMonth")}
+ >
+ <ChevronLeft className="size-[18px]" />
+ </button>
+ <span className="w-px bg-line" />
+ <button
+ type="button"
+ className={stepClass}
+ onClick={() => onDateChange(addMonths(currentDate, 1))}
+ aria-label={t("calendarView.nextMonth")}
+ >
+ <ChevronRight className="size-[18px]" />
+ </button>
+ </div>
+ );
+}
+
+export function MonthStepper({
+ currentDate,
+ onDateChange,
+ className,
+}: {
+ currentDate: Date;
+ onDateChange: (date: Date) => void;
+ className?: string;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const stepClass =
+ "flex size-[30px] items-center justify-center rounded-[7px] border border-line text-fg-secondary transition-colors hover:bg-surface-panel";
+
+ return (
+ <div className={cn("flex items-center gap-2", className)}>
+ <button
+ type="button"
+ className={stepClass}
+ onClick={() => onDateChange(subMonths(currentDate, 1))}
+ aria-label={t("calendarView.previousMonth")}
+ >
+ <ChevronLeft className="size-4" />
+ </button>
+ <span className="min-w-[150px] text-center text-[15px] font-semibold text-fg-strong">
+ {format(currentDate, "LLLL yyyy", { locale: getDateLocale(locale) })}
+ </span>
+ <button
+ type="button"
+ className={stepClass}
+ onClick={() => onDateChange(addMonths(currentDate, 1))}
+ aria-label={t("calendarView.nextMonth")}
+ >
+ <ChevronRight className="size-4" />
+ </button>
+ </div>
+ );
}
export function AppHeader({
calendars,
selectedCalendar,
- presets,
- selectedPresetId,
- showMobileCalendarDialog,
+ currentDate,
hasSyncErrors = false,
+ onDateChange,
onSelectCalendar,
- onSelectPreset,
onCreateCalendar,
onSettings,
onSyncNotifications,
onCompare,
- onPresetsChange,
- onShiftsChange,
- onManualShiftCreation,
- onMobileCalendarDialogChange,
- onViewSettingsClick,
- presetsLoading = false,
- hidePresetHeader = false,
- onHidePresetHeaderChange,
+ onViewSettings,
}: AppHeaderProps) {
const t = useTranslations();
const locale = useLocale();
const { isGuest } = useAuth();
const { isAuthEnabled } = useAuthFeatures();
const { versionInfo } = useVersionUpdateCheck();
- const { isOnline } = useConnectionStatus();
const [showChangelog, setShowChangelog] = useState(false);
- return (
- <>
- <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
- <div className="container max-w-4xl mx-auto p-3 sm:p-4">
- <div className="space-y-3 sm:space-y-4">
- {/* Desktop: Logo + Calendar Selector in one line */}
- <div className="hidden sm:flex items-center justify-between gap-4">
- {/* Logo Section - Clickable to go home */}
- <Link href="/" className="flex items-center gap-3 group">
- <motion.div
- className="flex items-center gap-3"
- initial={{ opacity: 0, x: -20 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ duration: 0.3 }}
- >
- <div className="relative shrink-0">
- <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50 transition-transform group-hover:scale-105">
- <CalendarIcon className="h-6 w-6 text-white" />
- </div>
- {/* Connection Status Indicator */}
- <div
- className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${
- isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"
- }`}
- title={
- isOnline ? t("sync.connected") : t("sync.disconnected")
- }
- ></div>
- </div>
- <div>
- <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text transition-all group-hover:from-primary group-hover:via-primary group-hover:to-primary/70">
- {t("app.title")}
- </h1>
- <p className="text-xs text-muted-foreground font-medium">
- {t("app.subtitle", { default: "Organize your shifts" })}
- </p>
- </div>
- </motion.div>
- </Link>
-
- {/* Right Section: Unified Container */}
- <motion.div
- className="flex items-center gap-2 bg-muted/30 rounded-xl p-2 border border-border/50"
- initial={{ opacity: 0, x: 20 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ duration: 0.3, delay: 0.1 }}
- >
- {/* Calendar Selector - Desktop */}
- <div className="flex items-center gap-2 min-w-0 flex-1 max-w-md">
- <div
- className="w-1 h-8 bg-gradient-to-b rounded-full transition-colors duration-300"
- style={{
- backgroundImage: selectedCalendar
- ? `linear-gradient(to bottom, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }80)`
- : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",
- }}
- ></div>
- <div className="flex-1 min-w-0">
- <CalendarSelector
- calendars={calendars}
- selectedId={selectedCalendar}
- onSelect={onSelectCalendar}
- onCreateNew={onCreateCalendar}
- onSettings={onSettings}
- onSyncNotifications={onSyncNotifications}
- onCompare={onCompare}
- hasSyncErrors={hasSyncErrors}
- />
- </div>
- </div>
-
- {/* Divider */}
- {isAuthEnabled && (
- <Separator orientation="vertical" className="h-8" />
- )}
-
- {/* User Menu or Guest Login Button */}
- {isAuthEnabled &&
- (isGuest ? (
- <Button asChild variant="default" size="sm">
- <Link href="/login">{t("auth.login")}</Link>
- </Button>
- ) : (
- <UserMenu />
- ))}
- </motion.div>
- </div>
-
- {/* Update Notification Banner - Desktop & Mobile */}
- {versionInfo?.hasUpdate && !versionInfo.isDev && (
- <motion.div
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.15 }}
- className="relative"
- >
- <button
- onClick={() => setShowChangelog(true)}
- className="w-full bg-gradient-to-r from-primary/10 via-primary/5 to-primary/10 backdrop-blur-sm border border-primary/30 rounded-xl p-3 sm:p-3.5 flex items-center justify-between gap-3 hover:from-primary/15 hover:via-primary/10 hover:to-primary/15 hover:border-primary/40 transition-all shadow-sm hover:shadow-md active:scale-[0.99] group"
- >
- <div className="flex items-center gap-2.5 sm:gap-3 flex-1 min-w-0">
- <div className="relative shrink-0 w-9 h-9 sm:w-10 sm:h-10 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
- <Bell className="h-4 w-4 sm:h-5 sm:w-5 text-primary group-hover:scale-110 transition-transform" />
- <div className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-primary rounded-full animate-pulse shadow-sm"></div>
- </div>
- <div className="text-left flex-1 min-w-0">
- <p className="text-sm sm:text-base font-semibold text-primary mb-0.5">
- {t("update.available")}
- </p>
- <p className="text-xs sm:text-sm text-muted-foreground font-medium">
- {t("update.newVersion", {
- version: versionInfo.latestVersion || "unknown",
- })}
- </p>
- </div>
- </div>
- <div className="shrink-0 flex items-center gap-2 text-primary">
- <span className="text-xs sm:text-sm font-medium hidden sm:inline">
- {t("update.viewChangelog")}
- </span>
- <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
- <ExternalLink className="h-4 w-4 group-hover:rotate-12 transition-transform" />
- </div>
- </div>
- </button>
- </motion.div>
- )}
-
- {/* Mobile: Add Button + Calendar Card + User Menu (Logo hidden) */}
- <div className="sm:hidden flex items-center gap-2">
- {/* Mobile Add Shift Button - Left */}
- {selectedCalendar && (
- <motion.div
- initial={{ scale: 0, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
- className="shrink-0"
- >
- <Button
- variant="ghost"
- size="icon"
- onClick={onManualShiftCreation}
- className="h-10 w-10 rounded-full bg-black dark:bg-white backdrop-blur-sm border border-border/50 hover:bg-accent transition-all shadow-sm"
- >
- <Plus className="h-5 w-5 dark:text-black text-white" />
- </Button>
- </motion.div>
- )}
+ const signedIn = isAuthEnabled && !isGuest;
+ const showUpdate = versionInfo?.hasUpdate && !versionInfo.isDev;
- {/* Calendar Selection Card with Connection Indicator */}
- <button
- onClick={() => onMobileCalendarDialogChange(true)}
- className="flex-1 bg-muted/30 backdrop-blur-sm border border-border/50 rounded-xl p-3 flex items-center justify-between gap-2 hover:bg-accent/50 transition-all active:scale-[0.98] shadow-sm relative"
- >
- {/* Connection Status Indicator - Top Right of Card */}
- <div
- className={`absolute top-2 right-2 w-2 h-2 rounded-full transition-colors ${
- isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"
- }`}
- title={
- isOnline ? t("sync.connected") : t("sync.disconnected")
- }
- ></div>
-
- <div className="flex items-center gap-2.5 min-w-0 flex-1">
- <div
- className="w-1 h-9 bg-gradient-to-b rounded-full transition-colors duration-300"
- style={{
- backgroundImage: selectedCalendar
- ? `linear-gradient(to bottom, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }, ${
- calendars.find((c) => c.id === selectedCalendar)
- ?.color || "hsl(var(--primary))"
- }80)`
- : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",
- }}
- ></div>
- <div className="min-w-0 flex-1 text-left">
- <p className="text-[10px] text-muted-foreground font-medium">
- {t("calendar.select", {
- default: "Your BetterShift Calendar",
- })}
- </p>
- <p className="text-sm font-semibold truncate">
- {calendars.find((c) => c.id === selectedCalendar)?.name ||
- t("calendar.title")}
- </p>
- </div>
- </div>
- <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center">
- <CalendarIcon className="h-4 w-4 text-primary" />
- </div>
- </button>
+ const brand = (
+ <Link
+ href="/"
+ aria-label={t("app.title")}
+ className="flex size-[26px] shrink-0 items-center justify-center rounded-[7px] bg-brand"
+ >
+ <CalendarDays className="size-[15px] text-white" />
+ </Link>
+ );
- {/* User Menu - Right */}
- {isAuthEnabled && (
- <motion.div
- initial={{ scale: 0, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ delay: 0.3, type: "spring", stiffness: 200 }}
- className="shrink-0"
- >
- {isGuest ? (
- <Button asChild variant="default" size="sm">
- <Link href="/login">{t("auth.login")}</Link>
- </Button>
- ) : (
- <UserMenu />
- )}
- </motion.div>
- )}
- </div>
+ const actions = (
+ <>
+ {selectedCalendar && (
+ <HeaderIconButton
+ label={
+ hasSyncErrors
+ ? t("syncNotifications.hasErrors")
+ : t("syncNotifications.title")
+ }
+ onClick={onSyncNotifications}
+ className={
+ hasSyncErrors
+ ? "border-danger-line bg-danger-soft text-danger hover:bg-danger-soft"
+ : undefined
+ }
+ >
+ {hasSyncErrors ? (
+ <TriangleAlert className="size-[17px]" />
+ ) : (
+ <Bell className="size-4" />
+ )}
+ {hasSyncErrors && (
+ <span className="absolute -right-1 -top-1 flex size-[15px] items-center justify-center rounded-full border-2 border-background bg-danger text-[10px] font-bold leading-none text-background">
+ !
+ </span>
+ )}
+ </HeaderIconButton>
+ )}
+ {selectedCalendar && (
+ <HeaderIconButton
+ label={t("settings.title")}
+ onClick={onSettings}
+ className="hidden lg:flex"
+ >
+ <Settings className="size-4" />
+ </HeaderIconButton>
+ )}
+ {/* On phones the menu button is the gear and opens the settings sheet with the calendar group */}
+ {signedIn ? (
+ <UserMenu onOpenViewSettings={onViewSettings} onOpenPhoneMenu={onSettings} />
+ ) : (
+ <GuestMenu
+ showLogin={isAuthEnabled}
+ // The guest banner right below already offers the login on phones
+ loginOnPhone={false}
+ onOpenViewSettings={onViewSettings}
+ onOpenPhoneMenu={onSettings}
+ />
+ )}
+ </>
+ );
- {/* Preset Selector */}
- {selectedCalendar && (
- <div className="px-0.5 sm:px-0">
- <PresetSelector
- calendars={calendars}
- presets={presets}
- selectedPresetId={selectedPresetId}
- onSelectPreset={onSelectPreset}
- onPresetsChange={onPresetsChange}
- onShiftsChange={onShiftsChange}
- calendarId={selectedCalendar}
- onViewSettingsClick={onViewSettingsClick}
- loading={presetsLoading}
- hidePresetHeader={hidePresetHeader}
- onHidePresetHeaderChange={onHidePresetHeaderChange}
- />
- </div>
- )}
- </div>
+ return (
+ <>
+ <header className="sticky top-0 z-30 border-b border-line bg-background">
+ {/* Desktop */}
+ <div className="hidden h-14 items-center gap-3 px-[18px] lg:flex">
+ {brand}
+ <CalendarSwitcher
+ calendars={calendars}
+ selectedId={selectedCalendar}
+ onSelect={onSelectCalendar}
+ onCreateNew={onCreateCalendar}
+ onCompare={onCompare}
+ />
+ <div className="h-6 w-px bg-line" />
+ <MonthStepper currentDate={currentDate} onDateChange={onDateChange} />
+ <div className="flex-1" />
+ {showUpdate && (
+ <button
+ type="button"
+ onClick={() => setShowChangelog(true)}
+ className="flex h-8 items-center gap-2 rounded-full bg-brand-soft px-3 text-[12.5px] font-semibold text-brand-ink transition-colors hover:bg-brand-soft/70"
+ >
+ <span className="size-1.5 rounded-full bg-brand-dot" />
+ {t("update.newVersion", {
+ version: versionInfo?.latestVersion || "",
+ })}
+ </button>
+ )}
+ {actions}
</div>
- </div>
- {/* Mobile Calendar Dialog */}
- <Dialog
- open={showMobileCalendarDialog}
- onOpenChange={onMobileCalendarDialogChange}
- >
- <DialogContent className="sm:max-w-md 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="flex items-center gap-2.5 text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {t("calendar.select", { default: "Your BetterShift Calendar" })}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("calendar.selectDescription", {
- default: "Choose a calendar to manage your shifts",
- })}
- </DialogDescription>
- </DialogHeader>
- <div className="p-6">
- <CalendarSelector
+ {/* Mobile */}
+ <div className="flex items-center gap-2.5 px-4 py-2.5 lg:hidden">
+ {brand}
+ <div className="min-w-0 flex-1">
+ <CalendarSwitcher
+ size="mobile"
calendars={calendars}
selectedId={selectedCalendar}
- onSelect={(id) => {
- onSelectCalendar(id);
- onMobileCalendarDialogChange(false);
- }}
- onCreateNew={() => {
- onMobileCalendarDialogChange(false);
- onCreateCalendar();
- }}
- onSettings={() => {
- onMobileCalendarDialogChange(false);
- onSettings();
- }}
- onSyncNotifications={() => {
- onMobileCalendarDialogChange(false);
- onSyncNotifications();
- }}
- onCompare={
- onCompare
- ? () => {
- onMobileCalendarDialogChange(false);
- onCompare();
- }
- : undefined
- }
- hasSyncErrors={hasSyncErrors}
- variant="mobile"
+ onSelect={onSelectCalendar}
+ onCreateNew={onCreateCalendar}
+ onCompare={onCompare}
/>
</div>
- </DialogContent>
- </Dialog>
+ {actions}
+ </div>
+ {showUpdate && (
+ <button
+ type="button"
+ onClick={() => setShowChangelog(true)}
+ className="flex w-full items-center gap-2 border-t border-line bg-brand-soft px-4 py-2 text-left text-[12.5px] font-semibold text-brand-ink lg:hidden"
+ >
+ <span className="size-1.5 rounded-full bg-brand-dot" />
+ {t("update.newVersion", { version: versionInfo?.latestVersion || "" })}
+ </button>
+ )}
+ </header>
- {/* Changelog Dialog */}
<ChangelogDialog
open={showChangelog}
onOpenChange={setShowChangelog}
diff --git a/components/app-preferences-menu-items.tsx b/components/app-preferences-menu-items.tsx
new file mode 100644
index 0000000..25e0327
--- /dev/null
+++ b/components/app-preferences-menu-items.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { useLocale, useTranslations } from "next-intl";
+import { useTheme } from "next-themes";
+import { Languages, ScrollText, SlidersHorizontal, SunMoon } from "lucide-react";
+import {
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from "@/components/ui/dropdown-menu";
+import { locales } from "@/lib/locales";
+import { useThemeOptions } from "@/components/appearance-picker";
+
+export function setLocaleCookie(locale: string) {
+ document.cookie = `NEXT_LOCALE=${locale}; path=/; max-age=31536000; SameSite=Lax`;
+ window.location.reload();
+}
+
+interface AppPreferencesMenuItemsProps {
+ onOpenChangelog: () => void;
+ onOpenViewSettings?: () => void;
+}
+
+/** Appearance, language and changelog entries shared by the user and guest menus. */
+export function AppPreferencesMenuItems({
+ onOpenChangelog,
+ onOpenViewSettings,
+}: AppPreferencesMenuItemsProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { theme, setTheme } = useTheme();
+ const themeOptions = useThemeOptions();
+
+ return (
+ <>
+ {onOpenViewSettings && (
+ <DropdownMenuItem onClick={onOpenViewSettings}>
+ <SlidersHorizontal className="mr-2 h-4 w-4" />
+ {t("appMenu.viewSettings")}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <SunMoon className="mr-2 h-4 w-4" />
+ {t("appearance.title")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup value={theme ?? "system"} onValueChange={setTheme}>
+ {themeOptions.map(({ value, title }) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ {title}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Languages className="mr-2 h-4 w-4" />
+ {t("appMenu.language")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup value={locale} onValueChange={setLocaleCookie}>
+ {locales.map((value) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ {t(`language.${value}`)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuItem onClick={onOpenChangelog}>
+ <ScrollText className="mr-2 h-4 w-4" />
+ {t("changelog.title")}
+ </DropdownMenuItem>
+ </>
+ );
+}
diff --git a/components/appearance-picker.tsx b/components/appearance-picker.tsx
new file mode 100644
index 0000000..163a488
--- /dev/null
+++ b/components/appearance-picker.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { useTheme } from "next-themes";
+import { useTranslations } from "next-intl";
+import { Check, Moon, Sun, SunMoon, type LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { useMounted } from "@/hooks/useMediaQuery";
+
+type ThemeOption = "system" | "light" | "dark";
+
+const PREVIEWS: Record<ThemeOption, { icon: LucideIcon; preview: [string, string] }> = {
+ system: { icon: SunMoon, preview: ["#ffffff", "#0e141f"] },
+ light: { icon: Sun, preview: ["#ffffff", "#ffffff"] },
+ dark: { icon: Moon, preview: ["#0e141f", "#0e141f"] },
+};
+
+
+export function useThemeOptions() {
+ const t = useTranslations();
+ return [
+ {
+ value: "system" as const,
+ title: t("appearance.system.title"),
+ description: t("appearance.system.description"),
+ },
+ {
+ value: "light" as const,
+ title: t("appearance.light.title"),
+ description: t("appearance.light.description"),
+ },
+ {
+ value: "dark" as const,
+ title: t("appearance.dark.title"),
+ description: t("appearance.dark.description"),
+ },
+ ];
+}
+
+export function AppearancePicker() {
+ const t = useTranslations();
+ const { theme, setTheme } = useTheme();
+ // next-themes only knows the stored value after hydration
+ const mounted = useMounted();
+ const current = mounted ? (theme ?? "system") : undefined;
+ const options = useThemeOptions();
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div role="radiogroup" aria-label={t("appearance.title")} className="flex flex-col gap-2">
+ {options.map(({ value, title, description }) => {
+ const { icon: Icon, preview } = PREVIEWS[value];
+ const selected = current === value;
+ return (
+ <button
+ key={value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => setTheme(value)}
+ className={cn(
+ "flex items-center gap-3 rounded-lg border-[1.5px] px-3 py-[11px] text-left transition-colors",
+ selected
+ ? "border-brand bg-surface-today"
+ : "border-line bg-surface-card hover:bg-surface-panel"
+ )}
+ >
+ <Icon
+ className={cn(
+ "size-[17px] shrink-0",
+ selected ? "text-brand-ink" : "text-fg-secondary"
+ )}
+ />
+ <span className="min-w-0 flex-1">
+ <span
+ className={cn(
+ "block text-[13.5px] font-semibold",
+ selected ? "text-brand-ink" : "text-fg-strong"
+ )}
+ >
+ {title}
+ </span>
+ <span
+ className={cn(
+ "mt-px block text-[11.5px]",
+ selected ? "text-brand-ink" : "text-fg-tertiary"
+ )}
+ >
+ {description}
+ </span>
+ </span>
+ <span className="flex" aria-hidden>
+ <span
+ className="h-[34px] w-[26px] rounded-l-[5px] border border-r-0 border-control"
+ style={{ background: preview[0] }}
+ />
+ <span
+ className="h-[34px] w-[26px] rounded-r-[5px] border border-control"
+ style={{ background: preview[1] }}
+ />
+ </span>
+ <Check
+ className={cn(
+ "size-[18px] shrink-0 text-brand",
+ !selected && "invisible"
+ )}
+ />
+ </button>
+ );
+ })}
+ </div>
+ <p className="rounded-lg border border-line bg-surface-panel px-3 py-2.5 text-[12px] leading-relaxed text-fg-secondary">
+ {t("appearance.hint")}
+ </p>
+ </div>
+ );
+}
diff --git a/components/auth-header.tsx b/components/auth-header.tsx
index 8f9283e..e2aec61 100644
--- a/components/auth-header.tsx
+++ b/components/auth-header.tsx
@@ -1,132 +1,72 @@
"use client";
-import { motion } from "motion/react";
-import { useTranslations, useLocale } from "next-intl";
import { useState } from "react";
import Link from "next/link";
-import { UserMenu } from "@/components/user-menu";
-import { Calendar as CalendarIcon, Bell, ExternalLink } from "lucide-react";
-import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
+import { useLocale, useTranslations } from "next-intl";
+import { CalendarDays } from "lucide-react";
+import { GuestMenu, UserMenu } from "@/components/user-menu";
import { ChangelogDialog } from "@/components/changelog-dialog";
-import { useConnectionStatus } from "@/hooks/useConnectionStatus";
+import { Pill } from "@/components/form-kit";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useVersionUpdateCheck } from "@/hooks/useVersionUpdate";
-/**
- * Simplified header for authentication pages
- * Shows only logo, app name, and user menu (for profile page)
- * No calendar-related elements
- */
interface AuthHeaderProps {
+ /** Right-hand controls: account menu when signed in, preferences and login for guests. */
showUserMenu?: boolean;
}
+/** Minimal 56px app header for pages without a calendar. */
export function AuthHeader({ showUserMenu = false }: AuthHeaderProps) {
const t = useTranslations();
+
+ return (
+ <header className="sticky top-0 z-30 flex h-14 shrink-0 items-center gap-3 border-b border-line bg-background px-4 lg:px-[18px]">
+ <Link href="/" className="flex min-w-0 items-center gap-3">
+ <span className="flex size-[26px] shrink-0 items-center justify-center rounded-[7px] bg-brand">
+ <CalendarDays className="size-[15px] text-white" />
+ </span>
+ <span className="truncate text-[15px] font-semibold text-fg-strong">
+ {t("app.title")}
+ </span>
+ </Link>
+ {/* Session lookups stay out of pages that only need the brand, e.g. while the DB is down */}
+ {showUserMenu && <HeaderSessionControls />}
+ </header>
+ );
+}
+
+function HeaderSessionControls() {
+ const t = useTranslations();
const locale = useLocale();
+ const { isGuest } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
const { versionInfo } = useVersionUpdateCheck();
- const { isOnline } = useConnectionStatus();
const [showChangelog, setShowChangelog] = useState(false);
+ const signedIn = isAuthEnabled && !isGuest;
+ const showUpdate = versionInfo?.hasUpdate && !versionInfo.isDev;
+
return (
<>
- <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
- <div className="container max-w-4xl mx-auto p-3 sm:p-4">
- <div className="space-y-3 sm:space-y-4">
- {/* Header with Logo and optional User Menu */}
- <div className="flex items-center justify-between gap-4">
- {/* Logo Section - Clickable to go home */}
- <Link href="/" className="flex items-center gap-3 group">
- <motion.div
- className="flex items-center gap-3"
- initial={{ opacity: 0, x: -20 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ duration: 0.3 }}
- >
- <div className="relative shrink-0">
- <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-700 dark:from-slate-800 dark:via-slate-700 dark:to-slate-600 flex items-center justify-center shadow-xl shadow-slate-900/50 dark:shadow-slate-950/70 ring-2 ring-slate-700/50 dark:ring-slate-600/50 transition-transform group-hover:scale-105">
- <CalendarIcon className="h-6 w-6 text-white" />
- </div>
- {/* Connection Status Indicator */}
- <div
- className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${
- isOnline ? "bg-green-500 animate-pulse" : "bg-red-500"
- }`}
- title={
- isOnline ? t("sync.connected") : t("sync.disconnected")
- }
- ></div>
- </div>
- <div>
- <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text transition-all group-hover:from-primary group-hover:via-primary group-hover:to-primary/70">
- {t("app.title")}
- </h1>
- <p className="text-xs text-muted-foreground font-medium">
- {t("app.subtitle", { default: "Organize your shifts" })}
- </p>
- </div>
- </motion.div>
- </Link>
-
- {/* User Menu (optional - shown on profile page) */}
- {showUserMenu && (
- <motion.div
- initial={{ opacity: 0, scale: 0.9 }}
- animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 0.3, delay: 0.15 }}
- >
- <UserMenu />
- </motion.div>
- )}
- </div>
-
- {/* Update Notification Banner */}
- {versionInfo?.hasUpdate && !versionInfo.isDev && (
- <motion.div
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3, delay: 0.15 }}
- className="relative"
- >
- <button
- onClick={() => setShowChangelog(true)}
- className="w-full bg-gradient-to-r from-primary/10 via-primary/5 to-primary/10 backdrop-blur-sm border border-primary/30 rounded-xl p-3 sm:p-3.5 flex items-center justify-between gap-3 hover:from-primary/15 hover:via-primary/10 hover:to-primary/15 hover:border-primary/40 transition-all shadow-sm hover:shadow-md active:scale-[0.99] group"
- >
- <div className="flex items-center gap-2.5 sm:gap-3 flex-1 min-w-0">
- <div className="relative shrink-0 w-9 h-9 sm:w-10 sm:h-10 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
- <Bell className="h-4 w-4 sm:h-5 sm:w-5 text-primary group-hover:scale-110 transition-transform" />
- <div className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-primary rounded-full animate-pulse shadow-sm"></div>
- </div>
- <div className="text-left flex-1 min-w-0">
- <p className="text-sm sm:text-base font-semibold text-primary mb-0.5">
- {t("update.available")}
- </p>
- <p className="text-xs sm:text-sm text-muted-foreground font-medium">
- {t("update.newVersion", {
- version: versionInfo.latestVersion || "unknown",
- })}
- </p>
- </div>
- </div>
- <div className="shrink-0 flex items-center gap-2 text-primary">
- <span className="text-xs sm:text-sm font-medium hidden sm:inline">
- {t("update.viewChangelog")}
- </span>
- <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/15 transition-colors">
- <ExternalLink className="h-4 w-4 group-hover:rotate-12 transition-transform" />
- </div>
- </div>
- </button>
- </motion.div>
- )}
- </div>
- </div>
- </div>
-
- {/* Changelog Dialog */}
- <ChangelogDialog
- open={showChangelog}
- onOpenChange={setShowChangelog}
- locale={locale}
- />
+ {isGuest && (
+ <Pill className="text-[11px] uppercase tracking-[0.04em]">
+ {t("emptyState.guestBadge")}
+ </Pill>
+ )}
+ <div className="flex-1" />
+ {showUpdate && (
+ <button
+ type="button"
+ onClick={() => setShowChangelog(true)}
+ className="hidden h-8 items-center gap-2 rounded-full bg-brand-soft px-3 text-[12.5px] font-semibold text-brand-ink transition-colors hover:bg-brand-soft/70 sm:flex"
+ >
+ <span className="size-1.5 rounded-full bg-brand-dot" />
+ {t("update.newVersion", { version: versionInfo?.latestVersion || "" })}
+ </button>
+ )}
+ {signedIn ? <UserMenu /> : <GuestMenu showLogin={isAuthEnabled} />}
+ <ChangelogDialog open={showChangelog} onOpenChange={setShowChangelog} locale={locale} />
</>
);
}
diff --git a/components/auth-provider-icons.tsx b/components/auth-provider-icons.tsx
new file mode 100644
index 0000000..2f77d63
--- /dev/null
+++ b/components/auth-provider-icons.tsx
@@ -0,0 +1,39 @@
+import type { SVGProps } from "react";
+
+// Monochrome brand marks from simple-icons (CC0); lucide's brand icons are deprecated.
+type IconProps = SVGProps<SVGSVGElement>;
+
+function BrandIcon({ d, ...props }: IconProps & { d: string }) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
+ <path d={d} />
+ </svg>
+ );
+}
+
+export function GoogleIcon(props: IconProps) {
+ return (
+ <BrandIcon
+ {...props}
+ d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"
+ />
+ );
+}
+
+export function GitHubIcon(props: IconProps) {
+ return (
+ <BrandIcon
+ {...props}
+ d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"
+ />
+ );
+}
+
+export function DiscordIcon(props: IconProps) {
+ return (
+ <BrandIcon
+ {...props}
+ d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
+ />
+ );
+}
diff --git a/components/auth-provider.tsx b/components/auth-provider.tsx
index 9ba2601..b069dfb 100644
--- a/components/auth-provider.tsx
+++ b/components/auth-provider.tsx
@@ -57,7 +57,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
// Redirect unauthenticated users from protected routes to login
// ONLY if guest access is NOT allowed
if (!isPublicRoute && !isAuthenticated && !auth.allowGuestAccess) {
- const loginUrl = `/login?returnUrl=${encodeURIComponent(pathname)}`;
+ const loginUrl = `/login?returnUrl=${encodeURIComponent(pathname + window.location.search)}`;
router.replace(loginUrl);
}
}, [
diff --git a/components/auth-shell.tsx b/components/auth-shell.tsx
new file mode 100644
index 0000000..dbec209
--- /dev/null
+++ b/components/auth-shell.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { ComponentProps, ReactNode, useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import {
+ eachDayOfInterval,
+ endOfMonth,
+ endOfWeek,
+ format,
+ isSameDay,
+ isSameMonth,
+ startOfMonth,
+ startOfWeek,
+} from "date-fns";
+import { CalendarDays, Eye, EyeOff } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { useClientValue } from "@/hooks/useMediaQuery";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+// The brand column is dark in both themes, so it uses fixed colors instead of tokens.
+const BRAND_SURFACE = "bg-[#101828] dark:bg-[#141b28] dark:border-[#1e2637]";
+
+// Early, late, night and vacation shift colors from the handoff; decorative only.
+const SAMPLE_SHIFTS = ["#2563eb", "#6d28d9", "#4338ca"];
+const SAMPLE_VACATION = "#047857";
+
+// 16px on phones keeps iOS from zooming into the field on focus.
+export const authInputClass =
+ "h-[42px] rounded-[9px] px-[13px] text-base sm:text-[14px]";
+
+export function AuthShell({
+ title,
+ description,
+ children,
+}: {
+ title: ReactNode;
+ description?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex min-h-dvh flex-col bg-background lg:flex-row">
+ <header
+ className={cn(
+ "flex h-14 shrink-0 items-center px-4 lg:hidden",
+ BRAND_SURFACE,
+ )}
+ >
+ <BrandMark />
+ </header>
+
+ <aside
+ className={cn(
+ "sticky top-0 hidden h-dvh w-[420px] shrink-0 flex-col overflow-y-auto px-[34px] py-9 lg:flex dark:border-r",
+ BRAND_SURFACE,
+ )}
+ >
+ <BrandMark />
+ <SampleMonth />
+ <InstanceFacts />
+ </aside>
+
+ <main className="flex flex-1 justify-center px-4 py-8 sm:py-12 lg:items-center lg:p-9">
+ <div className="flex w-full max-w-[380px] flex-col gap-[18px]">
+ <div>
+ <h1 className="text-[21px] font-semibold tracking-[-0.02em] text-fg-strong">
+ {title}
+ </h1>
+ {description && (
+ <p className="mt-1 text-[14px] text-fg-secondary">
+ {description}
+ </p>
+ )}
+ </div>
+ {children}
+ </div>
+ </main>
+ </div>
+ );
+}
+
+function BrandMark() {
+ const t = useTranslations();
+ return (
+ <div className="flex items-center gap-2.5">
+ <div className="flex size-[30px] items-center justify-center rounded-lg bg-brand">
+ <CalendarDays className="size-[17px] text-white" />
+ </div>
+ <span className="text-[16px] font-semibold tracking-[-0.01em] text-white">
+ {t("app.title")}
+ </span>
+ </div>
+ );
+}
+
+function sampleBars(day: Date, week: number): string[] {
+ const weekday = (day.getDay() + 6) % 7;
+ const n = day.getDate();
+ if (weekday === 6) return [];
+ if (week === 2 && weekday < 4) return [SAMPLE_VACATION];
+ if (weekday === 5 && n % 2 === 0) return [];
+ const first = SAMPLE_SHIFTS[(n + week) % 3];
+ return n % 3 === 2 ? [first, SAMPLE_SHIFTS[(n + week + 1) % 3]] : [first];
+}
+
+/** Abstract month pattern; nothing is fetched before sign-in. */
+function SampleMonth() {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const [today] = useState(() => new Date());
+
+ const days = useMemo(
+ () =>
+ eachDayOfInterval({
+ start: startOfWeek(startOfMonth(today), { weekStartsOn: 1 }),
+ end: endOfWeek(endOfMonth(today), { weekStartsOn: 1 }),
+ }),
+ [today],
+ );
+
+ return (
+ <div className="mt-8 flex flex-col gap-2.5">
+ <div className="flex items-baseline gap-2.5">
+ <span className="text-[14px] font-semibold text-white">
+ {format(today, "LLLL yyyy", { locale: dateLocale })}
+ </span>
+ <span className="font-mono text-[11.5px] text-[#98a2b3]">
+ {t("authPage.sampleMonth")}
+ </span>
+ </div>
+ <div aria-hidden="true" className="grid grid-cols-7 gap-1">
+ {days.slice(0, 7).map((day) => (
+ <div
+ key={`wd-${day.toISOString()}`}
+ className="text-center text-[9px] font-semibold uppercase tracking-[.04em] text-[#667085]"
+ >
+ {format(day, "EEEEEE", { locale: dateLocale })}
+ </div>
+ ))}
+ {days.map((day, i) => {
+ const inMonth = isSameMonth(day, today);
+ const isToday = isSameDay(day, today);
+ return (
+ <div
+ key={day.toISOString()}
+ className={cn(
+ "flex aspect-square flex-col items-center gap-0.5 rounded-[4px] px-0.5 py-[3px]",
+ isToday ? "bg-brand" : "bg-white/5",
+ !inMonth && "opacity-30",
+ )}
+ >
+ <span
+ className={cn(
+ "font-mono text-[8.5px] leading-[1.2]",
+ isToday ? "text-white" : "text-[#98a2b3]",
+ )}
+ >
+ {day.getDate()}
+ </span>
+ {inMonth &&
+ sampleBars(day, Math.floor(i / 7)).map((color, j) => (
+ <span
+ key={j}
+ className="h-[2.5px] w-[72%] rounded-full"
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+function InstanceFacts() {
+ const t = useTranslations();
+ const version = useVersionInfo()?.version;
+
+ const host = useClientValue(() => window.location.host, "");
+ const facts = [
+ { label: t("authPage.instance"), value: host },
+ { label: t("admin.systemInfo.version"), value: version ?? "–" },
+ ];
+
+ return (
+ <dl className="mt-auto flex flex-col gap-[9px] pt-7 font-mono text-[11.5px]">
+ {facts.map((fact) => (
+ <div key={fact.label} className="flex items-center gap-2.5">
+ <dt className="w-[78px] shrink-0 text-[#8a94a6]">{fact.label}</dt>
+ <dd className="min-w-0 truncate text-[#d0d5dd]">{fact.value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+export function PasswordInput({
+ className,
+ ...props
+}: Omit<ComponentProps<typeof Input>, "type">) {
+ const t = useTranslations();
+ const [visible, setVisible] = useState(false);
+ const Icon = visible ? EyeOff : Eye;
+ const label = visible
+ ? t("authPage.hidePassword")
+ : t("authPage.showPassword");
+
+ return (
+ <div className="relative">
+ <Input
+ {...props}
+ type={visible ? "text" : "password"}
+ className={cn(authInputClass, "pr-11", className)}
+ />
+ <button
+ type="button"
+ onClick={() => setVisible((v) => !v)}
+ disabled={props.disabled}
+ aria-label={label}
+ aria-pressed={visible}
+ title={label}
+ className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-r-[9px] text-fg-tertiary outline-none transition-colors hover:text-fg-body focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50"
+ >
+ <Icon className="size-[17px]" />
+ </button>
+ </div>
+ );
+}
+
+/** Horizontal rule with a centered word, e.g. "oder". */
+export function AuthDivider({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex items-center gap-3 text-[12px] text-fg-tertiary">
+ <span className="h-px flex-1 bg-line" />
+ {children}
+ <span className="h-px flex-1 bg-line" />
+ </div>
+ );
+}
diff --git a/components/calendar-compare-sheet.tsx b/components/calendar-compare-sheet.tsx
index 7b747d7..f81df03 100644
--- a/components/calendar-compare-sheet.tsx
+++ b/components/calendar-compare-sheet.tsx
@@ -1,14 +1,14 @@
"use client";
import { useTranslations } from "next-intl";
+import { Check } from "lucide-react";
import { CalendarWithCount } from "@/lib/types";
-import { BaseSheet } from "@/components/ui/base-sheet";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Alert, AlertDescription } from "@/components/ui/alert";
-import { Smartphone } from "lucide-react";
-import { motion } from "motion/react";
+import { Button } from "@/components/ui/button";
+import { PanelDialog } from "@/components/panel-dialog";
+import { cn } from "@/lib/utils";
interface CalendarCompareSheetProps {
+ open: boolean;
calendars: CalendarWithCount[];
selectedIds: string[];
onToggleCalendar: (id: string) => void;
@@ -16,9 +16,10 @@ interface CalendarCompareSheetProps {
onCancel: () => void;
}
-const MAX_CALENDARS = 3;
+export const MAX_COMPARE_CALENDARS = 3;
export function CalendarCompareSheet({
+ open,
calendars,
selectedIds,
onToggleCalendar,
@@ -26,85 +27,73 @@ export function CalendarCompareSheet({
onCancel,
}: CalendarCompareSheetProps) {
const t = useTranslations();
- const canStartCompare =
- selectedIds.length >= 2 && selectedIds.length <= MAX_CALENDARS;
- const isMaxReached = selectedIds.length >= MAX_CALENDARS;
+ const canStart = selectedIds.length >= 2 && selectedIds.length <= MAX_COMPARE_CALENDARS;
+ const maxReached = selectedIds.length >= MAX_COMPARE_CALENDARS;
return (
- <BaseSheet
- open={true}
- onOpenChange={onCancel}
+ <PanelDialog
+ open={open}
+ onOpenChange={(next) => !next && onCancel()}
title={t("calendar.selectToCompare")}
description={t("calendar.selectToCompareDescription")}
- showSaveButton
- onSave={onStartCompare}
- saveDisabled={!canStartCompare}
- saveLabel={t("calendar.startComparing")}
- maxWidth="md"
+ footer={
+ <>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onCancel}>
+ {t("common.cancel")}
+ </Button>
+ <Button className="h-10 flex-1 font-semibold" disabled={!canStart} onClick={onStartCompare}>
+ {t("calendar.startComparing")}
+ </Button>
+ </>
+ }
>
- {/* Mobile Warning */}
- <div className="lg:hidden mb-3">
- <Alert className="border-amber-500/50 bg-amber-50/50 dark:bg-amber-950/20">
- <Smartphone className="h-4 w-4 text-amber-600 dark:text-amber-500" />
- <AlertDescription className="text-sm text-amber-800 dark:text-amber-200">
- {t("calendar.mobileNotOptimized")}
- </AlertDescription>
- </Alert>
- </div>
-
- <div className="space-y-3">
+ <div className="flex flex-col gap-2">
{calendars.map((calendar) => {
- const isSelected = selectedIds.includes(calendar.id);
- const isDisabled = !isSelected && isMaxReached;
-
+ const selected = selectedIds.includes(calendar.id);
+ const disabled = !selected && maxReached;
return (
- <motion.div
+ <button
key={calendar.id}
- className={`border rounded-lg p-4 transition-all ${
- isDisabled
- ? "border-border opacity-50 cursor-not-allowed"
- : isSelected
- ? "border-primary bg-primary/5 cursor-pointer"
- : "border-border hover:border-primary/50 hover:bg-accent/50 cursor-pointer"
- }`}
- onClick={() => !isDisabled && onToggleCalendar(calendar.id)}
- whileHover={!isDisabled ? { scale: 1.01 } : {}}
- whileTap={!isDisabled ? { scale: 0.99 } : {}}
+ type="button"
+ role="checkbox"
+ aria-checked={selected}
+ disabled={disabled}
+ onClick={() => onToggleCalendar(calendar.id)}
+ className={cn(
+ "flex items-center gap-3 rounded-[10px] border-[1.5px] px-3 py-[11px] text-left transition-colors disabled:opacity-50",
+ selected
+ ? "border-brand bg-surface-today"
+ : "border-line bg-surface-card hover:bg-surface-panel"
+ )}
>
- <div className="flex items-center gap-3">
- <Checkbox
- checked={isSelected}
- disabled={isDisabled}
- onCheckedChange={() =>
- !isDisabled && onToggleCalendar(calendar.id)
- }
- className="pointer-events-none"
- />
- <div
- className="w-4 h-4 rounded-full shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <div className="flex-1 min-w-0">
- <p className="font-medium truncate">{calendar.name}</p>
- </div>
- </div>
- </motion.div>
+ <span
+ className="size-3 shrink-0 rounded-[4px]"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span
+ className={cn(
+ "flex-1 truncate text-[14px] font-semibold",
+ selected ? "text-brand-ink" : "text-fg-strong"
+ )}
+ >
+ {calendar.name}
+ </span>
+ <span
+ className={cn(
+ "flex size-5 items-center justify-center rounded-[6px] border",
+ selected ? "border-brand bg-brand text-white" : "border-control"
+ )}
+ >
+ {selected && <Check className="size-3.5" />}
+ </span>
+ </button>
);
})}
+ <p className="pt-1 text-[12px] text-fg-tertiary">
+ {t("calendar.compareSelected", { count: selectedIds.length })} ·{" "}
+ {t("calendarCompare.maxHint", { max: MAX_COMPARE_CALENDARS })}
+ </p>
</div>
-
- {/* Info Footer */}
- <div className="mt-4 text-sm text-muted-foreground text-center">
- {selectedIds.length > 0 ? (
- <span>
- {t("calendar.compareSelected", {
- count: selectedIds.length,
- })}
- </span>
- ) : (
- <span>{t("calendar.selectToCompareDescription")}</span>
- )}
- </div>
- </BaseSheet>
+ </PanelDialog>
);
}
diff --git a/components/calendar-compare-view.tsx b/components/calendar-compare-view.tsx
deleted file mode 100644
index 6737472..0000000
--- a/components/calendar-compare-view.tsx
+++ /dev/null
@@ -1,326 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { CalendarWithCount, ShiftWithCalendar } from "@/lib/types";
-import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
-import { Button } from "@/components/ui/button";
-import { CalendarContent } from "@/components/calendar-content";
-import { PresetSelector } from "@/components/preset-selector";
-import { Alert, AlertDescription } from "@/components/ui/alert";
-import { X, Link, Smartphone } from "lucide-react";
-import { motion } from "motion/react";
-import { Locale } from "date-fns";
-import { toast } from "sonner";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-
-interface CalendarCompareViewProps {
- calendars: CalendarWithCount[];
- selectedIds: string[];
- allCalendars: CalendarWithCount[];
- calendarDays: Date[];
- currentDate: Date;
- onDateChange: (date: Date) => void;
- shiftsMap: Map<string, ShiftWithCalendar[]>;
- notesMap: Map<string, CalendarNote[]>;
- externalSyncsMap: Map<string, ExternalSync[]>;
- presetsMap: Map<string, ShiftPreset[]>;
- selectedPresetId?: string;
- onSelectPreset: (id: string | undefined) => void;
- togglingDatesMap: Map<string, Set<string>>;
- maxShiftsToShow?: number;
- maxExternalShiftsToShow?: number;
- showShiftNotes: boolean;
- showFullTitles: boolean;
- shiftSortType: "startTime" | "createdAt" | "title";
- shiftSortOrder: "asc" | "desc";
- combinedSortMode: boolean;
- highlightedWeekdays?: number[];
- highlightColor?: string;
- locale?: Locale;
- onDayClick: (calendarId: string, date: Date) => void;
- onDayRightClick?: (
- calendarId: string,
- e: React.MouseEvent,
- date: Date
- ) => void;
- onNoteIconClick?: (
- calendarId: string,
- e: React.MouseEvent,
- date: Date
- ) => void;
- onLongPress?: (calendarId: string, date: Date) => void;
- onShowAllShifts: (
- calendarId: string,
- date: Date,
- shifts: ShiftWithCalendar[]
- ) => void;
- onShowSyncedShifts: (
- calendarId: string,
- date: Date,
- shifts: ShiftWithCalendar[]
- ) => void;
- onDeleteShift?: (calendarId: string, id: string) => void;
- onViewSettingsClick: () => void;
- onExit: () => void;
- hidePresetHeader?: boolean;
- onHidePresetHeaderChange?: (hide: boolean) => void;
- onPresetsChange: (calendarId: string) => void;
- onShiftsChange?: () => void;
- presetsLoadingMap?: Map<string, boolean>;
-}
-
-export function CalendarCompareView(props: CalendarCompareViewProps) {
- const t = useTranslations();
-
- const selectedCalendars = props.calendars.filter((cal) =>
- props.selectedIds.includes(cal.id)
- );
-
- // Pre-calculate permissions for all selected calendars
- // We need to call hooks unconditionally, so we always get permissions for all selected calendars
- const permission0 = useCalendarPermission(selectedCalendars[0]?.id);
- const permission1 = useCalendarPermission(selectedCalendars[1]?.id);
- const permission2 = useCalendarPermission(selectedCalendars[2]?.id);
-
- // Map permissions by calendar ID
- const permissionsMap = new Map<
- string,
- ReturnType<typeof useCalendarPermission>
- >();
- if (selectedCalendars[0])
- permissionsMap.set(selectedCalendars[0].id, permission0);
- if (selectedCalendars[1])
- permissionsMap.set(selectedCalendars[1].id, permission1);
- if (selectedCalendars[2])
- permissionsMap.set(selectedCalendars[2].id, permission2);
-
- // Find which calendar owns the selected preset
- const selectedPresetCalendarId = props.selectedPresetId
- ? (() => {
- for (const [calendarId, presets] of props.presetsMap.entries()) {
- if (presets.some((p) => p.id === props.selectedPresetId)) {
- return calendarId;
- }
- }
- return null;
- })()
- : null;
-
- const handleShareLink = () => {
- const url = new URL(window.location.href);
- url.searchParams.set("compare", props.selectedIds.join(","));
-
- navigator.clipboard
- .writeText(url.toString())
- .then(() => {
- toast.success(t("common.copied", { item: t("calendar.compareMode") }));
- })
- .catch(() => {
- toast.error(t("common.error"));
- });
- };
-
- return (
- <div className="min-h-screen flex flex-col bg-background">
- {/* Header */}
- <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">
- <div className="w-full px-3 sm:px-4 py-3 sm:py-4">
- <div className="space-y-3">
- {/* Title and Exit Button */}
- <div className="flex items-center justify-between">
- <div>
- <h1 className="text-xl sm:text-2xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- {t("calendar.compareMode")}
- </h1>
- <p className="text-sm text-muted-foreground mt-1">
- {t("calendar.compareSelected", {
- count: selectedCalendars.length,
- })}
- </p>
- </div>
- <div className="flex gap-2">
- <Button
- onClick={handleShareLink}
- variant="outline"
- className="gap-2"
- title={t("calendar.shareLinkDescription")}
- >
- <Link className="h-4 w-4" />
- <span className="hidden sm:inline">
- {t("calendar.shareLink")}
- </span>
- </Button>
- <Button
- onClick={props.onExit}
- variant="outline"
- className="gap-2"
- >
- <X className="h-4 w-4" />
- <span className="hidden sm:inline">
- {t("calendar.exitCompare")}
- </span>
- </Button>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Mobile Warning */}
- <div className="lg:hidden mx-3 mt-3 mb-1">
- <Alert className="border-amber-500/50 bg-amber-50/50 dark:bg-amber-950/20">
- <Smartphone className="h-4 w-4 text-amber-600 dark:text-amber-500" />
- <AlertDescription className="text-sm text-amber-800 dark:text-amber-200">
- {t("calendar.mobileNotOptimized")}
- </AlertDescription>
- </Alert>
- </div>
-
- {/* Calendars Grid */}
- <div className="flex-1 w-full px-1 sm:px-4 py-4">
- <div
- className={`grid gap-4 ${
- selectedCalendars.length === 2
- ? "grid-cols-1 lg:grid-cols-2"
- : "grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"
- }`}
- >
- {selectedCalendars.map((calendar) => {
- const shifts = props.shiftsMap.get(calendar.id) || [];
- const notes = props.notesMap.get(calendar.id) || [];
- const externalSyncs = props.externalSyncsMap.get(calendar.id) || [];
- const togglingDates =
- props.togglingDatesMap.get(calendar.id) || new Set();
- const calendarPresets = props.presetsMap.get(calendar.id) || [];
- const presetsLoading =
- props.presetsLoadingMap?.get(calendar.id) || false;
-
- // Get pre-calculated permission for this calendar
- const permission = permissionsMap.get(calendar.id)!;
-
- // Check if this calendar is disabled (preset from different calendar selected)
- const isDisabled =
- selectedPresetCalendarId !== null &&
- selectedPresetCalendarId !== calendar.id;
-
- return (
- <motion.div
- key={calendar.id}
- className="border border-border rounded-xl overflow-hidden bg-card shadow-sm"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3 }}
- >
- {/* Calendar Header */}
- <div
- className="px-4 py-3 border-b border-border/50 space-y-3"
- style={{
- background: `linear-gradient(135deg, ${calendar.color}20 0%, ${calendar.color}10 50%, transparent 100%)`,
- }}
- >
- <div className="flex items-center gap-3">
- <div
- className="w-5 h-5 rounded-full shrink-0 ring-2 ring-background"
- style={{ backgroundColor: calendar.color }}
- />
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold truncate text-base">
- {calendar.name}
- </h3>
- </div>
- </div>
-
- {/* Preset List for this calendar */}
- <div className="-mx-2">
- <PresetSelector
- calendars={props.allCalendars}
- presets={calendarPresets}
- selectedPresetId={props.selectedPresetId}
- onSelectPreset={props.onSelectPreset}
- onPresetsChange={() => props.onPresetsChange(calendar.id)}
- onShiftsChange={props.onShiftsChange}
- calendarId={calendar.id}
- onViewSettingsClick={props.onViewSettingsClick}
- loading={presetsLoading}
- hidePresetHeader={props.hidePresetHeader}
- onHidePresetHeaderChange={props.onHidePresetHeaderChange}
- hideManageButton={true}
- />
- </div>
- </div>
-
- {/* Calendar Content */}
- <div className="p-2 sm:p-3">
- {/* Hint when preset from different calendar is selected */}
- {isDisabled && (
- <div className="mb-3 p-3 bg-muted/50 border border-border/50 rounded-lg">
- <p className="text-xs text-muted-foreground text-center">
- {t("preset.cannotAddPresetHint")}
- </p>
- </div>
- )}
- <CalendarContent
- calendarDays={props.calendarDays}
- currentDate={props.currentDate}
- onDateChange={props.onDateChange}
- shifts={shifts}
- notes={notes}
- selectedPresetId={
- isDisabled ? undefined : props.selectedPresetId
- }
- togglingDates={togglingDates}
- externalSyncs={externalSyncs}
- maxShiftsToShow={props.maxShiftsToShow}
- maxExternalShiftsToShow={props.maxExternalShiftsToShow}
- showShiftNotes={props.showShiftNotes}
- showFullTitles={props.showFullTitles}
- shiftSortType={props.shiftSortType}
- shiftSortOrder={props.shiftSortOrder}
- combinedSortMode={props.combinedSortMode}
- highlightedWeekdays={props.highlightedWeekdays}
- highlightColor={props.highlightColor}
- selectedCalendar={calendar.id}
- locale={props.locale}
- onDayClick={
- isDisabled
- ? () => {}
- : (date) => props.onDayClick(calendar.id, date)
- }
- onDayRightClick={
- props.onDayRightClick && permission.canEdit
- ? (e, date) =>
- props.onDayRightClick!(calendar.id, e, date)
- : undefined
- }
- onNoteIconClick={
- props.onNoteIconClick && permission.canEdit
- ? (e, date) =>
- props.onNoteIconClick!(calendar.id, e, date)
- : undefined
- }
- onLongPress={
- props.onLongPress && permission.canEdit
- ? (date) => props.onLongPress!(calendar.id, date)
- : undefined
- }
- onShowAllShifts={(date, dayShifts) =>
- props.onShowAllShifts(calendar.id, date, dayShifts)
- }
- onShowSyncedShifts={(date, syncedShifts) =>
- props.onShowSyncedShifts(calendar.id, date, syncedShifts)
- }
- onDeleteShift={
- props.onDeleteShift && permission.canEdit
- ? (id) => props.onDeleteShift!(calendar.id, id)
- : undefined
- }
- />
- </div>
- </motion.div>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
diff --git a/components/calendar-content.tsx b/components/calendar-content.tsx
deleted file mode 100644
index c357396..0000000
--- a/components/calendar-content.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { motion } from "motion/react";
-import { useTranslations } from "next-intl";
-import { StickyNote } from "lucide-react";
-import { CalendarGrid } from "@/components/calendar-grid";
-import { ShiftStats } from "@/components/shift-stats";
-import { ShiftsList } from "@/components/shifts-list";
-import { MonthNavigation } from "@/components/month-navigation";
-import { GuestBanner } from "@/components/guest-banner";
-import { ShiftWithCalendar } from "@/lib/types";
-import { CalendarNote, ExternalSync } from "@/lib/db/schema";
-import { Locale } from "date-fns";
-import { useAuth } from "@/hooks/useAuth";
-
-interface CalendarContentProps {
- calendarDays: Date[];
- currentDate: Date;
- onDateChange: (date: Date) => void;
- shifts: ShiftWithCalendar[];
- notes: CalendarNote[];
- selectedPresetId?: string;
- togglingDates: Set<string>;
- externalSyncs: ExternalSync[];
- maxShiftsToShow?: number;
- maxExternalShiftsToShow?: number;
- showShiftNotes: boolean;
- showFullTitles: boolean;
- shiftSortType: "startTime" | "createdAt" | "title";
- shiftSortOrder: "asc" | "desc";
- combinedSortMode: boolean;
- highlightedWeekdays?: number[];
- highlightColor?: string;
- selectedCalendar: string | null;
- locale?: Locale;
- onDayClick: (date: Date) => void;
- onDayRightClick?: (e: React.MouseEvent, date: Date) => void;
- onNoteIconClick?: (e: React.MouseEvent, date: Date) => void;
- onLongPress?: (date: Date) => void;
- onShowAllShifts: (date: Date, shifts: ShiftWithCalendar[]) => void;
- onShowSyncedShifts: (date: Date, shifts: ShiftWithCalendar[]) => void;
- onDeleteShift?: (id: string) => void;
- onEditShift?: (shift: ShiftWithCalendar) => void;
-}
-
-export function CalendarContent(props: CalendarContentProps) {
- const t = useTranslations();
- const { isGuest } = useAuth();
-
- return (
- <>
- <MonthNavigation
- currentDate={props.currentDate}
- onDateChange={props.onDateChange}
- locale={props.locale}
- />
-
- {/* Guest Banner - compact on mobile, default on desktop */}
- {isGuest && (
- <>
- <div className="mb-4 px-2 sm:hidden">
- <GuestBanner variant="compact" />
- </div>
- <div className="hidden sm:block mb-4">
- <GuestBanner variant="default" />
- </div>
- </>
- )}
-
- <CalendarGrid
- calendarDays={props.calendarDays}
- currentDate={props.currentDate}
- shifts={props.shifts}
- notes={props.notes}
- selectedPresetId={props.selectedPresetId}
- togglingDates={props.togglingDates}
- externalSyncs={props.externalSyncs}
- maxShiftsToShow={props.maxShiftsToShow}
- maxExternalShiftsToShow={props.maxExternalShiftsToShow}
- showShiftNotes={props.showShiftNotes}
- showFullTitles={props.showFullTitles}
- shiftSortType={props.shiftSortType}
- shiftSortOrder={props.shiftSortOrder}
- combinedSortMode={props.combinedSortMode}
- highlightedWeekdays={props.highlightedWeekdays}
- highlightColor={props.highlightColor}
- onDayClick={props.onDayClick}
- onDayRightClick={props.onDayRightClick}
- onNoteIconClick={props.onNoteIconClick}
- onLongPress={props.onLongPress}
- onShowAllShifts={props.onShowAllShifts}
- onShowSyncedShifts={props.onShowSyncedShifts}
- onEditShift={props.onEditShift}
- />
-
- <motion.div
- className="px-2 sm:px-0 mb-4"
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: 0.3 }}
- >
- <div className="bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-xl p-3 sm:p-3.5 backdrop-blur-sm">
- <div className="flex items-center gap-2.5">
- <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/20 flex items-center justify-center">
- <StickyNote className="h-4 w-4 text-orange-500" />
- </div>
- <div className="flex-1">
- <p className="text-xs sm:hidden text-foreground/80 leading-relaxed">
- {t("note.hintMobile", {
- default:
- "Long press on a day to open notes. The note icon shows existing notes.",
- })}
- </p>
- <p className="hidden sm:block text-sm text-foreground/80 leading-relaxed">
- {t("note.hintDesktop", {
- default:
- "Right-click on a day to open notes. The note icon shows existing notes.",
- })}
- </p>
- </div>
- </div>
- </div>
- </motion.div>
-
- <div className="space-y-3 sm:space-y-4 px-2 sm:px-0">
- <ShiftStats
- calendarId={props.selectedCalendar || undefined}
- currentDate={props.currentDate}
- />
-
- <ShiftsList
- shifts={props.shifts}
- currentDate={props.currentDate}
- onDeleteShift={props.onDeleteShift}
- onEditShift={props.onEditShift}
- calendarId={props.selectedCalendar || undefined}
- />
- </div>
- </>
- );
-}
diff --git a/components/calendar-discovery-sheet.tsx b/components/calendar-discovery-sheet.tsx
index dcd3a8e..c3f543a 100644
--- a/components/calendar-discovery-sheet.tsx
+++ b/components/calendar-discovery-sheet.tsx
@@ -2,78 +2,47 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
- SheetFooter,
-} from "@/components/ui/sheet";
+import { EyeOff, Globe, Loader2, Search, UserPlus, type LucideIcon } from "lucide-react";
import { Input } from "@/components/ui/input";
-import { Badge } from "@/components/ui/badge";
-import { Switch } from "@/components/ui/switch";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Button } from "@/components/ui/button";
+import { PanelBody, PanelDialog } from "@/components/panel-dialog";
+import { SegmentedControl } from "@/components/segmented-control";
+import { ListRow, Pill, inputClass } from "@/components/form-kit";
import {
useCalendarSubscriptions,
type AvailableCalendar,
type DismissedCalendar,
} from "@/hooks/useCalendarSubscriptions";
-import {
- Users,
- Search,
- Eye,
- Edit,
- EyeOff,
- Loader2,
- UserPlus,
- Globe,
-} from "lucide-react";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
type CalendarDiscoverySheetProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
};
+type DiscoveryTab = "shared" | "public" | "hidden";
+
export function CalendarDiscoverySheet({
open,
onOpenChange,
}: CalendarDiscoverySheetProps) {
const t = useTranslations();
const [searchQuery, setSearchQuery] = useState("");
+ const [tab, setTab] = useState<DiscoveryTab>("shared");
const {
availableCalendars,
dismissedCalendars,
loading,
subscribe,
dismiss,
- } = useCalendarSubscriptions();
+ } = useCalendarSubscriptions(open);
- // Separate calendars by source
- const sharedCalendars = availableCalendars.filter(
- (cal) => cal.source === "shared"
- );
- const publicCalendars = availableCalendars.filter(
- (cal) => cal.source === "guest"
- );
+ const sharedCalendars = availableCalendars.filter((cal) => cal.source === "shared");
+ const publicCalendars = availableCalendars.filter((cal) => cal.source === "guest");
- // Filter search in all tabs
- const filterBySearch = (calendars: AvailableCalendar[]) =>
- calendars.filter((cal) =>
- cal.name.toLowerCase().includes(searchQuery.toLowerCase())
- );
-
- // Filter dismissed calendars by search
- const filteredDismissed = dismissedCalendars.filter((cal) =>
- cal.name.toLowerCase().includes(searchQuery.toLowerCase())
- );
+ const matchesSearch = (cal: { name: string }) =>
+ cal.name.toLowerCase().includes(searchQuery.toLowerCase());
const handleToggleSubscription = async (
calendar: AvailableCalendar,
@@ -90,336 +59,183 @@ export function CalendarDiscoverySheet({
await subscribe(calendar.id, calendar.name);
};
- const renderCalendarCard = (calendar: AvailableCalendar) => {
- // Use permission for shared calendars (owner/admin/write/read), guestPermission for public calendars
- const actualPermission =
- calendar.source === "shared" && calendar.permission
- ? calendar.permission
- : calendar.guestPermission;
- const isReadOnly = actualPermission === "read";
- const isAdmin =
- actualPermission === "admin" || actualPermission === "owner";
-
- return (
- <div
- key={calendar.id}
- className="flex flex-col sm:flex-row sm:items-center gap-3 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all p-4"
- style={{ borderLeftColor: calendar.color, borderLeftWidth: 4 }}
- >
- <div className="flex items-start sm:items-center gap-3 flex-1 min-w-0">
- {/* Calendar info */}
- <div className="flex-1 min-w-0">
- <div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-2 mb-1">
- <div className="font-semibold flex items-center gap-2">
- <div
- className="w-1 h-4 rounded-full"
- style={{ backgroundColor: calendar.color }}
- />
- <span className="truncate">{calendar.name}</span>
- </div>
- <div className="flex flex-wrap items-center gap-1.5">
- {isAdmin ? (
- <Badge
- variant="default"
- className="flex items-center gap-1 text-xs bg-blue-600 hover:bg-blue-700"
- >
- <Users className="h-3 w-3" />
- <span>{t("common.labels.permissions.admin")}</span>
- </Badge>
- ) : isReadOnly ? (
- <Badge
- variant="secondary"
- className="flex items-center gap-1 text-xs"
- >
- <Eye className="h-3 w-3" />
- <span>{t("common.labels.permissions.read")}</span>
- </Badge>
- ) : (
- <Badge
- variant="default"
- className="flex items-center gap-1 text-xs bg-green-600 hover:bg-green-700"
- >
- <Edit className="h-3 w-3" />
- <span>{t("common.labels.permissions.write")}</span>
- </Badge>
- )}
- </div>
- </div>
- {calendar.owner && (
- <p className="text-sm text-muted-foreground truncate">
- {calendar.owner.name}
- </p>
- )}
- </div>
- </div>
-
- {/* Toggle switch */}
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="flex items-center justify-end sm:justify-start gap-2 sm:pl-0">
- <span className="text-sm text-muted-foreground sm:hidden">
- {calendar.isSubscribed
- ? t("calendar.subscribed")
- : t("calendar.subscribe")}
- </span>
- <Switch
- checked={calendar.isSubscribed}
- onCheckedChange={() =>
- handleToggleSubscription(calendar, calendar.isSubscribed)
- }
- />
- </div>
- </TooltipTrigger>
- <TooltipContent>
- {calendar.isSubscribed
- ? t("calendar.unsubscribeTooltip")
- : t("calendar.subscribeTooltip")}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- );
+ const permissionPill = (permission: string | undefined) => {
+ if (permission === "owner" || permission === "admin") {
+ return (
+ <Pill tone="brand">
+ {permission === "owner"
+ ? t("sharingSheet.owner")
+ : t("common.labels.permissions.admin")}
+ </Pill>
+ );
+ }
+ if (permission === "write") {
+ return <Pill tone="warning">{t("sharingSheet.permWrite")}</Pill>;
+ }
+ return <Pill>{t("sharingSheet.permRead")}</Pill>;
};
- const renderDismissedCard = (calendar: DismissedCalendar) => {
- const isReadOnly = calendar.permission === "read";
- const isAdmin =
- calendar.permission === "admin" || calendar.permission === "owner";
-
- return (
- <div
- key={calendar.id}
- className="flex flex-col sm:flex-row sm:items-center gap-3 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all p-4 opacity-60"
- style={{ borderLeftColor: calendar.color, borderLeftWidth: 4 }}
- >
- <div className="flex items-start sm:items-center gap-3 flex-1 min-w-0">
- {/* Calendar info */}
- <div className="flex-1 min-w-0">
- <div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-2 mb-1">
- <div className="font-semibold flex items-center gap-2">
- <div
- className="w-1 h-4 rounded-full"
- style={{ backgroundColor: calendar.color }}
- />
- <span className="truncate">{calendar.name}</span>
- </div>
- <div className="flex flex-wrap items-center gap-1.5">
- {calendar.source === "shared" && (
- <Badge
- variant="secondary"
- className="flex items-center gap-1 text-xs"
- >
- <UserPlus className="h-3 w-3" />
- <span>{t("share.sharedWithYou")}</span>
- </Badge>
- )}
- {calendar.source === "guest" && (
- <Badge
- variant="outline"
- className="flex items-center gap-1 text-xs"
- >
- <Globe className="h-3 w-3" />
- <span>{t("calendar.publicBadge")}</span>
- </Badge>
- )}
- {isAdmin ? (
- <Badge
- variant="secondary"
- className="flex items-center gap-1 text-xs"
- >
- <Users className="h-3 w-3" />
- <span>{t("common.labels.permissions.admin")}</span>
- </Badge>
- ) : isReadOnly ? (
- <Badge
- variant="secondary"
- className="flex items-center gap-1 text-xs"
- >
- <Eye className="h-3 w-3" />
- <span>{t("common.labels.permissions.read")}</span>
- </Badge>
- ) : (
- <Badge
- variant="secondary"
- className="flex items-center gap-1 text-xs"
- >
- <Edit className="h-3 w-3" />
- <span>{t("common.labels.permissions.write")}</span>
- </Badge>
- )}
- </div>
- </div>
- {calendar.owner && (
- <p className="text-sm text-muted-foreground truncate">
- {calendar.owner.name}
- </p>
- )}
- </div>
+ const renderRow = ({
+ calendar,
+ pills,
+ action,
+ muted,
+ }: {
+ calendar: AvailableCalendar | DismissedCalendar;
+ pills: React.ReactNode;
+ action: React.ReactNode;
+ muted?: boolean;
+ }) => (
+ <ListRow key={calendar.id}>
+ <span
+ className={cn("shift-rail size-2.5 shrink-0 rounded-full", muted && "opacity-50")}
+ style={shiftVars(calendar.color)}
+ />
+ <div className="min-w-0 flex-1">
+ <div
+ className={cn(
+ "truncate text-[14px] font-semibold",
+ muted ? "text-fg-secondary" : "text-fg-strong"
+ )}
+ >
+ {calendar.name}
+ </div>
+ <div className="mt-1 flex min-w-0 flex-wrap items-center gap-1.5">
+ {pills}
+ {calendar.owner && (
+ <span className="truncate text-[12px] text-fg-tertiary">
+ {calendar.owner.name}
+ </span>
+ )}
</div>
-
- {/* Toggle switch */}
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="flex items-center justify-end sm:justify-start gap-2 sm:pl-0">
- <span className="text-sm text-muted-foreground sm:hidden">
- {t("calendar.showAgain")}
- </span>
- <Switch
- checked={false}
- onCheckedChange={() => handleShowAgain(calendar)}
- />
- </div>
- </TooltipTrigger>
- <TooltipContent>{t("calendar.subscribeTooltip")}</TooltipContent>
- </Tooltip>
- </TooltipProvider>
</div>
- );
- };
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- className="w-full sm:max-w-2xl flex flex-col p-0 gap-0"
- >
- <SheetHeader 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">
- <SheetTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text flex items-center gap-2">
- <Users className="h-5 w-5 flex-shrink-0" />
- <span className="truncate">{t("calendar.browseCalendars")}</span>
- </SheetTitle>
- <SheetDescription className="text-sm text-muted-foreground">
- {t("calendar.browseCalendarsDescription")}
- </SheetDescription>
- </SheetHeader>
-
- <div className="flex flex-col flex-1 min-h-0 p-6 space-y-4 overflow-y-auto">
- {/* Search */}
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("common.search")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-9"
- />
- </div>
+ {action}
+ </ListRow>
+ );
- {loading ? (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
- </div>
+ // Shared calendars carry the share permission, public ones the guest permission
+ const renderAvailable = (calendar: AvailableCalendar) =>
+ renderRow({
+ calendar,
+ pills: permissionPill(
+ calendar.source === "shared" && calendar.permission
+ ? calendar.permission
+ : calendar.guestPermission
+ ),
+ action: (
+ <Button
+ size="sm"
+ variant={calendar.isSubscribed ? "outline" : "default"}
+ title={
+ calendar.isSubscribed
+ ? t("calendar.unsubscribeTooltip")
+ : t("calendar.subscribeTooltip")
+ }
+ onClick={() => handleToggleSubscription(calendar, calendar.isSubscribed)}
+ className="h-8 shrink-0 rounded-lg px-3 text-[12.5px] font-semibold"
+ >
+ {calendar.isSubscribed ? t("discovery.unsubscribe") : t("calendar.subscribe")}
+ </Button>
+ ),
+ });
+
+ const renderDismissed = (calendar: DismissedCalendar) =>
+ renderRow({
+ calendar,
+ muted: true,
+ pills: (
+ <>
+ {calendar.source === "shared" ? (
+ <Pill>{t("share.sharedWithYou")}</Pill>
) : (
- <Tabs
- defaultValue="shared"
- className="flex-1 min-h-0 flex flex-col"
- >
- <TabsList className="grid w-full grid-cols-3">
- <TabsTrigger value="shared" className="gap-2">
- <UserPlus className="h-4 w-4" />
- {t("calendar.sharedTab")}
- {sharedCalendars.length > 0 && (
- <Badge variant="secondary" className="ml-1 text-xs">
- {sharedCalendars.length}
- </Badge>
- )}
- </TabsTrigger>
- <TabsTrigger value="public" className="gap-2">
- <Globe className="h-4 w-4" />
- {t("calendar.publicTab")}
- {publicCalendars.length > 0 && (
- <Badge variant="secondary" className="ml-1 text-xs">
- {publicCalendars.length}
- </Badge>
- )}
- </TabsTrigger>
- <TabsTrigger value="hidden" className="gap-2">
- <EyeOff className="h-4 w-4" />
- {t("calendar.hiddenTab")}
- {dismissedCalendars.length > 0 && (
- <Badge variant="secondary" className="ml-1 text-xs">
- {dismissedCalendars.length}
- </Badge>
- )}
- </TabsTrigger>
- </TabsList>
+ <Pill>{t("calendar.publicBadge")}</Pill>
+ )}
+ {permissionPill(calendar.permission)}
+ </>
+ ),
+ action: (
+ <Button
+ size="sm"
+ variant="outline"
+ title={t("calendar.subscribeTooltip")}
+ onClick={() => handleShowAgain(calendar)}
+ className="h-8 shrink-0 rounded-lg px-3 text-[12.5px] font-semibold"
+ >
+ {t("calendar.showAgain")}
+ </Button>
+ ),
+ });
+
+ const emptyState = (Icon: LucideIcon, message: string) => (
+ <div className="flex flex-col items-center justify-center gap-2.5 py-12 text-center">
+ <Icon className="size-6 text-fg-faint" />
+ <p className="text-[13px] text-fg-tertiary">
+ {searchQuery ? t("common.noResults") : message}
+ </p>
+ </div>
+ );
- <TabsContent
- value="shared"
- className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
- >
- {filterBySearch(sharedCalendars).length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-center">
- <UserPlus className="h-12 w-12 text-muted-foreground/50 mb-3" />
- <p className="text-sm text-muted-foreground">
- {searchQuery
- ? t("common.noResults")
- : t("calendar.noSharedCalendars")}
- </p>
- </div>
- ) : (
- filterBySearch(sharedCalendars).map((calendar) =>
- renderCalendarCard(calendar)
- )
- )}
- </TabsContent>
+ const count = (n: number) =>
+ n > 0 ? <span className="font-mono text-[11.5px] font-medium text-fg-tertiary">{n}</span> : null;
- <TabsContent
- value="public"
- className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
- >
- {filterBySearch(publicCalendars).length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-center">
- <Globe className="h-12 w-12 text-muted-foreground/50 mb-3" />
- <p className="text-sm text-muted-foreground">
- {searchQuery
- ? t("common.noResults")
- : t("calendar.noPublicCalendars")}
- </p>
- </div>
- ) : (
- filterBySearch(publicCalendars).map((calendar) =>
- renderCalendarCard(calendar)
- )
- )}
- </TabsContent>
+ const visibleShared = sharedCalendars.filter(matchesSearch);
+ const visiblePublic = publicCalendars.filter(matchesSearch);
+ const visibleDismissed = dismissedCalendars.filter(matchesSearch);
- <TabsContent
- value="hidden"
- className="flex-1 min-h-0 overflow-y-auto space-y-3 mt-4"
- >
- {filteredDismissed.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-center">
- <EyeOff className="h-12 w-12 text-muted-foreground/50 mb-3" />
- <p className="text-sm text-muted-foreground">
- {searchQuery
- ? t("common.noResults")
- : t("calendar.noHiddenCalendars")}
- </p>
- </div>
- ) : (
- filteredDismissed.map((calendar) =>
- renderDismissedCard(calendar)
- )
- )}
- </TabsContent>
- </Tabs>
- )}
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("calendar.browseCalendars")}
+ description={t("calendar.browseCalendarsDescription")}
+ width="md"
+ bare
+ >
+ <div className="flex shrink-0 flex-col gap-3 border-b border-line px-[22px] py-3.5">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <Input
+ placeholder={t("common.search")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ aria-label={t("common.search")}
+ className={cn(inputClass, "pl-9")}
+ />
</div>
-
- <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
+ <SegmentedControl
+ value={tab}
+ onChange={setTab}
+ label={t("calendar.browseCalendars")}
+ options={[
+ { value: "shared", label: t("calendar.sharedTab"), badge: count(sharedCalendars.length) },
+ { value: "public", label: t("calendar.publicTab"), badge: count(publicCalendars.length) },
+ { value: "hidden", label: t("calendar.hiddenTab"), badge: count(dismissedCalendars.length) },
+ ]}
+ />
+ </div>
+ <PanelBody className="min-h-[260px]">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="size-6 animate-spin text-fg-tertiary" />
+ </div>
+ ) : tab === "shared" ? (
+ visibleShared.length === 0 ? (
+ emptyState(UserPlus, t("calendar.noSharedCalendars"))
+ ) : (
+ <div className="flex flex-col gap-2">{visibleShared.map(renderAvailable)}</div>
+ )
+ ) : tab === "public" ? (
+ visiblePublic.length === 0 ? (
+ emptyState(Globe, t("calendar.noPublicCalendars"))
+ ) : (
+ <div className="flex flex-col gap-2">{visiblePublic.map(renderAvailable)}</div>
+ )
+ ) : visibleDismissed.length === 0 ? (
+ emptyState(EyeOff, t("calendar.noHiddenCalendars"))
+ ) : (
+ <div className="flex flex-col gap-2">{visibleDismissed.map(renderDismissed)}</div>
+ )}
+ </PanelBody>
+ </PanelDialog>
);
}
diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsx
deleted file mode 100644
index fab4756..0000000
--- a/components/calendar-grid.tsx
+++ /dev/null
@@ -1,570 +0,0 @@
-import { motion } from "motion/react";
-import { RefreshCw } from "lucide-react";
-import { ShiftWithCalendar } from "@/lib/types";
-import { CalendarNote, ExternalSync } from "@/lib/db/schema";
-import { isToday } from "date-fns";
-import { useTranslations } from "next-intl";
-import { useRef, useEffect } from "react";
-import { formatDateToLocal } from "@/lib/date-utils";
-import { CalendarShiftCard } from "./calendar-shift-card";
-import { findNotesForDate } from "@/lib/event-utils";
-
-interface CalendarGridProps {
- calendarDays: Date[];
- currentDate: Date;
- shifts: ShiftWithCalendar[];
- notes: CalendarNote[];
- selectedPresetId: string | undefined;
- togglingDates: Set<string>;
- externalSyncs: ExternalSync[];
- maxShiftsToShow?: number; // undefined = show all (regular shifts)
- maxExternalShiftsToShow?: number; // undefined = show all (external shifts)
- showShiftNotes?: boolean; // show notes in shift cards
- showFullTitles?: boolean; // show full titles without truncation
- shiftSortType?: "startTime" | "createdAt" | "title"; // sort type
- shiftSortOrder?: "asc" | "desc"; // sort order
- combinedSortMode?: boolean; // sort all shifts together or separately
- highlightedWeekdays?: number[]; // weekdays to highlight (0=Sunday, 6=Saturday)
- highlightColor?: string; // color for highlighted days
- onDayClick: (date: Date) => void;
- onDayRightClick?: (e: React.MouseEvent, date: Date) => void;
- onNoteIconClick?: (e: React.MouseEvent, date: Date) => void;
- onLongPress?: (date: Date) => void;
- onShowAllShifts?: (date: Date, shifts: ShiftWithCalendar[]) => void;
- onShowSyncedShifts?: (date: Date, shifts: ShiftWithCalendar[]) => void;
- onEditShift?: (shift: ShiftWithCalendar) => void;
-}
-
-export function CalendarGrid({
- calendarDays,
- currentDate,
- shifts,
- notes,
- selectedPresetId,
- togglingDates,
- externalSyncs,
- maxShiftsToShow,
- maxExternalShiftsToShow,
- showShiftNotes = false,
- showFullTitles = false,
- shiftSortType = "createdAt",
- shiftSortOrder = "asc",
- combinedSortMode = false,
- highlightedWeekdays = [],
- highlightColor = "#fbbf24",
- onDayClick,
- onDayRightClick,
- onNoteIconClick,
- onLongPress,
- onShowAllShifts,
- onShowSyncedShifts,
- onEditShift,
-}: CalendarGridProps) {
- const t = useTranslations();
- const pressTimerRef = useRef<Record<string, NodeJS.Timeout>>({});
-
- // Cleanup all timers on unmount
- useEffect(() => {
- return () => {
- Object.values(pressTimerRef.current).forEach((timer) => {
- if (timer) clearTimeout(timer);
- });
- pressTimerRef.current = {};
- };
- }, []);
-
- const getShiftsForDate = (date: Date) => {
- return shifts.filter(
- (shift) => shift.date && isSameDay(shift.date as Date, date),
- );
- };
-
- const isSameDay = (date1: Date, date2: Date) => {
- return (
- date1.getFullYear() === date2.getFullYear() &&
- date1.getMonth() === date2.getMonth() &&
- date1.getDate() === date2.getDate()
- );
- };
-
- const sortShifts = (shiftsToSort: ShiftWithCalendar[]) => {
- return [...shiftsToSort].sort((a, b) => {
- let comparison = 0;
-
- switch (shiftSortType) {
- case "startTime":
- comparison = a.startTime.localeCompare(b.startTime);
- break;
- case "createdAt": {
- // Handle null values by treating them as very old dates
- const aTime = a.createdAt ? new Date(a.createdAt).getTime() : 0;
- const bTime = b.createdAt ? new Date(b.createdAt).getTime() : 0;
- comparison = aTime - bTime;
- break;
- }
- case "title":
- comparison = a.title.localeCompare(b.title);
- break;
- }
-
- return shiftSortOrder === "asc" ? comparison : -comparison;
- });
- };
-
- return (
- <div className="grid grid-cols-7 gap-0 sm:gap-1.5 mb-6">
- {[
- t("common.weekday.monday"),
- t("common.weekday.tuesday"),
- t("common.weekday.wednesday"),
- t("common.weekday.thursday"),
- t("common.weekday.friday"),
- t("common.weekday.saturday"),
- t("common.weekday.sunday"),
- ].map((day) => (
- <div
- key={day}
- className="text-center text-[11px] sm:text-xs font-semibold text-muted-foreground p-1 sm:p-2"
- >
- {day}
- </div>
- ))}
- {calendarDays.map((day, idx) => {
- const dayShifts = getShiftsForDate(day);
-
- // Find all notes/events for this day (including recurring)
- const allDayNotes = findNotesForDate(notes, day);
-
- // Count events and regular notes separately
- const dayEvents = allDayNotes.filter((n) => n.type === "event");
- const dayRegularNotes = allDayNotes.filter((n) => n.type !== "event");
- const totalNotesCount = allDayNotes.length;
-
- // Get first event and note for display
- const dayEvent = dayEvents[0];
- const dayNote = dayRegularNotes[0];
-
- const isCurrentMonth = day.getMonth() === currentDate.getMonth();
- const isTodayDate = isToday(day);
-
- // Use formatDateToLocal to match the format used in handleAddShift
- const dayKey = formatDateToLocal(day);
- const isToggling = togglingDates.has(dayKey);
-
- const handleTouchStart = () => {
- if (onLongPress) {
- pressTimerRef.current[dayKey] = setTimeout(
- () => onLongPress(day),
- 500,
- );
- }
- };
- const handleTouchEnd = () => {
- if (pressTimerRef.current[dayKey]) {
- clearTimeout(pressTimerRef.current[dayKey]);
- delete pressTimerRef.current[dayKey];
- }
- };
-
- const isHighlighted =
- highlightedWeekdays.length > 0 &&
- highlightedWeekdays.includes(day.getDay());
-
- // Create gradient border for multiple events
- // Note: borderImage doesn't support border-radius, so we use a different approach
- const hasMultiEventBorder = dayEvents.length > 1 && !isTodayDate;
- const eventBorderStyle =
- dayEvents.length === 1 && !isTodayDate
- ? {
- borderColor: dayEvents[0].color || "#3b82f6",
- borderWidth: "2px",
- }
- : {};
-
- return (
- <motion.button
- key={idx}
- onClick={() => onDayClick(day)}
- onContextMenu={(e) => {
- e.preventDefault();
- if (onDayRightClick) {
- onDayRightClick(e, day);
- }
- }}
- onTouchStart={handleTouchStart}
- onTouchEnd={handleTouchEnd}
- onTouchMove={handleTouchEnd}
- disabled={isToggling}
- whileTap={{ scale: 0.95 }}
- style={{
- WebkitUserSelect: "none",
- userSelect: "none",
- WebkitTouchCallout: "none",
- ...(isHighlighted &&
- !isTodayDate && {
- backgroundColor: `${highlightColor}15`,
- borderColor: `${highlightColor}40`,
- }),
- // Event border styling (overrides highlight if both present)
- ...eventBorderStyle,
- // Multi-event gradient border using background trick to support border-radius
- ...(hasMultiEventBorder && {
- backgroundImage: `linear-gradient(var(--background), var(--background)), linear-gradient(to right, ${dayEvents
- .map((e) => e.color || "#3b82f6")
- .join(", ")})`,
- backgroundOrigin: "border-box",
- backgroundClip: "padding-box, border-box",
- border: "2px solid transparent",
- }),
- }}
- className={`
- min-h-25 sm:min-h-28 px-1 py-1.5 sm:p-2.5 rounded-md sm:rounded-lg text-sm transition-all relative flex flex-col border sm:border-2
- ${isCurrentMonth ? "text-foreground" : "text-muted-foreground/50"}
- ${
- isTodayDate
- ? "border-primary shadow-lg shadow-primary/20 bg-primary/5 ring-2 ring-primary/20"
- : dayEvent
- ? "" // Event border is handled by inline style
- : "border-border/30 sm:border-border/50"
- }
- ${
- isCurrentMonth
- ? "hover:bg-accent cursor-pointer active:bg-accent/80 hover:border-border"
- : selectedPresetId
- ? "cursor-not-allowed"
- : "cursor-pointer"
- }
- ${!isCurrentMonth ? "opacity-40" : ""}
- ${isToggling ? "opacity-50 cursor-wait pointer-events-none" : ""}
- `}
- >
- <div
- className={`text-sm sm:text-sm font-semibold mb-1 flex items-center justify-between gap-1 ${
- isTodayDate ? "text-primary" : ""
- }`}
- >
- <span className="shrink-0">{day.getDate()}</span>
- <div className="flex items-center gap-1 min-w-0">
- {/* Multi-indicator badge when multiple notes/events exist */}
- {totalNotesCount > 1 && (
- <span
- className={`inline-flex items-center justify-center text-[9px] sm:text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-primary/20 text-primary border border-primary/30 ${
- !selectedPresetId && onNoteIconClick
- ? "cursor-pointer hover:bg-primary/30 transition-colors"
- : ""
- }`}
- title={t("note.multipleEntries", {
- count: totalNotesCount,
- })}
- onClick={(e) => {
- if (!selectedPresetId && onNoteIconClick) {
- e.stopPropagation();
- onNoteIconClick(e, day);
- }
- }}
- >
- {totalNotesCount}
- </span>
- )}
- {/* Display first event title - clickable if no preset selected */}
- {dayEvent && totalNotesCount === 1 && (
- <span
- className={`text-[10px] sm:text-xs font-medium truncate opacity-75 min-w-0 ${
- !selectedPresetId && onNoteIconClick
- ? "cursor-pointer hover:opacity-100 transition-opacity"
- : ""
- }`}
- style={{ color: dayEvent.color || "#3b82f6" }}
- title={dayEvent.note}
- onClick={(e) => {
- if (!selectedPresetId && onNoteIconClick) {
- e.stopPropagation();
- onNoteIconClick(e, day);
- }
- }}
- >
- {dayEvent.note}
- </span>
- )}
- {/* Display first note title if no event and only one entry - clickable if no preset selected */}
- {!dayEvent && dayNote && totalNotesCount === 1 && (
- <span
- className={`text-[10px] sm:text-xs font-medium text-orange-500 truncate opacity-75 min-w-0 ${
- !selectedPresetId && onNoteIconClick
- ? "cursor-pointer hover:opacity-100 transition-opacity"
- : ""
- }`}
- title={dayNote.note}
- onClick={(e) => {
- if (!selectedPresetId && onNoteIconClick) {
- e.stopPropagation();
- onNoteIconClick(e, day);
- }
- }}
- >
- {dayNote.note}
- </span>
- )}
- </div>
- </div>
- <div className="flex-1 space-y-0.5 sm:space-y-1 overflow-visible">
- {(() => {
- // Separate shifts by sync displayMode
- const syncedShiftsByMode: {
- [key: string]: ShiftWithCalendar[];
- } = {};
-
- dayShifts.forEach((shift) => {
- if (shift.syncedFromExternal && shift.externalSyncId) {
- const sync = externalSyncs.find(
- (s) => s.id === shift.externalSyncId,
- );
- const displayMode = sync?.displayMode || "normal";
-
- if (displayMode === "minimal") {
- if (!syncedShiftsByMode[shift.externalSyncId]) {
- syncedShiftsByMode[shift.externalSyncId] = [];
- }
- syncedShiftsByMode[shift.externalSyncId].push(shift);
- }
- }
- });
-
- // Get shifts to display normally - separate regular from external
- const regularShifts = dayShifts.filter(
- (s) => !s.syncedFromExternal,
- );
- const externalNormalShifts = dayShifts.filter((s) => {
- if (!s.syncedFromExternal) return false;
- if (!s.externalSyncId) return false;
- const sync = externalSyncs.find(
- (sync) => sync.id === s.externalSyncId,
- );
- return sync && sync.displayMode === "normal";
- });
-
- // Apply sorting based on mode
- let sortedRegularShifts: ShiftWithCalendar[];
- let sortedExternalNormalShifts: ShiftWithCalendar[];
- let allSortedShifts: ShiftWithCalendar[];
-
- if (combinedSortMode) {
- // Combined mode: sort all shifts together
- const allNormalShifts = [
- ...regularShifts,
- ...externalNormalShifts,
- ];
- allSortedShifts = sortShifts(allNormalShifts);
- // Keep the separate arrays for individual limits
- sortedRegularShifts = sortShifts(regularShifts);
- sortedExternalNormalShifts = sortShifts(externalNormalShifts);
- } else {
- // Separate mode: sort each group separately
- sortedRegularShifts = sortShifts(regularShifts);
- sortedExternalNormalShifts = sortShifts(externalNormalShifts);
- allSortedShifts = [];
- }
-
- // Pre-compute index maps to avoid O(n²) complexity during rendering
- const regularIndexMap = new Map<string, number>();
- const externalIndexMap = new Map<string, number>();
-
- if (combinedSortMode) {
- sortedRegularShifts.forEach((shift, index) => {
- regularIndexMap.set(shift.id, index);
- });
- sortedExternalNormalShifts.forEach((shift, index) => {
- externalIndexMap.set(shift.id, index);
- });
- }
-
- // Calculate total hidden shifts for unified display
- const hiddenRegularCount =
- maxShiftsToShow !== undefined
- ? Math.max(0, sortedRegularShifts.length - maxShiftsToShow)
- : 0;
- const hiddenExternalCount =
- maxExternalShiftsToShow !== undefined
- ? Math.max(
- 0,
- sortedExternalNormalShifts.length -
- maxExternalShiftsToShow,
- )
- : 0;
- const totalHiddenCount =
- hiddenRegularCount + hiddenExternalCount;
-
- // Filter to get all displayable shifts (regular + external with normal display mode)
- const displayableShifts = dayShifts.filter(
- (s) =>
- !s.syncedFromExternal ||
- (s.externalSyncId &&
- externalSyncs.find((sync) => sync.id === s.externalSyncId)
- ?.displayMode === "normal"),
- );
-
- return (
- <>
- {combinedSortMode ? (
- // Combined mode: display all shifts together sorted, but respect individual limits
- <>
- {/* Display combined sorted shifts with individual limits */}
- {allSortedShifts.map((shift) => {
- const isRegular = !shift.syncedFromExternal;
- const regularIndex = isRegular
- ? (regularIndexMap.get(shift.id) ?? -1)
- : -1;
- const externalIndex = !isRegular
- ? (externalIndexMap.get(shift.id) ?? -1)
- : -1;
-
- // Check if shift should be displayed based on its type's limit
- const shouldDisplay =
- (isRegular &&
- (maxShiftsToShow === undefined ||
- regularIndex < maxShiftsToShow)) ||
- (!isRegular &&
- (maxExternalShiftsToShow === undefined ||
- externalIndex < maxExternalShiftsToShow));
-
- if (!shouldDisplay) return null;
-
- return (
- <CalendarShiftCard
- key={shift.id}
- shift={shift}
- showShiftNotes={showShiftNotes}
- showFullTitles={showFullTitles}
- onEditShift={
- !selectedPresetId ? onEditShift : undefined
- }
- />
- );
- })}
-
- {/* Show unified "+X shifts" when there are hidden shifts from either type */}
- {totalHiddenCount > 0 && (
- <div
- onClick={(e) => {
- if (selectedPresetId) return;
- e.stopPropagation();
- // Show all shifts dialog with all day shifts
- onShowAllShifts?.(day, displayableShifts);
- }}
- className={`text-[10px] sm:text-xs text-primary font-semibold text-center pt-0.5 transition-colors ${
- selectedPresetId
- ? "cursor-not-allowed opacity-50"
- : "hover:text-primary/80 hover:underline cursor-pointer"
- }`}
- >
- +{totalHiddenCount}{" "}
- {totalHiddenCount === 1
- ? t("shift.shift_one")
- : t("common.shifts")}
- </div>
- )}
- </>
- ) : (
- // Separate mode: display regular and external shifts separately
- <>
- {/* Display regular shifts */}
- {(maxShiftsToShow === undefined
- ? sortedRegularShifts
- : sortedRegularShifts.slice(0, maxShiftsToShow)
- ).map((shift) => (
- <CalendarShiftCard
- key={shift.id}
- shift={shift}
- showShiftNotes={showShiftNotes}
- showFullTitles={showFullTitles}
- onEditShift={
- !selectedPresetId ? onEditShift : undefined
- }
- />
- ))}
-
- {/* Display external shifts with normal display mode */}
- {(maxExternalShiftsToShow === undefined
- ? sortedExternalNormalShifts
- : sortedExternalNormalShifts.slice(
- 0,
- maxExternalShiftsToShow,
- )
- ).map((shift) => (
- <CalendarShiftCard
- key={shift.id}
- shift={shift}
- showShiftNotes={showShiftNotes}
- showFullTitles={showFullTitles}
- onEditShift={
- !selectedPresetId ? onEditShift : undefined
- }
- />
- ))}
-
- {/* Show unified "+X shifts" when there are hidden shifts from either type */}
- {totalHiddenCount > 0 && (
- <div
- onClick={(e) => {
- if (selectedPresetId) return;
- e.stopPropagation();
- // Show all shifts dialog with all day shifts
- onShowAllShifts?.(day, displayableShifts);
- }}
- className={`text-[10px] sm:text-xs text-primary font-semibold text-center pt-0.5 transition-colors ${
- selectedPresetId
- ? "cursor-not-allowed opacity-50"
- : "hover:text-primary/80 hover:underline cursor-pointer"
- }`}
- >
- +{totalHiddenCount}{" "}
- {totalHiddenCount === 1
- ? t("shift.shift_one")
- : t("common.shifts")}
- </div>
- )}
- </>
- )}
-
- {/* Show minimal badges for each sync with minimal display mode */}
- {Object.entries(syncedShiftsByMode).map(
- ([syncId, syncShifts]) => {
- const sync = externalSyncs.find((s) => s.id === syncId);
- if (!sync || syncShifts.length === 0) return null;
-
- return (
- <div
- key={syncId}
- onClick={(e) => {
- if (selectedPresetId) return;
- e.stopPropagation();
- onShowSyncedShifts?.(day, syncShifts);
- }}
- className={`text-[10px] sm:text-xs px-1 py-0.5 sm:px-1.5 sm:py-1 rounded bg-muted/50 border border-border/50 text-muted-foreground transition-colors text-center ${
- selectedPresetId
- ? "cursor-not-allowed opacity-50"
- : "hover:bg-muted hover:text-foreground cursor-pointer"
- }`}
- style={{
- borderLeftColor: sync.color,
- borderLeftWidth: "2px",
- }}
- >
- <span className="flex items-center justify-center gap-1">
- <span>+{syncShifts.length}</span>
- <RefreshCw className="h-3 w-3" />
- </span>
- </div>
- );
- },
- )}
- </>
- );
- })()}
- </div>
- </motion.button>
- );
- })}
- </div>
- );
-}
diff --git a/components/calendar-selector.tsx b/components/calendar-selector.tsx
deleted file mode 100644
index b85dc38..0000000
--- a/components/calendar-selector.tsx
+++ /dev/null
@@ -1,534 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { CalendarWithCount } from "@/lib/types";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import {
- Plus,
- Bell,
- Copy,
- Settings,
- Lock,
- User,
- Users,
- Globe,
- ShieldCheck,
-} from "lucide-react";
-import { useAuth } from "@/hooks/useAuth";
-import { useAuthFeatures } from "@/hooks/useAuthFeatures";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-
-interface CalendarSelectorProps {
- calendars: CalendarWithCount[];
- selectedId?: string;
- onSelect: (id: string) => void;
- onCreateNew: () => void;
- onSettings?: () => void;
- onSyncNotifications?: () => void;
- onCompare?: () => void;
- hasSyncErrors?: boolean;
- variant?: "desktop" | "mobile";
-}
-
-export function CalendarSelector({
- calendars,
- selectedId,
- onSelect,
- onCreateNew,
- onSettings,
- onSyncNotifications,
- onCompare,
- hasSyncErrors = false,
- variant = "desktop",
-}: CalendarSelectorProps) {
- const t = useTranslations();
- const { isGuest, user } = useAuth();
- const { isAuthEnabled } = useAuthFeatures();
-
- // Filter calendars: guests only see calendars with read or write permission
- const visibleCalendars = isGuest
- ? calendars.filter(
- (c) =>
- c.guestPermission === "read" ||
- c.guestPermission === "write" ||
- c.tokenPermission === "read" ||
- c.tokenPermission === "write"
- )
- : calendars;
-
- const selectedCalendar = visibleCalendars.find((c) => c.id === selectedId);
- const canCompare = visibleCalendars.length >= 2;
-
- // Group calendars by ownership
- const ownCalendars = visibleCalendars.filter(
- (c) => isAuthEnabled && user && !isGuest && c.ownerId === user.id
- );
- const sharedCalendars = visibleCalendars.filter(
- (c) =>
- isAuthEnabled &&
- user &&
- !isGuest &&
- c.ownerId !== user.id &&
- c.sharePermission // Only calendars with explicit share permission, not tokens
- );
- const tokenCalendars =
- isAuthEnabled && !isGuest
- ? visibleCalendars.filter(
- (c) =>
- c.tokenPermission &&
- !c.sharePermission &&
- (!user || c.ownerId !== user?.id)
- )
- : [];
- // Public calendars: Calendars with guestPermission that authenticated users have subscribed to
- // Exclude calendars already shown in other groups (own, shared, token)
- const publicCalendars =
- isAuthEnabled && user && !isGuest
- ? visibleCalendars.filter(
- (c) =>
- c.guestPermission &&
- !c.sharePermission &&
- !c.tokenPermission &&
- c.ownerId !== user.id
- )
- : [];
- // For guests or when auth is disabled, show all visible calendars without grouping
- // Guests see all their accessible calendars in one list (no separation by token/guest permission)
- const guestAccessibleCalendars =
- !isAuthEnabled || isGuest ? visibleCalendars : [];
-
- // Check if selected calendar is read-only
- // Owner is never read-only, even if guestPermission is "read"
- // Guests (no user) or non-owners see read-only based on permissions
- // Priority: owner > sharePermission > tokenPermission > guestPermission
- const isReadOnly =
- selectedCalendar &&
- (!user || selectedCalendar.ownerId !== user.id) &&
- (selectedCalendar.sharePermission === "read" ||
- (!selectedCalendar.sharePermission &&
- selectedCalendar.tokenPermission === "read") ||
- (!selectedCalendar.sharePermission &&
- !selectedCalendar.tokenPermission &&
- selectedCalendar.guestPermission === "read"));
-
- // Check if user can manage settings (owner or admin)
- const { canManage } = useCalendarPermission(selectedCalendar);
-
- // Helper function to render calendar icon
- const getCalendarIcon = (calendar: CalendarWithCount) => {
- if (!isAuthEnabled) {
- return null;
- }
- if (!user) {
- return <Globe className="h-3.5 w-3.5 text-muted-foreground/60" />;
- }
- // Check for admin/owner permission
- if (
- calendar.sharePermission === "admin" ||
- calendar.sharePermission === "owner"
- ) {
- return (
- <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500" />
- );
- }
- if (calendar.ownerId === user.id) {
- return <User className="h-3.5 w-3.5 text-muted-foreground/60" />;
- }
- return <Users className="h-3.5 w-3.5 text-muted-foreground/60" />;
- };
-
- // Helper function to render calendar item
- const renderCalendarItem = (calendar: CalendarWithCount) => {
- // Check for admin/owner first
- const isAdmin =
- isAuthEnabled &&
- (calendar.sharePermission === "admin" ||
- calendar.sharePermission === "owner");
-
- // Check if calendar is read-only
- // Owner is never read-only, even if guestPermission is "read"
- // Guests (no user) or non-owners see read-only based on permissions
- // Priority: owner > sharePermission > tokenPermission > guestPermission
- const isCalendarReadOnly =
- isAuthEnabled &&
- (!user || calendar.ownerId !== user.id) &&
- (calendar.sharePermission === "read" ||
- (!calendar.sharePermission && calendar.tokenPermission === "read") ||
- (!calendar.sharePermission &&
- !calendar.tokenPermission &&
- calendar.guestPermission === "read"));
-
- const icon = isAdmin ? (
- <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
- ) : isCalendarReadOnly ? (
- <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
- ) : (
- getCalendarIcon(calendar)
- );
-
- return (
- <SelectItem key={calendar.id} value={calendar.id}>
- <div className="flex items-center gap-2.5 w-full">
- {icon}
- <div
- className="w-3 h-3 rounded-full flex-shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <span className="flex-1 truncate">{calendar.name}</span>
- </div>
- </SelectItem>
- );
- };
-
- // Desktop: Compact icon-based layout
- if (variant === "desktop") {
- return (
- <div className="flex gap-2 items-center">
- <Select value={selectedId} onValueChange={onSelect}>
- <SelectTrigger className="flex-1 h-9 sm:h-10 text-sm">
- {selectedCalendar ? (
- <div className="flex items-center gap-2 flex-1">
- {isAuthEnabled &&
- (selectedCalendar.sharePermission === "admin" ||
- selectedCalendar.sharePermission === "owner" ? (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
- </TooltipTrigger>
- <TooltipContent>
- <p>{t("common.labels.permissions.admin")}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : isReadOnly ? (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
- </TooltipTrigger>
- <TooltipContent>
- <p>{t("common.labels.permissions.read")}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- getCalendarIcon(selectedCalendar)
- ))}
- <div
- className="w-3 h-3 rounded-full"
- style={{ backgroundColor: selectedCalendar.color }}
- />
- <span className="truncate">{selectedCalendar.name}</span>
- </div>
- ) : (
- <SelectValue placeholder={t("calendar.title")} />
- )}
- </SelectTrigger>
- <SelectContent>
- {/* Own Calendars */}
- {isAuthEnabled && ownCalendars.length > 0 && (
- <>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <User className="h-3 w-3" />
- {t("calendar.myCalendars", { default: "Meine Kalender" })}
- </div>
- {ownCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Shared Calendars */}
- {isAuthEnabled && sharedCalendars.length > 0 && (
- <>
- {ownCalendars.length > 0 && <Separator className="my-1" />}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Users className="h-3 w-3" />
- {t("calendar.sharedCalendars", {
- default: "Geteilte Kalender",
- })}
- </div>
- {sharedCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Token-accessible Calendars */}
- {tokenCalendars.length > 0 && (
- <>
- {(ownCalendars.length > 0 || sharedCalendars.length > 0) && (
- <Separator className="my-1" />
- )}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("calendar.tokenCalendars", {
- default: "Via Zugangslink",
- })}
- </div>
- {tokenCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Public Calendars (guestPermission subscribed by authenticated users) */}
- {publicCalendars.length > 0 && (
- <>
- {(ownCalendars.length > 0 ||
- sharedCalendars.length > 0 ||
- tokenCalendars.length > 0) && <Separator className="my-1" />}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("calendar.publicCalendars", {
- default: "Öffentliche Kalender",
- })}
- </div>
- {publicCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Guest Accessible Calendars (when auth disabled or user is guest) */}
- {(!isAuthEnabled || isGuest) &&
- guestAccessibleCalendars.length > 0 && (
- <>{guestAccessibleCalendars.map(renderCalendarItem)}</>
- )}
-
- {!isGuest && (
- <>
- <Separator className="my-1" />
- <div
- onClick={(e) => {
- e.stopPropagation();
- onCreateNew();
- }}
- className="relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
- >
- <Plus className="h-4 w-4 mr-2" />
- {t("calendar.create")}
- </div>
- </>
- )}
- </SelectContent>
- </Select>
- {onSettings && selectedId && canManage && (
- <Button
- onClick={onSettings}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("calendar.settings", {
- name: selectedCalendar?.name || "",
- })}
- >
- <Settings className="h-4 w-4" />
- </Button>
- )}
- {onSyncNotifications && selectedId && (
- <Button
- onClick={onSyncNotifications}
- size="icon"
- variant="outline"
- className={`h-9 w-9 sm:h-10 sm:w-10 relative ${
- hasSyncErrors
- ? "text-red-600 hover:text-red-600 border-red-300 hover:border-red-400"
- : ""
- }`}
- title={
- hasSyncErrors
- ? t("syncNotifications.hasErrors")
- : t("syncNotifications.title")
- }
- >
- <Bell className="h-4 w-4" />
- {hasSyncErrors && (
- <span className="absolute -top-1 -right-1 h-3 w-3 bg-red-600 rounded-full border-2 border-background animate-pulse" />
- )}
- </Button>
- )}
- {onCompare && canCompare && (
- <Button
- onClick={onCompare}
- size="icon"
- variant="outline"
- className="h-9 w-9 sm:h-10 sm:w-10"
- title={t("calendar.compare")}
- >
- <Copy className="h-4 w-4" />
- </Button>
- )}
- </div>
- );
- }
-
- // Mobile: Full-width dropdown with buttons in grid below
- return (
- <div className="flex flex-col gap-3">
- {/* Calendar Dropdown - Full Width */}
- <Select value={selectedId} onValueChange={onSelect}>
- <SelectTrigger className="w-full h-10 text-sm">
- {selectedCalendar ? (
- <div className="flex items-center gap-2 flex-1">
- {isAuthEnabled &&
- (selectedCalendar.sharePermission === "admin" ||
- selectedCalendar.sharePermission === "owner" ? (
- <ShieldCheck className="h-3.5 w-3.5 text-blue-600 dark:text-blue-500 flex-shrink-0" />
- ) : isReadOnly ? (
- <Lock className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500 flex-shrink-0" />
- ) : (
- getCalendarIcon(selectedCalendar)
- ))}
- <div
- className="w-3 h-3 rounded-full"
- style={{ backgroundColor: selectedCalendar.color }}
- />
- <span className="truncate">{selectedCalendar.name}</span>
- </div>
- ) : (
- <SelectValue placeholder={t("calendar.title")} />
- )}
- </SelectTrigger>
- <SelectContent>
- {/* Own Calendars */}
- {isAuthEnabled && ownCalendars.length > 0 && (
- <>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <User className="h-3 w-3" />
- {t("calendar.myCalendars", { default: "Meine Kalender" })}
- </div>
- {ownCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Shared Calendars */}
- {isAuthEnabled && sharedCalendars.length > 0 && (
- <>
- {ownCalendars.length > 0 && <Separator className="my-1" />}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Users className="h-3 w-3" />
- {t("calendar.sharedCalendars", {
- default: "Geteilte Kalender",
- })}
- </div>
- {sharedCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Token-accessible Calendars */}
- {tokenCalendars.length > 0 && (
- <>
- {(ownCalendars.length > 0 || sharedCalendars.length > 0) && (
- <Separator className="my-1" />
- )}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("calendar.tokenCalendars", {
- default: "Via Zugangslink",
- })}
- </div>
- {tokenCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Public Calendars (guestPermission subscribed by authenticated users) */}
- {publicCalendars.length > 0 && (
- <>
- {(ownCalendars.length > 0 ||
- sharedCalendars.length > 0 ||
- tokenCalendars.length > 0) && <Separator className="my-1" />}
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {t("calendar.publicCalendars", {
- default: "Öffentliche Kalender",
- })}
- </div>
- {publicCalendars.map(renderCalendarItem)}
- </>
- )}
-
- {/* Guest Accessible Calendars (when auth disabled or user is guest) */}
- {(!isAuthEnabled || isGuest) &&
- guestAccessibleCalendars.length > 0 && (
- <>{guestAccessibleCalendars.map(renderCalendarItem)}</>
- )}
-
- {!isGuest && (
- <>
- <Separator className="my-1" />
- <div
- onClick={(e) => {
- e.stopPropagation();
- onCreateNew();
- }}
- className="relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
- >
- <Plus className="h-4 w-4 mr-2" />
- {t("calendar.create")}
- </div>
- </>
- )}
- </SelectContent>
- </Select>
-
- {/* Action Buttons - Even distribution */}
- {selectedId && (
- <div className="grid grid-cols-3 gap-2">
- {onSettings && canManage && (
- <Button
- onClick={onSettings}
- size="sm"
- variant="outline"
- className="h-9"
- title={t("calendar.settings", {
- name: selectedCalendar?.name || "",
- })}
- >
- <Settings className="h-4 w-4" />
- </Button>
- )}
- {onSyncNotifications && (
- <Button
- onClick={onSyncNotifications}
- size="sm"
- variant="outline"
- className={`h-9 relative ${
- hasSyncErrors
- ? "text-red-600 hover:text-red-600 border-red-300 hover:border-red-400"
- : ""
- }`}
- title={
- hasSyncErrors
- ? t("syncNotifications.hasErrors")
- : t("syncNotifications.title")
- }
- >
- <Bell className="h-4 w-4" />
- {hasSyncErrors && (
- <span className="absolute -top-1 -right-1 h-2.5 w-2.5 bg-red-600 rounded-full border-2 border-background animate-pulse" />
- )}
- </Button>
- )}
- {onCompare && canCompare && (
- <Button
- onClick={onCompare}
- size="sm"
- variant="outline"
- className="h-9"
- >
- <Copy className="h-4 w-4 mr-2" />
- </Button>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/components/calendar-settings-sheet.tsx b/components/calendar-settings-sheet.tsx
deleted file mode 100644
index c038d94..0000000
--- a/components/calendar-settings-sheet.tsx
+++ /dev/null
@@ -1,339 +0,0 @@
-"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 { ColorPicker } from "@/components/ui/color-picker";
-import { CalendarShareManagementSheet } from "@/components/calendar-share-management-sheet";
-import { useCalendars } from "@/hooks/useCalendars";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-import { useAuthFeatures } from "@/hooks/useAuthFeatures";
-import { PRESET_COLORS } from "@/lib/constants";
-import { AlertTriangle, Trash2, Download, Cloud, Users } from "lucide-react";
-import { ExportDialog } from "@/components/export-dialog";
-import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { useDirtyState } from "@/hooks/useDirtyState";
-import { CalendarWithCount } from "@/lib/types";
-
-interface CalendarSettingsSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string;
- calendarName: string;
- calendarColor: string;
- calendarGuestPermission?: "none" | "read" | "write";
- onSuccess: () => void;
- onDelete: () => void;
- onExternalSync?: () => void;
- availableCalendars?: CalendarWithCount[];
-}
-
-interface FormState {
- name: string;
- selectedColor: string;
-}
-
-export function CalendarSettingsSheet({
- open,
- onOpenChange,
- calendarId,
- calendarName,
- calendarColor,
- calendarGuestPermission = "none",
- onSuccess,
- onDelete,
- onExternalSync,
- availableCalendars = [],
-}: CalendarSettingsSheetProps) {
- const t = useTranslations();
- const { updateCalendar } = useCalendars();
- const { canShare, canManage, canDelete } = useCalendarPermission(calendarId);
- const { isAuthEnabled } = useAuthFeatures();
-
- // Use props directly as initial state, controlled by key prop on component
- const [name, setName] = useState(calendarName);
- const [selectedColor, setSelectedColor] = useState(calendarColor);
- const [loading, setLoading] = useState(false);
- const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const [showExportDialog, setShowExportDialog] = useState(false);
- const [showShareManagement, setShowShareManagement] = useState(false);
- const initialFormStateRef = useRef<FormState | null>(null);
-
- // Initialize form state reference when opening
- useEffect(() => {
- if (open && !initialFormStateRef.current) {
- initialFormStateRef.current = {
- name: calendarName,
- selectedColor: calendarColor,
- };
- }
- if (!open) {
- initialFormStateRef.current = null;
- }
- }, [open, calendarName, calendarColor, calendarGuestPermission]);
-
- const hasChanges = () => {
- if (!initialFormStateRef.current) return false;
-
- const current: FormState = {
- name,
- selectedColor,
- };
-
- // Check basic fields
- return (
- JSON.stringify(current) !== JSON.stringify(initialFormStateRef.current)
- );
- };
-
- const {
- isDirty,
- handleClose,
- showConfirmDialog,
- setShowConfirmDialog,
- handleConfirmClose,
- } = useDirtyState({
- onClose: onOpenChange,
- hasChanges,
- });
-
- const handleSubmit = async () => {
- setLoading(true);
-
- const updates = {
- name: name !== calendarName ? name : undefined,
- color: selectedColor !== calendarColor ? selectedColor : undefined,
- };
-
- await updateCalendar(calendarId, updates);
-
- setLoading(false);
- onSuccess();
- onOpenChange(false);
- };
-
- const handleDelete = () => {
- onDelete();
- onOpenChange(false);
- };
-
- // Only owner/admin can access settings
- if (!canManage) {
- return null;
- }
-
- 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">
- {/* 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("common.labels.name")}
- </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 */}
- <ColorPicker
- color={selectedColor}
- onChange={setSelectedColor}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
- />
-
- {/* External Sync Section */}
- {onExternalSync && (
- <div className="pt-4 mt-4 border-t border-border/50">
- <div className="space-y-2.5">
- <Button
- type="button"
- variant="outline"
- onClick={onExternalSync}
- className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
- >
- <Cloud className="h-4 w-4 mr-2" />
- {t("externalSync.manageTitle")}
- </Button>
- </div>
- </div>
- )}
-
- {/* Export Section */}
- <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>
-
- {/* Manage Sharing Section */}
- {isAuthEnabled && canShare && (
- <div className="pt-4 mt-4 border-t border-border/50">
- <Button
- type="button"
- variant="outline"
- onClick={() => setShowShareManagement(true)}
- className="w-full h-11 border-primary/30 hover:bg-primary/10 hover:border-primary/50"
- >
- <Users className="h-4 w-4 mr-2" />
- {t("share.manageSharing")}
- </Button>
- </div>
- )}
-
- {/* Delete Section */}
- {canDelete && (
- <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}
- availableCalendars={availableCalendars}
- calendarName={calendarName}
- />
-
- <ConfirmationDialog
- open={showConfirmDialog}
- onOpenChange={setShowConfirmDialog}
- onConfirm={handleConfirmClose}
- />
-
- <CalendarShareManagementSheet
- open={showShareManagement}
- onOpenChange={setShowShareManagement}
- calendarId={calendarId}
- calendarName={calendarName}
- calendarGuestPermission={calendarGuestPermission}
- canManageShares={canShare}
- />
- </>
- );
-}
diff --git a/components/calendar-share-list.tsx b/components/calendar-share-list.tsx
index 79299ac..bae2cf7 100644
--- a/components/calendar-share-list.tsx
+++ b/components/calendar-share-list.tsx
@@ -1,300 +1,211 @@
"use client";
-import { useState } from "react";
+import { ReactNode, useState } from "react";
import { useTranslations } from "next-intl";
-import { format } from "date-fns";
-import { UserPlus, MoreVertical, Trash2, Shield } from "lucide-react";
-import { Button } from "@/components/ui/button";
+import { Check, ChevronDown, Trash2 } from "lucide-react";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { CalendarShareUserSearch } from "@/components/calendar-share-user-search";
+import { ListRow, SectionLabel } from "@/components/form-kit";
import {
- useCalendarShares,
- type CalendarShare,
-} from "@/hooks/useCalendarShares";
+ CalendarShareUserSearch,
+} from "@/components/calendar-share-user-search";
+import { useCalendarShares, type CalendarShare } from "@/hooks/useCalendarShares";
import { useAuth } from "@/hooks/useAuth";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
+import { cn, getUserInitials } from "@/lib/utils";
+
+type SharePermission = "admin" | "write" | "read";
interface CalendarShareListProps {
calendarId: string;
canManageShares: boolean;
}
-export function CalendarShareList({
- calendarId,
- canManageShares,
-}: CalendarShareListProps) {
+function PersonRow({
+ user,
+ highlight,
+ suffix,
+ action,
+}: {
+ user: { name: string | null; email: string; image?: string | null };
+ highlight?: boolean;
+ suffix?: ReactNode;
+ action: ReactNode;
+}) {
+ return (
+ <ListRow>
+ <Avatar className="size-8">
+ {user.image && <AvatarImage src={user.image} alt="" />}
+ <AvatarFallback
+ className={cn(
+ "text-[11.5px] font-semibold",
+ highlight ? "bg-brand-soft text-brand-ink" : "bg-surface-sunken text-fg-secondary"
+ )}
+ >
+ {getUserInitials(user)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">
+ {user.name || user.email || "…"}
+ {suffix}
+ </div>
+ {user.name && user.email && (
+ <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>
+ )}
+ </div>
+ {action}
+ </ListRow>
+ );
+}
+
+/** "Personen" tab: invite row plus everyone with access. */
+export function CalendarShareList({ calendarId, canManageShares }: CalendarShareListProps) {
const t = useTranslations();
- const locale = useLocale();
const { user: currentUser } = useAuth();
const { isOwner } = useCalendarPermission(calendarId);
const { shares, updateShare, removeShare } = useCalendarShares(calendarId);
+ const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(null);
- const [showAddUser, setShowAddUser] = useState(false);
- const [shareToDelete, setShareToDelete] = useState<CalendarShare | null>(
- null
- );
+ const permissionLabel = (permission: CalendarShare["permission"]) =>
+ permission === "owner"
+ ? t("sharingSheet.owner")
+ : permission === "admin"
+ ? t("common.labels.permissions.admin")
+ : permission === "write"
+ ? t("sharingSheet.permWrite")
+ : t("sharingSheet.permRead");
- const getUserInitials = (share: CalendarShare) => {
- if (share.user.name) {
- return share.user.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- }
- return share.user.email.slice(0, 2).toUpperCase();
- };
+ const permissionOptions: { value: SharePermission; title: string; description: string }[] = [
+ { value: "read", title: t("sharingSheet.permRead"), description: t("sharingSheet.permReadDesc") },
+ { value: "write", title: t("sharingSheet.permWrite"), description: t("sharingSheet.permWriteDesc") },
+ ...(isOwner
+ ? [
+ {
+ value: "admin" as const,
+ title: t("common.labels.permissions.admin"),
+ description: t("sharingSheet.permAdminDesc"),
+ },
+ ]
+ : []),
+ ];
- const getPermissionBadgeClass = (permission: string) => {
- switch (permission) {
- case "owner":
- return "bg-purple-500/10 text-purple-500 border-purple-500/20";
- case "admin":
- return "bg-orange-500/10 text-orange-500 border-orange-500/20";
- case "write":
- return "bg-blue-500/10 text-blue-500 border-blue-500/20";
- case "read":
- return "bg-green-500/10 text-green-500 border-green-500/20";
- default:
- return "bg-muted text-muted-foreground";
- }
- };
+ const you = <span className="ml-1.5 font-normal text-fg-tertiary">({t("share.you")})</span>;
+ const staticLabel = (label: string) => (
+ <span className="shrink-0 px-[9px] text-[12.5px] font-medium text-fg-secondary">{label}</span>
+ );
- const handlePermissionChange = async (
- shareId: string,
- newPermission: "admin" | "write" | "read"
- ) => {
- await updateShare(shareId, newPermission);
- };
+ const renderAction = (share: CalendarShare) => {
+ const isSelf = share.userId === currentUser?.id;
+ // Only the owner may touch admins; nobody changes their own level.
+ const canRemove = canManageShares && (isOwner || share.permission !== "admin");
+ const canChange = canRemove && !isSelf;
+ if (!canRemove) return staticLabel(permissionLabel(share.permission));
- const handleRemoveShare = async () => {
- if (!shareToDelete) return;
- await removeShare(shareToDelete.id);
- setShareToDelete(null);
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={t("sharingSheet.changePermission", {
+ name: share.user.name || share.user.email,
+ })}
+ className="flex h-[30px] shrink-0 items-center gap-1.5 rounded-lg border border-line px-[9px] text-[12.5px] font-medium text-fg-body transition-colors hover:bg-surface-panel data-[state=open]:bg-surface-panel"
+ >
+ {permissionLabel(share.permission)}
+ <ChevronDown className="size-[13px] text-fg-tertiary" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-64">
+ {canChange && (
+ <>
+ {permissionOptions.map((option) => (
+ <DropdownMenuItem
+ key={option.value}
+ onClick={() => {
+ if (option.value !== share.permission) updateShare(share.id, option.value);
+ }}
+ className="items-start gap-2.5 py-2"
+ >
+ <Check
+ className={cn(
+ "mt-0.5 size-4 shrink-0 text-brand",
+ option.value !== share.permission && "invisible"
+ )}
+ />
+ <span className="min-w-0">
+ <span className="block text-[13px] font-semibold text-fg-strong">
+ {option.title}
+ </span>
+ <span className="block text-[12px] text-fg-tertiary">{option.description}</span>
+ </span>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <DropdownMenuItem
+ onClick={() => setShareToDelete(share)}
+ className="gap-2.5 text-danger focus:text-danger"
+ >
+ <Trash2 className="size-4 text-danger" />
+ {t("share.removeAccess")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
};
- const isSelf = (share: CalendarShare) => share.userId === currentUser?.id;
+ // The shares endpoint lists grants only; the owner row is known just for the owner themself.
+ const ownerRow = isOwner && currentUser && (
+ <PersonRow
+ user={{ name: currentUser.name ?? null, email: currentUser.email, image: currentUser.image }}
+ highlight
+ suffix={you}
+ action={staticLabel(t("sharingSheet.owner"))}
+ />
+ );
return (
<>
- <div className="space-y-4">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div>
- <p className="text-sm font-medium">
- {t("share.userShares")} ({shares.length})
- </p>
- <p className="text-xs text-muted-foreground">
- {t("share.userSharesDescription")}
- </p>
- </div>
- {canManageShares && (
- <Button
- onClick={() => setShowAddUser(true)}
- size="sm"
- className="gap-2"
- >
- <UserPlus className="h-4 w-4" />
- {t("common.add")}
- </Button>
- )}
- </div>
+ {canManageShares && <CalendarShareUserSearch calendarId={calendarId} />}
- {/* Shares Table */}
- {shares.length === 0 ? (
- <div className="border rounded-lg p-8 text-center">
- <div className="flex flex-col items-center gap-3">
- <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
- <Shield className="h-6 w-6 text-muted-foreground" />
- </div>
- <div>
- <p className="text-sm font-medium">{t("share.noShares")}</p>
- <p className="text-xs text-muted-foreground mt-1">
- {t("share.noSharesDescription")}
- </p>
- </div>
- {canManageShares && (
- <Button
- onClick={() => setShowAddUser(true)}
- size="sm"
- className="gap-2 mt-2"
- >
- <UserPlus className="h-4 w-4" />
- {t("share.addUser")}
- </Button>
- )}
- </div>
- </div>
- ) : (
- <div className="border rounded-lg overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>{t("common.labels.user")}</TableHead>
- <TableHead>{t("common.labels.permission")}</TableHead>
- <TableHead>{t("share.sharedBy")}</TableHead>
- <TableHead>{t("share.sharedOn")}</TableHead>
- {canManageShares && (
- <TableHead className="w-[50px]"></TableHead>
- )}
- </TableRow>
- </TableHeader>
- <TableBody>
- {shares.map((share) => (
- <TableRow key={share.id}>
- <TableCell>
- <div className="flex items-center gap-3">
- <Avatar className="h-8 w-8">
- {share.user.image && (
- <AvatarImage src={share.user.image} />
- )}
- <AvatarFallback className="text-xs">
- {getUserInitials(share)}
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0">
- <p className="text-sm font-medium truncate">
- {share.user.name || share.user.email}
- {isSelf(share) && (
- <span className="ml-2 text-xs text-muted-foreground">
- ({t("share.you")})
- </span>
- )}
- </p>
- {share.user.name && (
- <p className="text-xs text-muted-foreground truncate">
- {share.user.email}
- </p>
- )}
- </div>
- </div>
- </TableCell>
- <TableCell>
- {canManageShares &&
- !isSelf(share) &&
- (isOwner || share.permission !== "admin") ? (
- <Select
- value={share.permission}
- onValueChange={(value) =>
- handlePermissionChange(
- share.id,
- value as "admin" | "write" | "read"
- )
- }
- >
- <SelectTrigger className="w-[140px] h-8">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="read">
- {t("common.labels.permissions.read")}
- </SelectItem>
- <SelectItem value="write">
- {t("common.labels.permissions.write")}
- </SelectItem>
- {isOwner && (
- <SelectItem value="admin">
- {t("common.labels.permissions.admin")}
- </SelectItem>
- )}
- </SelectContent>
- </Select>
- ) : (
- <span
- className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border ${getPermissionBadgeClass(
- share.permission
- )}`}
- >
- {t(`common.labels.permissions.${share.permission}`)}
- </span>
- )}
- </TableCell>
- <TableCell>
- <p className="text-sm truncate">
- {share.sharedByUser.name || share.sharedByUser.email}
- </p>
- </TableCell>
- <TableCell>
- <p className="text-sm text-muted-foreground">
- {format(new Date(share.createdAt), "PP", {
- locale: getDateLocale(locale),
- })}
- </p>
- </TableCell>
- {canManageShares &&
- (isOwner || share.permission !== "admin") && (
- <TableCell>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => setShareToDelete(share)}
- className="text-destructive"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("share.removeAccess")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- )}
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
+ <section className="flex flex-col gap-2">
+ <SectionLabel className="mb-0">{t("sharingSheet.haveAccess")}</SectionLabel>
+ {ownerRow}
+ {shares.map((share) => (
+ <PersonRow
+ key={share.id}
+ user={share.user}
+ suffix={share.userId === currentUser?.id ? you : undefined}
+ action={renderAction(share)}
+ />
+ ))}
+ {shares.length === 0 && (
+ <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">
+ {t("share.noSharesDescription")}
+ </p>
)}
- </div>
-
- {/* Add User Dialog */}
- <CalendarShareUserSearch
- open={showAddUser}
- onOpenChange={setShowAddUser}
- calendarId={calendarId}
- />
+ </section>
- {/* Remove Confirmation */}
{shareToDelete && (
<ConfirmationDialog
- open={!!shareToDelete}
+ open
onOpenChange={(open) => !open && setShareToDelete(null)}
- onConfirm={handleRemoveShare}
+ onConfirm={async () => {
+ await removeShare(shareToDelete.id);
+ setShareToDelete(null);
+ }}
title={t("share.removeShareConfirmTitle")}
description={t("share.removeShareConfirmDesc", {
user: shareToDelete.user.name || shareToDelete.user.email,
})}
confirmVariant="destructive"
- confirmText={t("common.delete")}
- cancelText={t("common.cancel")}
+ confirmText={t("share.removeAccess")}
/>
)}
</>
diff --git a/components/calendar-share-management-sheet.tsx b/components/calendar-share-management-sheet.tsx
index f16294e..776bfd9 100644
--- a/components/calendar-share-management-sheet.tsx
+++ b/components/calendar-share-management-sheet.tsx
@@ -2,178 +2,137 @@
import { useState } from "react";
import { useTranslations } from "next-intl";
-import { Users, Shield, Link as LinkIcon } from "lucide-react";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
- SheetFooter,
-} from "@/components/ui/sheet";
+import { Globe, Shield } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { SegmentedControl } from "@/components/segmented-control";
+import { StatusBanner } from "@/components/status-banner";
import { CalendarShareList } from "@/components/calendar-share-list";
-import { CalendarTokenList } from "@/components/calendar-token-list";
-import { GuestPermissionSelector } from "@/components/guest-permission-selector";
+import { AccessLinksPanel } from "@/components/calendar-token-list";
+import {
+ GuestPermissionSelector,
+ usePublicAccessNote,
+} from "@/components/guest-permission-selector";
import { useCalendars } from "@/hooks/useCalendars";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useAccessLinkForm } from "@/hooks/useAccessLinkForm";
+import { useReportDirty } from "@/hooks/useDirtyState";
-interface CalendarShareManagementSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
+type GuestPermission = "none" | "read" | "write";
+type SharingTab = "people" | "public" | "links";
+
+interface SharingPanelProps {
calendarId: string;
- calendarName: string;
- calendarGuestPermission?: "none" | "read" | "write";
- canManageShares: boolean; // owner/admin permission
+ onClose: () => void;
+ onDirtyChange?: (dirty: boolean) => void;
}
-export function CalendarShareManagementSheet({
- open,
- onOpenChange,
- calendarId,
- calendarName,
- calendarGuestPermission = "none",
- canManageShares,
-}: CalendarShareManagementSheetProps) {
+/** Sharing (screen 4d): people with access, public access and access links. */
+export function SharingPanel({ calendarId, onClose, onDirtyChange }: SharingPanelProps) {
const t = useTranslations();
- const { updateCalendar } = useCalendars();
- const { isAuthEnabled } = useAuthFeatures();
-
- const [activeTab, setActiveTab] = useState("users");
- const [optimisticGuestPermission, setOptimisticGuestPermission] = useState<
- "none" | "read" | "write" | null
- >(null);
- const [saving, setSaving] = useState(false);
+ const { calendars, updateCalendar } = useCalendars();
+ const { canShare } = useCalendarPermission(calendarId);
+ const { isAuthEnabled, allowGuest } = useAuthFeatures();
+ const publicAccessNote = usePublicAccessNote();
+ const [tab, setTab] = useState<SharingTab>("people");
+ const linkForm = useAccessLinkForm(calendarId);
- // Use optimistic value during save, otherwise use prop value
- // This avoids calling setState in an effect and potential cascading renders
- const guestPermission = optimisticGuestPermission ?? calendarGuestPermission;
+ useReportDirty(linkForm.dirty, onDirtyChange);
- // Show public access tab when auth is enabled (allows sharing with authenticated users via guestPermission)
- // This is separate from allowGuest which controls unauthenticated access
- const showGuestTab = isAuthEnabled;
+ const [optimisticGuest, setOptimisticGuest] = useState<GuestPermission | null>(null);
+ const [saving, setSaving] = useState(false);
+ const calendar = calendars.find((c) => c.id === calendarId);
+ const guestPermission = optimisticGuest ?? calendar?.guestPermission ?? "none";
- const handleGuestPermissionChange = async (
- value: "none" | "read" | "write"
- ) => {
- if (!canManageShares) return;
+ // guestPermission also governs signed-in users without a share, so it is offered whenever auth is on.
+ const showPublicTab = isAuthEnabled;
- setOptimisticGuestPermission(value);
+ const handleGuestPermissionChange = async (value: GuestPermission) => {
+ if (!canShare || value === guestPermission) return;
+ setOptimisticGuest(value);
setSaving(true);
-
- await updateCalendar(calendarId, {
- guestPermission: value,
- });
-
- setSaving(false);
- setOptimisticGuestPermission(null);
+ try {
+ await updateCalendar(calendarId, { guestPermission: value });
+ } catch {
+ // updateCalendar already reported the error and rolled back the cache.
+ } finally {
+ setSaving(false);
+ setOptimisticGuest(null);
+ }
};
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- className="w-full sm:max-w-[700px] 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 flex items-center gap-2">
- <Users className="h-5 w-5" />
- {t("share.manageSharing")}
- </SheetTitle>
- <SheetDescription className="text-sm text-muted-foreground">
- {t("share.manageSharingDescription", { name: calendarName })}
- </SheetDescription>
- </SheetHeader>
-
- <div className="flex-1 overflow-y-auto">
- <Tabs
- value={activeTab}
- onValueChange={setActiveTab}
- className="h-full"
- >
- <div className="border-b border-border/50 px-6 pt-4">
- <TabsList className="w-full grid grid-cols-3">
- <TabsTrigger value="users" className="gap-2">
- <Users className="h-4 w-4" />
- <span className="hidden sm:inline">
- {t("share.userShares")}
- </span>
- <span className="sm:hidden">{t("common.labels.users")}</span>
- </TabsTrigger>
- {showGuestTab && (
- <TabsTrigger value="public" className="gap-2">
- <Shield className="h-4 w-4" />
- <span className="hidden sm:inline">
- {t("share.publicAccess")}
- </span>
- <span className="sm:hidden">{t("share.public")}</span>
- </TabsTrigger>
- )}
- <TabsTrigger value="links" className="gap-2">
- <LinkIcon className="h-4 w-4" />
- <span className="hidden sm:inline">
- {t("share.accessLinks")}
- </span>
- <span className="sm:hidden">{t("share.links")}</span>
- </TabsTrigger>
- </TabsList>
- </div>
-
- <div className="px-6 py-6">
- {/* User Shares Tab */}
- <TabsContent value="users" className="mt-0 space-y-0">
- <CalendarShareList
- calendarId={calendarId}
- canManageShares={canManageShares}
- />
- </TabsContent>
-
- {/* Public Access Tab */}
- {showGuestTab && (
- <TabsContent value="public" className="mt-0 space-y-4">
- <div>
- <p className="text-sm font-medium mb-1">
- {t("share.publicAccess")}
- </p>
- <p className="text-xs text-muted-foreground mb-4">
- {t("share.publicAccessDescription")}
- </p>
- </div>
-
- <GuestPermissionSelector
- value={guestPermission}
- onChange={handleGuestPermissionChange}
- idPrefix="share-management"
- />
-
- {saving && (
- <p className="text-xs text-muted-foreground italic">
- {t("common.saving")}
- </p>
- )}
- </TabsContent>
- )}
+ const tabs: { value: SharingTab; label: string }[] = [
+ { value: "people", label: t("sharingSheet.tabPeople") },
+ ...(showPublicTab ? [{ value: "public" as const, label: t("share.public") }] : []),
+ { value: "links", label: t("share.links") },
+ ];
+ const activeTab = tabs.some((option) => option.value === tab) ? tab : "people";
+
+ const switcher = (
+ <SegmentedControl<SharingTab>
+ label={t("common.labels.shares")}
+ size="lg"
+ value={activeTab}
+ onChange={setTab}
+ options={tabs}
+ />
+ );
- {/* Access Links Tab */}
- <TabsContent value="links" className="mt-0">
- <CalendarTokenList calendarId={calendarId} />
- </TabsContent>
- </div>
- </Tabs>
- </div>
+ if (activeTab === "links") {
+ return (
+ <AccessLinksPanel
+ calendarId={calendarId}
+ form={linkForm}
+ onClose={onClose}
+ leading={switcher}
+ />
+ );
+ }
- <SheetFooter className="border-t border-border/50 bg-muted/20 px-6 py-4 mt-auto">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
+ return (
+ <>
+ <PanelBody className="flex flex-col gap-3.5">
+ {switcher}
+
+ {activeTab === "people" ? (
+ <>
+ <CalendarShareList calendarId={calendarId} canManageShares={canShare} />
+ {showPublicTab &&
+ (guestPermission === "none" ? (
+ <StatusBanner tone="info" icon={Shield} title={t("sharingSheet.publicOffTitle")}>
+ {allowGuest
+ ? t("sharingSheet.publicOffBodyGuestsOn")
+ : t("sharingSheet.publicOffBodyGuestsOff")}
+ </StatusBanner>
+ ) : (
+ <StatusBanner tone="info" icon={Globe} title={t("sharingSheet.publicOnTitle")}>
+ {publicAccessNote(guestPermission, allowGuest)}
+ </StatusBanner>
+ ))}
+ </>
+ ) : (
+ <>
+ <p className="text-[13px] text-fg-secondary">
+ {allowGuest
+ ? t("share.publicAccessDescriptionGuestsOn")
+ : t("share.publicAccessDescriptionGuestsOff")}
+ </p>
+ <GuestPermissionSelector
+ value={guestPermission}
+ onChange={handleGuestPermissionChange}
+ allowGuest={allowGuest}
+ disabled={!canShare}
+ />
+ {saving && <p className="text-[12px] text-fg-tertiary">{t("common.saving")}</p>}
+ </>
+ )}
+ </PanelBody>
+ <PanelFooter>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>
+ {t("common.close")}
+ </Button>
+ </PanelFooter>
+ </>
);
}
diff --git a/components/calendar-share-user-search.tsx b/components/calendar-share-user-search.tsx
index 3daf46c..6b9c61c 100644
--- a/components/calendar-share-user-search.tsx
+++ b/components/calendar-share-user-search.tsx
@@ -1,58 +1,28 @@
"use client";
-import { useState, useCallback, useEffect, useMemo, useRef } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
-import { Search, UserPlus, X } from "lucide-react";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
-} from "@/components/ui/dialog";
+import { UserPlus, X } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { useCalendarShares, type SearchUser } from "@/hooks/useCalendarShares";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { getUserInitials } from "@/lib/utils";
interface CalendarShareUserSearchProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
calendarId: string;
onSuccess?: () => void;
}
-export function CalendarShareUserSearch({
- open,
- onOpenChange,
- calendarId,
- onSuccess,
-}: CalendarShareUserSearchProps) {
+/** Invite row of the sharing panel: search a user and share with read access. */
+export function CalendarShareUserSearch({ calendarId, onSuccess }: CalendarShareUserSearchProps) {
const t = useTranslations();
- const { searchUsers, searchResults, searchLoading, addShare } =
- useCalendarShares(calendarId);
- const { isOwner } = useCalendarPermission(calendarId);
+ const { searchUsers, searchResults, searchLoading, addShare } = useCalendarShares(calendarId);
const [query, setQuery] = useState("");
const [selectedUser, setSelectedUser] = useState<SearchUser | null>(null);
- const [permission, setPermission] = useState<"admin" | "write" | "read">(
- "read"
- );
- const [loading, setLoading] = useState(false);
+ const [inviting, setInviting] = useState(false);
- // Debounced search. The timer lives in a ref because the previous version
- // returned a cleanup function from an event handler, where nothing ever
- // calls it -- every keystroke fired its own request.
+ // Debounce timer in a ref so each keystroke cancels the previous request.
const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
@@ -78,225 +48,99 @@ export function CalendarShareUserSearch({
setQuery(user.name || user.email);
};
- const handleAddShare = async () => {
- if (!selectedUser) return;
-
- setLoading(true);
- const result = await addShare(selectedUser.id, permission);
- setLoading(false);
-
- if (result.success) {
- setQuery("");
- setSelectedUser(null);
- setPermission("read");
- onSuccess?.();
- onOpenChange(false);
- }
- };
-
- const handleClose = () => {
+ const clear = () => {
setQuery("");
setSelectedUser(null);
- setPermission("read");
- onOpenChange(false);
};
- const getUserInitials = (user: SearchUser) => {
- if (user.name) {
- return user.name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
+ const handleInvite = async () => {
+ if (!selectedUser) return;
+ setInviting(true);
+ const result = await addShare(selectedUser.id, "read");
+ setInviting(false);
+ if (result.success) {
+ clear();
+ onSuccess?.();
}
- return user.email.slice(0, 2).toUpperCase();
};
- const showResults = useMemo(
- () => query.length >= 2 && !selectedUser && searchResults.length > 0,
- [query, selectedUser, searchResults]
- );
+ const searching = query.length >= 2 && !selectedUser;
+ const showResults = searching && searchResults.length > 0;
return (
- <Dialog open={open} onOpenChange={handleClose}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <UserPlus className="h-5 w-5" />
- {t("share.addUser")}
- </DialogTitle>
- <DialogDescription>{t("share.addUserDescription")}</DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* User Search */}
- <div className="space-y-2">
- <Label htmlFor="user-search">{t("share.searchUser")}</Label>
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- id="user-search"
- type="text"
- value={query}
- onChange={(e) => handleSearch(e.target.value)}
- placeholder={t("share.searchUserPlaceholder")}
- className="pl-10 pr-10"
- autoComplete="off"
- />
- {query && (
- <button
- type="button"
- onClick={() => {
- setQuery("");
- setSelectedUser(null);
- }}
- className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- >
- <X className="h-4 w-4" />
- </button>
- )}
- </div>
-
- {/* Search Results Dropdown */}
- {showResults && (
- <div className="border rounded-lg overflow-hidden bg-background shadow-lg">
- <div className="max-h-[200px] overflow-y-auto">
- {searchResults.map((user) => (
- <button
- key={user.id}
- type="button"
- onClick={() => handleSelectUser(user)}
- className="w-full flex items-center gap-3 p-3 hover:bg-muted transition-colors text-left"
- >
- <Avatar className="h-8 w-8">
- {user.image && <AvatarImage src={user.image} />}
- <AvatarFallback className="text-xs">
- {getUserInitials(user)}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {user.name || user.email}
- </p>
- {user.name && (
- <p className="text-xs text-muted-foreground truncate">
- {user.email}
- </p>
- )}
- </div>
- </button>
- ))}
- </div>
- </div>
- )}
-
- {/* Search Loading */}
- {searchLoading && (
- <p className="text-sm text-muted-foreground">
- {t("common.loading")}
- </p>
- )}
-
- {/* No Results */}
- {query.length >= 2 &&
- !selectedUser &&
- searchResults.length === 0 &&
- !searchLoading && (
- <p className="text-sm text-muted-foreground">
- {t("common.empty.noUsersFound")}
- </p>
- )}
- </div>
-
- {/* Selected User */}
- {selectedUser && (
- <div className="border rounded-lg p-3 bg-muted/50">
- <p className="text-xs font-medium text-muted-foreground mb-2">
- {t("share.selectedUser")}
- </p>
- <div className="flex items-center gap-3">
- <Avatar className="h-10 w-10">
- {selectedUser.image && (
- <AvatarImage src={selectedUser.image} />
- )}
- <AvatarFallback>
- {getUserInitials(selectedUser)}
- </AvatarFallback>
- </Avatar>
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium">
- {selectedUser.name || selectedUser.email}
- </p>
- {selectedUser.name && (
- <p className="text-xs text-muted-foreground">
- {selectedUser.email}
- </p>
- )}
- </div>
- </div>
- </div>
- )}
-
- {/* Permission Selection */}
- <div className="space-y-2">
- <Label htmlFor="permission">{t("common.labels.permission")}</Label>
- <Select
- value={permission}
- onValueChange={(value) =>
- setPermission(value as "admin" | "write" | "read")
- }
+ <div className="flex flex-col gap-1.5">
+ <div className="flex h-10 items-center gap-2 rounded-[9px] border border-control bg-surface-card pl-3 pr-1.5 transition-[box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50">
+ <UserPlus className="size-4 shrink-0 text-fg-tertiary" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => handleSearch(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter") return;
+ e.preventDefault();
+ if (selectedUser) handleInvite();
+ else if (showResults) handleSelectUser(searchResults[0]);
+ }}
+ placeholder={t("share.searchUserPlaceholder")}
+ aria-label={t("share.searchUser")}
+ autoComplete="off"
+ className="min-w-0 flex-1 bg-transparent text-[14px] text-fg-strong outline-none placeholder:text-fg-tertiary"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={clear}
+ aria-label={t("common.cancel")}
+ className="flex size-6 shrink-0 items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-sunken"
+ >
+ <X className="size-3.5" />
+ </button>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleInvite}
+ disabled={!selectedUser || inviting}
+ className="h-7 shrink-0 rounded-[7px] px-3 text-[12.5px] font-semibold"
+ >
+ {t("sharingSheet.invite")}
+ </Button>
+ </div>
+
+ {showResults && (
+ <div className="max-h-[220px] overflow-y-auto rounded-[10px] border border-line bg-surface-card p-1">
+ {searchResults.map((user) => (
+ <button
+ key={user.id}
+ type="button"
+ onClick={() => handleSelectUser(user)}
+ className="flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-surface-panel"
>
- <SelectTrigger id="permission">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="read">
- <div className="flex flex-col items-start">
- <span className="font-medium">
- {t("common.labels.permissions.read")}
- </span>
- </div>
- </SelectItem>
- <SelectItem value="write">
- <div className="flex flex-col items-start">
- <span className="font-medium">
- {t("common.labels.permissions.write")}
- </span>
- </div>
- </SelectItem>
- {isOwner && (
- <SelectItem value="admin">
- <div className="flex flex-col items-start">
- <span className="font-medium">
- {t("common.labels.permissions.admin")}
- </span>
- </div>
- </SelectItem>
+ <Avatar className="size-7">
+ {user.image && <AvatarImage src={user.image} alt="" />}
+ <AvatarFallback className="bg-surface-sunken text-[11px] font-semibold text-fg-secondary">
+ {getUserInitials(user)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">
+ {user.name || user.email}
+ </div>
+ {user.name && (
+ <div className="truncate text-[12px] text-fg-tertiary">{user.email}</div>
)}
- </SelectContent>
- </Select>
- </div>
+ </div>
+ </button>
+ ))}
</div>
-
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={handleClose}
- disabled={loading}
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="button"
- onClick={handleAddShare}
- disabled={!selectedUser || loading}
- >
- {loading ? t("common.adding") : t("common.add")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ )}
+
+ {searching && searchLoading && (
+ <p className="px-1 text-[12px] text-fg-tertiary">{t("common.loading")}</p>
+ )}
+ {searching && !searchLoading && searchResults.length === 0 && (
+ <p className="px-1 text-[12px] text-fg-tertiary">{t("common.empty.noUsersFound")}</p>
+ )}
+ </div>
);
}
diff --git a/components/calendar-sheet.tsx b/components/calendar-sheet.tsx
index 4c1ef01..e3b34f9 100644
--- a/components/calendar-sheet.tsx
+++ b/components/calendar-sheet.tsx
@@ -4,9 +4,9 @@ import { useState } from "react";
import { useTranslations } from "next-intl";
import { BaseSheet } from "@/components/ui/base-sheet";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { ColorPicker } from "@/components/ui/color-picker";
-import { PRESET_COLORS } from "@/lib/constants";
+import { ColorSwatches, Field, inputClass } from "@/components/form-kit";
+import { useAutoFocusRef } from "@/hooks/useAutoFocus";
+import { DEFAULT_COLOR } from "@/lib/constants";
interface CalendarSheetProps {
open: boolean;
@@ -20,7 +20,8 @@ export function CalendarSheet({
onSubmit,
}: CalendarSheetProps) {
const t = useTranslations();
- const initialColor = PRESET_COLORS[0].value;
+ const nameRef = useAutoFocusRef<HTMLInputElement>();
+ const initialColor = DEFAULT_COLOR;
const [name, setName] = useState("");
const [selectedColor, setSelectedColor] = useState(initialColor);
const [isSaving, setIsSaving] = useState(false);
@@ -54,25 +55,15 @@ export function CalendarSheet({
open={open}
onOpenChange={onOpenChange}
title={t("calendar.create")}
- description={t("calendar.createDescription", {
- default: "Create a new calendar to organize your shifts",
- })}
+ description={t("calendar.createDescription")}
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>
+ <div className="flex flex-col gap-4">
+ <Field label={t("calendar.name")} htmlFor="name">
<Input
id="name"
placeholder={t("form.namePlaceholder", {
@@ -80,17 +71,14 @@ export function CalendarSheet({
})}
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
+ className={inputClass}
+ ref={nameRef}
/>
- </div>
+ </Field>
- <ColorPicker
- color={selectedColor}
- onChange={setSelectedColor}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
- />
+ <Field label={t("form.colorLabel")}>
+ <ColorSwatches value={selectedColor} onChange={setSelectedColor} allowCustom />
+ </Field>
</div>
</BaseSheet>
);
diff --git a/components/calendar-shift-card.tsx b/components/calendar-shift-card.tsx
deleted file mode 100644
index 0112188..0000000
--- a/components/calendar-shift-card.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { ShiftWithCalendar } from "@/lib/types";
-import { useTranslations } from "next-intl";
-
-interface CalendarShiftCardProps {
- shift: ShiftWithCalendar;
- showShiftNotes?: boolean;
- showFullTitles?: boolean;
- onEditShift?: (shift: ShiftWithCalendar) => void;
-}
-
-export function CalendarShiftCard({
- shift,
- showShiftNotes = false,
- showFullTitles = false,
- onEditShift,
-}: CalendarShiftCardProps) {
- const t = useTranslations();
-
- const isClickable =
- onEditShift && !shift.externalSyncId && !shift.syncedFromExternal;
-
- const handleClick = (e: React.MouseEvent) => {
- if (isClickable) {
- e.stopPropagation(); // Prevent triggering day click
- onEditShift(shift);
- }
- };
-
- return (
- <div
- className={`text-[10px] sm:text-xs px-0.5 py-0.5 sm:px-1.5 sm:py-1 rounded transition-all duration-100 ${
- isClickable
- ? "cursor-pointer hover:ring-1 hover:ring-primary hover:ring-offset-1 hover:shadow-md"
- : ""
- }`}
- style={{
- backgroundColor: shift.color ? `${shift.color}20` : "#3b82f620",
- borderLeft: `2px solid ${shift.color || "#3b82f6"}`,
- }}
- title={`${shift.title} ${
- shift.isAllDay
- ? `(${t("shift.allDay")})`
- : `(${shift.startTime} - ${shift.endTime})`
- }${shift.notes ? `\n${shift.notes}` : ""}`}
- onClick={handleClick}
- >
- <div
- className={`font-semibold leading-[1.1] sm:leading-tight break-words ${
- showFullTitles ? "" : "line-clamp-2"
- }`}
- >
- {shift.title}
- </div>
- <div className="text-[9px] sm:text-[10px] opacity-70 leading-tight">
- {shift.isAllDay ? (
- t("shift.allDay")
- ) : (
- <>
- <span className="sm:hidden">{shift.startTime.substring(0, 5)}</span>
- <span className="hidden sm:inline">
- {shift.startTime.substring(0, 5)} -{" "}
- {shift.endTime.substring(0, 5)}
- </span>
- </>
- )}
- </div>
- {showShiftNotes && shift.notes && (
- <div className="text-[9px] sm:text-[10px] opacity-60 leading-tight mt-0.5 line-clamp-2">
- {shift.notes}
- </div>
- )}
- </div>
- );
-}
diff --git a/components/calendar-switcher.tsx b/components/calendar-switcher.tsx
new file mode 100644
index 0000000..7b0fca8
--- /dev/null
+++ b/components/calendar-switcher.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import {
+ ChevronDown,
+ Columns2,
+ Globe,
+ Link2,
+ Lock,
+ Plus,
+ ShieldCheck,
+ User,
+ Users,
+ type LucideIcon,
+} from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { CalendarWithCount } from "@/lib/types";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { cn } from "@/lib/utils";
+
+interface CalendarSwitcherProps {
+ calendars: CalendarWithCount[];
+ selectedId?: string;
+ onSelect: (id: string) => void;
+ onCreateNew: () => void;
+ onCompare?: () => void;
+ size?: "desktop" | "mobile";
+}
+
+type Group = { key: string; label: string; icon: LucideIcon; items: CalendarWithCount[] };
+
+export function isCalendarReadOnly(
+ calendar: CalendarWithCount,
+ userId: string | undefined
+): boolean {
+ if (userId && calendar.ownerId === userId) return false;
+ if (calendar.sharePermission) return calendar.sharePermission === "read";
+ if (calendar.tokenPermission) return calendar.tokenPermission === "read";
+ return calendar.guestPermission === "read";
+}
+
+export function CalendarSwitcher({
+ calendars,
+ selectedId,
+ onSelect,
+ onCreateNew,
+ onCompare,
+ size = "desktop",
+}: CalendarSwitcherProps) {
+ const t = useTranslations();
+ const { isGuest, user } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+
+ const visible = isGuest
+ ? calendars.filter(
+ (c) =>
+ c.guestPermission === "read" ||
+ c.guestPermission === "write" ||
+ c.tokenPermission === "read" ||
+ c.tokenPermission === "write"
+ )
+ : calendars;
+ const selected = visible.find((c) => c.id === selectedId);
+ const signedIn = isAuthEnabled && !!user && !isGuest;
+
+ const groups: Group[] = signedIn
+ ? [
+ {
+ key: "own",
+ label: t("calendar.myCalendars"),
+ icon: User,
+ items: visible.filter((c) => c.ownerId === user!.id),
+ },
+ {
+ key: "shared",
+ label: t("calendar.sharedCalendars"),
+ icon: Users,
+ items: visible.filter((c) => c.ownerId !== user!.id && c.sharePermission),
+ },
+ {
+ key: "token",
+ label: t("calendar.tokenCalendars"),
+ icon: Link2,
+ items: visible.filter(
+ (c) => c.tokenPermission && !c.sharePermission && c.ownerId !== user!.id
+ ),
+ },
+ {
+ key: "public",
+ label: t("calendar.publicCalendars"),
+ icon: Globe,
+ items: visible.filter(
+ (c) =>
+ c.guestPermission &&
+ !c.sharePermission &&
+ !c.tokenPermission &&
+ c.ownerId !== user!.id
+ ),
+ },
+ ].filter((g) => g.items.length > 0)
+ : [{ key: "all", label: "", icon: Globe, items: visible }];
+
+ const statusIcon = (calendar: CalendarWithCount) => {
+ if (!isAuthEnabled) return null;
+ if (calendar.sharePermission === "admin" || calendar.sharePermission === "owner") {
+ return <ShieldCheck className="h-3.5 w-3.5 text-brand-ink" />;
+ }
+ if (isCalendarReadOnly(calendar, user?.id)) {
+ return <Lock className="h-3.5 w-3.5 text-warning" />;
+ }
+ return null;
+ };
+
+ const mobile = size === "mobile";
+ const readOnly = selected && isAuthEnabled && isCalendarReadOnly(selected, user?.id);
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={cn(
+ "flex min-w-0 max-w-full items-center outline-none transition-colors",
+ mobile
+ ? "gap-2 rounded-lg py-1 pr-1"
+ : "h-[34px] gap-[9px] rounded-lg border border-line px-[11px] hover:bg-surface-panel"
+ )}
+ >
+ {readOnly ? (
+ <Lock className={cn("shrink-0 text-warning", mobile ? "size-4" : "size-3.5")} />
+ ) : (
+ <span
+ className={cn("shrink-0 rounded-full", mobile ? "size-[9px]" : "size-2")}
+ style={{ backgroundColor: selected?.color ?? "var(--brand)" }}
+ />
+ )}
+ <span
+ className={cn(
+ "truncate font-semibold text-fg-strong",
+ mobile ? "text-base" : "max-w-[220px] text-sm"
+ )}
+ >
+ {selected?.name ?? t("calendar.title")}
+ </span>
+ <ChevronDown
+ className={cn("shrink-0 text-fg-tertiary", mobile ? "size-4" : "size-[15px]")}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-72">
+ <DropdownMenuRadioGroup value={selectedId} onValueChange={onSelect}>
+ {groups.map((group, index) => (
+ <div key={group.key}>
+ {index > 0 && <DropdownMenuSeparator />}
+ {group.label && (
+ <DropdownMenuLabel className="flex items-center gap-1.5 eyebrow">
+ <group.icon className="size-3" />
+ {group.label}
+ </DropdownMenuLabel>
+ )}
+ {group.items.map((calendar) => (
+ <DropdownMenuRadioItem key={calendar.id} value={calendar.id} className="gap-2.5">
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ backgroundColor: calendar.color }}
+ />
+ <span className="flex-1 truncate">{calendar.name}</span>
+ {statusIcon(calendar)}
+ </DropdownMenuRadioItem>
+ ))}
+ </div>
+ ))}
+ </DropdownMenuRadioGroup>
+ {(!isGuest || (onCompare && visible.length >= 2)) && <DropdownMenuSeparator />}
+ {onCompare && visible.length >= 2 && (
+ <DropdownMenuItem onClick={onCompare}>
+ <Columns2 className="mr-2 h-4 w-4" />
+ {t("calendar.compare")}
+ </DropdownMenuItem>
+ )}
+ {!isGuest && (
+ <DropdownMenuItem onClick={onCreateNew}>
+ <Plus className="mr-2 h-4 w-4" />
+ {t("calendar.create")}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/components/calendar-token-badge.tsx b/components/calendar-token-badge.tsx
deleted file mode 100644
index 14f7767..0000000
--- a/components/calendar-token-badge.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { Badge } from "@/components/ui/badge";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { Link as LinkIcon, Eye, Edit } from "lucide-react";
-
-interface CalendarTokenBadgeProps {
- /**
- * Token name (optional)
- */
- tokenName?: string | null;
-
- /**
- * Permission level granted by token
- */
- permission: "read" | "write";
-
- /**
- * Show full info or compact version
- */
- variant?: "full" | "compact";
-}
-
-/**
- * Badge to indicate a calendar is being accessed via share link/token
- * Shown in calendar header when user has token-based access
- */
-export function CalendarTokenBadge({
- tokenName,
- permission,
- variant = "full",
-}: CalendarTokenBadgeProps) {
- const t = useTranslations();
-
- if (variant === "compact") {
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="secondary" className="gap-1 cursor-help">
- <LinkIcon className="h-3 w-3" />
- {permission === "read" ? (
- <Eye className="h-3 w-3" />
- ) : (
- <Edit className="h-3 w-3" />
- )}
- </Badge>
- </TooltipTrigger>
- <TooltipContent>
- <div className="space-y-1">
- <p className="font-medium">{t("token.accessedViaLink")}</p>
- {tokenName && (
- <p className="text-xs text-muted-foreground">
- {t("token.linkName")}: {tokenName}
- </p>
- )}
- <p className="text-xs">
- {permission === "read"
- ? t("common.labels.permissions.read")
- : t("common.labels.permissions.write")}
- </p>
- </div>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
- }
-
- return (
- <Badge variant="secondary" className="gap-1.5">
- <LinkIcon className="h-3.5 w-3.5" />
- <span>{t("token.accessedViaLink")}</span>
- {permission === "read" ? (
- <>
- <Eye className="h-3.5 w-3.5" />
- <span>{t("common.labels.permissions.read")}</span>
- </>
- ) : (
- <>
- <Edit className="h-3.5 w-3.5" />
- <span>{t("common.labels.permissions.write")}</span>
- </>
- )}
- {tokenName && (
- <span className="text-muted-foreground">({tokenName})</span>
- )}
- </Badge>
- );
-}
diff --git a/components/calendar-token-create-dialog.tsx b/components/calendar-token-create-dialog.tsx
index 79db723..332e291 100644
--- a/components/calendar-token-create-dialog.tsx
+++ b/components/calendar-token-create-dialog.tsx
@@ -1,304 +1,200 @@
"use client";
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { toast } from "sonner";
+import { Check, Copy, Link as LinkIcon, TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { format } from "date-fns";
-import { Copy, Check, AlertTriangle, Link as LinkIcon } from "lucide-react";
-import { useCalendarTokens } from "@/hooks/useCalendarTokens";
-import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Field, InfoNote, OptionCards, inputClass } from "@/components/form-kit";
+import { StatusBanner } from "@/components/status-banner";
+import type {
+ CreatedAccessLink,
+ LinkPermission,
+ LinkValidity,
+ useAccessLinkForm,
+} from "@/hooks/useAccessLinkForm";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
+import { cn } from "@/lib/utils";
-interface CalendarTokenCreateDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string;
- onSuccess?: () => void;
-}
+type AccessLinkForm = ReturnType<typeof useAccessLinkForm>;
-export function CalendarTokenCreateDialog({
- open,
- onOpenChange,
- calendarId,
- onSuccess,
-}: CalendarTokenCreateDialogProps) {
+function useValidityLabel() {
const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const { createToken, getShareLink } = useCalendarTokens(calendarId);
-
- const [step, setStep] = useState<"config" | "success">("config");
- const [name, setName] = useState("");
- const [permission, setPermission] = useState<"read" | "write">("read");
- const [expiresAt, setExpiresAt] = useState<Date | undefined>(undefined);
- const [isCreating, setIsCreating] = useState(false);
- const [generatedToken, setGeneratedToken] = useState<string | null>(null);
- const [shareLink, setShareLink] = useState<string | null>(null);
- const [copied, setCopied] = useState(false);
+ return (validity: LinkValidity) =>
+ validity === "1"
+ ? t("token.expiration1Day")
+ : validity === "7"
+ ? t("token.expiration7Days")
+ : validity === "30"
+ ? t("token.expiration30Days")
+ : t("sharingSheet.validityUnlimited");
+}
- // Helper function to check if a preset button should be highlighted
- const isPresetActive = (days: number): boolean => {
- if (!expiresAt) return false;
- const now = new Date();
- const targetDate = new Date(now.getTime() + days * 86400000);
- return Math.abs(expiresAt.getTime() - targetDate.getTime()) < 3600000;
- };
+function usePermissionLabel() {
+ const t = useTranslations();
+ return (permission: LinkPermission) =>
+ permission === "read" ? t("sharingSheet.permRead") : t("sharingSheet.permWrite");
+}
- const handleCreate = async () => {
- setIsCreating(true);
+/** Fields of the "Neuen Link erzeugen" block; submit lives in the owning panel's footer. */
+export function AccessLinkCreateForm({ form }: { form: AccessLinkForm }) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const validityLabel = useValidityLabel();
- const token = await createToken({
- name: name.trim() || undefined,
- permission,
- expiresAt: expiresAt?.toISOString() || null,
- });
+ return (
+ <section className="flex flex-col gap-3.5">
+ <h3 className="text-[14px] font-semibold text-fg-strong">
+ {t("sharingSheet.newLink")}
+ </h3>
+
+ <Field
+ htmlFor="access-link-name"
+ label={
+ <>
+ {t("sharingSheet.linkName")}{" "}
+ <span className="font-normal text-fg-tertiary">
+ {t("sharingSheet.linkNameHint")}
+ </span>
+ </>
+ }
+ >
+ <Input
+ id="access-link-name"
+ value={form.name}
+ onChange={(e) => form.setName(e.target.value)}
+ placeholder={t("sharingSheet.linkNamePlaceholder")}
+ maxLength={50}
+ className={inputClass}
+ />
+ </Field>
+
+ <Field label={t("common.labels.permission")}>
+ <OptionCards<LinkPermission>
+ label={t("common.labels.permission")}
+ value={form.permission}
+ onChange={form.setPermission}
+ options={[
+ {
+ value: "read",
+ title: t("sharingSheet.permRead"),
+ description: t("sharingSheet.permReadDesc"),
+ },
+ {
+ value: "write",
+ title: t("sharingSheet.permWrite"),
+ description: t("sharingSheet.permWriteDesc"),
+ },
+ ]}
+ />
+ </Field>
+
+ <Field label={t("sharingSheet.validity")}>
+ <OptionCards<LinkValidity>
+ label={t("sharingSheet.validity")}
+ columns={4}
+ value={form.validity}
+ onChange={form.setValidity}
+ options={(["1", "7", "30", "never"] as const).map((value) => ({
+ value,
+ title: validityLabel(value),
+ }))}
+ />
+ <p className="font-mono text-[12px] text-fg-tertiary">
+ {form.expiresAt
+ ? t("sharingSheet.expiresOn", {
+ date: format(form.expiresAt, "PPP", { locale: getDateLocale(locale) }),
+ })
+ : t("sharingSheet.validUntilRevoked")}
+ </p>
+ </Field>
+ </section>
+ );
+}
- setIsCreating(false);
+/** Header block of the result view (9b), shown inside the panel body. */
+export function AccessLinkCreatedHeader({ created }: { created: CreatedAccessLink }) {
+ const t = useTranslations();
+ const validityLabel = useValidityLabel();
+ const permissionLabel = usePermissionLabel();
- if (token && token.token) {
- setGeneratedToken(token.token);
- setShareLink(getShareLink(token.token));
- setStep("success");
- }
- };
+ return (
+ <div className="flex items-start gap-3">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-success-soft text-success">
+ <Check className="size-[17px]" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <h3 className="text-[17px] font-semibold leading-tight tracking-[-0.01em] text-fg-strong">
+ {t("sharingSheet.linkReady")}
+ </h3>
+ <p className="mt-1 truncate text-[13px] text-fg-secondary">
+ {[
+ created.name || t("token.unnamed"),
+ permissionLabel(created.permission),
+ validityLabel(created.validity),
+ ].join(" · ")}
+ </p>
+ </div>
+ </div>
+ );
+}
- const handleCopyLink = async () => {
- if (!shareLink) return;
+/** The one-time view of a freshly created token. */
+export function AccessLinkCreated({ created }: { created: CreatedAccessLink }) {
+ const t = useTranslations();
+ const { allowGuest } = useAuthFeatures();
+ const linkInput = useRef<HTMLInputElement>(null);
+ const [copied, setCopied] = useState(false);
+ const handleCopy = async () => {
try {
- await navigator.clipboard.writeText(shareLink);
+ await navigator.clipboard.writeText(created.link);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
- } catch (error) {
- console.error("Failed to copy:", error);
- }
- };
-
- const handleClose = () => {
- // Call onSuccess when closing after successful creation
- if (step === "success") {
- onSuccess?.();
- }
-
- // Reset state
- setStep("config");
- setName("");
- setPermission("read");
- setExpiresAt(undefined);
- setGeneratedToken(null);
- setShareLink(null);
- setCopied(false);
- onOpenChange(false);
- };
-
- const handleExpirationPreset = (days: number | null) => {
- if (days === null) {
- setExpiresAt(undefined);
- } else {
- const date = new Date();
- date.setDate(date.getDate() + days);
- setExpiresAt(date);
+ } catch {
+ // Clipboard API needs a secure context; leave the link selected for manual copying.
+ linkInput.current?.select();
+ toast.error(t("common.copyError", { item: t("sharingSheet.shareLinkLabel") }));
}
};
return (
- <Dialog open={open} onOpenChange={handleClose}>
- <DialogContent className="max-w-md">
- {step === "config" && (
- <>
- <DialogHeader>
- <DialogTitle>{t("token.createLink")}</DialogTitle>
- <DialogDescription>
- {t("token.createLinkDescription")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Name (Optional) */}
- <div className="space-y-2">
- <Label htmlFor="token-name">
- {t("common.labels.name")} {t("common.optional")}
- </Label>
- <Input
- id="token-name"
- placeholder={t("token.namePlaceholder")}
- value={name}
- onChange={(e) => setName(e.target.value)}
- maxLength={50}
- />
- </div>
-
- {/* Permission */}
- <div className="space-y-2">
- <Label htmlFor="token-permission">
- {t("common.labels.permission")}
- </Label>
- <Select
- value={permission}
- onValueChange={(value: "read" | "write") =>
- setPermission(value)
- }
- >
- <SelectTrigger id="token-permission">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="read">
- {t("common.labels.permissions.read")} -{" "}
- {t("token.readOnlyDescription")}
- </SelectItem>
- <SelectItem value="write">
- {t("common.labels.permissions.write")} -{" "}
- {t("token.editDescription")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Expiration */}
- <div className="space-y-2">
- <Label>{t("token.expiration")}</Label>
- <div className="grid grid-cols-2 gap-2">
- <Button
- type="button"
- variant={isPresetActive(1) ? "default" : "outline"}
- size="sm"
- onClick={() => handleExpirationPreset(1)}
- >
- {t("token.expiration1Day")}
- </Button>
- <Button
- type="button"
- variant={isPresetActive(7) ? "default" : "outline"}
- size="sm"
- onClick={() => handleExpirationPreset(7)}
- >
- {t("token.expiration7Days")}
- </Button>
- <Button
- type="button"
- variant={isPresetActive(30) ? "default" : "outline"}
- size="sm"
- onClick={() => handleExpirationPreset(30)}
- >
- {t("token.expiration30Days")}
- </Button>
- <Button
- type="button"
- variant={!expiresAt ? "default" : "outline"}
- size="sm"
- onClick={() => handleExpirationPreset(null)}
- >
- {t("token.expirationNever")}
- </Button>
- </div>
- {expiresAt && (
- <p className="text-xs text-muted-foreground mt-2">
- {t("token.expiresOn")}:{" "}
- {format(expiresAt, "PPP", { locale: dateLocale })}
- </p>
- )}
- </div>
- </div>
-
- <DialogFooter>
- <Button variant="outline" onClick={handleClose}>
- {t("common.cancel")}
- </Button>
- <Button onClick={handleCreate} disabled={isCreating}>
- {isCreating ? t("common.adding") : t("token.generate")}
- </Button>
- </DialogFooter>
- </>
- )}
-
- {step === "success" && (
- <>
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Check className="h-5 w-5 text-green-500" />
- {t("token.linkCreated")}
- </DialogTitle>
- <DialogDescription>
- {t("token.linkCreatedDescription")}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 py-4">
- {/* Warning */}
- <Alert>
- <AlertTriangle className="h-4 w-4" />
- <AlertDescription>{t("token.saveWarning")}</AlertDescription>
- </Alert>
-
- {/* Share Link */}
- <div className="space-y-2">
- <Label>{t("token.shareLink")}</Label>
- <div className="flex gap-2">
- <Input
- value={shareLink || ""}
- readOnly
- className="font-mono text-sm"
- />
- <Button
- size="icon"
- variant="outline"
- onClick={handleCopyLink}
- >
- {copied ? (
- <Check className="h-4 w-4" />
- ) : (
- <Copy className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Token Preview */}
- {generatedToken && (
- <div className="space-y-2">
- <Label>{t("token.tokenValue")}</Label>
- <div className="p-3 bg-muted rounded-md font-mono text-xs break-all">
- {generatedToken}
- </div>
- </div>
- )}
-
- {/* Info */}
- <div className="text-sm text-muted-foreground space-y-1">
- <div className="flex items-start gap-2">
- <LinkIcon className="h-4 w-4 mt-0.5 flex-shrink-0" />
- <span>{t("token.shareInfo")}</span>
- </div>
- </div>
- </div>
-
- <DialogFooter>
- <Button onClick={handleClose} className="w-full">
- {t("common.close")}
- </Button>
- </DialogFooter>
- </>
- )}
- </DialogContent>
- </Dialog>
+ <div className="flex flex-col gap-3.5">
+ <AccessLinkCreatedHeader created={created} />
+
+ <StatusBanner tone="warning" icon={TriangleAlert} title={t("sharingSheet.copyNowTitle")}>
+ {t("sharingSheet.copyNowBody")}
+ </StatusBanner>
+
+ <Field label={t("sharingSheet.shareLinkLabel")} htmlFor="access-link-url">
+ <div className="flex gap-2">
+ <Input
+ id="access-link-url"
+ ref={linkInput}
+ value={created.link}
+ readOnly
+ onFocus={(e) => e.currentTarget.select()}
+ className={cn(inputClass, "min-w-0 flex-1 font-mono text-[12.5px] text-fg-strong md:text-[12.5px]")}
+ />
+ <Button type="button" onClick={handleCopy} className="h-10 shrink-0 gap-1.5 px-3.5 font-semibold">
+ {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
+ {copied ? t("sharingSheet.copied") : t("common.copy")}
+ </Button>
+ </div>
+ </Field>
+
+ <Field label={t("token.token")}>
+ <div className="select-all break-all rounded-[9px] border border-line bg-surface-panel px-3 py-[11px] font-mono text-[12px] leading-relaxed text-fg-body">
+ {created.token}
+ </div>
+ </Field>
+
+ <InfoNote icon={LinkIcon}>
+ {allowGuest ? t("sharingSheet.linkInfoGuestsOn") : t("sharingSheet.linkInfoGuestsOff")}
+ </InfoNote>
+ </div>
);
}
diff --git a/components/calendar-token-list.tsx b/components/calendar-token-list.tsx
index 98e6b90..7b8a673 100644
--- a/components/calendar-token-list.tsx
+++ b/components/calendar-token-list.tsx
@@ -1,293 +1,211 @@
"use client";
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import {
- useCalendarTokens,
- CalendarAccessToken,
-} from "@/hooks/useCalendarTokens";
+import { ReactNode, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format, formatDistanceToNow } from "date-fns";
+import { Eye, EyeOff, Link as LinkIcon, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { ListRow, Pill, RowIconButton, SectionLabel } from "@/components/form-kit";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { Badge } from "@/components/ui/badge";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
-import { CalendarTokenCreateDialog } from "@/components/calendar-token-create-dialog";
-import {
- Plus,
- MoreVertical,
- Eye,
- EyeOff,
- Trash2,
- Link as LinkIcon,
-} from "lucide-react";
-import { formatDistanceToNow } from "date-fns";
+ AccessLinkCreateForm,
+ AccessLinkCreated,
+} from "@/components/calendar-token-create-dialog";
+import { useCalendarTokens, type CalendarAccessToken } from "@/hooks/useCalendarTokens";
+import type { useAccessLinkForm } from "@/hooks/useAccessLinkForm";
import { getDateLocale } from "@/lib/locales";
-import { useLocale } from "next-intl";
+import { cn } from "@/lib/utils";
-interface CalendarTokenListProps {
- calendarId: string;
+function isExpired(token: CalendarAccessToken) {
+ return !!token.expiresAt && new Date(token.expiresAt) < new Date();
}
-export function CalendarTokenList({ calendarId }: CalendarTokenListProps) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
-
- const { tokens, updateToken, deleteToken } = useCalendarTokens(calendarId);
-
- const [createDialogOpen, setCreateDialogOpen] = useState(false);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const [tokenToDelete, setTokenToDelete] =
- useState<CalendarAccessToken | null>(null);
-
- const handleToggleActive = async (token: CalendarAccessToken) => {
- await updateToken(token.id, { isActive: !token.isActive });
- };
-
- const handleDelete = async () => {
- if (!tokenToDelete) return;
+export function isUsableToken(token: CalendarAccessToken) {
+ return token.isActive && !isExpired(token);
+}
- const success = await deleteToken(tokenToDelete.id);
- if (success) {
- setDeleteDialogOpen(false);
- setTokenToDelete(null);
- }
- };
+function TokenRow({
+ token,
+ onToggleActive,
+ onRevoke,
+}: {
+ token: CalendarAccessToken;
+ onToggleActive: () => void;
+ onRevoke: () => void;
+}) {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const expired = isExpired(token);
+ const dimmed = expired || !token.isActive;
+
+ const expiryDate = token.expiresAt
+ ? format(new Date(token.expiresAt), "P", { locale: dateLocale })
+ : null;
+ const expiry = !expiryDate
+ ? t("sharingSheet.noExpiry")
+ : expired
+ ? t("sharingSheet.expiredOn", { date: expiryDate })
+ : t("sharingSheet.expiresOn", { date: expiryDate });
+
+ const usage = [
+ t("token.usedCount", { count: token.usageCount }),
+ token.lastUsedAt &&
+ t("sharingSheet.lastUsed", {
+ time: formatDistanceToNow(new Date(token.lastUsedAt), {
+ addSuffix: true,
+ locale: dateLocale,
+ }),
+ }),
+ ]
+ .filter(Boolean)
+ .join(" · ");
return (
- <div className="space-y-4">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div>
- <p className="text-sm font-medium">
- {t("token.accessLinks")} ({tokens.length})
- </p>
- <p className="text-xs text-muted-foreground">
- {t("token.accessLinksDescription")}
- </p>
+ <ListRow className={cn(dimmed && "bg-surface-panel")}>
+ <LinkIcon className="size-4 shrink-0 text-fg-tertiary" />
+ <div className="min-w-0 flex-1">
+ <div
+ className={cn(
+ "truncate text-[14px] font-semibold",
+ dimmed ? "text-fg-secondary" : "text-fg-strong"
+ )}
+ >
+ {token.name || (
+ <span className="font-normal italic text-fg-tertiary">{t("token.unnamed")}</span>
+ )}
</div>
- <Button
- onClick={() => setCreateDialogOpen(true)}
- size="sm"
- className="gap-2"
+ <div
+ className={cn(
+ "mt-0.5 truncate font-mono text-[12px]",
+ expired ? "text-danger" : "text-fg-tertiary"
+ )}
>
- <Plus className="h-4 w-4" />
- {t("common.add")}
- </Button>
- </div>
-
- {/* Token List */}
- {tokens.length === 0 ? (
- <div className="border rounded-lg p-8 text-center">
- <div className="flex flex-col items-center gap-3">
- <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
- <LinkIcon className="h-6 w-6 text-muted-foreground" />
- </div>
- <div>
- <p className="text-sm font-medium">{t("token.noTokensYet")}</p>
- <p className="text-xs text-muted-foreground mt-1">
- {t("token.noTokensDescription")}
- </p>
- </div>
- <Button
- onClick={() => setCreateDialogOpen(true)}
- size="sm"
- className="gap-2 mt-2"
- >
- <Plus className="h-4 w-4" />
- {t("token.createFirstLink")}
- </Button>
- </div>
+ {expiry}
</div>
+ <div className="truncate text-[12px] text-fg-tertiary">{usage}</div>
+ </div>
+ {token.permission === "write" ? (
+ <Pill tone="warning">{t("sharingSheet.permWrite")}</Pill>
) : (
- <div className="border rounded-lg overflow-hidden">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>{t("common.labels.name")}</TableHead>
- <TableHead>{t("token.token")}</TableHead>
- <TableHead>{t("common.labels.permission")}</TableHead>
- <TableHead>{t("token.expires")}</TableHead>
- <TableHead>{t("token.usage")}</TableHead>
- <TableHead>{t("common.labels.status")}</TableHead>
- <TableHead className="w-[50px]"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {tokens.map((token) => (
- <TableRow key={token.id}>
- {/* Name */}
- <TableCell className="font-medium">
- {token.name || (
- <span className="text-muted-foreground italic">
- {t("token.unnamed")}
- </span>
- )}
- </TableCell>
-
- {/* Token Preview */}
- <TableCell className="font-mono text-xs">
- {token.tokenPreview}
- </TableCell>
-
- {/* Permission */}
- <TableCell>
- <Badge variant="secondary">
- {token.permission === "read"
- ? t("common.labels.permissions.read")
- : t("common.labels.permissions.write")}
- </Badge>
- </TableCell>
-
- {/* Expiration */}
- <TableCell className="text-sm">
- {token.expiresAt ? (
- <span>
- {new Date(token.expiresAt) < new Date() ? (
- <span className="text-destructive">
- {t("token.expired")}
- </span>
- ) : (
- formatDistanceToNow(new Date(token.expiresAt), {
- addSuffix: true,
- locale: dateLocale,
- })
- )}
- </span>
- ) : (
- <span className="text-muted-foreground">
- {t("common.time.never")}
- </span>
- )}
- </TableCell>
+ <Pill>{t("sharingSheet.permRead")}</Pill>
+ )}
+ <RowIconButton
+ icon={token.isActive ? EyeOff : Eye}
+ label={token.isActive ? t("token.disable") : t("token.enable")}
+ onClick={onToggleActive}
+ />
+ <RowIconButton icon={Trash2} tone="danger" label={t("token.revoke")} onClick={onRevoke} />
+ </ListRow>
+ );
+}
- {/* Usage Stats */}
- <TableCell className="text-sm">
- <div className="space-y-0.5">
- <div>
- {t("token.usedCount", { count: token.usageCount })}
- </div>
- {token.lastUsedAt ? (
- <div className="text-xs text-muted-foreground">
- {" "}
- {formatDistanceToNow(new Date(token.lastUsedAt), {
- addSuffix: true,
- locale: dateLocale,
- })}
- </div>
- ) : (
- <div className="text-xs text-muted-foreground">
- {t("token.neverUsed")}
- </div>
- )}
- </div>
- </TableCell>
+/** Existing links of a calendar, split into active and inactive/expired. */
+export function CalendarTokenList({ calendarId }: { calendarId: string }) {
+ const t = useTranslations();
+ const { tokens, updateToken, deleteToken } = useCalendarTokens(calendarId);
+ const [tokenToRevoke, setTokenToRevoke] = useState<CalendarAccessToken | null>(null);
+
+ const active = tokens.filter(isUsableToken);
+ const inactive = tokens.filter((token) => !isUsableToken(token));
+
+ const renderRows = (list: CalendarAccessToken[]) =>
+ list.map((token) => (
+ <TokenRow
+ key={token.id}
+ token={token}
+ onToggleActive={() => updateToken(token.id, { isActive: !token.isActive })}
+ onRevoke={() => setTokenToRevoke(token)}
+ />
+ ));
- {/* Status */}
- <TableCell>
- <Badge variant={token.isActive ? "default" : "secondary"}>
- {token.isActive
- ? t("common.status.active")
- : t("common.status.inactive")}
- </Badge>
- </TableCell>
+ return (
+ <>
+ <section className="flex flex-col gap-2">
+ <SectionLabel className="mb-0">{t("sharingSheet.activeLinks")}</SectionLabel>
+ {active.length === 0 ? (
+ <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">
+ {t("sharingSheet.noActiveLinks")}
+ </p>
+ ) : (
+ renderRows(active)
+ )}
+ </section>
+
+ {inactive.length > 0 && (
+ <section className="flex flex-col gap-2">
+ <SectionLabel className="mb-0">{t("sharingSheet.inactiveLinks")}</SectionLabel>
+ {renderRows(inactive)}
+ </section>
+ )}
- {/* Actions */}
- <TableCell>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => handleToggleActive(token)}
- >
- {token.isActive ? (
- <>
- <EyeOff className="h-4 w-4 mr-2" />
- {t("token.disable")}
- </>
- ) : (
- <>
- <Eye className="h-4 w-4 mr-2" />
- {t("token.enable")}
- </>
- )}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => {
- setTokenToDelete(token);
- setDeleteDialogOpen(true);
- }}
- className="text-destructive"
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("token.revoke")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </div>
+ {tokenToRevoke && (
+ <ConfirmationDialog
+ open
+ onOpenChange={(open) => !open && setTokenToRevoke(null)}
+ onConfirm={async () => {
+ if (await deleteToken(tokenToRevoke.id)) setTokenToRevoke(null);
+ }}
+ title={t("token.revokeConfirm")}
+ description={t("token.revokeConfirmDescription", {
+ name: tokenToRevoke.name || t("token.unnamed"),
+ })}
+ confirmText={t("token.revoke")}
+ confirmVariant="destructive"
+ />
)}
+ </>
+ );
+}
- {/* Create Dialog */}
- <CalendarTokenCreateDialog
- open={createDialogOpen}
- onOpenChange={setCreateDialogOpen}
- calendarId={calendarId}
- />
+/**
+ * Access links (screens 9a/9b). The owner holds `form` so its input survives tab
+ * switches; `leading` renders above the list, e.g. a tab switcher.
+ */
+export function AccessLinksPanel({
+ calendarId,
+ form,
+ onClose,
+ leading,
+}: {
+ calendarId: string;
+ form: ReturnType<typeof useAccessLinkForm>;
+ onClose: () => void;
+ leading?: ReactNode;
+}) {
+ const t = useTranslations();
+
+ if (form.created) {
+ return (
+ <>
+ <PanelBody>
+ <AccessLinkCreated created={form.created} />
+ </PanelBody>
+ <PanelFooter>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={form.reset}>
+ {t("common.close")}
+ </Button>
+ </PanelFooter>
+ </>
+ );
+ }
- {/* Delete Confirmation */}
- <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{t("token.revokeConfirm")}</AlertDialogTitle>
- <AlertDialogDescription>
- {t("token.revokeConfirmDescription", {
- name: tokenToDelete?.name || t("token.unnamed"),
- })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
- <AlertDialogAction
- onClick={handleDelete}
- className="bg-destructive"
- >
- {t("token.revoke")}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
+ return (
+ <>
+ <PanelBody className="flex flex-col gap-3.5">
+ {leading}
+ <CalendarTokenList calendarId={calendarId} />
+ <div className="h-px shrink-0 bg-line" />
+ <AccessLinkCreateForm form={form} />
+ </PanelBody>
+ <PanelFooter>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>
+ {t("common.cancel")}
+ </Button>
+ <Button className="h-10 flex-1 font-semibold" onClick={form.create} disabled={form.creating}>
+ {form.creating ? t("sharingSheet.creating") : t("sharingSheet.createLink")}
+ </Button>
+ </PanelFooter>
+ </>
);
}
diff --git a/components/calendar-workspace.tsx b/components/calendar-workspace.tsx
new file mode 100644
index 0000000..15a5b92
--- /dev/null
+++ b/components/calendar-workspace.tsx
@@ -0,0 +1,253 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format, startOfWeek } from "date-fns";
+import { RefreshCw, WifiOff } from "lucide-react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Button } from "@/components/ui/button";
+import { MonthArrows } from "@/components/app-header";
+import { MonthGrid } from "@/components/month-grid";
+import { DayInspector, DayActions, DayViewModel } from "@/components/day-inspector";
+import { MobileDayFooter, MobileDaySheet, MobileStatsSheet } from "@/components/mobile-day-sheet";
+import { MobilePresetBar, StampDock, orderStampPresets } from "@/components/stamp-dock";
+import { GuestBanner } from "@/components/guest-banner";
+import { ReadOnlyBanner } from "@/components/read-only-banner";
+import { StatusBanner } from "@/components/status-banner";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
+import { DayLayoutOptions } from "@/lib/shift-display";
+import { getDateLocale } from "@/lib/locales";
+import { useDayData, usePeriodSummary, StatsPeriod } from "@/hooks/useDaySummary";
+import { useStampShortcuts } from "@/hooks/useStampShortcuts";
+import { useConnectionStatus } from "@/hooks/useConnectionStatus";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { useAuth } from "@/hooks/useAuth";
+
+interface CalendarWorkspaceProps {
+ header: React.ReactNode;
+ calendarId: string | undefined;
+ calendarDays: Date[];
+ currentDate: Date;
+ onDateChange: (date: Date) => void;
+ selectedDay: Date;
+ onDayClick: (date: Date) => void;
+ onDayContextMenu: (date: Date) => void;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ presets: ShiftPreset[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ layout: DayLayoutOptions;
+ showShiftNotes: boolean;
+ highlightedWeekdays: number[];
+ highlightColor: string;
+ canEdit: boolean;
+ showStampBar: boolean;
+ selectedPresetId: string | undefined;
+ onSelectPreset: (id: string | undefined) => void;
+ onManagePresets: () => void;
+ actions: DayActions;
+ sheetOpen: boolean;
+ onSheetOpenChange: (open: boolean) => void;
+}
+
+export function CalendarWorkspace({
+ header,
+ calendarId,
+ calendarDays,
+ currentDate,
+ onDateChange,
+ selectedDay,
+ onDayClick,
+ onDayContextMenu,
+ shifts,
+ notes,
+ presets,
+ externalSyncs,
+ togglingDates,
+ layout,
+ showShiftNotes,
+ highlightedWeekdays,
+ highlightColor,
+ canEdit,
+ showStampBar,
+ selectedPresetId,
+ onSelectPreset,
+ onManagePresets,
+ actions,
+ sheetOpen,
+ onSheetOpenChange,
+}: CalendarWorkspaceProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const queryClient = useQueryClient();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const { isGuest } = useAuth();
+ const { isOnline } = useConnectionStatus({ toasts: false });
+ const [period, setPeriod] = useState<StatsPeriod>("month");
+ const [statsOpen, setStatsOpen] = useState(false);
+
+ const dayData = useDayData({ selectedDay, shifts, notes });
+ const monthSummary = usePeriodSummary({
+ calendarId,
+ anchorDate: currentDate,
+ period: "month",
+ shifts,
+ });
+ // Anchored on the week, not the day, so tapping around inside a week reuses one cache entry
+ const sheetSummary = usePeriodSummary({
+ calendarId: statsOpen ? calendarId : undefined,
+ anchorDate: period === "week" ? startOfWeek(selectedDay, { weekStartsOn: 1 }) : currentDate,
+ period,
+ shifts,
+ });
+
+ const stampingEnabled = canEdit && isOnline && showStampBar;
+ const stampPresetIds = useMemo(
+ () => orderStampPresets(presets).map((p) => p.id),
+ [presets]
+ );
+ useStampShortcuts({
+ presetIds: stampPresetIds,
+ selectedPresetId,
+ onSelectPreset,
+ enabled: stampingEnabled && desktop,
+ });
+
+ const model: DayViewModel = {
+ selectedDay,
+ currentDate,
+ ...dayData,
+ summary: monthSummary,
+ canEdit: canEdit && isOnline,
+ };
+
+ const banners = (
+ <>
+ {!isOnline && (
+ <StatusBanner
+ tone="danger"
+ icon={WifiOff}
+ title={t("calendarView.offlineTitle")}
+ >
+ {t("calendarView.offlineMessage")}
+ </StatusBanner>
+ )}
+ {isGuest && <GuestBanner variant={desktop ? "default" : "compact"} />}
+ {!canEdit && !isGuest && calendarId && (
+ <ReadOnlyBanner
+ title={t("calendarView.readOnlyTitle")}
+ message={t("calendarView.readOnlyMessage")}
+ />
+ )}
+ </>
+ );
+ const hasBanner = !isOnline || isGuest || (!canEdit && !!calendarId);
+
+ const grid = (
+ <MonthGrid
+ variant={desktop ? "desktop" : "phone"}
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ selectedDay={selectedDay}
+ shifts={shifts}
+ notes={notes}
+ externalSyncs={externalSyncs}
+ togglingDates={togglingDates}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={onDayClick}
+ onDayContextMenu={canEdit ? onDayContextMenu : undefined}
+ />
+ );
+
+ if (desktop) {
+ return (
+ <div className="flex h-dvh flex-col bg-background">
+ {header}
+ <div className="flex min-h-0 flex-1">
+ <main className="relative flex min-w-0 flex-1 flex-col pb-[18px]">
+ {hasBanner && <div className="flex flex-col gap-2 px-[18px] pt-3.5">{banners}</div>}
+ <div className={isOnline ? "contents" : "contents [&>div]:opacity-60"}>{grid}</div>
+ {stampingEnabled && (
+ <StampDock
+ presets={presets}
+ selectedPresetId={selectedPresetId}
+ onSelectPreset={onSelectPreset}
+ onManage={onManagePresets}
+ />
+ )}
+ </main>
+ <DayInspector model={model} actions={actions} />
+ </div>
+ </div>
+ );
+ }
+
+ const dateLocale = getDateLocale(locale);
+
+ return (
+ <div className="flex h-dvh flex-col bg-background">
+ {header}
+ <main className="flex min-h-0 flex-1 flex-col overflow-y-auto">
+ {hasBanner && <div className="flex flex-col gap-2 px-3 pt-3">{banners}</div>}
+ <div className="flex items-center justify-between gap-2 px-3.5 pb-[9px] pt-3">
+ <h1 className="text-[19px] font-semibold tracking-[-0.015em] text-fg-strong">
+ {format(currentDate, "LLLL yyyy", { locale: dateLocale })}
+ </h1>
+ {isOnline ? (
+ <MonthArrows currentDate={currentDate} onDateChange={onDateChange} />
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-9 gap-2 font-semibold"
+ onClick={() => queryClient.refetchQueries()}
+ >
+ <RefreshCw className="size-4" />
+ {t("calendarView.retry")}
+ </Button>
+ )}
+ </div>
+ <div className={`flex flex-1 flex-col pb-1${isOnline ? "" : " opacity-60"}`}>{grid}</div>
+ </main>
+ <div className="shrink-0">
+ {stampingEnabled && (
+ <MobilePresetBar
+ presets={presets}
+ selectedPresetId={selectedPresetId}
+ onSelectPreset={onSelectPreset}
+ onManage={onManagePresets}
+ />
+ )}
+ <MobileDayFooter
+ summary={monthSummary}
+ onOpenStats={() => {
+ // The footer shows the month, so the sheet opens on it
+ setPeriod("month");
+ setStatsOpen(true);
+ }}
+ onAddShift={model.canEdit ? actions.onAddShift : undefined}
+ />
+ </div>
+ <MobileDaySheet
+ model={model}
+ actions={actions}
+ open={sheetOpen}
+ onOpenChange={onSheetOpenChange}
+ />
+ <MobileStatsSheet
+ model={model}
+ actions={actions}
+ period={period}
+ onPeriodChange={setPeriod}
+ summary={sheetSummary}
+ open={statsOpen}
+ onOpenChange={setStatsOpen}
+ />
+ </div>
+ );
+}
diff --git a/components/changelog-dialog.tsx b/components/changelog-dialog.tsx
index 9ab660f..6b08df8 100644
--- a/components/changelog-dialog.tsx
+++ b/components/changelog-dialog.tsx
@@ -2,17 +2,10 @@
import { useEffect, useState, Fragment, ReactNode } from "react";
import { useTranslations } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
-import { Loader2, ExternalLink, Calendar, Tag } from "lucide-react";
-import { Button } from "@/components/ui/button";
+import { ExternalLink, Loader2 } from "lucide-react";
import { format } from "date-fns";
-import { de, enUS, it } from "date-fns/locale";
+import { PanelDialog } from "@/components/panel-dialog";
+import { getDateLocale } from "@/lib/locales";
interface GitHubRelease {
id: number;
@@ -32,402 +25,338 @@ interface ChangelogDialogProps {
locale: string;
}
-export function ChangelogDialog({
- open,
- onOpenChange,
- locale,
-}: ChangelogDialogProps) {
- const t = useTranslations();
- const [releases, setReleases] = useState<GitHubRelease[]>([]);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- if (open) {
- fetchReleases();
+/** Resolves to an empty list on any failure so the dialog shows its empty state. */
+async function fetchReleases(): Promise<GitHubRelease[]> {
+ try {
+ const response = await fetch("/api/releases");
+ if (!response.ok) {
+ console.error("Failed to fetch releases:", response.status, response.statusText);
+ return [];
}
- }, [open]);
-
- const fetchReleases = async () => {
- setLoading(true);
- try {
- const response = await fetch("/api/releases");
- if (!response.ok) {
- console.error(
- "Failed to fetch releases:",
- response.status,
- response.statusText
- );
- setLoading(false);
- return;
- }
- const contentType = response.headers.get("content-type");
- if (!contentType || !contentType.includes("application/json")) {
- console.error("Invalid content type:", contentType);
- setLoading(false);
- return;
- }
-
- const data = await response.json();
- setReleases(data);
- } catch (error) {
- console.error("Failed to fetch releases:", error);
- } finally {
- setLoading(false);
+ const contentType = response.headers.get("content-type");
+ if (!contentType || !contentType.includes("application/json")) {
+ console.error("Invalid content type:", contentType);
+ return [];
}
- };
- const formatDate = (dateString: string) => {
- const date = new Date(dateString);
- return format(date, "PPP", {
- locale: locale === "de" ? de : locale === "it" ? it : enUS,
- });
- };
+ return await response.json();
+ } catch (error) {
+ console.error("Failed to fetch releases:", error);
+ return [];
+ }
+}
- // Sanitize and validate URLs to prevent XSS
- const sanitizeUrl = (url: string): string | null => {
- try {
- const parsed = new URL(url, window.location.href);
- // Only allow http, https, and data:image URLs
- if (
- parsed.protocol === "http:" ||
- parsed.protocol === "https:" ||
- (parsed.protocol === "data:" && url.startsWith("data:image/"))
- ) {
- return parsed.href;
- }
- return null;
- } catch {
- return null;
+// Sanitize and validate URLs to prevent XSS
+function sanitizeUrl(url: string): string | null {
+ try {
+ const parsed = new URL(url, window.location.href);
+ // Only allow http, https, and data:image URLs
+ if (
+ parsed.protocol === "http:" ||
+ parsed.protocol === "https:" ||
+ (parsed.protocol === "data:" && url.startsWith("data:image/"))
+ ) {
+ return parsed.href;
}
- };
+ return null;
+ } catch {
+ return null;
+ }
+}
- // Parse inline markdown elements (bold, code, links) into React elements
- const parseInlineMarkdown = (text: string): ReactNode[] => {
- const elements: ReactNode[] = [];
- let currentText = "";
- let index = 0;
- let key = 0;
-
- const flushText = () => {
- if (currentText) {
- elements.push(<Fragment key={`text-${key++}`}>{currentText}</Fragment>);
- currentText = "";
- }
- };
+const linkClass = "font-medium text-brand-ink hover:underline";
- while (index < text.length) {
- // Auto-link URLs
- const urlMatch = text
- .slice(index)
- .match(/^https?:\/\/[^\s<]+[^\s<.,;:!?"')]/);
- if (urlMatch) {
- flushText();
- const url = urlMatch[0];
- const sanitized = sanitizeUrl(url);
- if (sanitized) {
- elements.push(
- <a
- key={`link-${key++}`}
- href={sanitized}
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline font-medium break-all"
- >
- {url}
- </a>
- );
- } else {
- currentText += url;
- }
- index += url.length;
- continue;
- }
+// Parse inline markdown elements (bold, code, links) into React elements
+function parseInlineMarkdown(text: string): ReactNode[] {
+ const elements: ReactNode[] = [];
+ let currentText = "";
+ let index = 0;
+ let key = 0;
- // Markdown links [text](url)
- const linkMatch = text.slice(index).match(/^\[([^\]]+)\]\(([^)]+)\)/);
- if (linkMatch) {
- flushText();
- const linkText = linkMatch[1];
- const linkUrl = linkMatch[2];
- const sanitized = sanitizeUrl(linkUrl);
- if (sanitized) {
- elements.push(
- <a
- key={`link-${key++}`}
- href={sanitized}
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline font-medium"
- >
- {linkText}
- </a>
- );
- } else {
- currentText += linkText;
- }
- index += linkMatch[0].length;
- continue;
- }
+ const flushText = () => {
+ if (currentText) {
+ elements.push(<Fragment key={`text-${key++}`}>{currentText}</Fragment>);
+ currentText = "";
+ }
+ };
- // Bold **text**
- const boldMatch = text.slice(index).match(/^\*\*([^*]+)\*\*/);
- if (boldMatch) {
- flushText();
+ while (index < text.length) {
+ // Auto-link URLs
+ const urlMatch = text.slice(index).match(/^https?:\/\/[^\s<]+[^\s<.,;:!?"')]/);
+ if (urlMatch) {
+ flushText();
+ const url = urlMatch[0];
+ const sanitized = sanitizeUrl(url);
+ if (sanitized) {
elements.push(
- <strong
- key={`bold-${key++}`}
- className="font-semibold text-foreground"
+ <a
+ key={`link-${key++}`}
+ href={sanitized}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={`${linkClass} break-all`}
>
- {boldMatch[1]}
- </strong>
+ {url}
+ </a>
);
- index += boldMatch[0].length;
- continue;
+ } else {
+ currentText += url;
}
+ index += url.length;
+ continue;
+ }
- // Inline code `text`
- const codeMatch = text.slice(index).match(/^`([^`]+)`/);
- if (codeMatch) {
- flushText();
+ // Markdown links [text](url)
+ const linkMatch = text.slice(index).match(/^\[([^\]]+)\]\(([^)]+)\)/);
+ if (linkMatch) {
+ flushText();
+ const linkText = linkMatch[1];
+ const sanitized = sanitizeUrl(linkMatch[2]);
+ if (sanitized) {
elements.push(
- <code
- key={`code-${key++}`}
- className="px-1.5 py-0.5 rounded bg-muted/80 text-xs font-mono text-foreground whitespace-nowrap"
+ <a
+ key={`link-${key++}`}
+ href={sanitized}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={linkClass}
>
- {codeMatch[1]}
- </code>
+ {linkText}
+ </a>
);
- index += codeMatch[0].length;
- continue;
+ } else {
+ currentText += linkText;
}
-
- // Regular character
- currentText += text[index];
- index++;
+ index += linkMatch[0].length;
+ continue;
}
- flushText();
- return elements;
- };
+ // Bold **text**
+ const boldMatch = text.slice(index).match(/^\*\*([^*]+)\*\*/);
+ if (boldMatch) {
+ flushText();
+ elements.push(
+ <strong key={`bold-${key++}`} className="font-semibold text-fg-strong">
+ {boldMatch[1]}
+ </strong>
+ );
+ index += boldMatch[0].length;
+ continue;
+ }
- // Parse markdown text into React elements
- const parseMarkdown = (text: string): ReactNode[] => {
- const lines = text.split("\n");
- const elements: ReactNode[] = [];
- let listItems: ReactNode[] = [];
- let inCodeBlock = false;
- let codeBlockLines: string[] = [];
- let elementKey = 0;
-
- const flushList = () => {
- if (listItems.length > 0) {
- elements.push(
- <ul
- key={`list-${elementKey++}`}
- className="list-disc ml-6 space-y-1 my-2"
- >
- {listItems}
- </ul>
- );
- listItems = [];
- }
- };
+ // Inline code `text`
+ const codeMatch = text.slice(index).match(/^`([^`]+)`/);
+ if (codeMatch) {
+ flushText();
+ elements.push(
+ <code
+ key={`code-${key++}`}
+ className="whitespace-nowrap rounded bg-surface-sunken px-1.5 py-0.5 font-mono text-[12px] text-fg-strong"
+ >
+ {codeMatch[1]}
+ </code>
+ );
+ index += codeMatch[0].length;
+ continue;
+ }
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
-
- // Code blocks (```)
- if (line.startsWith("```")) {
- flushList();
- if (inCodeBlock) {
- // Close code block
- elements.push(
- <pre
- key={`code-${elementKey++}`}
- className="bg-muted/50 border border-border/50 rounded-lg p-4 my-3 overflow-x-auto"
- >
- <code className="text-sm font-mono text-foreground block">
- {codeBlockLines.join("\n")}
- </code>
- </pre>
- );
- codeBlockLines = [];
- inCodeBlock = false;
- } else {
- inCodeBlock = true;
- }
- continue;
- }
+ currentText += text[index];
+ index++;
+ }
- // Inside code block
- if (inCodeBlock) {
- codeBlockLines.push(line);
- continue;
- }
+ flushText();
+ return elements;
+}
- // Headers
- if (line.startsWith("### ")) {
- flushList();
- elements.push(
- <h4
- key={`h4-${elementKey++}`}
- className="text-base font-semibold mt-4 mb-2 text-foreground"
- >
- {parseInlineMarkdown(line.slice(4))}
- </h4>
- );
- continue;
- }
- if (line.startsWith("## ")) {
- flushList();
- elements.push(
- <h3
- key={`h3-${elementKey++}`}
- className="text-lg font-semibold mt-5 mb-3 text-foreground"
- >
- {parseInlineMarkdown(line.slice(3))}
- </h3>
- );
- continue;
- }
- if (line.startsWith("# ")) {
- flushList();
- elements.push(
- <h2
- key={`h2-${elementKey++}`}
- className="text-xl font-bold mt-6 mb-4 text-foreground"
- >
- {parseInlineMarkdown(line.slice(2))}
- </h2>
- );
- continue;
- }
+function codeBlock(lines: string[], key: string) {
+ return (
+ <pre
+ key={key}
+ className="my-2.5 overflow-x-auto rounded-lg border border-line bg-surface-panel p-3"
+ >
+ <code className="block font-mono text-[12px] text-fg-body">{lines.join("\n")}</code>
+ </pre>
+ );
+}
- // Bullet points
- if (line.startsWith("- ") || line.startsWith("* ")) {
- const content = line.slice(2);
- listItems.push(
- <li
- key={`li-${elementKey++}`}
- className="text-sm text-muted-foreground leading-relaxed"
- >
- {parseInlineMarkdown(content)}
- </li>
- );
- continue;
- }
+// Parse markdown text into React elements
+function parseMarkdown(text: string): ReactNode[] {
+ const lines = text.split("\n");
+ const elements: ReactNode[] = [];
+ let listItems: ReactNode[] = [];
+ let inCodeBlock = false;
+ let codeBlockLines: string[] = [];
+ let elementKey = 0;
+
+ const flushList = () => {
+ if (listItems.length > 0) {
+ elements.push(
+ <ul
+ key={`list-${elementKey++}`}
+ className="my-1.5 list-disc space-y-1 pl-5 marker:text-fg-faint"
+ >
+ {listItems}
+ </ul>
+ );
+ listItems = [];
+ }
+ };
- // Close list if we're in one and hit a non-list line
- if (listItems.length > 0) {
- flushList();
+ for (const line of lines) {
+ if (line.startsWith("```")) {
+ flushList();
+ if (inCodeBlock) {
+ elements.push(codeBlock(codeBlockLines, `code-${elementKey++}`));
+ codeBlockLines = [];
+ inCodeBlock = false;
+ } else {
+ inCodeBlock = true;
}
+ continue;
+ }
- // Empty lines
- if (line.trim() === "") {
- elements.push(<div key={`space-${elementKey++}`} className="h-2" />);
- continue;
- }
+ if (inCodeBlock) {
+ codeBlockLines.push(line);
+ continue;
+ }
- // Regular paragraphs
+ if (line.startsWith("### ")) {
+ flushList();
+ elements.push(
+ <h6 key={`h6-${elementKey++}`} className="eyebrow mb-1.5 mt-3.5">
+ {parseInlineMarkdown(line.slice(4))}
+ </h6>
+ );
+ continue;
+ }
+ if (line.startsWith("## ")) {
+ flushList();
elements.push(
- <p
- key={`p-${elementKey++}`}
- className="text-sm text-muted-foreground my-1"
+ <h5
+ key={`h5-${elementKey++}`}
+ className="mb-1.5 mt-3.5 text-[14px] font-semibold text-fg-strong"
>
- {parseInlineMarkdown(line)}
- </p>
+ {parseInlineMarkdown(line.slice(3))}
+ </h5>
);
+ continue;
}
-
- // Close list if still open at end
- flushList();
-
- // Close code block if still open at end
- if (inCodeBlock) {
+ if (line.startsWith("# ")) {
+ flushList();
elements.push(
- <pre
- key={`code-${elementKey++}`}
- className="bg-muted/50 border border-border/50 rounded-lg p-4 my-3 overflow-x-auto"
+ <h4
+ key={`h4-${elementKey++}`}
+ className="mb-2 mt-4 text-[15px] font-semibold text-fg-strong"
>
- <code className="text-sm font-mono text-foreground block">
- {codeBlockLines.join("\n")}
- </code>
- </pre>
+ {parseInlineMarkdown(line.slice(2))}
+ </h4>
);
+ continue;
}
- return elements;
- };
+ if (line.startsWith("- ") || line.startsWith("* ")) {
+ listItems.push(
+ <li key={`li-${elementKey++}`} className="text-[13px] leading-relaxed text-fg-body">
+ {parseInlineMarkdown(line.slice(2))}
+ </li>
+ );
+ continue;
+ }
+
+ flushList();
+
+ if (line.trim() === "") {
+ elements.push(<div key={`space-${elementKey++}`} className="h-1.5" />);
+ continue;
+ }
+
+ elements.push(
+ <p key={`p-${elementKey++}`} className="my-1 text-[13px] leading-relaxed text-fg-body">
+ {parseInlineMarkdown(line)}
+ </p>
+ );
+ }
+
+ flushList();
+ if (inCodeBlock) {
+ elements.push(codeBlock(codeBlockLines, `code-${elementKey++}`));
+ }
+
+ return elements;
+}
+
+export function ChangelogDialog({ open, onOpenChange, locale }: ChangelogDialogProps) {
+ const t = useTranslations();
+ // null until the first response arrives
+ const [releases, setReleases] = useState<GitHubRelease[] | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ fetchReleases().then((data) => {
+ if (!cancelled) setReleases(data);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open]);
+
+ const formatDate = (dateString: string) =>
+ format(new Date(dateString), "PPP", { locale: getDateLocale(locale) });
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[700px] 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 flex items-center gap-2">
- <ExternalLink className="h-5 w-5" />
- {t("changelog.title")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {t("changelog.description")}
- </DialogDescription>
- </DialogHeader>
- <div className="overflow-y-auto flex-1 px-6 pb-6">
- {loading ? (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
- </div>
- ) : releases.length === 0 ? (
- <div className="text-center py-12 text-muted-foreground">
- {t("changelog.noReleases")}
- </div>
- ) : (
- <div className="space-y-6 mt-6">
- {releases.map((release) => (
- <div
- key={release.id}
- className="border border-border/50 rounded-lg p-4 bg-gradient-to-br from-background to-muted/20 hover:border-border transition-colors"
- >
- <div className="flex items-start justify-between gap-4 mb-3">
- <div className="flex-1">
- <div className="flex items-center gap-2 mb-1">
- <Tag className="h-4 w-4 text-primary" />
- <h3 className="text-lg font-semibold text-foreground">
- {release.name || release.tag_name}
- </h3>
- </div>
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Calendar className="h-3 w-3" />
- {formatDate(release.published_at)}
- </div>
- </div>
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- window.open(
- release.html_url,
- "_blank",
- "noopener,noreferrer"
- )
- }
- className="shrink-0"
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("changelog.title")}
+ description={t("changelog.description")}
+ width="lg"
+ bodyClassName="py-0"
+ >
+ {releases === null ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="size-6 animate-spin text-fg-tertiary" />
+ </div>
+ ) : releases.length === 0 ? (
+ <p className="py-12 text-center text-[13px] text-fg-tertiary">
+ {t("changelog.noReleases")}
+ </p>
+ ) : (
+ <div className="divide-y divide-line-subtle">
+ {releases.map((release) => {
+ const title = release.name && release.name !== release.tag_name ? release.name : null;
+ const releaseUrl = sanitizeUrl(release.html_url);
+ return (
+ <section key={release.id} className="py-[18px]">
+ <div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-1">
+ <h3 className="font-mono text-[14px] font-semibold text-fg-strong">
+ {release.tag_name}
+ </h3>
+ <span className="text-[12px] text-fg-tertiary">
+ {formatDate(release.published_at)}
+ </span>
+ {releaseUrl && (
+ <a
+ href={releaseUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="ml-auto inline-flex items-center gap-1 text-[12.5px] font-medium text-brand-ink hover:underline"
>
- <ExternalLink className="h-4 w-4 mr-1.5" />
{t("changelog.viewOnGitHub")}
- </Button>
- </div>
- {release.body && (
- <div className="prose prose-sm max-w-none dark:prose-invert">
- {parseMarkdown(release.body)}
- </div>
+ <ExternalLink className="size-3.5" />
+ </a>
)}
</div>
- ))}
- </div>
- )}
+ {title && (
+ <div className="mt-1 text-[13.5px] font-semibold text-fg-body">{title}</div>
+ )}
+ {release.body && <div className="mt-2">{parseMarkdown(release.body)}</div>}
+ </section>
+ );
+ })}
</div>
- </DialogContent>
- </Dialog>
+ )}
+ </PanelDialog>
);
}
diff --git a/components/compare-workspace.tsx b/components/compare-workspace.tsx
new file mode 100644
index 0000000..051cd8b
--- /dev/null
+++ b/components/compare-workspace.tsx
@@ -0,0 +1,652 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format, isSameDay, isSameMonth, isToday } from "date-fns";
+import { toast } from "sonner";
+import {
+ Columns2,
+ Info,
+ Link2,
+ Plus,
+ Share,
+ SlidersHorizontal,
+ X,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { MonthGrid } from "@/components/month-grid";
+import { MonthArrows, MonthStepper } from "@/components/app-header";
+import { PresetManageSheet } from "@/components/preset-manage-sheet";
+import { MorePresets, orderStampPresets, splitStampPresets } from "@/components/stamp-dock";
+import { MAX_COMPARE_CALENDARS } from "@/components/calendar-compare-sheet";
+import { useDayLabels } from "@/components/day-inspector";
+import { CalendarWithCount, ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync, ShiftPreset } from "@/lib/db/schema";
+import {
+ DayLayoutOptions,
+ formatHours,
+ getDayShifts,
+ getShiftCode,
+ getShiftMinutes,
+ shiftVars,
+ sortShifts,
+ sumShiftMinutes,
+} from "@/lib/shift-display";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { getDateLocale } from "@/lib/locales";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useConnectionStatus } from "@/hooks/useConnectionStatus";
+import { useStampShortcuts } from "@/hooks/useStampShortcuts";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { cn } from "@/lib/utils";
+
+interface CompareWorkspaceProps {
+ calendars: CalendarWithCount[];
+ calendarDays: Date[];
+ currentDate: Date;
+ onDateChange: (date: Date) => void;
+ selectedDay: Date;
+ onSelectDay: (date: Date) => void;
+ shiftsMap: Map<string, ShiftWithCalendar[]>;
+ notesMap: Map<string, CalendarNote[]>;
+ externalSyncsMap: Map<string, ExternalSync[]>;
+ presetsMap: Map<string, ShiftPreset[]>;
+ togglingDatesMap: Map<string, Set<string>>;
+ layout: DayLayoutOptions;
+ showShiftNotes: boolean;
+ highlightedWeekdays: number[];
+ highlightColor: string;
+ selectedPresetId: string | undefined;
+ onSelectPreset: (id: string | undefined) => void;
+ onDayClick: (calendarId: string, date: Date) => void;
+ onDayContextMenu: (calendarId: string, date: Date) => void;
+ onOpenDayShifts: (date: Date, shifts: ShiftWithCalendar[]) => void;
+ onPresetsChange: (calendarId: string) => void;
+ onAddCalendar: () => void;
+ onViewSettings: () => void;
+ onExit: () => void;
+}
+
+function monthTotals(shifts: ShiftWithCalendar[], month: Date) {
+ const inMonth = shifts.filter((s) => s.date && isSameMonth(s.date as Date, month));
+ return {
+ count: inMonth.length,
+ minutes: inMonth.reduce((sum, s) => sum + getShiftMinutes(s), 0),
+ };
+}
+
+function useShareCompareLink(ids: string[]) {
+ const t = useTranslations();
+ return () => {
+ const url = new URL(window.location.href);
+ url.searchParams.set("compare", ids.join(","));
+ navigator.clipboard
+ .writeText(url.toString())
+ .then(() => toast.success(t("common.copied", { item: t("calendar.compareMode") })))
+ .catch(() => toast.error(t("common.error")));
+ };
+}
+
+export function CompareWorkspace(props: CompareWorkspaceProps) {
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const [manageCalendarId, setManageCalendarId] = useState<string | null>(null);
+
+ const presetOwner = useMemo(() => {
+ if (!props.selectedPresetId) return null;
+ for (const [calendarId, presets] of props.presetsMap) {
+ if (presets.some((p) => p.id === props.selectedPresetId)) return calendarId;
+ }
+ return null;
+ }, [props.presetsMap, props.selectedPresetId]);
+
+ const activeColumnId = presetOwner ?? props.calendars[0]?.id;
+ const activePresets = orderStampPresets(props.presetsMap.get(activeColumnId ?? "") ?? []);
+
+ // Each column carries its own permission, and only an editable one renders the
+ // presets the shortcuts arm — without this a key press stamps into a read-only
+ // calendar and the write is rejected server-side.
+ const { canEdit: canEditActiveColumn } = useCalendarPermission(activeColumnId);
+ const { isOnline } = useConnectionStatus({ toasts: false });
+
+ useStampShortcuts({
+ presetIds: activePresets.map((p) => p.id),
+ selectedPresetId: props.selectedPresetId,
+ onSelectPreset: props.onSelectPreset,
+ enabled: desktop && canEditActiveColumn && isOnline,
+ });
+
+ const managed = props.calendars.find((c) => c.id === manageCalendarId);
+
+ return (
+ <>
+ {desktop ? (
+ <CompareDesktop
+ {...props}
+ presetOwner={presetOwner}
+ activeColumnId={activeColumnId}
+ onManagePresets={setManageCalendarId}
+ />
+ ) : (
+ <CompareMobile {...props} />
+ )}
+ {managed && (
+ <PresetManageSheet
+ open={!!manageCalendarId}
+ onOpenChange={(open) => !open && setManageCalendarId(null)}
+ calendarId={managed.id}
+ onPresetsChange={() => props.onPresetsChange(managed.id)}
+ />
+ )}
+ </>
+ );
+}
+
+function CompareDesktop({
+ calendars,
+ currentDate,
+ onDateChange,
+ onSelectDay,
+ selectedDay,
+ onAddCalendar,
+ onViewSettings,
+ onExit,
+ shiftsMap,
+ onOpenDayShifts,
+ presetOwner,
+ activeColumnId,
+ onManagePresets,
+ ...rest
+}: CompareWorkspaceProps & {
+ presetOwner: string | null;
+ activeColumnId: string | undefined;
+ onManagePresets: (calendarId: string) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const share = useShareCompareLink(calendars.map((c) => c.id));
+ const labels = useDayLabels(selectedDay);
+
+ return (
+ <div className="flex h-dvh flex-col bg-background">
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b border-line px-[18px]">
+ <span className="flex size-[26px] items-center justify-center rounded-[7px] bg-brand">
+ <Columns2 className="size-[15px] text-white" />
+ </span>
+ <h1 className="text-[15px] font-semibold text-fg-strong">{t("calendarCompare.title")}</h1>
+ <div className="mx-1 h-6 w-px bg-line" />
+ <MonthStepper currentDate={currentDate} onDateChange={onDateChange} />
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 font-semibold"
+ onClick={() => {
+ onDateChange(new Date());
+ onSelectDay(new Date());
+ }}
+ >
+ {t("calendarView.today")}
+ </Button>
+ <div className="flex-1" />
+ {calendars.length < MAX_COMPARE_CALENDARS && (
+ <Button variant="outline" size="sm" className="h-8 gap-1.5 font-semibold" onClick={onAddCalendar}>
+ <Plus className="size-4" />
+ {t("calendarCompare.addCalendar")}
+ </Button>
+ )}
+ <Button variant="outline" size="sm" className="h-8 gap-1.5 font-semibold" onClick={share}>
+ <Link2 className="size-4" />
+ {t("calendar.shareLink")}
+ </Button>
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-8"
+ onClick={onViewSettings}
+ aria-label={t("appMenu.viewSettings")}
+ >
+ <SlidersHorizontal className="size-4 text-fg-secondary" />
+ </Button>
+ <Button
+ size="sm"
+ onClick={onExit}
+ className="h-8 gap-1.5 bg-fg-strong font-semibold text-background hover:bg-fg-strong/90"
+ >
+ <X className="size-4" />
+ {t("calendarCompare.exit")}
+ </Button>
+ </header>
+
+ <div className="flex min-h-0 flex-1 divide-x divide-line">
+ {calendars.map((calendar) => (
+ <CompareColumn
+ key={calendar.id}
+ calendar={calendar}
+ currentDate={currentDate}
+ selectedDay={selectedDay}
+ shifts={shiftsMap.get(calendar.id) ?? []}
+ stampActive={presetOwner === calendar.id}
+ keysActive={activeColumnId === calendar.id}
+ onManagePresets={() => onManagePresets(calendar.id)}
+ {...rest}
+ />
+ ))}
+ </div>
+
+ <footer className="flex shrink-0 items-center gap-3 border-t border-line bg-surface-panel px-[18px] py-3">
+ <div className="w-[150px] shrink-0">
+ <div className={cn("eyebrow", labels.isToday && "text-brand-ink")}>{labels.eyebrow}</div>
+ <div className="mt-0.5 truncate text-[15px] font-semibold text-fg-strong">
+ {labels.short}
+ </div>
+ </div>
+ {calendars.map((calendar) => {
+ const dayShifts = getDayShifts(shiftsMap.get(calendar.id) ?? [], selectedDay);
+ const minutes = sumShiftMinutes(dayShifts);
+ return (
+ <button
+ key={calendar.id}
+ type="button"
+ disabled={dayShifts.length === 0}
+ onClick={() => onOpenDayShifts(selectedDay, dayShifts)}
+ className="flex min-w-0 flex-1 items-center gap-3 rounded-[11px] border border-line bg-surface-card px-3 py-3 text-left transition-colors enabled:hover:bg-surface-panel"
+ >
+ <span className="h-6 w-1 shrink-0 rounded-full" style={{ backgroundColor: calendar.color }} />
+ <span className="shrink-0 text-[13.5px] font-semibold text-fg-strong">{calendar.name}</span>
+ <span className="h-5 w-px shrink-0 bg-line" />
+ <span className="min-w-0 flex-1 truncate text-[13px] text-fg-secondary">
+ {dayShifts.length
+ ? dayShifts.map((s) => s.title).join(", ")
+ : t("calendarView.dayFree")}
+ </span>
+ {minutes > 0 && (
+ <span className="shrink-0 font-mono text-[13px] text-fg-secondary">
+ {formatHours(minutes, locale)}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </footer>
+ </div>
+ );
+}
+
+function CompareColumn({
+ calendar,
+ currentDate,
+ selectedDay,
+ shifts,
+ stampActive,
+ keysActive,
+ onManagePresets,
+ calendarDays,
+ notesMap,
+ externalSyncsMap,
+ presetsMap,
+ togglingDatesMap,
+ layout,
+ showShiftNotes,
+ highlightedWeekdays,
+ highlightColor,
+ selectedPresetId,
+ onSelectPreset,
+ onDayClick,
+ onDayContextMenu,
+}: Omit<
+ CompareWorkspaceProps,
+ | "calendars"
+ | "onDateChange"
+ | "onSelectDay"
+ | "onAddCalendar"
+ | "onViewSettings"
+ | "onExit"
+ | "shiftsMap"
+ | "onOpenDayShifts"
+ | "onPresetsChange"
+> & {
+ calendar: CalendarWithCount;
+ shifts: ShiftWithCalendar[];
+ stampActive: boolean;
+ keysActive: boolean;
+ onManagePresets: () => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { canEdit } = useCalendarPermission(calendar.id);
+ const { primary, secondary } = splitStampPresets(presetsMap.get(calendar.id) ?? []);
+ const totals = monthTotals(shifts, currentDate);
+
+ return (
+ <section className="flex min-h-0 min-w-0 flex-1 flex-col pb-3">
+ <div className="px-4 pt-3.5">
+ <div className="flex items-center gap-2.5">
+ <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: calendar.color }} />
+ <h2 className="truncate text-[15px] font-semibold text-fg-strong">{calendar.name}</h2>
+ {stampActive && (
+ <span className="rounded-full bg-brand-soft px-[7px] py-0.5 text-[11px] font-semibold uppercase tracking-[0.04em] text-brand-ink">
+ {t("calendarCompare.stampActive")}
+ </span>
+ )}
+ <span className="ml-auto shrink-0 font-mono text-[12px] text-fg-tertiary">
+ {t("calendarView.shiftCount", { count: totals.count })} ·{" "}
+ {formatHours(totals.minutes, locale)}
+ </span>
+ </div>
+ {canEdit && (
+ <div className="mt-2.5 flex h-8 items-center gap-1.5 overflow-hidden">
+ <div className="flex min-w-0 items-center gap-1.5 overflow-hidden empty:hidden">
+ {primary.map((preset, index) => {
+ const active = preset.id === selectedPresetId;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ aria-pressed={active}
+ onClick={() => onSelectPreset(active ? undefined : preset.id)}
+ className={cn(
+ "flex h-7 shrink-0 items-center gap-[7px] rounded-[7px] border px-2.5 text-[12.5px] font-medium transition-colors",
+ active
+ ? "border-brand bg-brand-soft text-brand-ink"
+ : "border-line bg-surface-card text-fg-body hover:bg-surface-panel"
+ )}
+ >
+ <span className="size-[7px] rounded-full" style={{ backgroundColor: preset.color }} />
+ {preset.title}
+ {keysActive && index < 9 && (
+ <kbd className="rounded-[4px] bg-surface-sunken px-1 font-mono text-[10px] font-normal text-fg-tertiary">
+ {index + 1}
+ </kbd>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ <MorePresets
+ variant="compare"
+ presets={secondary}
+ selectedPresetId={selectedPresetId}
+ onSelectPreset={onSelectPreset}
+ />
+ <button
+ type="button"
+ onClick={onManagePresets}
+ aria-label={t("calendarView.managePresets")}
+ className="flex size-7 shrink-0 items-center justify-center rounded-[7px] text-fg-tertiary hover:bg-surface-sunken"
+ >
+ <SlidersHorizontal className="size-3.5" />
+ </button>
+ {!keysActive && primary.length + secondary.length > 0 && (
+ <span className="min-w-0 flex-1 truncate pl-1 text-[12px] text-fg-tertiary">
+ {t("calendarCompare.tapToMoveStamp")}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ <MonthGrid
+ variant="compare"
+ calendarDays={calendarDays}
+ currentDate={currentDate}
+ selectedDay={selectedDay}
+ shifts={shifts}
+ notes={notesMap.get(calendar.id) ?? []}
+ externalSyncs={externalSyncsMap.get(calendar.id) ?? []}
+ togglingDates={togglingDatesMap.get(calendar.id) ?? new Set()}
+ layout={layout}
+ showShiftNotes={showShiftNotes}
+ highlightedWeekdays={highlightedWeekdays}
+ highlightColor={highlightColor}
+ onDayClick={(date) => onDayClick(calendar.id, date)}
+ onDayContextMenu={canEdit ? (date) => onDayContextMenu(calendar.id, date) : undefined}
+ />
+ </section>
+ );
+}
+
+function CompareMobile({
+ calendars,
+ calendarDays,
+ currentDate,
+ onDateChange,
+ selectedDay,
+ onSelectDay,
+ shiftsMap,
+ presetsMap,
+ onAddCalendar,
+ onExit,
+ onOpenDayShifts,
+}: CompareWorkspaceProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const share = useShareCompareLink(calendars.map((c) => c.id));
+ const labels = useDayLabels(selectedDay);
+
+ // Grouped once per calendar instead of filtering the whole list in every day cell
+ const shiftsByDay = useMemo(() => {
+ const grouped = new Map<string, Map<string, ShiftWithCalendar[]>>();
+ for (const [calendarId, list] of shiftsMap) {
+ const byDay = new Map<string, ShiftWithCalendar[]>();
+ for (const shift of list) {
+ if (!shift.date) continue;
+ const key = formatDateToLocal(shift.date as Date);
+ const entry = byDay.get(key);
+ if (entry) entry.push(shift);
+ else byDay.set(key, [shift]);
+ }
+ for (const [key, entry] of byDay) byDay.set(key, sortShifts(entry, "startTime"));
+ grouped.set(calendarId, byDay);
+ }
+ return grouped;
+ }, [shiftsMap]);
+
+ // One legend entry per shift title across all compared calendars
+ const legend = useMemo(() => {
+ const seen = new Map<string, string>();
+ for (const calendar of calendars) {
+ const { primary, secondary } = splitStampPresets(presetsMap.get(calendar.id) ?? []);
+ for (const preset of [...primary, ...secondary]) {
+ if (!seen.has(preset.title)) seen.set(preset.title, preset.color);
+ }
+ }
+ return [...seen.entries()];
+ }, [calendars, presetsMap]);
+
+ const laneHint =
+ calendars.length === 2
+ ? t("calendarCompare.laneHintTwo", { top: calendars[0].name, bottom: calendars[1].name })
+ : t("calendarCompare.laneHintMany", { order: calendars.map((c) => c.name).join(", ") });
+
+ return (
+ <div className="flex h-dvh flex-col bg-background">
+ <header className="flex shrink-0 items-center gap-3 border-b border-line px-4 py-2.5">
+ <button
+ type="button"
+ onClick={onExit}
+ aria-label={t("calendarCompare.exit")}
+ className="flex size-9 items-center justify-center rounded-lg text-fg-secondary"
+ >
+ <X className="size-5" />
+ </button>
+ <div className="min-w-0 flex-1">
+ <h1 className="text-[17px] font-semibold text-fg-strong">{t("calendarCompare.title")}</h1>
+ <p className="truncate text-[12.5px] text-fg-tertiary">
+ {t("calendarCompare.subtitle", { count: calendars.length })} ·{" "}
+ {format(currentDate, "LLLL yyyy", { locale: dateLocale })}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={share}
+ aria-label={t("calendar.shareLink")}
+ className="flex size-9 items-center justify-center rounded-lg text-fg-secondary"
+ >
+ <Share className="size-5" />
+ </button>
+ </header>
+
+ <main className="min-h-0 flex-1 overflow-y-auto">
+ <div className="flex flex-col gap-2.5 border-b border-line px-4 py-3">
+ <div className="flex gap-2">
+ {calendars.map((calendar) => (
+ <span
+ key={calendar.id}
+ className="flex h-10 min-w-0 flex-1 items-center gap-2 rounded-[10px] border-[1.5px] px-3 text-[13.5px] font-semibold"
+ style={{
+ borderColor: calendar.color,
+ color: calendar.color,
+ backgroundColor: `color-mix(in oklch, ${calendar.color} 7%, var(--surface-card))`,
+ }}
+ >
+ <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: calendar.color }} />
+ <span className="truncate">{calendar.name}</span>
+ </span>
+ ))}
+ {calendars.length < MAX_COMPARE_CALENDARS && (
+ <button
+ type="button"
+ onClick={onAddCalendar}
+ aria-label={t("calendarCompare.addCalendar")}
+ className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-dashed border-control text-fg-secondary"
+ >
+ <Plus className="size-4" />
+ </button>
+ )}
+ </div>
+ <p className="flex gap-2 text-[12px] leading-snug text-fg-secondary">
+ <Info className="mt-px size-3.5 shrink-0" />
+ {laneHint}
+ </p>
+ {legend.length > 0 && (
+ <div className="flex flex-wrap gap-x-3 gap-y-1.5">
+ {legend.map(([title, color]) => (
+ <span key={title} className="flex items-center gap-1.5 text-[12px] text-fg-body">
+ <span
+ className="shift-solid flex size-[17px] items-center justify-center rounded-[4px] text-[10px] font-bold"
+ style={shiftVars(color)}
+ >
+ {getShiftCode(title)}
+ </span>
+ {title}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-end gap-2 px-4 pt-2">
+ <MonthArrows currentDate={currentDate} onDateChange={onDateChange} />
+ </div>
+
+ <div className="grid grid-cols-7 px-2 pt-2">
+ {(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] as const).map(
+ (key) => (
+ <div
+ key={key}
+ className="pb-2 text-center text-[11px] font-semibold uppercase tracking-[0.06em] text-fg-tertiary"
+ >
+ {t(`calendarView.weekdayShort.${key}`)}
+ </div>
+ )
+ )}
+ </div>
+ <div className="mx-2 mb-3 grid grid-cols-7 gap-px bg-line-grid">
+ {calendarDays.map((day) => {
+ const dayKey = formatDateToLocal(day);
+ const inMonth = isSameMonth(day, currentDate);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ return (
+ <button
+ key={day.toISOString()}
+ type="button"
+ aria-pressed={selected}
+ onClick={() => {
+ onSelectDay(day);
+ if (!inMonth) onDateChange(day);
+ }}
+ className={cn(
+ "flex min-w-0 flex-col items-center gap-1 px-1 pb-1.5 pt-[5px]",
+ today ? "bg-surface-today" : weekend ? "bg-surface-weekend" : "bg-surface-cell",
+ !inMonth && "opacity-45",
+ selected && "shadow-[inset_0_0_0_1.5px_var(--brand-dot)]"
+ )}
+ >
+ <span
+ className={cn(
+ "inline-flex size-[22px] items-center justify-center rounded-full font-mono text-[12.5px] font-medium",
+ today ? "bg-brand font-semibold text-white" : "text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ {calendars.map((calendar) => {
+ const dayShifts = inMonth
+ ? (shiftsByDay.get(calendar.id)?.get(dayKey) ?? [])
+ : [];
+ const first = dayShifts[0];
+ return (
+ <span key={calendar.id} className="flex w-full items-center gap-[3px]">
+ <span
+ className="h-[18px] w-[3px] shrink-0 rounded-full"
+ style={{ backgroundColor: calendar.color, opacity: inMonth ? 1 : 0.5 }}
+ />
+ {first ? (
+ <span
+ className="shift-solid flex h-[18px] min-w-0 flex-1 items-center justify-center rounded-[4px] text-[10.5px] font-bold"
+ style={shiftVars(first.color)}
+ >
+ {getShiftCode(first.title)}
+ {dayShifts.length > 1 && (
+ <span className="ml-0.5 font-mono text-[9px] font-semibold opacity-85">
+ +{dayShifts.length - 1}
+ </span>
+ )}
+ </span>
+ ) : (
+ <span className="h-[18px] min-w-0 flex-1 rounded-[4px] border border-dashed border-control" />
+ )}
+ </span>
+ );
+ })}
+ </button>
+ );
+ })}
+ </div>
+ </main>
+
+ <div className="shrink-0 border-t border-line bg-surface-panel px-4 pb-[max(12px,env(safe-area-inset-bottom))] pt-3">
+ <div className="mb-2 flex items-center gap-2">
+ <span className={cn("eyebrow", labels.isToday && "text-brand-ink")}>{labels.eyebrow}</span>
+ <span className="text-[14px] font-semibold text-fg-strong">{labels.long}</span>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ {calendars.map((calendar) => {
+ const dayShifts = getDayShifts(shiftsMap.get(calendar.id) ?? [], selectedDay);
+ return (
+ <button
+ key={calendar.id}
+ type="button"
+ disabled={dayShifts.length === 0}
+ onClick={() => onOpenDayShifts(selectedDay, dayShifts)}
+ className="flex items-center gap-2.5 rounded-[10px] border border-line bg-surface-card px-3 py-2.5 text-left"
+ >
+ <span className="h-5 w-1 shrink-0 rounded-full" style={{ backgroundColor: calendar.color }} />
+ <span className="min-w-0 flex-1 truncate text-[13.5px] text-fg-strong">
+ {calendar.name} ·{" "}
+ {dayShifts.length ? dayShifts.map((s) => s.title).join(", ") : t("calendarView.dayFree")}
+ </span>
+ {dayShifts[0] && !dayShifts[0].isAllDay && (
+ <span className="font-mono text-[13px] text-fg-tertiary">
+ {dayShifts[0].startTime.slice(0, 5)}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/day-detail.tsx b/components/day-detail.tsx
new file mode 100644
index 0000000..800be85
--- /dev/null
+++ b/components/day-detail.tsx
@@ -0,0 +1,287 @@
+"use client";
+
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import {
+ CalendarClock,
+ Ellipsis,
+ Pencil,
+ RefreshCw,
+ StickyNote,
+ Trash2,
+} from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote } from "@/lib/db/schema";
+import { getDateLocale } from "@/lib/locales";
+import { formatHours, formatTimeRange, getShiftMinutes, shiftVars } from "@/lib/shift-display";
+import { PeriodSummary } from "@/hooks/useDaySummary";
+import { cn } from "@/lib/utils";
+
+export function Kpi({
+ label,
+ value,
+ size = "md",
+ muted = false,
+}: {
+ label: string;
+ value: React.ReactNode;
+ size?: "md" | "lg";
+ muted?: boolean;
+}) {
+ return (
+ <div className="min-w-0">
+ <div className={cn("text-fg-tertiary", size === "lg" ? "text-[11.5px]" : "text-[11px]")}>
+ {label}
+ </div>
+ <div
+ className={cn(
+ "font-mono font-medium",
+ size === "lg" ? "text-[17px]" : "text-base",
+ muted ? "text-fg-faint" : "text-fg-strong"
+ )}
+ >
+ {value}
+ </div>
+ </div>
+ );
+}
+
+interface ShiftDetailRowProps {
+ shift: ShiftWithCalendar;
+ canEdit: boolean;
+ actions: "menu" | "inline";
+ onEdit: (shift: ShiftWithCalendar) => void;
+ onDelete: (shift: ShiftWithCalendar) => void;
+}
+
+export function ShiftDetailRow({
+ shift,
+ canEdit,
+ actions,
+ onEdit,
+ onDelete,
+}: ShiftDetailRowProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const synced = shift.syncedFromExternal || !!shift.externalSyncId;
+ const editable = canEdit && !synced;
+ const minutes = getShiftMinutes(shift);
+
+ return (
+ <div className="flex items-center gap-[11px] rounded-lg border border-line bg-surface-card px-3 py-[11px]">
+ <span
+ className="shift-rail h-[34px] w-1 shrink-0 rounded-full"
+ style={shiftVars(shift.color)}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[13.5px] font-semibold text-fg-strong">
+ {shift.title}
+ </div>
+ <div className="mt-0.5 font-mono text-xs text-fg-tertiary">
+ {shift.isAllDay ? t("shift.allDayShift") : formatTimeRange(shift)}
+ </div>
+ {shift.notes && (
+ <div className="mt-1 line-clamp-2 text-xs text-fg-secondary">{shift.notes}</div>
+ )}
+ </div>
+ {synced && (
+ <span
+ className="flex items-center gap-1 rounded-full bg-surface-sunken px-2 py-0.5 text-[11px] font-semibold text-fg-secondary"
+ title={t("calendarView.syncedReadOnly")}
+ >
+ <RefreshCw className="size-3" />
+ {t("calendarView.external")}
+ </span>
+ )}
+ {!shift.isAllDay && minutes > 0 && (
+ <span className="rounded-sm bg-surface-sunken px-[7px] py-0.5 font-mono text-xs text-fg-secondary">
+ {formatHours(minutes, locale)}
+ </span>
+ )}
+ {editable &&
+ (actions === "menu" ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
+ aria-label={t("calendarView.shiftActions")}
+ >
+ <Ellipsis className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => onEdit(shift)}>
+ <Pencil className="mr-2 size-4" />
+ {t("shift.edit")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => onDelete(shift)}
+ className="text-danger focus:text-danger"
+ >
+ <Trash2 className="mr-2 size-4" />
+ {t("common.delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <div className="flex items-center">
+ <button
+ type="button"
+ onClick={() => onEdit(shift)}
+ aria-label={t("shift.edit")}
+ className="flex size-9 items-center justify-center rounded-md text-fg-secondary"
+ >
+ <Pencil className="size-[17px]" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onDelete(shift)}
+ aria-label={t("common.delete")}
+ className="flex size-9 items-center justify-center rounded-md text-fg-secondary"
+ >
+ <Trash2 className="size-[17px]" />
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export function NoteDetailCard({
+ note,
+ onOpen,
+}: {
+ note: CalendarNote;
+ onOpen?: (note: CalendarNote) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const isEvent = note.type === "event";
+ const Icon = isEvent ? CalendarClock : StickyNote;
+ const updatedAt = note.updatedAt ? new Date(note.updatedAt) : null;
+ // Rows created through the SQL default carry no usable timestamp
+ const changed =
+ updatedAt && updatedAt.getFullYear() >= 2020
+ ? format(updatedAt, "P", { locale: getDateLocale(locale) })
+ : null;
+
+ const content = (
+ <>
+ <Icon
+ className={cn("mt-px size-4 shrink-0", !isEvent && "text-[#d97706] dark:text-warning")}
+ style={isEvent ? { color: note.color || "var(--brand)" } : undefined}
+ />
+ <div className="min-w-0 flex-1 text-left">
+ <div className="whitespace-pre-line break-words text-[13px] leading-normal text-fg-body">
+ {note.note}
+ </div>
+ <div className="mt-[3px] text-[11.5px] text-fg-tertiary">
+ {isEvent ? t("calendarView.event") : t("calendarView.note")}
+ {changed && ` · ${t("calendarView.changedOn", { date: changed })}`}
+ </div>
+ </div>
+ </>
+ );
+
+ const className =
+ "flex w-full items-start gap-2.5 rounded-lg border border-line bg-surface-card px-3 py-[11px]";
+
+ return onOpen ? (
+ <button
+ type="button"
+ onClick={() => onOpen(note)}
+ className={cn(className, "transition-colors hover:bg-surface-panel")}
+ >
+ {content}
+ </button>
+ ) : (
+ <div className={className}>{content}</div>
+ );
+}
+
+export function PeriodSummaryView({
+ summary,
+ columns = "list",
+}: {
+ summary: PeriodSummary;
+ columns?: "list" | "cards";
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { stats, freeDays, byType } = summary;
+ const max = byType[0]?.count ?? 0;
+ const kpis = [
+ { label: t("calendarView.kpiShifts"), value: stats?.totalShifts ?? "–" },
+ {
+ label: t("calendarView.kpiHours"),
+ value: stats ? formatHours(stats.totalMinutes, locale) : "–",
+ },
+ {
+ label: t("calendarView.kpiAvgPerShift"),
+ value: stats ? formatHours(stats.avgMinutesPerShift, locale) : "–",
+ },
+ { label: t("calendarView.kpiFreeDays"), value: freeDays ?? "–" },
+ ];
+
+ return (
+ <div className="flex flex-col gap-3">
+ {columns === "cards" ? (
+ <div className="grid grid-cols-2 gap-2">
+ {kpis.map((kpi) => (
+ <div key={kpi.label} className="rounded-lg border border-line bg-surface-card px-3 py-2.5">
+ <div className="text-[11.5px] text-fg-tertiary">{kpi.label}</div>
+ <div className="mt-1 font-mono text-[21px] font-medium text-fg-strong">
+ {kpi.value}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-x-3.5 gap-y-2.5">
+ {kpis.map((kpi) => (
+ <Kpi key={kpi.label} label={kpi.label} value={kpi.value} size="lg" />
+ ))}
+ </div>
+ )}
+ {byType.length > 0 && (
+ <div className="flex flex-col gap-1.5">
+ {columns === "cards" && (
+ <div className="eyebrow mt-1">{t("stats.byType")}</div>
+ )}
+ {byType.map((row) => (
+ <div key={row.title} className="flex items-center gap-[9px]">
+ <span
+ className="shift-rail size-[7px] shrink-0 rounded-full"
+ style={shiftVars(row.color)}
+ />
+ <span className="min-w-0 flex-1 truncate text-[12.5px] text-fg-body">
+ {row.title}
+ </span>
+ <span
+ className={cn(
+ "h-1 overflow-hidden rounded-full bg-line-grid",
+ columns === "cards" ? "w-[104px]" : "w-[76px]"
+ )}
+ >
+ <span
+ className="shift-rail block h-full rounded-full"
+ style={{
+ ...shiftVars(row.color),
+ width: `${max ? Math.round((row.count / max) * 100) : 0}%`,
+ }}
+ />
+ </span>
+ <span className="w-[22px] text-right font-mono text-xs text-fg-tertiary">
+ {row.count}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/components/day-inspector.tsx b/components/day-inspector.tsx
new file mode 100644
index 0000000..161b8a9
--- /dev/null
+++ b/components/day-inspector.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useLocale, useTranslations } from "next-intl";
+import { formatLongDate } from "@/lib/date-utils";
+import { format, getISOWeek, isToday, isTomorrow, isYesterday } from "date-fns";
+import { ArrowUpRight, List, Plus } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote } from "@/lib/db/schema";
+import { getDateLocale } from "@/lib/locales";
+import { formatHours } from "@/lib/shift-display";
+import { PeriodSummary } from "@/hooks/useDaySummary";
+import {
+ Kpi,
+ NoteDetailCard,
+ PeriodSummaryView,
+ ShiftDetailRow,
+} from "@/components/day-detail";
+import { cn } from "@/lib/utils";
+
+export interface DayActions {
+ onAddShift: () => void;
+ onEditShift: (shift: ShiftWithCalendar) => void;
+ onDeleteShift: (shift: ShiftWithCalendar) => void;
+ onAddNote: () => void;
+ onOpenNote: (note: CalendarNote) => void;
+ onOpenStats: () => void;
+ onOpenMonthShifts: () => void;
+}
+
+export interface DayViewModel {
+ selectedDay: Date;
+ currentDate: Date;
+ dayShifts: ShiftWithCalendar[];
+ dayNotes: CalendarNote[];
+ totalMinutes: number;
+ summary: PeriodSummary;
+ canEdit: boolean;
+}
+
+export function useDayLabels(day: Date) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const eyebrow = isToday(day)
+ ? t("calendarView.today")
+ : isTomorrow(day)
+ ? t("calendarView.tomorrow")
+ : isYesterday(day)
+ ? t("calendarView.yesterday")
+ : t("calendarView.calendarWeek", { week: getISOWeek(day) });
+ const long = formatLongDate(day, locale);
+ const short = formatLongDate(day, locale, { month: "short" });
+ return { eyebrow, long, short, isToday: isToday(day) };
+}
+
+export function DayInspector({
+ model,
+ actions,
+}: {
+ model: DayViewModel;
+ actions: DayActions;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { selectedDay, currentDate, dayShifts, dayNotes, totalMinutes, summary, canEdit } =
+ model;
+ const labels = useDayLabels(selectedDay);
+ const monthName = format(currentDate, "LLLL", { locale: getDateLocale(locale) });
+
+ return (
+ <aside className="flex w-[344px] shrink-0 flex-col border-l border-line bg-surface-panel">
+ <div className="border-b border-line px-[18px] pb-3.5 pt-4">
+ <div className="flex items-start justify-between gap-2.5">
+ <div className="min-w-0">
+ <div
+ className={cn(
+ "eyebrow",
+ labels.isToday && "text-brand-ink dark:text-brand-ink"
+ )}
+ >
+ {labels.eyebrow}
+ </div>
+ <h2 className="mt-[3px] truncate text-[19px] font-semibold tracking-[-0.01em] text-fg-strong">
+ {labels.short}
+ </h2>
+ </div>
+ {canEdit && (
+ <Button
+ size="sm"
+ onClick={actions.onAddShift}
+ className="h-[30px] gap-1.5 rounded-lg px-[11px] text-[13px] font-semibold"
+ >
+ <Plus className="size-[15px]" />
+ {t("calendarView.shift")}
+ </Button>
+ )}
+ </div>
+ <div className="mt-3 flex gap-4">
+ <Kpi label={t("calendarView.kpiShifts")} value={dayShifts.length} />
+ <Kpi label={t("calendarView.kpiHours")} value={formatHours(totalMinutes, locale)} />
+ <Kpi label={t("calendarView.kpiNotes")} value={dayNotes.length} />
+ </div>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-[18px] py-3.5">
+ {dayShifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ canEdit={canEdit}
+ actions="menu"
+ onEdit={actions.onEditShift}
+ onDelete={actions.onDeleteShift}
+ />
+ ))}
+ {dayNotes.map((note) => (
+ <NoteDetailCard
+ key={note.id}
+ note={note}
+ onOpen={canEdit ? actions.onOpenNote : undefined}
+ />
+ ))}
+ {dayShifts.length === 0 && dayNotes.length === 0 && (
+ <p className="px-1 py-2 text-[13px] text-fg-tertiary">
+ {t("calendarView.dayEmpty")}
+ </p>
+ )}
+ {canEdit && (
+ <button
+ type="button"
+ onClick={actions.onAddNote}
+ className="flex items-center justify-center gap-2 rounded-lg border border-dashed border-control p-2.5 text-[13px] font-medium text-fg-secondary transition-colors hover:bg-surface-card"
+ >
+ <Plus className="size-[15px]" />
+ {t("calendarView.addNoteOrEvent")}
+ </button>
+ )}
+ </div>
+
+ <div className="border-t border-line px-[18px] py-3.5">
+ <div className="mb-2.5 flex items-center justify-between">
+ <span className="eyebrow">
+ {t("calendarView.monthTotal", { month: monthName })}
+ </span>
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={actions.onOpenMonthShifts}
+ title={t("calendarView.allShiftsIn", { month: monthName })}
+ aria-label={t("calendarView.allShiftsIn", { month: monthName })}
+ className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
+ >
+ <List className="size-[15px]" />
+ </button>
+ <button
+ type="button"
+ onClick={actions.onOpenStats}
+ title={t("calendarView.openStats")}
+ aria-label={t("calendarView.openStats")}
+ className="flex size-7 items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken"
+ >
+ <ArrowUpRight className="size-[15px]" />
+ </button>
+ </div>
+ </div>
+ <PeriodSummaryView summary={summary} />
+ </div>
+ </aside>
+ );
+}
diff --git a/components/dialog-manager.tsx b/components/dialog-manager.tsx
index 723fffc..eac0a53 100644
--- a/components/dialog-manager.tsx
+++ b/components/dialog-manager.tsx
@@ -1,13 +1,16 @@
import { CalendarSheet } from "@/components/calendar-sheet";
import { ShiftSheet, ShiftFormData } from "@/components/shift-sheet";
-import { CalendarSettingsSheet } from "@/components/calendar-settings-sheet";
-import { ExternalSyncManageSheet } from "@/components/external-sync-manage-sheet";
+import { SettingsDialog } from "@/components/settings-dialog";
+import { PhoneMenu } from "@/components/phone-menu";
import { SyncNotificationDialog } from "@/components/sync-notification-dialog";
import { ShiftsOverviewDialog } from "@/components/shifts-overview-dialog";
-import { ViewSettingsSheet } from "@/components/view-settings-sheet";
+import { ViewSettingsSheet, ViewSettingsState } from "@/components/view-settings-sheet";
import { NoteSheet } from "@/components/note-sheet";
import { NotesListDialog } from "@/components/notes-list-dialog";
-import { CalendarWithCount, ShiftWithCalendar } from "@/lib/types";
+import { PresetManageSheet } from "@/components/preset-manage-sheet";
+import { MonthShiftsDialog, MonthStatsDialog } from "@/components/month-dialogs";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { ShiftWithCalendar } from "@/lib/types";
import { CalendarNote } from "@/lib/db/schema";
interface DialogManagerProps {
@@ -22,69 +25,32 @@ interface DialogManagerProps {
onShiftSubmit: (data: ShiftFormData) => void;
selectedDate?: Date;
selectedCalendar: string | null;
- onPresetsChange?: () => void;
- calendars: CalendarWithCount[];
- editingShift?: ShiftWithCalendar; // For editing existing shifts
-
- // Calendar Settings Dialog
- showCalendarSettingsDialog: boolean;
- onCalendarSettingsDialogChange: (open: boolean) => void;
- onCalendarSettingsSuccess: () => void;
- onDeleteCalendar: () => void;
- onExternalSyncFromSettings?: () => void;
+ editingShift?: ShiftWithCalendar;
- // External Sync Sheet
- showExternalSyncDialog: boolean;
- onExternalSyncDialogChange: (open: boolean) => void;
+ // Calendar settings on desktop; on phones the same flag opens the phone menu
+ showSettingsDialog: boolean;
+ onSettingsDialogChange: (open: boolean) => void;
+ onDeleteCalendar: () => void;
onSyncComplete: () => void;
+ viewSettings: ViewSettingsState;
+
+ // Personal view ("Meine Ansicht") from the user menu, header and compare mode
+ showViewSettingsDialog: boolean;
+ onViewSettingsDialogChange: (open: boolean) => void;
// Sync Notification Dialog
showSyncNotificationDialog: boolean;
onSyncNotificationDialogChange: (open: boolean) => void;
- // Shifts Overview Dialog (for day shifts and synced shifts)
+ // Shifts Overview Dialog
showDayShiftsDialog: boolean;
onDayShiftsDialogChange: (open: boolean) => void;
selectedDayDate: Date | null;
selectedDayShifts: ShiftWithCalendar[];
- locale: string;
- onDeleteShiftFromDayDialog: (id: string) => void;
- onEditShiftFromDayDialog?: (shift: ShiftWithCalendar) => void; // Edit shift from day dialog
-
- // Synced Shifts Overview
- showSyncedShiftsDialog: boolean;
- onSyncedShiftsDialogChange: (open: boolean) => void;
- selectedSyncedShifts: ShiftWithCalendar[];
-
- // View Settings Dialog
- showViewSettingsDialog: boolean;
- onViewSettingsDialogChange: (open: boolean) => void;
- viewSettings: {
- shiftsPerDay: number | null;
- externalShiftsPerDay: number | null;
- showShiftNotes: boolean;
- showFullTitles: boolean;
- shiftSortType: "startTime" | "createdAt" | "title";
- shiftSortOrder: "asc" | "desc";
- combinedSortMode: boolean;
- highlightWeekends: boolean;
- highlightedWeekdays: number[];
- highlightColor: string;
- };
- onViewSettingsChange: {
- handleShiftsPerDayChange: (count: number | null) => void;
- handleExternalShiftsPerDayChange: (count: number | null) => void;
- handleShowShiftNotesChange: (show: boolean) => void;
- handleShowFullTitlesChange: (show: boolean) => void;
- handleShiftSortTypeChange: (
- type: "startTime" | "createdAt" | "title"
- ) => void;
- handleShiftSortOrderChange: (order: "asc" | "desc") => void;
- handleCombinedSortModeChange: (combined: boolean) => void;
- handleHighlightWeekendsChange: (highlight: boolean) => void;
- handleHighlightedWeekdaysChange: (days: number[]) => void;
- handleHighlightColorChange: (color: string) => void;
- };
+ onDeleteShiftFromDayDialog?: (id: string) => void;
+ onEditShiftFromDayDialog?: (shift: ShiftWithCalendar) => void;
+ /** Calendar the note dialogs act on when it differs from the selected one (compare mode) */
+ noteCalendarId?: string;
// Note Dialog
showNoteDialog: boolean;
@@ -107,9 +73,24 @@ interface DialogManagerProps {
onEditNoteFromList: (note: CalendarNote) => void;
onDeleteNoteFromList: (noteId: string) => void;
onAddNewNote: () => void;
+
+ // Month summary dialogs opened from the day inspector
+ currentDate: Date;
+ shifts: ShiftWithCalendar[];
+ canEditShifts: boolean;
+ showMonthStatsDialog: boolean;
+ onMonthStatsDialogChange: (open: boolean) => void;
+ showMonthShiftsDialog: boolean;
+ onMonthShiftsDialogChange: (open: boolean) => void;
+ onDeleteShift: (shift: ShiftWithCalendar) => void;
+
+ // Preset management opened from the stamp dock
+ showPresetManageDialog: boolean;
+ onPresetManageDialogChange: (open: boolean) => void;
}
export function DialogManager(props: DialogManagerProps) {
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
return (
<>
<CalendarSheet
@@ -124,48 +105,45 @@ export function DialogManager(props: DialogManagerProps) {
onSubmit={props.onShiftSubmit}
selectedDate={props.selectedDate}
shift={props.editingShift}
- onPresetsChange={props.onPresetsChange}
calendarId={props.selectedCalendar || undefined}
/>
+ {desktop ? (
+ <SettingsDialog
+ key={props.selectedCalendar}
+ open={props.showSettingsDialog}
+ onOpenChange={props.onSettingsDialogChange}
+ calendarId={props.selectedCalendar}
+ viewSettings={props.viewSettings}
+ onDeleteCalendar={props.onDeleteCalendar}
+ onSyncComplete={props.onSyncComplete}
+ />
+ ) : (
+ <PhoneMenu
+ open={props.showSettingsDialog}
+ onOpenChange={props.onSettingsDialogChange}
+ context={{
+ calendarId: props.selectedCalendar,
+ viewSettings: props.viewSettings,
+ onDeleteCalendar: props.onDeleteCalendar,
+ onSyncComplete: props.onSyncComplete,
+ }}
+ />
+ )}
+
+ <ViewSettingsSheet
+ open={props.showViewSettingsDialog}
+ onOpenChange={props.onViewSettingsDialogChange}
+ settings={props.viewSettings}
+ calendarId={props.selectedCalendar}
+ />
+
{props.selectedCalendar && (
- <>
- <CalendarSettingsSheet
- key={`settings-${props.selectedCalendar}-${props.showCalendarSettingsDialog}`}
- open={props.showCalendarSettingsDialog}
- onOpenChange={props.onCalendarSettingsDialogChange}
- calendarId={props.selectedCalendar}
- calendarName={
- props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.name || ""
- }
- calendarColor={
- props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.color || "#3b82f6"
- }
- calendarGuestPermission={
- props.calendars.find((c) => c.id === props.selectedCalendar)
- ?.guestPermission || "none"
- }
- onSuccess={props.onCalendarSettingsSuccess}
- onDelete={props.onDeleteCalendar}
- onExternalSync={props.onExternalSyncFromSettings}
- availableCalendars={props.calendars}
- />
-
- <ExternalSyncManageSheet
- open={props.showExternalSyncDialog}
- onOpenChange={props.onExternalSyncDialogChange}
- calendarId={props.selectedCalendar}
- onSyncComplete={props.onSyncComplete}
- />
-
- <SyncNotificationDialog
- open={props.showSyncNotificationDialog}
- onOpenChange={props.onSyncNotificationDialogChange}
- calendarId={props.selectedCalendar}
- />
- </>
+ <SyncNotificationDialog
+ open={props.showSyncNotificationDialog}
+ onOpenChange={props.onSyncNotificationDialogChange}
+ calendarId={props.selectedCalendar}
+ />
)}
<ShiftsOverviewDialog
@@ -175,58 +153,7 @@ export function DialogManager(props: DialogManagerProps) {
shifts={props.selectedDayShifts}
onDeleteShift={props.onDeleteShiftFromDayDialog}
onEditShift={props.onEditShiftFromDayDialog}
- />
-
- <ShiftsOverviewDialog
- open={props.showSyncedShiftsDialog}
- onOpenChange={props.onSyncedShiftsDialogChange}
- date={props.selectedDayDate}
- shifts={props.selectedSyncedShifts}
- />
-
- <ViewSettingsSheet
- open={props.showViewSettingsDialog}
- onOpenChange={props.onViewSettingsDialogChange}
- shiftsPerDay={props.viewSettings.shiftsPerDay}
- externalShiftsPerDay={props.viewSettings.externalShiftsPerDay}
- showShiftNotes={props.viewSettings.showShiftNotes}
- showFullTitles={props.viewSettings.showFullTitles}
- shiftSortType={props.viewSettings.shiftSortType}
- shiftSortOrder={props.viewSettings.shiftSortOrder}
- combinedSortMode={props.viewSettings.combinedSortMode}
- highlightWeekends={props.viewSettings.highlightWeekends}
- highlightedWeekdays={props.viewSettings.highlightedWeekdays}
- highlightColor={props.viewSettings.highlightColor}
- onShiftsPerDayChange={
- props.onViewSettingsChange.handleShiftsPerDayChange
- }
- onExternalShiftsPerDayChange={
- props.onViewSettingsChange.handleExternalShiftsPerDayChange
- }
- onShowShiftNotesChange={
- props.onViewSettingsChange.handleShowShiftNotesChange
- }
- onShowFullTitlesChange={
- props.onViewSettingsChange.handleShowFullTitlesChange
- }
- onShiftSortTypeChange={
- props.onViewSettingsChange.handleShiftSortTypeChange
- }
- onShiftSortOrderChange={
- props.onViewSettingsChange.handleShiftSortOrderChange
- }
- onCombinedSortModeChange={
- props.onViewSettingsChange.handleCombinedSortModeChange
- }
- onHighlightWeekendsChange={
- props.onViewSettingsChange.handleHighlightWeekendsChange
- }
- onHighlightedWeekdaysChange={
- props.onViewSettingsChange.handleHighlightedWeekdaysChange
- }
- onHighlightColorChange={
- props.onViewSettingsChange.handleHighlightColorChange
- }
+ canEdit={props.canEditShifts}
/>
{props.selectedDayDate && (
@@ -238,7 +165,29 @@ export function DialogManager(props: DialogManagerProps) {
onEditNote={props.onEditNoteFromList}
onDeleteNote={props.onDeleteNoteFromList}
onAddNew={props.onAddNewNote}
- calendarId={props.selectedCalendar || undefined}
+ calendarId={props.noteCalendarId ?? (props.selectedCalendar || undefined)}
+ />
+ )}
+ <MonthStatsDialog
+ open={props.showMonthStatsDialog}
+ onOpenChange={props.onMonthStatsDialogChange}
+ currentDate={props.currentDate}
+ calendarId={props.selectedCalendar || undefined}
+ />
+ <MonthShiftsDialog
+ open={props.showMonthShiftsDialog}
+ onOpenChange={props.onMonthShiftsDialogChange}
+ currentDate={props.currentDate}
+ shifts={props.shifts}
+ canEdit={props.canEditShifts}
+ onEditShift={(shift) => props.onEditShiftFromDayDialog?.(shift)}
+ onDeleteShift={props.onDeleteShift}
+ />
+ {props.selectedCalendar && (
+ <PresetManageSheet
+ open={props.showPresetManageDialog}
+ onOpenChange={props.onPresetManageDialogChange}
+ calendarId={props.selectedCalendar}
/>
)}
<NoteSheet
@@ -248,7 +197,7 @@ export function DialogManager(props: DialogManagerProps) {
onDelete={props.onNoteDelete}
selectedDate={props.selectedNoteDate}
note={props.selectedNote}
- calendarId={props.selectedCalendar || undefined}
+ calendarId={props.noteCalendarId ?? (props.selectedCalendar || undefined)}
/>
</>
);
diff --git a/components/empty-calendar-state.tsx b/components/empty-calendar-state.tsx
index 715b5f5..64eaa3c 100644
--- a/components/empty-calendar-state.tsx
+++ b/components/empty-calendar-state.tsx
@@ -1,10 +1,14 @@
-import { motion } from "motion/react";
+"use client";
+
+import { useState } from "react";
import { useTranslations } from "next-intl";
+import { CalendarPlus, Compass, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { AuthHeader } from "@/components/auth-header";
-import { AppFooter } from "@/components/app-footer";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
-import { Calendar as CalendarIcon, Plus } from "lucide-react";
+import { CalendarDiscoverySheet } from "@/components/calendar-discovery-sheet";
+import { EmptyStateBlock, stateActionClass } from "@/components/empty-state-block";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
interface EmptyCalendarStateProps {
onCreateCalendar: () => void;
@@ -16,46 +20,45 @@ export function EmptyCalendarState({
showUserMenu = false,
}: EmptyCalendarStateProps) {
const t = useTranslations();
- const versionInfo = useVersionInfo();
+ const { isAuthenticated } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+ const [discoveryOpen, setDiscoveryOpen] = useState(false);
+
+ // Shares and public calendars only exist for signed-in users
+ const canDiscover = isAuthEnabled && isAuthenticated;
return (
- <div className="min-h-screen flex flex-col">
+ <div className="flex min-h-dvh flex-col bg-background">
<AuthHeader showUserMenu={showUserMenu} />
- <div className="flex-1 flex items-center justify-center p-4 bg-gradient-to-br from-background via-background to-primary/5">
- <motion.div
- className="text-center space-y-6 max-w-md"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- >
- <motion.div
- initial={{ scale: 0 }}
- animate={{ scale: 1 }}
- transition={{ delay: 0.1, type: "spring", stiffness: 200 }}
- className="w-20 h-20 mx-auto rounded-full bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center"
- >
- <CalendarIcon className="h-10 w-10 text-primary" />
- </motion.div>
- <div className="space-y-3">
- <h1 className="text-2xl sm:text-3xl font-bold">
- {t("onboarding.welcome")}
- </h1>
- <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
- {t("onboarding.description")}
- </p>
- </div>
- <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
- <Button
- onClick={onCreateCalendar}
- size="lg"
- className="h-12 px-8 text-base font-semibold shadow-lg shadow-primary/20"
- >
- <Plus className="mr-2 h-5 w-5" />
- {t("onboarding.createCalendar")}
- </Button>
- </motion.div>
- </motion.div>
- </div>
- <AppFooter versionInfo={versionInfo} />
+ <main className="flex flex-1 items-center justify-center px-4 py-10 sm:p-10">
+ <EmptyStateBlock
+ icon={CalendarPlus}
+ tone="brand"
+ title={t("emptyState.noCalendarTitle")}
+ description={t("emptyState.noCalendarDescription")}
+ actions={
+ <>
+ <Button onClick={onCreateCalendar} className={stateActionClass}>
+ <Plus className="size-[17px]" />
+ {t("emptyState.createCalendar")}
+ </Button>
+ {canDiscover && (
+ <Button
+ variant="outline"
+ onClick={() => setDiscoveryOpen(true)}
+ className={stateActionClass}
+ >
+ <Compass className="size-[17px]" />
+ {t("emptyState.browseShared")}
+ </Button>
+ )}
+ </>
+ }
+ />
+ </main>
+ {canDiscover && (
+ <CalendarDiscoverySheet open={discoveryOpen} onOpenChange={setDiscoveryOpen} />
+ )}
</div>
);
}
diff --git a/components/empty-state-block.tsx b/components/empty-state-block.tsx
new file mode 100644
index 0000000..f390edf
--- /dev/null
+++ b/components/empty-state-block.tsx
@@ -0,0 +1,54 @@
+import { ReactNode } from "react";
+import type { LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+const TONES = {
+ brand: "bg-brand-soft text-brand",
+ neutral: "bg-surface-sunken text-fg-secondary",
+ danger: "bg-danger-soft text-danger",
+};
+
+/** Centered icon tile, title and next step for empty and blocked screens. */
+export function EmptyStateBlock({
+ icon: Icon,
+ tone = "neutral",
+ title,
+ description,
+ actions,
+}: {
+ icon: LucideIcon;
+ tone?: keyof typeof TONES;
+ title: ReactNode;
+ description: ReactNode;
+ actions?: ReactNode;
+}) {
+ return (
+ <div className="flex w-full max-w-[520px] flex-col items-center gap-4 text-center">
+ <div
+ className={cn(
+ "flex size-[52px] items-center justify-center rounded-[14px]",
+ TONES[tone]
+ )}
+ >
+ <Icon className="size-6" />
+ </div>
+ <div>
+ <h1 className="text-[21px] font-semibold leading-tight tracking-[-0.02em] text-fg-strong">
+ {title}
+ </h1>
+ <p className="mt-[7px] text-pretty text-[14.5px] leading-[1.6] text-fg-secondary">
+ {description}
+ </p>
+ </div>
+ {actions && (
+ <div className="mt-1 flex w-full flex-col gap-2.5 sm:w-auto sm:flex-row">
+ {actions}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Button sizing for the actions of an EmptyStateBlock; give icons `size-[17px]`. */
+export const stateActionClass =
+ "h-[42px] gap-2 rounded-[9px] px-[18px] text-[14px] font-semibold has-[>svg]:px-[18px]";
diff --git a/components/export-dialog.tsx b/components/export-dialog.tsx
index 4e682a5..ad36ad2 100644
--- a/components/export-dialog.tsx
+++ b/components/export-dialog.tsx
@@ -1,16 +1,10 @@
"use client";
-import { useState, useEffect, useMemo } from "react";
-import { useTranslations, useLocale } from "next-intl";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
+import { useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { Check, Download } from "lucide-react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
-import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
@@ -18,179 +12,101 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
-import { Checkbox } from "@/components/ui/checkbox";
-import {
- isRateLimitError,
- handleRateLimitError,
-} from "@/lib/rate-limit-client";
-import { Download, FileText, Calendar } from "lucide-react";
-import { toast } from "sonner";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { ChoiceChips, Field, OptionCards, ToggleRow } from "@/components/form-kit";
+import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";
import { CalendarWithCount } from "@/lib/types";
-import { motion } from "motion/react";
+import { useCalendars } from "@/hooks/useCalendars";
+import { cn } from "@/lib/utils";
-interface ExportDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string;
- calendarName: string;
- availableCalendars?: CalendarWithCount[];
+type Format = "ics" | "pdf";
+type Range = "all" | "month" | "year";
+
+function monthValue(date: Date) {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
-export function ExportDialog({
- open,
- onOpenChange,
+export function ExportPanel({
calendarId,
- calendarName,
- availableCalendars = [],
-}: ExportDialogProps) {
+ onClose,
+}: {
+ calendarId: string;
+ onClose: () => void;
+}) {
const t = useTranslations();
const locale = useLocale();
- const [exportFormat, setExportFormat] = useState<"ics" | "pdf">("ics");
- const [exportRange, setExportRange] = useState<"all" | "month" | "year">(
- "all"
- );
- const [selectedMonth, setSelectedMonth] = useState("");
- const [selectedYear, setSelectedYear] = useState("");
+ const { calendars } = useCalendars();
+ const calendar = calendars.find((c) => c.id === calendarId);
+ const [format, setFormat] = useState<Format>("ics");
+ const [range, setRange] = useState<Range>("all");
+ const [month, setMonth] = useState(() => monthValue(new Date()));
+ const [year, setYear] = useState(() => String(new Date().getFullYear()));
+ const [multi, setMulti] = useState(false);
+ const [selectedIds, setSelectedIds] = useState<string[]>([calendarId]);
const [loading, setLoading] = useState(false);
- const [multiCalendar, setMultiCalendar] = useState(false);
- const [selectedCalendarIds, setSelectedCalendarIds] = useState<string[]>([]);
- // Generate month options (current month ± 12 months)
const monthOptions = useMemo(() => {
- const options = [];
const today = new Date();
- for (let i = -12; i <= 12; i++) {
- const date = new Date(today.getFullYear(), today.getMonth() + i, 1);
- const value = `${date.getFullYear()}-${String(
- date.getMonth() + 1
- ).padStart(2, "0")}`;
- const label = date.toLocaleDateString(locale, {
- month: "long",
- year: "numeric",
- });
- options.push({ value, label });
- }
- return options;
+ return Array.from({ length: 25 }, (_, i) => {
+ const date = new Date(today.getFullYear(), today.getMonth() + i - 12, 1);
+ return {
+ value: monthValue(date),
+ label: date.toLocaleDateString(locale, { month: "long", year: "numeric" }),
+ };
+ });
}, [locale]);
-
- // Generate year options (current year ± 5 years)
const yearOptions = useMemo(() => {
- const options = [];
- const today = new Date();
- const currentYear = today.getFullYear();
- for (let i = -5; i <= 5; i++) {
- const year = currentYear + i;
- options.push({ value: year.toString(), label: year.toString() });
- }
- return options;
+ const current = new Date().getFullYear();
+ return Array.from({ length: 11 }, (_, i) => String(current - 5 + i));
}, []);
- // Initialize or reset state when dialog opens/closes
- useEffect(() => {
- if (open) {
- // Set default selections when dialog opens
- const today = new Date();
- const defaultMonth = `${today.getFullYear()}-${String(
- today.getMonth() + 1
- ).padStart(2, "0")}`;
- const currentYear = today.getFullYear();
- setSelectedMonth(defaultMonth);
- setSelectedYear(currentYear.toString());
- setSelectedCalendarIds([calendarId]); // Pre-select current calendar
- } else {
- // Reset state when dialog closes
- setExportFormat("ics");
- setExportRange("all");
- setSelectedMonth("");
- setSelectedYear("");
- setLoading(false);
- setMultiCalendar(false);
- setSelectedCalendarIds([]);
- }
- }, [open, calendarId]);
-
- // Handle export action
const handleExport = async () => {
- // Validate calendar selection for multi-calendar export
- if (multiCalendar && selectedCalendarIds.length === 0) {
+ if (multi && selectedIds.length === 0) {
toast.error(t("export.selectAtLeastOne"));
return;
}
-
setLoading(true);
-
try {
- // Unified API endpoint
- const url = `/api/export/${exportFormat}`;
const params = new URLSearchParams();
-
- // Add PDF-specific params
- if (exportFormat === "pdf") {
+ if (format === "pdf") {
params.append("locale", locale);
- if (exportRange === "month" && selectedMonth) {
- params.append("month", selectedMonth);
- } else if (exportRange === "year" && selectedYear) {
- params.append("year", selectedYear);
- }
+ if (range === "month") params.append("month", month);
+ if (range === "year") params.append("year", year);
}
-
- const urlWithParams = params.toString() ? `${url}?${params}` : url;
-
- // Determine calendar IDs to export
- const idsToExport = multiCalendar ? selectedCalendarIds : [calendarId];
-
- const fetchOptions: RequestInit = {
+ const url = `/api/export/${format}${params.toString() ? `?${params}` : ""}`;
+ const response = await fetch(url, {
method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ calendarIds: idsToExport }),
- };
-
- // Fetch the file
- const response = await fetch(urlWithParams, fetchOptions);
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ calendarIds: multi ? selectedIds : [calendarId] }),
+ });
if (isRateLimitError(response)) {
await handleRateLimitError(response, t);
- setLoading(false);
return;
}
-
if (!response.ok) {
if (response.status === 401) {
toast.error(t("validation.passwordRequired"));
- setLoading(false);
return;
}
throw new Error("Export failed");
}
- // Download the file
const blob = await response.blob();
const downloadUrl = window.URL.createObjectURL(blob);
+ const match = response.headers.get("Content-Disposition")?.match(/filename="(.+)"/);
const link = document.createElement("a");
link.href = downloadUrl;
-
- // Get filename from Content-Disposition header or create one
- const contentDisposition = response.headers.get("Content-Disposition");
- let filename = `${calendarName
- .replace(/[^a-z0-9]/gi, "_")
- .toLowerCase()}_export.${exportFormat}`;
- if (contentDisposition) {
- const filenameMatch = contentDisposition.match(/filename="(.+)"/);
- if (filenameMatch) {
- filename = filenameMatch[1];
- }
- }
-
- link.download = filename;
+ link.download =
+ match?.[1] ??
+ `${(calendar?.name ?? "calendar").replace(/[^a-z0-9]/gi, "_").toLowerCase()}_export.${format}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
toast.success(t("common.success"));
- onOpenChange(false);
+ onClose();
} catch (error) {
console.error("Export error:", error);
toast.error(t("common.error"));
@@ -200,214 +116,127 @@ export function ExportDialog({
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Download className="size-5" />
- {t("export.title")}
- </DialogTitle>
- <DialogDescription>{t("export.description")}</DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4">
- {/* Multi-Calendar Export Toggle */}
- {availableCalendars.length > 1 && (
- <div className="space-y-2 rounded-lg border border-border/50 bg-muted/20 p-4">
- <div className="flex items-start gap-3">
- <Checkbox
- id="multi-calendar"
- checked={multiCalendar}
- onCheckedChange={(checked) => {
- setMultiCalendar(checked === true);
- if (checked) {
- setSelectedCalendarIds([calendarId]);
- }
- }}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-1">
- <Label
- htmlFor="multi-calendar"
- className="cursor-pointer font-medium"
- >
- {t("export.multiCalendar")}
- </Label>
- <p className="text-xs text-muted-foreground">
- {t("export.multiCalendarHint")}
- </p>
- </div>
- </div>
- </div>
- )}
-
- {/* Calendar Selection (shown when multi-calendar is enabled) */}
- {multiCalendar && availableCalendars.length > 0 && (
- <div className="space-y-2">
- <Label>{t("export.selectCalendars")}</Label>
- <p className="text-xs text-muted-foreground mb-3">
- {t("export.selectCalendarsDescription")}
- </p>
- <div className="max-h-[200px] overflow-y-auto space-y-2 border border-border/50 rounded-md p-3 bg-background/50">
- {availableCalendars.map((calendar) => {
- const isSelected = selectedCalendarIds.includes(calendar.id);
- return (
- <motion.div
- key={calendar.id}
- className="flex items-center gap-3 p-2 rounded-md hover:bg-accent/50 cursor-pointer transition-colors"
- onClick={() => {
- setSelectedCalendarIds((prev) =>
- prev.includes(calendar.id)
- ? prev.filter((id) => id !== calendar.id)
- : [...prev, calendar.id]
- );
- }}
- whileHover={{ scale: 1.01 }}
- whileTap={{ scale: 0.99 }}
- >
- <Checkbox
- checked={isSelected}
- className="pointer-events-none"
- />
- <div
- className="w-4 h-4 rounded-full shrink-0"
- style={{ backgroundColor: calendar.color }}
- />
- <div className="flex-1 min-w-0">
- <p className="font-medium truncate text-sm">
- {calendar.name}
- </p>
- </div>
- </motion.div>
- );
- })}
- </div>
- <p className="text-xs text-muted-foreground mt-2">
- {t("export.selectedCount", {
- count: selectedCalendarIds.length,
- })}
- </p>
- </div>
- )}
-
- {/* Export Format */}
- <div className="space-y-2">
- <Label>{t("export.formatLabel")}</Label>
- <Select
- value={exportFormat}
- onValueChange={(value) => setExportFormat(value as "ics" | "pdf")}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="ics">
- <div className="flex items-center gap-2">
- <Calendar className="h-4 w-4" />
- <span>{t("export.icsFormat")}</span>
- </div>
- </SelectItem>
- <SelectItem value="pdf">
- <div className="flex items-center gap-2">
- <FileText className="h-4 w-4" />
- <span>{t("export.pdfFormat")}</span>
- </div>
- </SelectItem>
- </SelectContent>
- </Select>
- <p className="text-xs text-muted-foreground">
- {exportFormat === "ics"
- ? t("export.icsHint")
- : t("export.pdfHint")}
- </p>
- </div>
-
- {/* Export Range (only for PDF) */}
- {exportFormat === "pdf" && (
- <>
- <div className="space-y-2">
- <Label>{t("export.rangeLabel")}</Label>
- <Select
- value={exportRange}
- onValueChange={(value) =>
- setExportRange(value as "all" | "month" | "year")
- }
- >
- <SelectTrigger>
+ <>
+ <PanelBody>
+ <div className="flex flex-col gap-5">
+ <Field label={t("export.formatLabel")}>
+ <OptionCards<Format>
+ value={format}
+ onChange={setFormat}
+ options={[
+ { value: "ics", title: t("export.icsFormat"), description: t("export.icsHint") },
+ { value: "pdf", title: t("export.pdfFormat"), description: t("export.pdfHint") },
+ ]}
+ />
+ </Field>
+
+ {format === "pdf" && (
+ <Field label={t("export.rangeLabel")}>
+ <ChoiceChips<Range>
+ value={range}
+ onChange={setRange}
+ options={[
+ { value: "all", label: t("export.rangeAll") },
+ { value: "month", label: t("export.rangeMonth") },
+ { value: "year", label: t("export.rangeYear") },
+ ]}
+ />
+ {range === "month" && (
+ <Select value={month} onValueChange={setMonth}>
+ <SelectTrigger className="h-10 w-full rounded-[9px]" aria-label={t("export.monthLabel")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="all">{t("export.rangeAll")}</SelectItem>
- <SelectItem value="month">
- {t("export.rangeMonth")}
- </SelectItem>
- <SelectItem value="year">
- {t("export.rangeYear")}
- </SelectItem>
+ {monthOptions.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
</SelectContent>
</Select>
- </div>
-
- {/* Month Selector */}
- {exportRange === "month" && (
- <div className="space-y-2">
- <Label>{t("export.monthLabel")}</Label>
- <Select
- value={selectedMonth}
- onValueChange={setSelectedMonth}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {monthOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
)}
+ {range === "year" && (
+ <Select value={year} onValueChange={setYear}>
+ <SelectTrigger className="h-10 w-full rounded-[9px]" aria-label={t("export.yearLabel")}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {yearOptions.map((y) => (
+ <SelectItem key={y} value={y}>
+ {y}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </Field>
+ )}
- {/* Year Selector */}
- {exportRange === "year" && (
- <div className="space-y-2">
- <Label>{t("export.yearLabel")}</Label>
- <Select value={selectedYear} onValueChange={setSelectedYear}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {yearOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ {calendars.length > 1 && (
+ <div className="flex flex-col gap-2 border-t border-line pt-4">
+ <ToggleRow
+ id="export-multi"
+ title={t("export.multiCalendar")}
+ description={t("export.multiCalendarHint")}
+ checked={multi}
+ onCheckedChange={(checked) => {
+ setMulti(checked);
+ if (checked) setSelectedIds([calendarId]);
+ }}
+ />
+ {multi && (
+ <div className="flex flex-col gap-1.5">
+ {calendars.map((c: CalendarWithCount) => {
+ const selected = selectedIds.includes(c.id);
+ return (
+ <button
+ key={c.id}
+ type="button"
+ role="checkbox"
+ aria-checked={selected}
+ onClick={() =>
+ setSelectedIds((prev) =>
+ prev.includes(c.id) ? prev.filter((id) => id !== c.id) : [...prev, c.id]
+ )
+ }
+ className={cn(
+ "flex items-center gap-3 rounded-[10px] border px-3 py-2.5 text-left",
+ selected ? "border-brand bg-surface-today" : "border-line bg-surface-card"
+ )}
+ >
+ <span className="size-2.5 rounded-full" style={{ backgroundColor: c.color }} />
+ <span className="flex-1 truncate text-[13.5px] font-medium text-fg-strong">
+ {c.name}
+ </span>
+ <span
+ className={cn(
+ "flex size-5 items-center justify-center rounded-[6px] border",
+ selected ? "border-brand bg-brand text-white" : "border-control"
+ )}
+ >
+ {selected && <Check className="size-3.5" />}
+ </span>
+ </button>
+ );
+ })}
+ <p className="text-[12px] text-fg-tertiary">
+ {t("export.selectedCount", { count: selectedIds.length })}
+ </p>
</div>
)}
- </>
+ </div>
)}
-
- {/* Export Button */}
- <div className="flex justify-end gap-2 pt-4">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={loading}
- >
- {t("common.cancel")}
- </Button>
- <Button onClick={handleExport} disabled={loading}>
- <Download className="h-4 w-4 mr-2" />
- {loading ? t("common.loading") : t("export.download")}
- </Button>
- </div>
</div>
- </DialogContent>
- </Dialog>
+ </PanelBody>
+ <PanelFooter>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose} disabled={loading}>
+ {t("common.cancel")}
+ </Button>
+ <Button className="h-10 flex-1 gap-2 font-semibold" onClick={handleExport} disabled={loading}>
+ <Download className="size-4" />
+ {loading ? t("common.loading") : t("export.download")}
+ </Button>
+ </PanelFooter>
+ </>
);
}
diff --git a/components/external-sync-form.tsx b/components/external-sync-form.tsx
new file mode 100644
index 0000000..a42dc88
--- /dev/null
+++ b/components/external-sync-form.tsx
@@ -0,0 +1,256 @@
+"use client";
+
+import { useId } from "react";
+import { useTranslations } from "next-intl";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+import { ChevronDown, FileUp } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { CheckRow, ColorSwatches, Field, inputClass, SectionLabel } from "@/components/form-kit";
+import { SegmentedControl } from "@/components/segmented-control";
+import { formatSyncInterval } from "@/components/external-sync-list";
+import {
+ AUTO_SYNC_INTERVALS,
+ ExternalSyncFormValues,
+ SyncDisplayMode,
+ SyncImportType,
+} from "@/hooks/useExternalSyncForm";
+import { cn } from "@/lib/utils";
+
+interface ExternalSyncFormProps {
+ values: ExternalSyncFormValues;
+ setField: <K extends keyof ExternalSyncFormValues>(
+ key: K,
+ value: ExternalSyncFormValues[K]
+ ) => void;
+ mode: "add" | "edit";
+ /** Uploaded file: no address and no auto-sync */
+ isOneTimeImport?: boolean;
+ disabled?: boolean;
+}
+
+export function ExternalSyncForm({
+ values,
+ setField,
+ mode,
+ isOneTimeImport = false,
+ disabled = false,
+}: ExternalSyncFormProps) {
+ const t = useTranslations();
+ const id = useId();
+ const adding = mode === "add";
+ const fileImport = adding ? values.importType === "file" : isOneTimeImport;
+
+ return (
+ <div className="flex flex-col gap-4">
+ <Field label={t("common.labels.name")} htmlFor={`${id}-name`}>
+ <Input
+ id={`${id}-name`}
+ className={inputClass}
+ placeholder={t("form.namePlaceholder", { example: t("externalSync.syncTypeCustom") })}
+ value={values.name}
+ onChange={(e) => setField("name", e.target.value)}
+ disabled={disabled}
+ />
+ </Field>
+
+ {adding && (
+ <Field
+ label={t("externalSync.importMethod")}
+ hint={
+ fileImport
+ ? t("externalSync.importMethodFileHint")
+ : t("externalSync.importMethodUrlHint")
+ }
+ >
+ <SegmentedControl<SyncImportType>
+ label={t("externalSync.importMethod")}
+ value={values.importType}
+ onChange={(next) => {
+ setField("importType", next);
+ setField("url", "");
+ setField("file", null);
+ }}
+ options={[
+ { value: "url", label: t("syncSheet.sourceUrl") },
+ { value: "file", label: t("syncSheet.sourceFile") },
+ ]}
+ />
+ </Field>
+ )}
+
+ {adding && fileImport ? (
+ <Field label={t("externalSync.fileLabel")}>
+ <label
+ className={cn(
+ "flex h-10 cursor-pointer items-center gap-2.5 rounded-[9px] border border-dashed px-3 text-[13px] transition-colors focus-within:ring-[3px] focus-within:ring-ring/50 hover:bg-surface-panel",
+ values.file ? "border-brand text-fg-strong" : "border-control text-fg-secondary"
+ )}
+ >
+ <FileUp className="size-4 shrink-0" />
+ <span className={cn("min-w-0 flex-1 truncate", values.file && "font-mono text-[12.5px]")}>
+ {values.file ? values.file.name : t("syncSheet.chooseFile")}
+ </span>
+ <input
+ type="file"
+ accept=".ics,.ical"
+ className="sr-only"
+ disabled={disabled}
+ value=""
+ onChange={(e) => setField("file", e.target.files?.[0] ?? null)}
+ />
+ </label>
+ </Field>
+ ) : (
+ !fileImport && (
+ <Field
+ label={t("syncSheet.urlLabel")}
+ htmlFor={`${id}-url`}
+ hint={adding ? t("externalSync.urlHintCustom") : undefined}
+ >
+ <Input
+ id={`${id}-url`}
+ className={cn(
+ inputClass,
+ "font-mono text-[12.5px]",
+ !adding && "cursor-default bg-surface-panel text-fg-secondary"
+ )}
+ placeholder={t("form.urlPlaceholder")}
+ value={values.url}
+ onChange={(e) => setField("url", e.target.value)}
+ readOnly={!adding}
+ disabled={disabled}
+ spellCheck={false}
+ autoComplete="off"
+ />
+ </Field>
+ )
+ )}
+
+ <Field label={t("syncSheet.colorLabel")}>
+ <ColorSwatches
+ value={values.color}
+ onChange={(color) => setField("color", color)}
+ allowCustom
+ disabled={disabled}
+ />
+ </Field>
+
+ <Field label={t("syncSheet.displayLabel")}>
+ <SegmentedControl<SyncDisplayMode>
+ label={t("syncSheet.displayLabel")}
+ value={values.displayMode}
+ onChange={(next) => setField("displayMode", next)}
+ options={[
+ { value: "minimal", label: t("syncSheet.displayMinimal") },
+ { value: "normal", label: t("syncSheet.displayNormal") },
+ ]}
+ />
+ </Field>
+
+ {!fileImport && (
+ <IntervalSlider
+ value={values.autoSyncInterval}
+ onChange={(minutes) => setField("autoSyncInterval", minutes)}
+ disabled={disabled}
+ />
+ )}
+
+ <div className="flex flex-col gap-[9px]">
+ <CheckRow
+ id={`${id}-hidden`}
+ label={t("syncSheet.hideShifts")}
+ checked={values.isHidden}
+ onCheckedChange={(checked) => setField("isHidden", checked)}
+ disabled={disabled}
+ />
+ {/* Hidden shifts never count, so the stats option is implied and locked. */}
+ <CheckRow
+ id={`${id}-stats`}
+ label={t("syncSheet.excludeFromStats")}
+ checked={values.isHidden || values.hideFromStats}
+ onCheckedChange={(checked) => setField("hideFromStats", checked)}
+ disabled={disabled || values.isHidden}
+ />
+ </div>
+
+ {adding && !fileImport && <UrlHints />}
+ </div>
+ );
+}
+
+function IntervalSlider({
+ value,
+ onChange,
+ disabled,
+}: {
+ value: number;
+ onChange: (minutes: number) => void;
+ disabled?: boolean;
+}) {
+ const t = useTranslations();
+ const index = Math.max(0, AUTO_SYNC_INTERVALS.indexOf(value));
+ const valueText =
+ value === 0
+ ? t("externalSync.autoSyncManual")
+ : t("syncSheet.intervalValue", { interval: formatSyncInterval(value) });
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2">
+ <span className="flex-1 text-[13px] font-semibold text-fg-body">
+ {t("syncSheet.autoSyncLabel")}
+ </span>
+ <span className="font-mono text-[12.5px] font-medium text-fg-strong">{valueText}</span>
+ </div>
+ <SliderPrimitive.Root
+ value={[index]}
+ onValueChange={([next]) => onChange(AUTO_SYNC_INTERVALS[next])}
+ max={AUTO_SYNC_INTERVALS.length - 1}
+ step={1}
+ disabled={disabled}
+ className="relative flex h-5 w-full touch-none select-none items-center data-[disabled]:opacity-50"
+ >
+ <SliderPrimitive.Track className="relative h-1.5 grow overflow-hidden rounded-full bg-surface-sunken">
+ <SliderPrimitive.Range className="absolute h-full rounded-full bg-brand" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb
+ aria-label={t("syncSheet.autoSyncLabel")}
+ aria-valuetext={valueText}
+ className="block size-4 rounded-full border-2 border-brand bg-surface-card outline-none transition-shadow focus-visible:ring-[3px] focus-visible:ring-ring/50"
+ />
+ </SliderPrimitive.Root>
+ <div className="flex justify-between text-[11.5px] text-fg-tertiary">
+ <span>{t("externalSync.autoSyncManual")}</span>
+ <span>{t("externalSync.autoSync24hShort")}</span>
+ </div>
+ </div>
+ );
+}
+
+
+function UrlHints() {
+ const t = useTranslations();
+ const hints = [
+ { title: t("externalSync.syncTypeICloud"), body: t("externalSync.hintICloud") },
+ { title: t("externalSync.syncTypeGoogle"), body: t("externalSync.hintGoogle") },
+ { title: t("externalSync.customCalendar"), body: t("externalSync.hintCustom") },
+ ];
+
+ return (
+ <div className="pt-1">
+ <SectionLabel>{t("externalSync.hintsTitle")}</SectionLabel>
+ <p className="mb-2 text-[12px] text-fg-tertiary">{t("externalSync.hintsDescription")}</p>
+ <div className="overflow-hidden rounded-[11px] border border-line bg-surface-card">
+ {hints.map((hint) => (
+ <details key={hint.title} className="group border-b border-line-subtle last:border-b-0">
+ <summary className="flex cursor-pointer list-none items-center justify-between px-3.5 py-2.5 text-[13.5px] font-medium text-fg-strong transition-colors hover:bg-surface-panel [&::-webkit-details-marker]:hidden">
+ {hint.title}
+ <ChevronDown className="size-4 text-fg-tertiary transition-transform group-open:rotate-180" />
+ </summary>
+ <p className="px-3.5 pb-3 text-[12.5px] leading-relaxed text-fg-secondary">{hint.body}</p>
+ </details>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/components/external-sync-list.tsx b/components/external-sync-list.tsx
new file mode 100644
index 0000000..9e1309c
--- /dev/null
+++ b/components/external-sync-list.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import { useLocale, useTranslations } from "next-intl";
+import { RefreshCw, Trash2 } from "lucide-react";
+import { ExternalSync } from "@/lib/db/schema";
+import { ListRow, Pill, RowIconButton } from "@/components/form-kit";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
+
+/** "5 min", "2 h", "24 h" — unit abbreviations are the same in every locale. */
+export function formatSyncInterval(minutes: number) {
+ return minutes < 60 ? `${minutes} min` : `${minutes / 60} h`;
+}
+
+function formatLastSync(value: Date | string, locale: string) {
+ const date = new Date(value);
+ const today = date.toDateString() === new Date().toDateString();
+ return new Intl.DateTimeFormat(
+ locale,
+ today
+ ? { hour: "2-digit", minute: "2-digit" }
+ : { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }
+ ).format(date);
+}
+
+interface ExternalSyncRowProps {
+ sync: ExternalSync;
+ error?: string;
+ selected: boolean;
+ syncing: boolean;
+ deleting: boolean;
+ /** Another row is syncing or being deleted */
+ busy: boolean;
+ onSelect: () => void;
+ onSync: () => void;
+ onDelete: () => void;
+}
+
+export function ExternalSyncRow({
+ sync,
+ error,
+ selected,
+ syncing,
+ deleting,
+ busy,
+ onSelect,
+ onSync,
+ onDelete,
+}: ExternalSyncRowProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const lastSynced = sync.lastSyncedAt ? new Date(sync.lastSyncedAt) : null;
+
+ return (
+ <ListRow highlighted={selected} className="gap-2 px-[13px]">
+ <button
+ type="button"
+ onClick={onSelect}
+ disabled={busy || syncing || deleting}
+ aria-pressed={selected}
+ className="flex min-w-0 flex-1 items-center gap-[11px] text-left disabled:cursor-default"
+ >
+ <span
+ className="shift-rail h-[34px] w-1 shrink-0 self-center rounded-full"
+ style={shiftVars(sync.color)}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[14px] font-semibold text-fg-strong">
+ {sync.name}
+ </span>
+ <span className="mt-[3px] flex flex-wrap items-center gap-x-[7px] gap-y-1">
+ {error && <Pill tone="danger">{t("syncNotifications.statusError")}</Pill>}
+ {sync.isOneTimeImport ? (
+ <Pill>{t("externalSync.oneTimeImport")}</Pill>
+ ) : sync.autoSyncInterval > 0 ? (
+ <Pill tone="success">
+ {t("syncSheet.intervalPill", {
+ interval: formatSyncInterval(sync.autoSyncInterval),
+ })}
+ </Pill>
+ ) : (
+ <Pill>{t("externalSync.autoSyncManual")}</Pill>
+ )}
+ {lastSynced && (
+ <span
+ className="font-mono text-[11.5px] text-fg-tertiary"
+ title={lastSynced.toLocaleString(locale)}
+ >
+ {t("syncSheet.lastSynced", { time: formatLastSync(lastSynced, locale) })}
+ </span>
+ )}
+ </span>
+ {error && (
+ <span className="mt-1.5 block break-words text-[12px] leading-snug text-danger-body">
+ {error}
+ </span>
+ )}
+ </span>
+ </button>
+ <div className="flex shrink-0 items-center">
+ {!sync.isOneTimeImport && (
+ <span className={cn("contents", syncing && "[&_svg]:animate-spin")}>
+ <RowIconButton
+ icon={RefreshCw}
+ label={t("syncSheet.syncNow")}
+ onClick={onSync}
+ disabled={busy || syncing || deleting}
+ />
+ </span>
+ )}
+ <span className={cn("contents", deleting && "[&_svg]:animate-pulse")}>
+ <RowIconButton
+ icon={Trash2}
+ label={t("externalSync.delete")}
+ tone="danger"
+ onClick={onDelete}
+ disabled={busy || syncing || deleting}
+ />
+ </span>
+ </div>
+ </ListRow>
+ );
+}
diff --git a/components/external-sync-manage-sheet.tsx b/components/external-sync-manage-sheet.tsx
index 386b9f8..338ccea 100644
--- a/components/external-sync-manage-sheet.tsx
+++ b/components/external-sync-manage-sheet.tsx
@@ -1,1228 +1,150 @@
"use client";
-import { useState, useEffect, useCallback, useRef, useMemo } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-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 { REFETCH_INTERVAL } from "@/lib/query-client";
-import {
- Trash2,
- RefreshCw,
- Plus,
- Edit2,
- ChevronDown,
- Loader2,
-} from "lucide-react";
-import { toast } from "sonner";
-import {
- isRateLimitError,
- handleRateLimitError,
-} from "@/lib/rate-limit-client";
-import { PRESET_COLORS } from "@/lib/constants";
-import {
- isValidCalendarUrl,
- detectCalendarSyncType,
- type CalendarSyncType,
-} from "@/lib/external-calendar-utils";
+import { Loader2, Plus } from "lucide-react";
+import { Button } from "@/components/ui/button";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
-import { useDirtyState } from "@/hooks/useDirtyState";
-import { queryKeys } from "@/lib/query-keys";
-
-interface ExternalSyncManageSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string | null;
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { ExternalSyncRow } from "@/components/external-sync-list";
+import { ExternalSyncForm } from "@/components/external-sync-form";
+import { useExternalSyncPanel } from "@/hooks/useExternalSyncPanel";
+
+interface ExternalSyncPanelProps {
+ calendarId: string;
+ onClose: () => void;
onSyncComplete?: () => void;
- syncErrorRefreshTrigger?: number;
+ /** Lets the surrounding frame guard its close button against unsaved changes */
+ onDirtyChange?: (dirty: boolean) => void;
}
-export function ExternalSyncManageSheet({
- open,
- onOpenChange,
+export function ExternalSyncPanel({
calendarId,
+ onClose,
onSyncComplete,
-}: // syncErrorRefreshTrigger is no longer needed - React Query polls automatically
-ExternalSyncManageSheetProps) {
+ onDirtyChange,
+}: ExternalSyncPanelProps) {
const t = useTranslations();
- 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);
- const [isSubmitting, setIsSubmitting] = useState(false); // For form submission loading
-
- // 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 queryClient = useQueryClient();
-
- // Fetch external syncs with React Query for live updates
- const { data: syncsData = [] } = useQuery({
- queryKey: queryKeys.externalSyncs.byCalendar(calendarId!),
- queryFn: async () => {
- const params = new URLSearchParams({ calendarId: calendarId! });
- const response = await fetch(`/api/external-syncs?${params}`);
- if (!response.ok) throw new Error("Failed to fetch syncs");
- return (await response.json()) as ExternalSync[];
- },
- enabled: !!calendarId && open,
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true,
- });
-
- // Fetch sync logs with React Query for live updates
- const { data: syncLogsData = [] } = useQuery({
- queryKey: queryKeys.externalSyncs.logs(calendarId!),
- queryFn: async () => {
- const params = new URLSearchParams({
- calendarId: calendarId!,
- limit: "50",
- });
- const response = await fetch(`/api/sync-logs?${params}`);
- if (!response.ok) throw new Error("Failed to fetch sync logs");
- return (await response.json()) as SyncLog[];
- },
- enabled: !!calendarId && open,
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true,
- });
-
- // Compute sync errors from logs
- const syncErrors = useMemo(() => {
- const errors: Record<string, string> = {};
- syncsData.forEach((sync: ExternalSync) => {
- const syncLogs = syncLogsData.filter(
- (log: SyncLog) => log.externalSyncId === sync.id
- );
- const latestError = syncLogs.find(
- (log: SyncLog) => log.status === "error" && !log.isRead
- );
- if (latestError) {
- errors[sync.id] =
- latestError.errorMessage || t("syncNotifications.statusError");
- }
- });
- return errors;
- }, [syncsData, syncLogsData, t]);
-
- // Use syncsData from React Query
- const syncs = syncsData;
-
- // Invalidate queries function to refetch data
- const invalidateSyncs = useCallback(() => {
- if (calendarId) {
- queryClient.invalidateQueries({
- queryKey: queryKeys.externalSyncs.byCalendar(calendarId),
- });
- queryClient.invalidateQueries({
- queryKey: queryKeys.externalSyncs.logs(calendarId),
- });
- }
- }, [calendarId, queryClient]);
-
- // Reset form state when dialog closes
- useEffect(() => {
- if (!open) {
- // Reset all internal state when dialog closes
- setIsSyncing(null);
- setIsDeleting(null);
- setShowAddForm(false);
- setEditingSync(null);
- setFormName("");
- setFormUrl("");
- setFormColor("#3b82f6");
- setFormDisplayMode("normal");
- setFormAutoSyncInterval(0);
- setIcsFile(null);
- setImportType("url");
- setFormIsHidden(false);
- setFormHideFromStats(false);
- setIsSubmitting(false);
- }
- }, [open]);
-
- 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;
- }
- }
-
- setIsSubmitting(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" }));
- setIsSubmitting(false);
- return;
- }
- icsContent = await icsFile.text();
- }
-
- 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,
- }),
- });
-
- 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);
- invalidateSyncs();
- 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 {
- setIsSubmitting(false);
- }
- };
-
- const handleSync = async (syncId: string) => {
- setIsSyncing(syncId);
- try {
- const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
-
- if (isRateLimitError(response)) {
- await handleRateLimitError(response, t);
- return;
- }
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new Error(data.error || "Failed to sync calendar");
- }
-
- invalidateSyncs();
- 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 response = await fetch(`/api/external-syncs/${deleteTargetId}`, {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
-
- if (response.ok) {
- invalidateSyncs();
- 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 response = await fetch(`/api/external-syncs/${syncId}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- [field]: !currentValue,
- }),
- });
-
- if (response.ok) {
- invalidateSyncs();
- 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 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,
- }),
- });
-
- if (response.ok) {
- invalidateSyncs();
- 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);
- }
- }, [
- editingSync,
- formName,
- formUrl,
- formColor,
- formDisplayMode,
- formAutoSyncInterval,
- invalidateSyncs,
- onSyncComplete,
- t,
- ]);
-
const {
- isDirty,
- handleClose: handleDialogClose,
- showConfirmDialog,
- setShowConfirmDialog,
- handleConfirmClose,
- } = useDirtyState({
- 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");
- }
- };
+ syncs,
+ syncErrors,
+ editingSync,
+ formOpen,
+ values,
+ setField,
+ isSubmitting,
+ isSyncing,
+ isDeleting,
+ busy,
+ canSubmit,
+ deleteTargetId,
+ setDeleteTargetId,
+ showList,
+ startAdd,
+ startEdit,
+ guardUnsaved,
+ confirmProps,
+ handleSync,
+ handleAdd,
+ handleSave,
+ confirmDelete,
+ } = useExternalSyncPanel({ calendarId, onSyncComplete, onDirtyChange });
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("common.labels.name")}</Label>
- <Input
- id="sync-name"
- type="text"
- placeholder={t("form.namePlaceholder", {
- example: t("externalSync.syncTypeCustom"),
- })}
- value={formName}
- onChange={(e) => setFormName(e.target.value)}
- disabled={isSubmitting}
- />
- </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={isSubmitting}
- 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={isSubmitting}
- 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>
+ <PanelBody>
+ <div className="flex flex-col gap-3.5">
+ {syncs.length === 0 && !formOpen && (
+ <p className="rounded-[11px] border border-dashed border-control px-4 py-8 text-center text-[13px] text-fg-tertiary">
+ {t("externalSync.noSyncs")}
+ </p>
)}
- {/* 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={isSubmitting}
- className="flex-1 h-11 border-border/50 hover:bg-muted/50"
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="button"
- onClick={handleAddSync}
- disabled={
- isSubmitting ||
- !formName.trim() ||
- (importType === "file" ? !icsFile : !formUrl.trim())
+ {syncs.length > 0 && (
+ <div className="flex flex-col gap-2">
+ {syncs.map((sync) => (
+ <ExternalSyncRow
+ key={sync.id}
+ sync={sync}
+ error={syncErrors[sync.id]}
+ selected={editingSync?.id === sync.id}
+ syncing={isSyncing === sync.id}
+ deleting={isDeleting === sync.id}
+ busy={busy}
+ onSelect={() =>
+ guardUnsaved(() =>
+ editingSync?.id === sync.id ? showList() : startEdit(sync)
+ )
}
- 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"
- >
- {isSubmitting ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- {t("common.saving")}
- </>
- ) : (
- t("common.add")
- )}
- </Button>
- </div>
- </SheetFooter>
+ onSync={() => handleSync(sync.id)}
+ onDelete={() =>
+ // Deleting the sync being edited closes the form; other rows leave it alone
+ editingSync?.id === sync.id
+ ? guardUnsaved(() => setDeleteTargetId(sync.id))
+ : setDeleteTargetId(sync.id)
+ }
+ />
+ ))}
+ </div>
)}
- </SheetContent>
- </Sheet>
- <ConfirmationDialog
- open={showConfirmDialog}
- onOpenChange={setShowConfirmDialog}
- onConfirm={handleConfirmClose}
- />
+ {formOpen && (
+ <>
+ {syncs.length > 0 && <div className="h-px shrink-0 bg-line" />}
+ <ExternalSyncForm
+ key={editingSync?.id ?? "new"}
+ values={values}
+ setField={setField}
+ mode={editingSync ? "edit" : "add"}
+ isOneTimeImport={editingSync?.isOneTimeImport}
+ disabled={isSubmitting}
+ />
+ </>
+ )}
+ </div>
+ </PanelBody>
+
+ <PanelFooter>
+ {formOpen ? (
+ <>
+ <Button
+ variant="outline"
+ className="h-10 flex-1 font-semibold"
+ onClick={showList}
+ disabled={isSubmitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ className="h-10 flex-1 font-semibold"
+ onClick={editingSync ? handleSave : handleAdd}
+ disabled={!canSubmit}
+ >
+ {isSubmitting && <Loader2 className="size-4 animate-spin" />}
+ {isSubmitting
+ ? t("common.saving")
+ : editingSync
+ ? t("common.save")
+ : t("syncSheet.addSubscription")}
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>
+ {t("common.close")}
+ </Button>
+ <Button className="h-10 flex-1 font-semibold" onClick={startAdd} disabled={busy}>
+ <Plus className="size-4" />
+ {t("syncSheet.addSubscription")}
+ </Button>
+ </>
+ )}
+ </PanelFooter>
+
+ <ConfirmationDialog {...confirmProps} />
<ConfirmationDialog
- open={showDeleteConfirm}
- onOpenChange={setShowDeleteConfirm}
+ open={deleteTargetId !== null}
+ onOpenChange={(open) => !open && setDeleteTargetId(null)}
onConfirm={confirmDelete}
title={t("externalSync.delete")}
description={t("externalSync.deleteConfirm")}
diff --git a/components/form-kit.tsx b/components/form-kit.tsx
new file mode 100644
index 0000000..317b1df
--- /dev/null
+++ b/components/form-kit.tsx
@@ -0,0 +1,438 @@
+"use client";
+
+import { ReactNode } from "react";
+import { useTranslations } from "next-intl";
+import { HexColorPicker } from "react-colorful";
+import { Pipette, type LucideIcon } from "lucide-react";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { PRESET_COLORS } from "@/lib/constants";
+import { cn } from "@/lib/utils";
+
+/*
+ * Building blocks for sheets and settings sections. They only encode the
+ * visual system; data handling stays in the owning component or hook.
+ */
+
+export function Field({
+ label,
+ htmlFor,
+ optional,
+ hint,
+ children,
+ className,
+}: {
+ label: ReactNode;
+ htmlFor?: string;
+ optional?: boolean;
+ hint?: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ const t = useTranslations();
+ return (
+ // min-w-0 lets native date/time inputs shrink instead of overflowing their column
+ <div className={cn("flex min-w-0 flex-col gap-1.5 lg:gap-2", className)}>
+ <Label htmlFor={htmlFor} className="text-[13px] font-semibold text-fg-body">
+ {label}
+ {optional && (
+ <span className="font-normal text-fg-tertiary">{t("formKit.optional")}</span>
+ )}
+ </Label>
+ {children}
+ {hint && <p className="text-[12px] text-fg-tertiary">{hint}</p>}
+ </div>
+ );
+}
+
+/** Uppercase label above a group of rows. */
+export function SectionLabel({ children, className }: { children: ReactNode; className?: string }) {
+ return <div className={cn("eyebrow mb-2", className)}>{children}</div>;
+}
+
+// text-base (16px) below md prevents iOS Safari's auto-zoom on focus
+export const zoomSafeText = "text-base md:text-[14px]";
+export const inputClass = `h-10 rounded-[9px] px-3 ${zoomSafeText}`;
+export const textareaClass = `resize-none rounded-[9px] px-3 py-2.5 ${zoomSafeText}`;
+
+export function ColorSwatches({
+ value,
+ onChange,
+ colors = PRESET_COLORS,
+ allowCustom = false,
+ disabled = false,
+ size = "md",
+}: {
+ value: string;
+ onChange: (color: string) => void;
+ colors?: { name: string; value: string }[];
+ allowCustom?: boolean;
+ disabled?: boolean;
+ size?: "sm" | "md";
+}) {
+ const t = useTranslations();
+ const isCustom = !colors.some((c) => c.value.toLowerCase() === value?.toLowerCase());
+ const box = size === "sm" ? "size-8 rounded-lg" : "size-[34px] rounded-[9px]";
+
+ return (
+ <div role="radiogroup" className="flex flex-wrap items-center gap-2">
+ {colors.map((color) => {
+ const selected = color.value.toLowerCase() === value?.toLowerCase();
+ return (
+ <button
+ key={color.value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ aria-label={color.name}
+ disabled={disabled}
+ onClick={() => onChange(color.value)}
+ className={cn(box, "transition-shadow disabled:opacity-50")}
+ style={{
+ backgroundColor: color.value,
+ boxShadow: selected
+ ? `0 0 0 2px var(--background), 0 0 0 4px ${color.value}`
+ : undefined,
+ }}
+ />
+ );
+ })}
+ {allowCustom && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ className={cn(
+ "flex h-[34px] items-center gap-2 rounded-[9px] border border-dashed px-3 text-[13px] font-medium text-fg-secondary",
+ isCustom ? "border-brand" : "border-control"
+ )}
+ >
+ {isCustom ? (
+ <span className="size-3.5 rounded-[4px]" style={{ backgroundColor: value }} />
+ ) : (
+ <Pipette className="size-3.5" />
+ )}
+ {t("formKit.customColor")}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-3" align="start">
+ <HexColorPicker color={value} onChange={onChange} />
+ <div className="mt-2 text-center font-mono text-[12px] text-fg-secondary">{value}</div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ );
+}
+
+/** Checkbox with a clickable label, optionally with a hint line below it. */
+export function CheckRow({
+ id,
+ checked,
+ onCheckedChange,
+ disabled,
+ label,
+ hint,
+ children,
+}: {
+ id: string;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ disabled?: boolean;
+ label?: ReactNode;
+ hint?: ReactNode;
+ children?: ReactNode;
+}) {
+ return (
+ <div className="flex items-start gap-2.5">
+ <Checkbox
+ id={id}
+ checked={checked}
+ onCheckedChange={(value) => onCheckedChange(value === true)}
+ disabled={disabled}
+ className="mt-px size-[17px] rounded-[5px] border-[1.5px] border-control bg-surface-card shadow-none"
+ />
+ <label
+ htmlFor={id}
+ className={cn(
+ "text-[13.5px] leading-[18px] text-fg-body",
+ disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"
+ )}
+ >
+ {children ?? label}
+ {hint && <span className="mt-px block text-[12px] text-fg-tertiary">{hint}</span>}
+ </label>
+ </div>
+ );
+}
+
+export function ToggleRow({
+ title,
+ description,
+ checked,
+ onCheckedChange,
+ disabled,
+ id,
+}: {
+ title: ReactNode;
+ description?: ReactNode;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ disabled?: boolean;
+ id?: string;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-4 py-1">
+ <label htmlFor={id} className="min-w-0 cursor-pointer">
+ <span className="block text-[14px] font-semibold text-fg-strong">{title}</span>
+ {description && (
+ <span className="mt-0.5 block text-[12.5px] text-fg-secondary">{description}</span>
+ )}
+ </label>
+ <Switch id={id} checked={checked} onCheckedChange={onCheckedChange} disabled={disabled} />
+ </div>
+ );
+}
+
+export function ChoiceChips<T extends string>({
+ value,
+ onChange,
+ options,
+ label,
+ disabled,
+}: {
+ value: T | undefined;
+ onChange: (value: T) => void;
+ options: { value: T; label: ReactNode; color?: string }[];
+ label?: string;
+ disabled?: boolean;
+}) {
+ return (
+ <div role="radiogroup" aria-label={label} className="flex flex-wrap gap-2">
+ {options.map((option) => {
+ const selected = option.value === value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={disabled}
+ onClick={() => onChange(option.value)}
+ className={cn(
+ "flex h-8 items-center gap-2 rounded-lg border px-3 text-[13px] font-medium transition-colors disabled:opacity-50",
+ selected
+ ? "border-brand bg-brand-soft font-semibold text-brand-ink"
+ : "border-line bg-surface-card text-fg-body hover:bg-surface-panel"
+ )}
+ >
+ {option.color && (
+ <span className="size-[7px] rounded-full" style={{ backgroundColor: option.color }} />
+ )}
+ {option.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+export function OptionCards<T extends string>({
+ value,
+ onChange,
+ options,
+ label,
+ columns = 2,
+}: {
+ value: T;
+ onChange: (value: T) => void;
+ options: { value: T; title: ReactNode; description?: ReactNode }[];
+ label?: string;
+ columns?: 2 | 3 | 4;
+}) {
+ return (
+ <div
+ role="radiogroup"
+ aria-label={label}
+ className={cn(
+ "grid gap-2",
+ columns === 2 && "grid-cols-2",
+ columns === 3 && "grid-cols-3",
+ columns === 4 && "grid-cols-2 sm:grid-cols-4"
+ )}
+ >
+ {options.map((option) => {
+ const selected = option.value === value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => onChange(option.value)}
+ className={cn(
+ "rounded-[10px] border px-3 py-2.5 text-left transition-colors",
+ option.description ? "" : "text-center",
+ selected
+ ? "border-brand bg-brand-soft"
+ : "border-line bg-surface-card hover:bg-surface-panel"
+ )}
+ >
+ <span
+ className={cn(
+ "block text-[13.5px] font-semibold",
+ selected ? "text-brand-ink" : "text-fg-strong"
+ )}
+ >
+ {option.title}
+ </span>
+ {option.description && (
+ <span
+ className={cn(
+ "mt-0.5 block text-[12px]",
+ selected ? "text-brand-ink" : "text-fg-tertiary"
+ )}
+ >
+ {option.description}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/** Neutral hint box, e.g. explaining what an option does. */
+export function InfoNote({
+ icon: Icon,
+ children,
+ className,
+}: {
+ icon: LucideIcon;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex gap-2.5 rounded-[10px] border border-line bg-surface-panel px-3 py-2.5 text-[12px] leading-relaxed text-fg-secondary",
+ className
+ )}
+ >
+ <Icon className="mt-px size-4 shrink-0" />
+ <div className="min-w-0">{children}</div>
+ </div>
+ );
+}
+
+/** The single red block of a panel. */
+export function DangerZone({
+ icon: Icon,
+ title,
+ description,
+ action,
+}: {
+ icon: LucideIcon;
+ title: ReactNode;
+ description?: ReactNode;
+ action: ReactNode;
+}) {
+ return (
+ <div className="flex items-center gap-3 rounded-[11px] border border-danger-line bg-danger-surface px-4 py-3.5">
+ <Icon className="size-[18px] shrink-0 text-danger" />
+ <div className="min-w-0 flex-1">
+ <div className="text-[14px] font-semibold text-danger">{title}</div>
+ {description && <div className="text-[13px] text-danger-body">{description}</div>}
+ </div>
+ <div className="shrink-0">{action}</div>
+ </div>
+ );
+}
+
+/** Bordered row used by every list in sheets (presets, links, syncs, people). */
+export function ListRow({
+ children,
+ className,
+ highlighted,
+}: {
+ children: ReactNode;
+ className?: string;
+ highlighted?: boolean;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-3 rounded-[11px] border bg-surface-card px-3.5 py-3",
+ highlighted ? "border-brand" : "border-line",
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function RowIconButton({
+ icon: Icon,
+ label,
+ onClick,
+ tone = "neutral",
+ disabled,
+}: {
+ icon: LucideIcon;
+ label: string;
+ onClick: () => void;
+ tone?: "neutral" | "danger";
+ disabled?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={label}
+ title={label}
+ className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-surface-sunken disabled:opacity-40",
+ tone === "danger" ? "text-danger" : "text-fg-secondary"
+ )}
+ >
+ <Icon className="size-[17px]" />
+ </button>
+ );
+}
+
+/** Small rounded label, e.g. "Sekundär", "Nur lesen", "aktiv". */
+export function Pill({
+ tone = "neutral",
+ children,
+ className,
+}: {
+ tone?: "neutral" | "brand" | "success" | "warning" | "danger" | "violet";
+ children: ReactNode;
+ className?: string;
+}) {
+ const tones = {
+ neutral: "bg-surface-sunken text-fg-secondary",
+ brand: "bg-brand-soft text-brand-ink",
+ success: "bg-success-soft text-success",
+ warning: "bg-warning-soft text-warning",
+ danger: "bg-danger-soft text-danger",
+ violet: "bg-[#f4f0ff] text-[#6d28d9] dark:bg-[#a78bfa]/15 dark:text-[#d3c4fe]",
+ };
+ return (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-full px-2 py-0.5 text-[11.5px] font-semibold",
+ tones[tone],
+ className
+ )}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/components/fullscreen-loader.tsx b/components/fullscreen-loader.tsx
index 3a16e21..9225ad2 100644
--- a/components/fullscreen-loader.tsx
+++ b/components/fullscreen-loader.tsx
@@ -1,35 +1,19 @@
-"use client";
-
import { Loader2 } from "lucide-react";
-import { motion } from "motion/react";
interface FullscreenLoaderProps {
message?: string;
}
-/**
- * Fullscreen loading spinner component
- *
- * Shows a centered spinner with optional message during initial page load.
- * Prevents skeleton flicker by providing single consistent loading state.
- *
- * Usage:
- * ```tsx
- * {isLoading ? <FullscreenLoader message="Loading calendars..." /> : <PageContent />}
- * ```
- */
+/** Single quiet loading state for initial page loads, instead of flickering skeletons. */
export function FullscreenLoader({ message }: FullscreenLoaderProps) {
return (
- <motion.div
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ duration: 0.2, delay: 0.1 }}
- className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-background"
+ <div
+ role="status"
+ aria-live="polite"
+ className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 bg-background"
>
- <Loader2 className="h-12 w-12 animate-spin text-primary" />
- {message && (
- <p className="mt-4 text-sm text-muted-foreground">{message}</p>
- )}
- </motion.div>
+ <Loader2 className="size-7 animate-spin text-brand" aria-hidden />
+ {message && <p className="text-[13px] text-fg-tertiary">{message}</p>}
+ </div>
);
}
diff --git a/components/guest-banner.tsx b/components/guest-banner.tsx
index 4d3db92..80b471f 100644
--- a/components/guest-banner.tsx
+++ b/components/guest-banner.tsx
@@ -1,10 +1,10 @@
"use client";
+import Link from "next/link";
import { useTranslations } from "next-intl";
-import { Info, LogIn } from "lucide-react";
+import { Info } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { motion } from "motion/react";
-import Link from "next/link";
+import { StatusBanner } from "@/components/status-banner";
interface GuestBannerProps {
variant?: "default" | "compact";
@@ -13,62 +13,18 @@ interface GuestBannerProps {
export function GuestBanner({ variant = "default" }: GuestBannerProps) {
const t = useTranslations();
- if (variant === "compact") {
- return (
- <motion.div
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/50 rounded-lg p-3 flex items-center justify-between gap-3"
- >
- <div className="flex items-center gap-2 min-w-0">
- <Info className="h-4 w-4 text-blue-600 dark:text-blue-400 shrink-0" />
- <p className="text-sm text-blue-900 dark:text-blue-100 truncate">
- {t("guest.viewingAsGuest")}
- </p>
- </div>
- <Button asChild size="sm" variant="outline" className="shrink-0">
- <Link href="/login">
- <LogIn className="h-3.5 w-3.5 mr-1.5" />
- {t("auth.login")}
- </Link>
- </Button>
- </motion.div>
- );
- }
-
return (
- <motion.div
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-900/50 rounded-xl p-4 shadow-sm"
- >
- <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
- <div className="flex items-start gap-3 min-w-0">
- <div className="mt-0.5 shrink-0">
- <div className="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center">
- <Info className="h-5 w-5 text-blue-600 dark:text-blue-400" />
- </div>
- </div>
- <div className="min-w-0">
- <h3 className="font-medium text-blue-900 dark:text-blue-100 mb-1">
- {t("guest.viewingAsGuest")}
- </h3>
- <p className="text-sm text-blue-700 dark:text-blue-300">
- {t("guest.bannerMessage")}
- </p>
- </div>
- </div>
- <Button
- asChild
- size="sm"
- className="bg-blue-600 hover:bg-blue-700 text-white shrink-0"
- >
- <Link href="/login">
- <LogIn className="h-4 w-4 mr-2" />
- {t("guest.loginForFullAccess")}
- </Link>
+ <StatusBanner
+ tone="info"
+ icon={Info}
+ title={t("guest.viewingAsGuest")}
+ action={
+ <Button asChild size="sm" variant="outline" className="h-8 font-semibold">
+ <Link href="/login">{t("auth.login")}</Link>
</Button>
- </div>
- </motion.div>
+ }
+ >
+ {variant === "default" ? t("guest.bannerMessage") : undefined}
+ </StatusBanner>
);
}
diff --git a/components/guest-empty-state.tsx b/components/guest-empty-state.tsx
index 6ed407e..d447478 100644
--- a/components/guest-empty-state.tsx
+++ b/components/guest-empty-state.tsx
@@ -1,65 +1,155 @@
"use client";
-import { motion } from "motion/react";
+import { useId, useState } from "react";
+import Link from "next/link";
import { useTranslations } from "next-intl";
+import { Link2, Lock } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import { AuthHeader } from "@/components/auth-header";
-import { AppFooter } from "@/components/app-footer";
-import { useVersionInfo } from "@/hooks/useVersionInfo";
-import { Calendar as CalendarIcon, LogIn } from "lucide-react";
-import { useRouter } from "next/navigation";
+import { PanelDialog } from "@/components/panel-dialog";
+import { Field, inputClass } from "@/components/form-kit";
+import { EmptyStateBlock, stateActionClass } from "@/components/empty-state-block";
+import { useAutoFocusRef } from "@/hooks/useAutoFocus";
+import { cn } from "@/lib/utils";
-/**
- * Empty state shown to guests when no public calendars are available
- * Displays a message prompting them to log in
- */
+const SHARE_PATH = "/share/token/";
+// Tokens are base64url (see generateAccessToken)
+const TOKEN_PATTERN = /^[A-Za-z0-9_-]{16,}$/;
+
+/** Accepts a full access link (any host) or the bare token. */
+function extractAccessToken(input: string): string | null {
+ const value = input.trim();
+ const index = value.indexOf(SHARE_PATH);
+ const candidate =
+ index >= 0 ? value.slice(index + SHARE_PATH.length).split(/[/?#]/)[0] : value;
+ return TOKEN_PATTERN.test(candidate) ? candidate : null;
+}
+
+/** Shown to guests when no calendar is open to them. */
export function GuestEmptyState() {
const t = useTranslations();
- const router = useRouter();
- const versionInfo = useVersionInfo();
+ const [linkOpen, setLinkOpen] = useState(false);
+
+ return (
+ <div className="flex min-h-dvh flex-col bg-background">
+ <AuthHeader showUserMenu />
+ <main className="flex flex-1 items-center justify-center px-4 py-10 sm:p-10">
+ <EmptyStateBlock
+ icon={Lock}
+ title={t("emptyState.guestTitle")}
+ description={t("emptyState.guestDescription")}
+ actions={
+ <>
+ <Button asChild className={stateActionClass}>
+ <Link href="/login">{t("auth.login")}</Link>
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() => setLinkOpen(true)}
+ className={stateActionClass}
+ >
+ <Link2 className="size-[17px]" />
+ {t("emptyState.pasteAccessLink")}
+ </Button>
+ </>
+ }
+ />
+ </main>
+ <AccessLinkDialog open={linkOpen} onOpenChange={setLinkOpen} />
+ </div>
+ );
+}
+
+function AccessLinkDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations();
+ const formId = useId();
+ const inputId = useId();
+ const linkRef = useAutoFocusRef<HTMLInputElement>();
+ const [value, setValue] = useState("");
+ const [invalid, setInvalid] = useState(false);
+ const [navigating, setNavigating] = useState(false);
+
+ const handleOpenChange = (next: boolean) => {
+ if (!next) {
+ setValue("");
+ setInvalid(false);
+ }
+ onOpenChange(next);
+ };
- const handleLoginClick = () => {
- router.push("/login");
+ const handleSubmit = (event: React.FormEvent) => {
+ event.preventDefault();
+ const token = extractAccessToken(value);
+ if (!token) {
+ setInvalid(true);
+ return;
+ }
+ setNavigating(true);
+ // Full page load on purpose: only the proxy handles this route (no page exists),
+ // validating the token and setting the grant cookie before redirecting.
+ window.location.assign(new URL(`${SHARE_PATH}${token}`, window.location.origin).href);
};
return (
- <div className="min-h-screen flex flex-col">
- <AuthHeader showUserMenu={false} />
- <div className="flex-1 flex items-center justify-center p-4 bg-gradient-to-br from-background via-background to-primary/5">
- <motion.div
- className="text-center space-y-6 max-w-md"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- >
- <motion.div
- initial={{ scale: 0 }}
- animate={{ scale: 1 }}
- transition={{ delay: 0.1, type: "spring", stiffness: 200 }}
- className="w-20 h-20 mx-auto rounded-full bg-gradient-to-br from-muted/50 to-muted/20 flex items-center justify-center"
+ <PanelDialog
+ open={open}
+ onOpenChange={handleOpenChange}
+ title={t("emptyState.pasteAccessLink")}
+ description={t("emptyState.accessLinkDescription")}
+ width="sm"
+ footer={
+ <>
+ <Button
+ variant="outline"
+ className="h-10 flex-1 font-semibold"
+ onClick={() => handleOpenChange(false)}
>
- <CalendarIcon className="h-10 w-10 text-muted-foreground" />
- </motion.div>
- <div className="space-y-3">
- <h1 className="text-2xl sm:text-3xl font-bold">
- {t("guestEmptyState.title")}
- </h1>
- <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
- {t("guestEmptyState.description")}
- </p>
- </div>
- <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
- <Button
- onClick={handleLoginClick}
- size="lg"
- className="h-12 px-8 text-base font-semibold shadow-lg shadow-primary/20"
- >
- <LogIn className="mr-2 h-5 w-5" />
- {t("guestEmptyState.loginButton")}
- </Button>
- </motion.div>
- </motion.div>
- </div>
- <AppFooter versionInfo={versionInfo} />
- </div>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="submit"
+ form={formId}
+ className="h-10 flex-1 font-semibold"
+ disabled={!value.trim() || navigating}
+ >
+ {t("emptyState.openAccessLink")}
+ </Button>
+ </>
+ }
+ >
+ <form id={formId} onSubmit={handleSubmit}>
+ <Field
+ label={t("emptyState.accessLinkLabel")}
+ htmlFor={inputId}
+ hint={
+ invalid ? (
+ <span className="text-danger">{t("emptyState.accessLinkInvalid")}</span>
+ ) : undefined
+ }
+ >
+ <Input
+ id={inputId}
+ value={value}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setInvalid(false);
+ }}
+ placeholder="https://…/share/token/…"
+ autoComplete="off"
+ spellCheck={false}
+ ref={linkRef}
+ aria-invalid={invalid || undefined}
+ className={cn(inputClass, "font-mono text-[13px]")}
+ />
+ </Field>
+ </form>
+ </PanelDialog>
);
}
diff --git a/components/guest-permission-selector.tsx b/components/guest-permission-selector.tsx
index 2694a42..2594e66 100644
--- a/components/guest-permission-selector.tsx
+++ b/components/guest-permission-selector.tsx
@@ -1,105 +1,76 @@
"use client";
import { useTranslations } from "next-intl";
-import { Label } from "@/components/ui/label";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
-import { AlertTriangle, Eye, Edit } from "lucide-react";
+import { Info } from "lucide-react";
+import { InfoNote, OptionCards } from "@/components/form-kit";
+import { cn } from "@/lib/utils";
+
+type GuestPermission = "none" | "read" | "write";
+
+/** Who a public-access level reaches; visitors without an account only with ALLOW_GUEST_ACCESS. */
+export function usePublicAccessNote() {
+ const t = useTranslations();
+ return (value: GuestPermission, allowGuest: boolean) => {
+ if (value === "none") return t("share.publicPermissionNoneDesc");
+ if (value === "read")
+ return allowGuest
+ ? t("share.publicPermissionReadDescGuestsOn")
+ : t("share.publicPermissionReadDescGuestsOff");
+ return allowGuest
+ ? t("share.publicPermissionWriteDescGuestsOn")
+ : t("share.publicPermissionWriteDescGuestsOff");
+ };
+}
interface GuestPermissionSelectorProps {
- value: "none" | "read" | "write";
- onChange: (value: "none" | "read" | "write") => void;
- idPrefix?: string;
+ value: GuestPermission;
+ onChange: (value: GuestPermission) => void;
+ allowGuest: boolean;
+ disabled?: boolean;
}
export function GuestPermissionSelector({
value,
onChange,
- idPrefix = "guest",
+ allowGuest,
+ disabled = false,
}: GuestPermissionSelectorProps) {
const t = useTranslations();
+ const publicAccessNote = usePublicAccessNote();
return (
- <div className="space-y-3">
- <RadioGroup
- value={value}
- onValueChange={(val) => onChange(val as "none" | "read" | "write")}
- className="space-y-3"
- >
- {/* No Access */}
- <div className="group relative">
- <Label
- htmlFor={`${idPrefix}-none`}
- className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
- >
- <RadioGroupItem
- value="none"
- id={`${idPrefix}-none`}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-2">
- <div className="flex items-center gap-2">
- <AlertTriangle className="h-4 w-4 text-red-500 shrink-0" />
- <span className="font-semibold text-sm">
- {t("common.labels.permissions.none")}
- </span>
- </div>
- <p className="text-xs text-muted-foreground leading-relaxed pl-6">
- {t("share.publicPermissionNoneDesc")}
- </p>
- </div>
- </Label>
- </div>
-
- {/* Read Only */}
- <div className="group relative">
- <Label
- htmlFor={`${idPrefix}-read`}
- className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
- >
- <RadioGroupItem
- value="read"
- id={`${idPrefix}-read`}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-2">
- <div className="flex items-center gap-2">
- <Eye className="h-4 w-4 text-blue-500 shrink-0" />
- <span className="font-semibold text-sm">
- {t("common.labels.permissions.read")}
- </span>
- </div>
- <p className="text-xs text-muted-foreground leading-relaxed pl-6">
- {t("share.publicPermissionReadDesc")}
- </p>
- </div>
- </Label>
- </div>
-
- {/* Read & Write */}
- <div className="group relative">
- <Label
- htmlFor={`${idPrefix}-write`}
- className="flex items-start gap-3 p-4 rounded-xl border-2 border-border/50 hover:border-border hover:bg-muted/50 transition-all cursor-pointer"
- >
- <RadioGroupItem
- value="write"
- id={`${idPrefix}-write`}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-2">
- <div className="flex items-center gap-2">
- <Edit className="h-4 w-4 text-green-500 shrink-0" />
- <span className="font-semibold text-sm">
- {t("common.labels.permissions.write")}
- </span>
- </div>
- <p className="text-xs text-muted-foreground leading-relaxed pl-6">
- {t("share.publicPermissionWriteDesc")}
- </p>
- </div>
- </Label>
- </div>
- </RadioGroup>
+ <div className="flex flex-col gap-2.5">
+ {/* A disabled fieldset disables the option buttons natively. */}
+ <fieldset disabled={disabled} className={cn("m-0 min-w-0 border-0 p-0", disabled && "opacity-60")}>
+ <OptionCards<GuestPermission>
+ label={t("share.publicAccess")}
+ columns={3}
+ value={value}
+ onChange={onChange}
+ options={[
+ {
+ value: "none",
+ title: t("sharingSheet.accessNone"),
+ description: t("sharingSheet.guestNoneShort"),
+ },
+ {
+ value: "read",
+ title: t("sharingSheet.permRead"),
+ description: allowGuest
+ ? t("sharingSheet.guestReadShortGuestsOn")
+ : t("sharingSheet.guestReadShortGuestsOff"),
+ },
+ {
+ value: "write",
+ title: t("sharingSheet.permWrite"),
+ description: allowGuest
+ ? t("sharingSheet.guestWriteShortGuestsOn")
+ : t("sharingSheet.guestWriteShortGuestsOff"),
+ },
+ ]}
+ />
+ </fieldset>
+ <InfoNote icon={Info}>{publicAccessNote(value, allowGuest)}</InfoNote>
</div>
);
}
diff --git a/components/language-switcher.tsx b/components/language-switcher.tsx
deleted file mode 100644
index cb11d8b..0000000
--- a/components/language-switcher.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { useLocale, useTranslations } from "next-intl";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Languages } from "lucide-react";
-import { locales, type Locale } from "@/lib/locales";
-
-export function LanguageSwitcher() {
- const currentLocale = useLocale() as Locale;
- const t = useTranslations();
-
- const handleLocaleChange = (newLocale: string) => {
- // Set cookie to persist user's choice
- document.cookie = `NEXT_LOCALE=${newLocale}; path=/; max-age=31536000; SameSite=Lax`;
- // Reload to apply new locale
- window.location.reload();
- };
-
- return (
- <div className="flex items-center gap-2">
- <Languages className="h-4 w-4 text-muted-foreground" />
- <Select value={currentLocale} onValueChange={handleLocaleChange}>
- <SelectTrigger className="w-[140px] h-9">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {locales.map((locale) => (
- <SelectItem key={locale} value={locale}>
- {t(`language.${locale}`)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- );
-}
diff --git a/components/mobile-day-sheet.tsx b/components/mobile-day-sheet.tsx
new file mode 100644
index 0000000..8fbf914
--- /dev/null
+++ b/components/mobile-day-sheet.tsx
@@ -0,0 +1,381 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format, getISOWeek } from "date-fns";
+import { ChevronDown, ChevronRight, ChevronUp, List, Plus, StickyNote } from "lucide-react";
+import {
+ Drawer,
+ DrawerContent,
+ DrawerDescription,
+ DrawerTitle,
+} from "@/components/ui/drawer";
+import { Button } from "@/components/ui/button";
+import { SegmentedControl } from "@/components/segmented-control";
+import {
+ NoteDetailCard,
+ PeriodSummaryView,
+ ShiftDetailRow,
+} from "@/components/day-detail";
+import { DayActions, DayViewModel, useDayLabels } from "@/components/day-inspector";
+import { PeriodSummary, StatsPeriod } from "@/hooks/useDaySummary";
+import { getDateLocale } from "@/lib/locales";
+
+const TALL = 0.92;
+const LOW_MAX = 0.6;
+// vaul's own snap transition, so the inner height moves with the sheet
+const SNAP_EASE = "duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]";
+
+/** Bottom bar under the phone grid: the visible month in figures and a button to add a shift. */
+export function MobileDayFooter({
+ summary,
+ onOpenStats,
+ onAddShift,
+}: {
+ summary: PeriodSummary;
+ onOpenStats: () => void;
+ /** Hidden when the calendar can't be edited */
+ onAddShift?: () => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { stats, freeDays } = summary;
+ const figures = [
+ { label: t("calendarView.kpiShifts"), value: stats?.totalShifts ?? "–" },
+ {
+ label: t("calendarView.kpiHours"),
+ value: stats
+ ? new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(stats.totalMinutes / 60)
+ : "–",
+ },
+ { label: t("calendarView.kpiFreeDays"), value: freeDays ?? "–" },
+ ];
+
+ return (
+ <div className="flex items-center gap-2.5 border-t border-line bg-surface-panel px-3.5 pb-[max(9px,env(safe-area-inset-bottom))] pt-[9px]">
+ <button
+ type="button"
+ onClick={onOpenStats}
+ className="flex min-w-0 flex-1 items-center gap-2 py-0.5 text-left"
+ >
+ <span className="grid min-w-0 flex-1 grid-cols-3 gap-2">
+ {figures.map((figure) => (
+ <span key={figure.label} className="min-w-0">
+ <span className="block truncate font-mono text-[15px] font-medium leading-5 text-fg-strong">
+ {figure.value}
+ </span>
+ <span className="block truncate text-[10.5px] leading-[14px] text-fg-tertiary">
+ {figure.label}
+ </span>
+ </span>
+ ))}
+ </span>
+ <ChevronUp className="size-4 shrink-0 text-fg-tertiary" />
+ </button>
+ {onAddShift && (
+ <button
+ type="button"
+ onClick={onAddShift}
+ aria-label={t("calendarView.addShiftManually")}
+ className="flex size-10 shrink-0 items-center justify-center rounded-[11px] bg-brand text-white"
+ >
+ <Plus className="size-[19px]" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+/** Height of an element, kept current while it is mounted. */
+function useElementHeight<T extends HTMLElement>() {
+ const [height, setHeight] = useState(0);
+ const [el, setEl] = useState<T | null>(null);
+
+ useEffect(() => {
+ if (!el) return;
+ const observer = new ResizeObserver(() => setHeight(el.offsetHeight));
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [el]);
+
+ return [useCallback((node: T | null) => setEl(node), []), el ? height : 0] as const;
+}
+
+function useWindowHeight() {
+ const [height, setHeight] = useState(() =>
+ typeof window === "undefined" ? 800 : window.innerHeight
+ );
+ useEffect(() => {
+ const onResize = () => setHeight(window.innerHeight);
+ window.addEventListener("resize", onResize);
+ return () => window.removeEventListener("resize", onResize);
+ }, []);
+ return height;
+}
+
+/** The tapped day: fits its content, and snaps between that height and nearly full screen. */
+export function MobileDaySheet({
+ model,
+ actions,
+ open,
+ onOpenChange,
+}: {
+ model: DayViewModel;
+ actions: DayActions;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations();
+ const [snapIndex, setSnapIndex] = useState(0);
+ const [wasOpen, setWasOpen] = useState(open);
+ const pressY = useRef<number | null>(null);
+ // Every opening starts low, however the sheet was closed before
+ if (open !== wasOpen) {
+ setWasOpen(open);
+ if (open) setSnapIndex(0);
+ }
+ const { selectedDay, dayShifts, dayNotes, canEdit } = model;
+ const labels = useDayLabels(selectedDay);
+
+ const windowHeight = useWindowHeight();
+ const [topRef, topHeight] = useElementHeight<HTMLDivElement>();
+ const [listRef, listHeight] = useElementHeight<HTMLDivElement>();
+ const [barRef, barHeight] = useElementHeight<HTMLDivElement>();
+
+ const tall = Math.round(windowHeight * TALL);
+ const natural = topHeight + listHeight + barHeight;
+ const low = Math.min(natural > 0 ? natural : windowHeight / 2, Math.round(windowHeight * LOW_MAX));
+ // vaul measures snap points from the window top, and the list only scrolls at the last point,
+ // so the last point is the full sheet and the low one is shifted by the space the sheet leaves free
+ const snapPoints: (string | number)[] = [`${Math.round(low + windowHeight - tall)}px`, 1];
+ const expanded = snapIndex === 1;
+
+ const close = () => onOpenChange(false);
+ const run = (fn: () => void) => () => {
+ close();
+ fn();
+ };
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={onOpenChange}
+ snapPoints={snapPoints}
+ activeSnapPoint={snapPoints[snapIndex]}
+ setActiveSnapPoint={(point) => setSnapIndex(point === 1 ? 1 : 0)}
+ fadeFromIndex={0}
+ snapToSequentialPoint
+ >
+ <DrawerContent
+ style={{ height: tall }}
+ className="rounded-t-[18px] border-line bg-background shadow-sheet dark:bg-surface-panel [&>div:first-child]:hidden data-[vaul-drawer-direction=bottom]:max-h-none data-[vaul-drawer-direction=bottom]:rounded-t-[18px]"
+ >
+ <div
+ style={{ height: expanded ? tall : low }}
+ className={`flex flex-col overflow-hidden transition-[height] ${SNAP_EASE}`}
+ >
+ <div ref={topRef} className="shrink-0">
+ <button
+ type="button"
+ onPointerDown={(e) => {
+ pressY.current = e.clientY;
+ }}
+ onClick={(e) => {
+ // vaul captures the pointer, so a drag that starts here also ends in a click
+ if (pressY.current !== null && Math.abs(e.clientY - pressY.current) > 6) return;
+ setSnapIndex(expanded ? 0 : 1);
+ }}
+ aria-label={expanded ? t("calendarView.sheetShrink") : t("calendarView.sheetExpand")}
+ className="flex w-full justify-center pb-1 pt-2"
+ >
+ <span className="h-1 w-[34px] rounded-full bg-control" />
+ </button>
+
+ <div className="flex items-start justify-between gap-3 px-4 pb-3 pt-1">
+ <div className="min-w-0">
+ <div className={labels.isToday ? "eyebrow text-brand-ink" : "eyebrow"}>
+ {labels.eyebrow}
+ </div>
+ <DrawerTitle className="mt-0.5 truncate text-[17px] font-semibold tracking-[-0.01em] text-fg-strong">
+ {labels.long}
+ </DrawerTitle>
+ <DrawerDescription className="sr-only">
+ {t("calendarView.sheetDescription")}
+ </DrawerDescription>
+ </div>
+ <button
+ type="button"
+ onClick={close}
+ aria-label={t("common.close")}
+ className="flex size-9 shrink-0 items-center justify-center rounded-[9px] border border-line text-fg-secondary"
+ >
+ <ChevronDown className="size-[18px]" />
+ </button>
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-4">
+ <div ref={listRef} className="flex flex-col gap-2 pb-3">
+ {dayShifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ canEdit={canEdit}
+ actions="inline"
+ onEdit={(s) => {
+ close();
+ actions.onEditShift(s);
+ }}
+ onDelete={actions.onDeleteShift}
+ />
+ ))}
+ {dayNotes.map((note) => (
+ <NoteDetailCard
+ key={note.id}
+ note={note}
+ onOpen={canEdit ? (n) => { close(); actions.onOpenNote(n); } : undefined}
+ />
+ ))}
+ {dayShifts.length === 0 && dayNotes.length === 0 && (
+ <p className="py-3 text-center text-[13px] text-fg-tertiary">
+ {t("calendarView.dayEmpty")}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {canEdit && (
+ <div
+ ref={barRef}
+ className="flex shrink-0 gap-2 border-t border-line px-4 pb-[max(12px,env(safe-area-inset-bottom))] pt-3"
+ >
+ <Button
+ onClick={run(actions.onAddShift)}
+ className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"
+ >
+ <Plus className="size-[18px]" />
+ {t("calendarView.shift")}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={run(actions.onAddNote)}
+ className="h-11 flex-1 gap-2 rounded-[10px] text-[14px] font-semibold"
+ >
+ <StickyNote className="size-[18px]" />
+ {t("calendarView.note")}
+ </Button>
+ </div>
+ )}
+ </div>
+ </DrawerContent>
+ </Drawer>
+ );
+}
+
+/** Week, month or year in figures, opened from the footer. */
+export function MobileStatsSheet({
+ model,
+ actions,
+ period,
+ onPeriodChange,
+ summary,
+ open,
+ onOpenChange,
+}: {
+ model: DayViewModel;
+ actions: DayActions;
+ period: StatsPeriod;
+ onPeriodChange: (period: StatsPeriod) => void;
+ summary: PeriodSummary;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const { selectedDay, currentDate } = model;
+ const dateLocale = getDateLocale(locale);
+ const monthName = format(currentDate, "LLLL", { locale: dateLocale });
+
+ const heading =
+ period === "week"
+ ? {
+ eyebrow: t("calendarView.wholeWeek"),
+ title: t("calendarView.calendarWeek", { week: getISOWeek(selectedDay) }),
+ }
+ : period === "year"
+ ? { eyebrow: t("calendarView.wholeYear"), title: format(currentDate, "yyyy") }
+ : {
+ eyebrow: t("calendarView.wholeMonth"),
+ title: format(currentDate, "LLLL yyyy", { locale: dateLocale }),
+ };
+
+ const close = () => onOpenChange(false);
+ const run = (fn: () => void) => () => {
+ close();
+ fn();
+ };
+
+ return (
+ <Drawer open={open} onOpenChange={onOpenChange}>
+ <DrawerContent className="rounded-t-[18px] border-line bg-background shadow-sheet dark:bg-surface-panel [&>div:first-child]:hidden data-[vaul-drawer-direction=bottom]:max-h-[92dvh] data-[vaul-drawer-direction=bottom]:rounded-t-[18px]">
+ <div className="flex justify-center pb-1 pt-2">
+ <span className="h-1 w-[34px] rounded-full bg-control" />
+ </div>
+
+ <div className="flex items-start justify-between gap-3 px-4 pb-3 pt-1">
+ <div className="min-w-0">
+ <div className="eyebrow">{heading.eyebrow}</div>
+ <DrawerTitle className="mt-0.5 truncate text-[17px] font-semibold tracking-[-0.01em] text-fg-strong">
+ {heading.title}
+ </DrawerTitle>
+ <DrawerDescription className="sr-only">
+ {t("calendarView.statsSheetDescription")}
+ </DrawerDescription>
+ </div>
+ <button
+ type="button"
+ onClick={close}
+ aria-label={t("common.close")}
+ className="flex size-9 shrink-0 items-center justify-center rounded-[9px] border border-line text-fg-secondary"
+ >
+ <ChevronDown className="size-[18px]" />
+ </button>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-4 pb-[max(16px,env(safe-area-inset-bottom))]">
+ <SegmentedControl<StatsPeriod>
+ label={t("calendarView.periodLabel")}
+ value={period}
+ onChange={onPeriodChange}
+ options={[
+ { value: "week", label: t("stats.week") },
+ { value: "month", label: t("stats.month") },
+ { value: "year", label: t("stats.year") },
+ ]}
+ />
+ <PeriodSummaryView summary={summary} columns="cards" />
+ {period === "month" && (
+ <button
+ type="button"
+ onClick={run(actions.onOpenMonthShifts)}
+ className="flex items-center gap-2.5 rounded-lg border border-line bg-surface-card px-3 py-3 text-left"
+ >
+ <List className="size-4 text-fg-secondary" />
+ <span className="flex-1 text-[13.5px] font-semibold text-fg-strong">
+ {t("calendarView.allShiftsIn", { month: monthName })}
+ </span>
+ <ChevronRight className="size-4 text-fg-tertiary" />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={run(actions.onOpenStats)}
+ className="text-left text-[13px] font-semibold text-brand-ink"
+ >
+ {t("calendarView.openStats")}
+ </button>
+ </div>
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/components/month-dialogs.tsx b/components/month-dialogs.tsx
new file mode 100644
index 0000000..9f43125
--- /dev/null
+++ b/components/month-dialogs.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useMemo } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { PanelDialog } from "@/components/panel-dialog";
+import { ShiftStats } from "@/components/shift-stats";
+import { ShiftDetailRow } from "@/components/day-detail";
+import { ShiftWithCalendar } from "@/lib/types";
+import { getDateLocale } from "@/lib/locales";
+import { formatDateToLocal, formatLongDate } from "@/lib/date-utils";
+import { formatHours, getShiftMinutes, sortShifts } from "@/lib/shift-display";
+
+interface MonthDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ currentDate: Date;
+}
+
+export function MonthStatsDialog({
+ open,
+ onOpenChange,
+ currentDate,
+ calendarId,
+}: MonthDialogProps & { calendarId: string | undefined }) {
+ const t = useTranslations();
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("stats.title")}
+ width="lg"
+ bodyClassName="px-3 py-3 sm:px-4"
+ >
+ <ShiftStats calendarId={calendarId} currentDate={currentDate} />
+ </PanelDialog>
+ );
+}
+
+export function MonthShiftsDialog({
+ open,
+ onOpenChange,
+ currentDate,
+ shifts,
+ canEdit,
+ onEditShift,
+ onDeleteShift,
+}: MonthDialogProps & {
+ shifts: ShiftWithCalendar[];
+ canEdit: boolean;
+ onEditShift: (shift: ShiftWithCalendar) => void;
+ onDeleteShift: (shift: ShiftWithCalendar) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+
+ const days = useMemo(() => {
+ const inMonth = shifts.filter((s) => {
+ const d = s.date as Date | null;
+ return (
+ d &&
+ d.getMonth() === currentDate.getMonth() &&
+ d.getFullYear() === currentDate.getFullYear()
+ );
+ });
+ const groups = new Map<string, { date: Date; shifts: ShiftWithCalendar[] }>();
+ for (const shift of inMonth) {
+ const date = shift.date as Date;
+ const key = formatDateToLocal(date);
+ const group = groups.get(key) ?? { date, shifts: [] };
+ group.shifts.push(shift);
+ groups.set(key, group);
+ }
+ return [...groups.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, group]) => ({
+ key,
+ date: group.date,
+ shifts: sortShifts(group.shifts, "startTime"),
+ }));
+ }, [shifts, currentDate]);
+
+ const total = days.reduce((sum, d) => sum + d.shifts.length, 0);
+ const monthLabel = format(currentDate, "LLLL yyyy", { locale: dateLocale });
+
+ return (
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("calendarView.allShiftsIn", {
+ month: format(currentDate, "LLLL", { locale: dateLocale }),
+ })}
+ description={`${monthLabel} · ${t("calendarView.shiftCount", { count: total })}`}
+ width="md"
+ >
+ {days.length === 0 ? (
+ <p className="py-6 text-center text-[13px] text-fg-tertiary">
+ {t("shift.noShiftsInMonth")}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-4">
+ {days.map((day) => {
+ const minutes = day.shifts.reduce((sum, s) => sum + getShiftMinutes(s), 0);
+ return (
+ <section key={day.key} className="flex flex-col gap-1.5">
+ <h3 className="flex items-baseline gap-2 text-[13px] font-semibold text-fg-strong">
+ {formatLongDate(day.date, locale)}
+ <span className="font-mono text-[11.5px] font-normal text-fg-tertiary">
+ {t("calendarView.shiftCount", { count: day.shifts.length })}
+ {minutes > 0 && ` · ${formatHours(minutes, locale)}`}
+ </span>
+ </h3>
+ {day.shifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ canEdit={canEdit}
+ actions="menu"
+ onEdit={(s) => {
+ onOpenChange(false);
+ onEditShift(s);
+ }}
+ onDelete={onDeleteShift}
+ />
+ ))}
+ </section>
+ );
+ })}
+ </div>
+ )}
+ </PanelDialog>
+ );
+}
diff --git a/components/month-grid.tsx b/components/month-grid.tsx
new file mode 100644
index 0000000..c36d629
--- /dev/null
+++ b/components/month-grid.tsx
@@ -0,0 +1,720 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { isSameDay, isToday } from "date-fns";
+import { CalendarClock, RefreshCw, StickyNote } from "lucide-react";
+import { ShiftWithCalendar } from "@/lib/types";
+import { CalendarNote, ExternalSync } from "@/lib/db/schema";
+import { formatDateToLocal } from "@/lib/date-utils";
+import { findNotesForDate } from "@/lib/event-utils";
+import {
+ DayLayoutOptions,
+ DayShiftLayout,
+ buildDayShiftLayout,
+ shiftVars,
+} from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+
+const WEEKDAY_KEYS = [
+ "monday",
+ "tuesday",
+ "wednesday",
+ "thursday",
+ "friday",
+ "saturday",
+ "sunday",
+] as const;
+
+const LONG_PRESS_MS = 500;
+
+// The filled day number of "today", shared by the desktop, phone and compare cells
+const TODAY_BADGE = "bg-brand font-semibold text-white dark:bg-brand-dot dark:text-[#0a1020]";
+
+// Cell geometry in px. These mirror the Tailwind sizes of the cell markup below;
+// change both together or the fitting clips rows.
+const DESKTOP_MAX_ROWS = 4;
+const DESKTOP_CHROME = 37; // 7 + 7 padding, 20 day number, 3 gap
+const DESKTOP_GAP = 3;
+const DESKTOP_ROW = 20;
+const DESKTOP_PLAIN_ROW = 18;
+const DESKTOP_SUB_LINE = 14;
+const DESKTOP_OVERFLOW = 14;
+
+const PHONE_MIN_ROW = 84; // two fields plus the counter
+const PHONE_CHROME = 30; // 5 padding, 22 head, 3 gap
+const PHONE_GAP = 2;
+const PHONE_FIELD = 19;
+const PHONE_COUNTER = 12;
+const PHONE_MAX_FIELDS = 3;
+const PHONE_HEAD_FIXED = 32; // 4 cell padding, 3 head padding, 22 day number, 3 gap
+const PHONE_MARK = 10;
+const PHONE_MAX_MARKS = 3;
+const PHONE_FALLBACK_COL = 54; // 390px viewport, used until the grid is measured
+
+type Variant = "desktop" | "phone" | "compare";
+
+/** Desktop rows in cell order; "count" is a count-only external sync */
+type CellEntry =
+ | { kind: "shift" | "external"; key: string; shift: ShiftWithCalendar }
+ | { kind: "event" | "note"; key: string; note: CalendarNote };
+
+/** How many items fit into `space`, keeping room for an overflow line whenever something stays hidden. */
+function fitCount(
+ heights: number[],
+ alreadyHidden: number,
+ space: number,
+ max: number,
+ gap: number,
+ overflow: number
+): number {
+ let used = 0;
+ let shown = 0;
+ for (let i = 0; i < heights.length && shown < max; i++) {
+ const cost = heights[i] + (shown > 0 ? gap : 0);
+ const hiddenAfter = heights.length - i - 1 + alreadyHidden;
+ const reserve = hiddenAfter > 0 ? gap + overflow : 0;
+ if (used + cost + reserve > space) break;
+ used += cost;
+ shown++;
+ }
+ return shown;
+}
+
+/** Runs of adjacent highlighted columns (Monday first), so neighbouring days share one band. */
+function highlightBands(weekdays: number[]): { start: number; span: number }[] {
+ const bands: { start: number; span: number }[] = [];
+ for (let col = 0; col < 7; col++) {
+ if (!weekdays.includes((col + 1) % 7)) continue;
+ const last = bands[bands.length - 1];
+ if (last && last.start + last.span === col) last.span++;
+ else bands.push({ start: col, span: 1 });
+ }
+ return bands;
+}
+
+/** Grid box size; both month layouts fit their cells to it. */
+function useGridSize(enabled: boolean) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!enabled || !el) return;
+ const observer = new ResizeObserver(() => {
+ const width = el.offsetWidth;
+ const height = el.offsetHeight;
+ setSize((prev) =>
+ prev.width === width && prev.height === height ? prev : { width, height }
+ );
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [enabled]);
+
+ return [ref, size] as const;
+}
+
+interface DayContent {
+ layout: DayShiftLayout;
+ events: CalendarNote[];
+ notes: CalendarNote[];
+}
+
+interface MonthGridProps {
+ calendarDays: Date[];
+ currentDate: Date;
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+ externalSyncs: ExternalSync[];
+ togglingDates: Set<string>;
+ layout: DayLayoutOptions;
+ /** Desktop only: a shift's own note as a second line */
+ showShiftNotes?: boolean;
+ highlightedWeekdays?: number[];
+ highlightColor?: string;
+ onDayClick: (date: Date) => void;
+ onDayContextMenu?: (date: Date) => void;
+ /** "compare" is the narrow desktop column used side by side in compare mode */
+ variant?: Variant;
+}
+
+export function MonthGrid({
+ calendarDays,
+ currentDate,
+ selectedDay,
+ shifts,
+ notes,
+ externalSyncs,
+ togglingDates,
+ layout,
+ showShiftNotes = false,
+ highlightedWeekdays = [],
+ highlightColor,
+ onDayClick,
+ onDayContextMenu,
+ variant = "desktop",
+}: MonthGridProps) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const phone = variant === "phone";
+ const desktop = variant === "desktop";
+ // 2024-01-01 was a Monday
+ const longWeekdays = useMemo(() => {
+ const formatter = new Intl.DateTimeFormat(locale, { weekday: "long" });
+ return WEEKDAY_KEYS.map((_, i) => formatter.format(new Date(2024, 0, 1 + i)));
+ }, [locale]);
+ const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const longPressed = useRef(false);
+ const [gridRef, gridSize] = useGridSize(variant !== "compare");
+ const rows = Math.max(1, Math.ceil(calendarDays.length / 7));
+ const measured = gridSize.height > 0;
+ const rowHeight = phone
+ ? Math.max(PHONE_MIN_ROW, (gridSize.height - (rows - 1) * PHONE_GAP) / rows)
+ : (gridSize.height - (rows - 1)) / rows;
+ const colWidth = gridSize.width > 0 ? (gridSize.width - 8) / 7 : PHONE_FALLBACK_COL;
+
+ useEffect(
+ () => () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ },
+ []
+ );
+
+ // One pass over the month instead of scanning every shift and note per cell
+ const { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort } = layout;
+ const dayContents = useMemo(() => {
+ const month = currentDate.getMonth();
+ const shiftsByDay = new Map<string, ShiftWithCalendar[]>();
+ for (const shift of shifts) {
+ if (!shift.date) continue;
+ const key = formatDateToLocal(shift.date as Date);
+ const list = shiftsByDay.get(key);
+ if (list) list.push(shift);
+ else shiftsByDay.set(key, [shift]);
+ }
+
+ const contents = new Map<string, DayContent>();
+ for (const day of calendarDays) {
+ const key = formatDateToLocal(day);
+ const inMonth = day.getMonth() === month;
+ const dayNotes = inMonth ? findNotesForDate(notes, day) : [];
+ contents.set(key, {
+ layout: buildDayShiftLayout(
+ inMonth ? (shiftsByDay.get(key) ?? []) : [],
+ externalSyncs,
+ { maxShifts, maxExternalShifts, sortType, sortOrder, combinedSort }
+ ),
+ events: dayNotes.filter((n) => n.type === "event"),
+ notes: dayNotes.filter((n) => n.type !== "event"),
+ });
+ }
+ return contents;
+ }, [
+ calendarDays,
+ currentDate,
+ shifts,
+ notes,
+ externalSyncs,
+ maxShifts,
+ maxExternalShifts,
+ sortType,
+ sortOrder,
+ combinedSort,
+ ]);
+
+ const cancelPress = () => {
+ if (pressTimer.current) clearTimeout(pressTimer.current);
+ pressTimer.current = null;
+ };
+
+ /**
+ * Day number, plus one counter per minimal-mode sync. Those carry no text, so
+ * the header row has space for them and the cell body keeps its full budget.
+ */
+ const renderDesktopHead = (
+ content: DayContent,
+ day: Date,
+ inMonth: boolean,
+ today: boolean
+ ) => (
+ <span className="flex shrink-0 items-center gap-1">
+ <span
+ className={cn(
+ "inline-flex size-5 shrink-0 items-center justify-center rounded-full font-mono text-[12.5px] font-medium leading-none",
+ today ? TODAY_BADGE : inMonth ? "text-fg-body dark:text-fg-secondary" : "text-fg-faint"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ {content.layout.minimalGroups.length > 0 && (
+ <span className="ml-auto flex shrink-0 items-center gap-1">
+ {content.layout.minimalGroups.map(({ sync, shifts: synced }) => (
+ <span
+ key={sync.id}
+ className="shift-chip flex shrink-0 items-center gap-1 rounded-[6px] px-[5px] py-0.5 dark:[--shift-tint:14%]"
+ style={shiftVars(sync.color)}
+ title={sync.name}
+ >
+ <RefreshCw className="size-3 shrink-0" />
+ <span className="font-mono text-[11px] font-semibold leading-4">
+ {synced.length}
+ </span>
+ </span>
+ ))}
+ </span>
+ )}
+ </span>
+ );
+
+ const renderDesktop = (content: DayContent) => {
+ const { visible, hiddenCount, hiddenExternalCount } = content.layout;
+ const entries: CellEntry[] = [
+ ...visible.map((shift) => ({
+ kind: shift.syncedFromExternal ? ("external" as const) : ("shift" as const),
+ key: shift.id,
+ shift,
+ })),
+ ...content.events.map((note) => ({ kind: "event" as const, key: note.id, note })),
+ ...content.notes.map((note) => ({ kind: "note" as const, key: note.id, note })),
+ ];
+ const heights = entries.map((entry) => {
+ if (entry.kind === "shift") {
+ return DESKTOP_ROW + (showShiftNotes && entry.shift.notes ? DESKTOP_SUB_LINE : 0);
+ }
+ return entry.kind === "note" ? DESKTOP_PLAIN_ROW : DESKTOP_ROW;
+ });
+ const shown = fitCount(
+ heights,
+ hiddenCount,
+ measured ? rowHeight - DESKTOP_CHROME : Infinity,
+ DESKTOP_MAX_ROWS,
+ DESKTOP_GAP,
+ DESKTOP_OVERFLOW
+ );
+
+ let hiddenShifts = hiddenCount - hiddenExternalCount;
+ let hiddenExternal = hiddenExternalCount;
+ let hiddenEvents = 0;
+ let hiddenNotes = 0;
+ for (const entry of entries.slice(shown)) {
+ if (entry.kind === "shift") hiddenShifts++;
+ else if (entry.kind === "external") hiddenExternal++;
+ else if (entry.kind === "event") hiddenEvents++;
+ else hiddenNotes++;
+ }
+ const overflow = [
+ hiddenShifts > 0 && t("calendarView.shiftCount", { count: hiddenShifts }),
+ hiddenEvents > 0 && t("calendarView.eventCount", { count: hiddenEvents }),
+ hiddenNotes > 0 && t("calendarView.notesCount", { count: hiddenNotes }),
+ hiddenExternal > 0 && t("calendarView.externalCount", { count: hiddenExternal }),
+ ].filter(Boolean);
+
+ const chip =
+ "shift-chip flex min-w-0 shrink-0 gap-1.5 rounded-[6px] py-0.5 pr-[7px] dark:[--shift-tint:14%]";
+ const time = (shift: ShiftWithCalendar) => (
+ <span className="shrink-0 font-mono text-[10.5px] leading-4 opacity-75">
+ {shift.isAllDay ? t("calendarView.allDayShort") : shift.startTime.slice(0, 5)}
+ </span>
+ );
+
+ return (
+ <>
+ {entries.slice(0, shown).map((entry) => {
+ switch (entry.kind) {
+ case "shift": {
+ const { shift } = entry;
+ return (
+ <span
+ key={entry.key}
+ className={cn(chip, "pl-[5px]")}
+ style={shiftVars(shift.color)}
+ title={`${shift.title}${shift.notes ? `\n${shift.notes}` : ""}`}
+ >
+ <span className="shift-rail w-[3px] shrink-0 self-stretch rounded-full" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[11.5px] font-medium leading-4">
+ {shift.title}
+ </span>
+ {showShiftNotes && shift.notes && (
+ <span className="block truncate text-[10.5px] leading-[14px] opacity-75">
+ {shift.notes}
+ </span>
+ )}
+ </span>
+ {time(shift)}
+ </span>
+ );
+ }
+ case "external":
+ // The sync icon takes the rail's place so imported entries stay recognisable
+ return (
+ <span
+ key={entry.key}
+ className={cn(chip, "items-center pl-[5px]")}
+ style={shiftVars(entry.shift.color)}
+ title={entry.shift.title}
+ >
+ <RefreshCw className="size-3 shrink-0" />
+ <span className="min-w-0 flex-1 truncate text-[11.5px] font-medium leading-4">
+ {entry.shift.title}
+ </span>
+ {time(entry.shift)}
+ </span>
+ );
+ case "event":
+ return (
+ <span
+ key={entry.key}
+ className="flex h-5 min-w-0 shrink-0 items-center gap-1.5 rounded-[6px] bg-cell-event px-[7px] shadow-[inset_0_0_0_1px_var(--cell-event-line)]"
+ title={entry.note.note}
+ >
+ <CalendarClock
+ className="shift-icon size-3 shrink-0"
+ style={shiftVars(entry.note.color || undefined)}
+ />
+ <span className="min-w-0 flex-1 truncate text-[11.5px] font-medium text-cell-event-ink">
+ {entry.note.note}
+ </span>
+ </span>
+ );
+ case "note":
+ return (
+ <span
+ key={entry.key}
+ className="flex h-[18px] min-w-0 shrink-0 items-center gap-1.5 px-1"
+ title={entry.note.note}
+ >
+ <StickyNote className="size-3 shrink-0 text-cell-note" />
+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-fg-body dark:text-fg-secondary">
+ {entry.note.note}
+ </span>
+ </span>
+ );
+ }
+ })}
+ {overflow.length > 0 && (
+ <span
+ className="shrink-0 truncate pl-[5px] text-[11px] font-medium leading-[14px] text-brand-ink"
+ title={`+ ${overflow.join(", ")}`}
+ >
+ + {overflow.join(", ")}
+ </span>
+ )}
+ </>
+ );
+ };
+
+ const renderPhoneBody = (content: DayContent) => {
+ const { visible, hiddenCount, minimalGroups } = content.layout;
+ const fields = [
+ ...visible.map((shift) => ({ key: shift.id, color: shift.color, count: 1, shift })),
+ ...minimalGroups.map(({ sync, shifts: synced }) => ({
+ key: sync.id,
+ color: sync.color,
+ count: synced.length,
+ shift: undefined,
+ })),
+ ];
+ const shown = fitCount(
+ fields.map(() => PHONE_FIELD),
+ hiddenCount,
+ rowHeight - PHONE_CHROME,
+ PHONE_MAX_FIELDS,
+ PHONE_GAP,
+ PHONE_COUNTER
+ );
+ const rest = fields.slice(shown).reduce((sum, field) => sum + field.count, hiddenCount);
+
+ return (
+ <span className="flex min-w-0 flex-col gap-[2px]">
+ {fields.slice(0, shown).map((field) => (
+ // Cut hard at the field edge, no ellipsis: the first letters identify a shift
+ <span
+ key={field.key}
+ className="shift-field flex h-[19px] shrink-0 items-center gap-[2px] overflow-hidden whitespace-nowrap rounded-[4px] px-1 text-[11px] font-semibold leading-[19px]"
+ style={shiftVars(field.color)}
+ >
+ {field.shift ? (
+ field.shift.title
+ ) : (
+ <>
+ <RefreshCw className="size-2.5 shrink-0" />
+ <span className="font-mono">{field.count}</span>
+ </>
+ )}
+ </span>
+ ))}
+ {rest > 0 && (
+ <span className="shrink-0 pl-1 font-mono text-[10px] font-semibold leading-3 text-brand-ink">
+ +{rest}
+ </span>
+ )}
+ </span>
+ );
+ };
+
+ /** One mark per event, then one for notes; extra events give way to the note mark. */
+ const renderPhoneMarks = (content: DayContent) => {
+ const room = Math.min(
+ PHONE_MAX_MARKS,
+ Math.floor((colWidth - PHONE_HEAD_FIXED + PHONE_GAP) / (PHONE_MARK + PHONE_GAP))
+ );
+ const hasEvent = content.events.length > 0;
+ const noteShown = content.notes.length > 0 && room >= (hasEvent ? 2 : 1);
+ const eventCount = Math.min(content.events.length, room - (noteShown ? 1 : 0));
+ if (eventCount + (noteShown ? 1 : 0) <= 0) return null;
+
+ return (
+ <span className="flex shrink-0 items-center gap-[2px]" aria-hidden>
+ {content.events.slice(0, Math.max(0, eventCount)).map((event) => (
+ <CalendarClock
+ key={event.id}
+ className="shift-icon size-2.5 shrink-0"
+ style={shiftVars(event.color || undefined)}
+ />
+ ))}
+ {noteShown && <StickyNote className="size-2.5 shrink-0 text-cell-note" />}
+ </span>
+ );
+ };
+
+ const renderCompare = (content: DayContent, day: Date, inMonth: boolean, today: boolean) => {
+ const { visible, hiddenCount, minimalGroups } = content.layout;
+ const { events, notes: plainNotes } = content;
+ return (
+ <>
+ <div className="mb-1.5 flex w-full items-center justify-between gap-1.5">
+ <span
+ className={cn(
+ "inline-flex size-[22px] shrink-0 items-center justify-center rounded-full font-mono text-[12.5px] font-medium leading-none",
+ today
+ ? TODAY_BADGE
+ : inMonth
+ ? "text-fg-body"
+ : "text-fg-tertiary"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ {hiddenCount > 0 && (
+ <span className="ml-auto rounded-[4px] bg-brand-soft px-1 py-px font-mono text-[10px] font-bold text-brand-ink">
+ +{hiddenCount}
+ </span>
+ )}
+ <span className="flex min-w-0 items-center gap-1">
+ {plainNotes.length > 0 && (
+ <StickyNote
+ className="size-3.5 shrink-0 text-warning"
+ aria-label={t("calendarView.hasNotes", { count: plainNotes.length })}
+ />
+ )}
+ {events[0] && (
+ <span
+ className="shift-chip max-w-[88px] truncate rounded-[5px] px-1.5 py-0.5 text-[10.5px] font-semibold"
+ style={shiftVars(events[0].color || "var(--brand)")}
+ title={events.map((e) => e.note).join("\n")}
+ >
+ {events[0].note}
+ {events.length > 1 && ` +${events.length - 1}`}
+ </span>
+ )}
+ </span>
+ </div>
+ <div className="flex min-w-0 flex-col gap-[3px]">
+ {visible.map((shift) => (
+ <span
+ key={shift.id}
+ className="flex min-w-0 items-center gap-1.5 rounded-sm bg-surface-sunken/70 px-1.5 py-[3px] text-[11.5px] text-fg-body"
+ title={`${shift.title} · ${
+ shift.isAllDay ? t("shift.allDayShift") : `${shift.startTime}–${shift.endTime}`
+ }`}
+ >
+ <span
+ className="shift-rail h-[13px] w-[3px] shrink-0 rounded-full"
+ style={shiftVars(shift.color)}
+ />
+ <span className="min-w-0 flex-1 truncate">{shift.title}</span>
+ </span>
+ ))}
+ {minimalGroups.map(({ sync, shifts: syncShifts }) => (
+ <span
+ key={sync.id}
+ className="shift-chip flex items-center gap-1.5 rounded-sm px-[7px] py-[3px] text-[11.5px] font-medium"
+ style={shiftVars(sync.color)}
+ title={sync.name}
+ >
+ <RefreshCw className="size-3 shrink-0" />
+ <span className="truncate">
+ {t("calendarView.externalCount", { count: syncShifts.length })}
+ </span>
+ </span>
+ ))}
+ </div>
+ </>
+ );
+ };
+
+ return (
+ // On phones the grid may not shrink below its minimum rows, so the page scrolls instead
+ <div className={cn("flex flex-1 flex-col", phone ? "relative isolate" : "min-h-0")}>
+ {phone && highlightColor && highlightedWeekdays.length > 0 && (
+ // Phone cells have no surface, so a highlighted weekday is one band behind the column
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 -top-1 bottom-0 -z-10 grid grid-cols-7 px-1"
+ style={{ "--highlight": highlightColor } as React.CSSProperties}
+ >
+ {highlightBands(highlightedWeekdays).map(({ start, span }) => (
+ <span
+ key={start}
+ className="day-highlight rounded-[8px] [--highlight-tint:8%] dark:[--highlight-tint:10%]"
+ style={{ gridColumn: `${start + 1} / span ${span}` }}
+ />
+ ))}
+ </div>
+ )}
+ <div
+ className={cn(
+ "grid grid-cols-7",
+ phone ? "px-1 pb-[5px]" : "border-b border-line",
+ desktop && "px-[18px] pt-3.5",
+ variant === "compare" && "px-4 pt-3"
+ )}
+ >
+ {WEEKDAY_KEYS.map((key, index) =>
+ phone ? (
+ // Sits right above the left-aligned day number
+ <div
+ key={key}
+ className="ml-1 w-[22px] text-center text-[10.5px] font-semibold uppercase tracking-[0.06em] text-cell-muted"
+ >
+ {t(`calendarView.weekdayShort.${key}`)}
+ </div>
+ ) : (
+ <div
+ key={key}
+ className={cn(
+ "px-2.5 pb-2 font-semibold uppercase tracking-[0.06em] text-fg-tertiary",
+ desktop ? "text-[11.5px]" : "text-[11px]"
+ )}
+ >
+ {desktop ? longWeekdays[index] : t(`calendarView.weekdayShort.${key}`)}
+ </div>
+ )
+ )}
+ </div>
+
+ <div
+ ref={gridRef}
+ className={cn(
+ "grid flex-1 grid-cols-7",
+ phone
+ ? "auto-rows-[minmax(84px,1fr)] gap-y-[2px] px-1"
+ : "min-h-0 auto-rows-[minmax(0,1fr)] gap-px bg-line-grid",
+ desktop && "mx-[18px]",
+ variant === "compare" && "mx-4"
+ )}
+ >
+ {calendarDays.map((day) => {
+ const key = formatDateToLocal(day);
+ const inMonth = day.getMonth() === currentDate.getMonth();
+ const today = isToday(day);
+ const selected = isSameDay(day, selectedDay);
+ const weekend = day.getDay() === 0 || day.getDay() === 6;
+ const highlighted =
+ !phone && !!highlightColor && highlightedWeekdays.includes(day.getDay());
+ const toggling = togglingDates.has(key);
+
+ const content = dayContents.get(key)!;
+
+ return (
+ <button
+ key={key}
+ type="button"
+ disabled={toggling}
+ aria-pressed={selected}
+ aria-label={day.toLocaleDateString()}
+ onClick={() => {
+ if (longPressed.current) {
+ longPressed.current = false;
+ return;
+ }
+ onDayClick(day);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ onDayContextMenu?.(day);
+ }}
+ onTouchStart={() => {
+ longPressed.current = false;
+ if (!onDayContextMenu) return;
+ pressTimer.current = setTimeout(() => {
+ longPressed.current = true;
+ onDayContextMenu(day);
+ }, LONG_PRESS_MS);
+ }}
+ onTouchEnd={cancelPress}
+ onTouchMove={cancelPress}
+ style={
+ highlighted ? ({ "--highlight": highlightColor } as React.CSSProperties) : undefined
+ }
+ className={cn(
+ "relative flex min-h-0 min-w-0 select-none flex-col items-stretch overflow-hidden text-left outline-none transition-colors [-webkit-touch-callout:none]",
+ // Phone cells have no surface and no lines; the fields carry the grid
+ phone
+ ? "gap-[3px] rounded-[6px] px-[2px] pt-[5px] [contain:size]"
+ : cn(
+ weekend ? "bg-surface-weekend" : "bg-surface-cell",
+ "hover:bg-surface-panel",
+ selected && "shadow-[inset_0_0_0_1.5px_var(--brand-dot)]"
+ ),
+ desktop && "gap-[3px] px-2 py-[7px]",
+ variant === "compare" && "px-[9px] py-2",
+ highlighted && "day-highlight",
+ !inMonth && (phone ? "opacity-30" : desktop ? "opacity-35" : "opacity-45"),
+ toggling && "cursor-wait opacity-60",
+ "focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]"
+ )}
+ >
+ {desktop && (
+ <>
+ {renderDesktopHead(content, day, inMonth, today)}
+ {renderDesktop(content)}
+ </>
+ )}
+
+ {phone && (
+ <>
+ <span className="flex min-h-[22px] shrink-0 items-center gap-[3px] overflow-hidden pl-[2px] pr-px">
+ <span
+ className={cn(
+ "inline-flex size-[22px] shrink-0 items-center justify-center rounded-full font-mono text-[14px] leading-none",
+ today
+ ? TODAY_BADGE
+ : selected
+ ? "bg-cell-selected font-semibold text-fg-strong"
+ : !inMonth
+ ? "font-normal text-cell-outside-num"
+ : weekend
+ ? "font-[450] text-cell-weekend-num"
+ : "font-[450] text-fg-body"
+ )}
+ >
+ {day.getDate()}
+ </span>
+ {renderPhoneMarks(content)}
+ </span>
+ {renderPhoneBody(content)}
+ </>
+ )}
+
+ {variant === "compare" && renderCompare(content, day, inMonth, today)}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/components/month-navigation.tsx b/components/month-navigation.tsx
deleted file mode 100644
index d5d91e7..0000000
--- a/components/month-navigation.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { motion } from "motion/react";
-import { Button } from "@/components/ui/button";
-import { ChevronLeft, ChevronRight } from "lucide-react";
-import { format, addMonths, subMonths, Locale } from "date-fns";
-
-interface MonthNavigationProps {
- currentDate: Date;
- onDateChange: (date: Date) => void;
- locale?: Locale;
-}
-
-export function MonthNavigation({
- currentDate,
- onDateChange,
- locale,
-}: MonthNavigationProps) {
- return (
- <motion.div
- className="flex items-center justify-between mb-4 sm:mb-5 px-2 sm:px-0"
- initial={{ opacity: 0, y: -10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.3 }}
- >
- <Button
- variant="outline"
- size="icon"
- className="h-10 w-10 sm:h-11 sm:w-11 rounded-full active:scale-95 transition-transform"
- onClick={() => onDateChange(subMonths(currentDate, 1))}
- >
- <ChevronLeft className="h-5 w-5" />
- </Button>
- <motion.h2
- className="text-lg sm:text-xl font-bold"
- key={format(currentDate, "MMMM yyyy")}
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.2 }}
- >
- {format(currentDate, "MMMM yyyy", { locale })}
- </motion.h2>
- <Button
- variant="outline"
- size="icon"
- className="h-10 w-10 sm:h-11 sm:w-11 rounded-full active:scale-95 transition-transform"
- onClick={() => onDateChange(addMonths(currentDate, 1))}
- >
- <ChevronRight className="h-5 w-5" />
- </Button>
- </motion.div>
- );
-}
diff --git a/components/note-sheet.tsx b/components/note-sheet.tsx
index 76972d4..28c0a8c 100644
--- a/components/note-sheet.tsx
+++ b/components/note-sheet.tsx
@@ -1,36 +1,39 @@
"use client";
-import { useState, useEffect, useRef } from "react";
+import { useMemo, useState } from "react";
import { useTranslations, useLocale } from "next-intl";
+import { formatLongDate } from "@/lib/date-utils";
+import { Info, Trash2, TriangleAlert } from "lucide-react";
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 { ColorPicker } from "@/components/ui/color-picker";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
+import {
+ ChoiceChips,
+ ColorSwatches,
+ Field,
+ InfoNote,
+ textareaClass,
+ zoomSafeText,
+} from "@/components/form-kit";
+import { SegmentedControl } from "@/components/segmented-control";
+import { StatusBanner } from "@/components/status-banner";
import { ReadOnlyBanner } from "@/components/read-only-banner";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
import { CalendarNote } from "@/lib/db/schema";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import { PRESET_COLORS } from "@/lib/constants";
-import { AlertCircle } from "lucide-react";
-import { Alert, AlertDescription } from "@/components/ui/alert";
+import { DEFAULT_COLOR } from "@/lib/constants";
+import { cn } from "@/lib/utils";
+
+type NoteType = "note" | "event";
+/** UI view of the stored patterns; "years" is stored as custom-months × 12. */
+type Repeat = "none" | "weeks" | "months" | "years";
interface NoteSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSubmit: (
note: string,
- type: "note" | "event",
+ type: NoteType,
color?: string,
recurringPattern?: string,
recurringInterval?: number
@@ -42,6 +45,47 @@ interface NoteSheetProps {
readOnly?: boolean;
}
+interface NoteFormState {
+ text: string;
+ type: NoteType;
+ color: string;
+ repeat: Repeat;
+ interval: number;
+}
+
+const MAX_INTERVAL = 52;
+
+const EMPTY_STATE: NoteFormState = {
+ text: "",
+ type: "note",
+ color: DEFAULT_COLOR,
+ repeat: "none",
+ interval: 1,
+};
+
+export function parseRecurrence(
+ pattern: string | null | undefined,
+ interval: number | null | undefined
+): { repeat: Repeat; interval: number } {
+ const count = interval && interval > 0 ? interval : 1;
+ if (pattern === "custom-weeks") return { repeat: "weeks", interval: count };
+ if (pattern === "custom-months") {
+ return count % 12 === 0
+ ? { repeat: "years", interval: count / 12 }
+ : { repeat: "months", interval: count };
+ }
+ return { repeat: "none", interval: 1 };
+}
+
+function stateFromNote(note: CalendarNote): NoteFormState {
+ return {
+ text: note.note || "",
+ type: (note.type as NoteType) || "note",
+ color: note.color || DEFAULT_COLOR,
+ ...parseRecurrence(note.recurringPattern, note.recurringInterval),
+ };
+}
+
export function NoteSheet({
open,
onOpenChange,
@@ -54,125 +98,68 @@ export function NoteSheet({
}: NoteSheetProps) {
const t = useTranslations();
const locale = useLocale();
- const dateLocale = getDateLocale(locale);
const permission = useCalendarPermission(calendarId);
- const [noteText, setNoteText] = useState("");
- const [type, setType] = useState<"note" | "event">("note");
- const [color, setColor] = useState<string>("#3b82f6");
- const [recurringPattern, setRecurringPattern] = useState<string>("none");
- const [recurringInterval, setRecurringInterval] = useState<number>(1);
- const [recurringUnit, setRecurringUnit] = useState<string>("months");
+ const initial = useMemo(
+ () => (open && note ? stateFromNote(note) : EMPTY_STATE),
+ [open, note]
+ );
+ const [form, setForm] = useState<NoteFormState>(initial);
+ const [source, setSource] = useState({ open, note });
const [isSaving, setIsSaving] = useState(false);
+ // Raw field text, so the interval can be cleared before a new number is typed
+ const [intervalDraft, setIntervalDraft] = useState<string | null>(null);
- // Determine if sheet should be in read-only mode
- const isReadOnly = readOnly || !permission.canEdit;
- const initialStateRef = useRef<{
- text: string;
- type: "note" | "event";
- color: string;
- recurringPattern: string;
- recurringInterval: number;
- recurringUnit: string;
- }>({
- text: "",
- type: "note",
- color: "#3b82f6",
- recurringPattern: "none",
- recurringInterval: 1,
- recurringUnit: "months",
- });
-
- // Reset state when dialog opens/closes or note changes
- useEffect(() => {
- if (open) {
- const initialText = note?.note || "";
- const initialType = (note?.type as "note" | "event") || "note";
- const initialColor = note?.color || "#3b82f6";
+ // Reset whenever the sheet opens, closes or switches notes
+ if (source.open !== open || source.note !== note) {
+ setSource({ open, note });
+ setForm(initial);
+ setIntervalDraft(null);
+ }
- // Set recurring pattern from note
- const initialPattern = note?.recurringPattern || "none";
- const initialInterval = note?.recurringInterval || 1;
-
- // Extract unit from pattern: "custom-weeks" or "custom-months"
- let displayPattern = initialPattern;
- let initialUnit = "months";
-
- if (initialPattern?.startsWith("custom-")) {
- displayPattern = "custom";
- initialUnit = initialPattern.split("-")[1] || "months";
- }
+ const isReadOnly = readOnly || !permission.canEdit;
+ const isEvent = form.type === "event";
+ const update = (patch: Partial<NoteFormState>) => setForm((prev) => ({ ...prev, ...patch }));
- setNoteText(initialText);
- setType(initialType);
- setColor(initialColor);
- setRecurringPattern(displayPattern);
- setRecurringInterval(initialInterval);
- setRecurringUnit(initialUnit);
+ const clampInterval = (value: number) => Math.min(MAX_INTERVAL, Math.max(1, value));
- if (note) {
- initialStateRef.current = {
- text: initialText,
- type: initialType,
- color: initialColor,
- recurringPattern: displayPattern,
- recurringInterval: initialInterval,
- recurringUnit: initialUnit,
- };
- }
- } else {
- // Reset to defaults when closing
- setType("note");
- setColor("#3b82f6");
- setRecurringPattern("none");
- setRecurringInterval(1);
- setRecurringUnit("months");
- initialStateRef.current = {
- text: "",
- type: "note",
- color: "#3b82f6",
- recurringPattern: "none",
- recurringInterval: 1,
- recurringUnit: "months",
- };
- }
- }, [open, note]);
+ const commitInterval = () => {
+ const parsed = parseInt(intervalDraft ?? "", 10);
+ if (!Number.isNaN(parsed)) update({ interval: clampInterval(parsed) });
+ setIntervalDraft(null);
+ };
const hasChanges = () => {
if (note) {
- // Edit mode: check if anything changed from initial
return (
- noteText !== initialStateRef.current.text ||
- type !== initialStateRef.current.type ||
- color !== initialStateRef.current.color ||
- recurringPattern !== initialStateRef.current.recurringPattern ||
- recurringInterval !== initialStateRef.current.recurringInterval ||
- recurringUnit !== initialStateRef.current.recurringUnit
+ form.text !== initial.text ||
+ form.type !== initial.type ||
+ form.color !== initial.color ||
+ form.repeat !== initial.repeat ||
+ form.interval !== initial.interval
);
- } else {
- // Create mode: check if any text was entered
- return noteText.trim() !== "";
}
+ return form.text.trim() !== "";
};
const handleSave = async () => {
- if (!noteText.trim() || isSaving) return;
+ if (!form.text.trim() || isSaving) return;
setIsSaving(true);
try {
- // Build pattern with unit: "custom-weeks" or "custom-months"
- const finalPattern =
- recurringPattern === "custom"
- ? `custom-${recurringUnit}`
- : recurringPattern;
+ const pattern =
+ form.repeat === "weeks"
+ ? "custom-weeks"
+ : form.repeat === "none"
+ ? "none"
+ : "custom-months";
+ const interval = form.repeat === "years" ? form.interval * 12 : form.interval;
onSubmit(
- noteText,
- type,
- type === "event" ? color : undefined,
- type === "event" ? finalPattern : undefined,
- type === "event" && recurringPattern === "custom"
- ? recurringInterval
- : undefined
+ form.text,
+ form.type,
+ isEvent ? form.color : undefined,
+ isEvent ? pattern : undefined,
+ isEvent && form.repeat !== "none" ? interval : undefined
);
onOpenChange(false);
} finally {
@@ -188,234 +175,152 @@ export function NoteSheet({
};
const formattedDate = selectedDate
- ? format(selectedDate, "PPP", { locale: dateLocale })
+ ? formatLongDate(selectedDate, locale, { year: true })
: "";
- const customFooter = note ? (
- // Edit mode: Delete button on left, Cancel/Save on right
- <div className="flex gap-2.5 w-full">
- {onDelete && !isReadOnly && (
+ const unitLabel = {
+ none: t("noteSheet.intervalInactive"),
+ weeks: t("noteSheet.unitWeeks", { count: form.interval }),
+ months: t("noteSheet.unitMonths", { count: form.interval }),
+ years: t("noteSheet.unitYears", { count: form.interval }),
+ }[form.repeat];
+
+ const footer = (
+ <>
+ {note && onDelete && !isReadOnly && (
<Button
type="button"
- variant="destructive"
+ variant="outline"
onClick={handleDelete}
disabled={isSaving}
- className="h-11 shadow-lg shadow-destructive/25"
+ className="h-10 border-danger-line font-semibold text-danger hover:bg-danger-soft hover:text-danger"
>
+ <Trash2 className="size-4" />
{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"
+ className="h-10 flex-1 font-semibold"
>
- {t("common.cancel")}
+ {isReadOnly ? t("common.close") : t("common.cancel")}
</Button>
{!isReadOnly && (
<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"
+ disabled={isSaving || !form.text.trim() || (!!note && !hasChanges())}
+ className="h-10 flex-1 font-semibold"
>
- {isSaving ? t("common.saving") : t("common.save")}
+ {isSaving
+ ? t("common.saving")
+ : note
+ ? t("common.save")
+ : t("noteSheet.createAction")}
</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>
- {!isReadOnly && (
- <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>
+ </>
);
- const getSheetTitle = () => {
- const itemType =
- type === "event" ? t("note.typeEvent") : t("note.typeNote");
- if (note) {
- return t("note.edit", { item: itemType });
- }
- return t("note.create", { item: itemType });
- };
-
return (
<BaseSheet
open={open}
onOpenChange={onOpenChange}
- title={getSheetTitle()}
+ title={note ? t("noteSheet.editTitle") : t("noteSheet.createTitle")}
description={formattedDate}
- footer={customFooter}
+ footer={footer}
hasUnsavedChanges={hasChanges()}
- maxWidth="md"
>
- <div className="space-y-6">
- {/* Read-Only Banner */}
+ <div className="flex flex-col gap-4">
{isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
- {/* Recurring Event Warning */}
- {note &&
- type === "event" &&
- note.recurringPattern &&
- note.recurringPattern !== "none" && (
- <Alert className="border-amber-500/50 bg-amber-50/50 dark:bg-amber-950/20">
- <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-500" />
- <AlertDescription className="text-sm text-amber-800 dark:text-amber-200">
- {t("note.recurringEditWarning")}
- </AlertDescription>
- </Alert>
- )}
+ {note && isEvent && note.recurringPattern && note.recurringPattern !== "none" && (
+ <StatusBanner tone="warning" icon={TriangleAlert}>
+ {t("note.recurringEditWarning")}
+ </StatusBanner>
+ )}
- {/* Type Selection */}
- <div className="space-y-3">
- <Label className="text-sm font-medium">{t("note.type")}</Label>
- <RadioGroup
- value={type}
- onValueChange={(value) => setType(value as "note" | "event")}
- className="flex gap-4"
+ <SegmentedControl<NoteType>
+ label={t("note.type")}
+ size="lg"
+ value={form.type}
+ onChange={(type) => !isReadOnly && update({ type })}
+ options={[
+ { value: "event", label: t("noteSheet.typeEvent") },
+ { value: "note", label: t("noteSheet.typeNote") },
+ ]}
+ />
+
+ <InfoNote icon={Info}>{t("noteSheet.typeHint")}</InfoNote>
+
+ <Field label={t("noteSheet.text")} htmlFor="note-text">
+ <Textarea
+ id="note-text"
+ value={form.text}
+ onChange={(e) => update({ text: e.target.value })}
+ placeholder={isEvent ? t("note.eventPlaceholder") : t("note.placeholder")}
+ rows={3}
+ className={cn(textareaClass, "min-h-[74px]")}
disabled={isReadOnly}
- >
- <div className="flex items-center space-x-2">
- <RadioGroupItem
- value="note"
- id="type-note"
- disabled={isReadOnly}
- />
- <Label htmlFor="type-note" className="cursor-pointer font-normal">
- {t("note.typeNote")}
- </Label>
- </div>
- <div className="flex items-center space-x-2">
- <RadioGroupItem
- value="event"
- id="type-event"
+ />
+ </Field>
+
+ {isEvent && (
+ <>
+ <Field label={t("note.eventColor")}>
+ <ColorSwatches
+ value={form.color}
+ onChange={(color) => update({ color })}
+ allowCustom
disabled={isReadOnly}
/>
- <Label
- htmlFor="type-event"
- className="cursor-pointer font-normal"
- >
- {t("note.typeEvent")}
- </Label>
- </div>
- </RadioGroup>
- </div>
-
- {/* Event Options */}
- {type === "event" && (
- <div className="space-y-4 pl-6 border-l-2 border-border/50">
- {/* Color Selection */}
- <ColorPicker
- color={color}
- onChange={setColor}
- label={t("note.eventColor")}
- presetColors={PRESET_COLORS}
- disabled={isReadOnly}
- />
+ </Field>
- {/* Recurring Pattern */}
- <div className="space-y-2">
- <Label className="text-sm font-medium">
- {t("note.recurring")}
- </Label>
- <Select
- value={recurringPattern}
- onValueChange={setRecurringPattern}
+ <Field label={t("noteSheet.repeat")}>
+ <ChoiceChips<Repeat>
+ label={t("noteSheet.repeat")}
+ value={form.repeat}
+ onChange={(repeat) => update({ repeat })}
disabled={isReadOnly}
+ options={[
+ { value: "none", label: t("noteSheet.repeatNone") },
+ { value: "weeks", label: t("noteSheet.repeatWeekly") },
+ { value: "months", label: t("noteSheet.repeatMonthly") },
+ { value: "years", label: t("noteSheet.repeatYearly") },
+ ]}
+ />
+ <div
+ className={cn(
+ "flex items-center gap-2.5 text-[13px] text-fg-body",
+ form.repeat === "none" && "opacity-45"
+ )}
>
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="none">
- {t("note.recurringNone")}
- </SelectItem>
- <SelectItem value="custom">
- {t("note.recurringCustom")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- {/* Custom Interval */}
- {recurringPattern === "custom" && (
- <div className="space-y-2">
- <Label className="text-sm font-medium">
- {t("note.customInterval")}
- </Label>
- <div className="flex items-center gap-2">
- <span className="text-sm text-muted-foreground whitespace-nowrap">
- {t("note.every")}
- </span>
- <Input
- type="number"
- min={1}
- max={52}
- value={recurringInterval}
- onChange={(e) =>
- setRecurringInterval(parseInt(e.target.value) || 1)
- }
- className="w-20"
- disabled={isReadOnly}
- />
- <Select
- value={recurringUnit}
- onValueChange={setRecurringUnit}
- disabled={isReadOnly}
- >
- <SelectTrigger className="flex-1">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="weeks">{t("note.weeks")}</SelectItem>
- <SelectItem value="months">{t("note.months")}</SelectItem>
- </SelectContent>
- </Select>
- </div>
+ <span>{t("note.every")}</span>
+ <Input
+ type="number"
+ inputMode="numeric"
+ min={1}
+ max={MAX_INTERVAL}
+ aria-label={t("note.customInterval")}
+ value={intervalDraft ?? String(form.interval)}
+ onChange={(e) => {
+ const raw = e.target.value;
+ setIntervalDraft(raw);
+ const parsed = parseInt(raw, 10);
+ if (parsed >= 1 && parsed <= MAX_INTERVAL) update({ interval: parsed });
+ }}
+ onBlur={commitInterval}
+ disabled={isReadOnly || form.repeat === "none"}
+ className={cn(zoomSafeText, "h-[34px] w-[58px] rounded-lg px-2 text-center font-mono")}
+ />
+ <span>{unitLabel}</span>
</div>
- )}
- </div>
+ </Field>
+ </>
)}
-
- {/* Note Text */}
- <div className="space-y-3">
- <Label htmlFor="note-text" className="text-sm font-medium">
- {type === "event" ? t("note.eventTitle") : t("note.note")}
- </Label>
- <Textarea
- id="note-text"
- value={noteText}
- onChange={(e) => setNoteText(e.target.value)}
- placeholder={
- type === "event"
- ? t("note.eventPlaceholder")
- : t("note.placeholder")
- }
- className="min-h-[200px] resize-none focus-visible:ring-primary/30 border-border/50"
- disabled={isReadOnly}
- />
- </div>
</div>
</BaseSheet>
);
diff --git a/components/notes-list-dialog.tsx b/components/notes-list-dialog.tsx
index 63732ef..59e52b0 100644
--- a/components/notes-list-dialog.tsx
+++ b/components/notes-list-dialog.tsx
@@ -1,21 +1,16 @@
"use client";
+import { useLocale, useTranslations } from "next-intl";
+import { formatLongDate } from "@/lib/date-utils";
+import { CalendarClock, Keyboard, Pencil, Plus, StickyNote, Trash2 } from "lucide-react";
import { CalendarNote } from "@/lib/db/schema";
-import { useTranslations, useLocale } from "next-intl";
-import { format } from "date-fns";
-import { getDateLocale } from "@/lib/locales";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
-import { Pencil, Trash2, Plus, Calendar } from "lucide-react";
-import { Badge } from "@/components/ui/badge";
+import { PanelDialog } from "@/components/panel-dialog";
+import { InfoNote, ListRow, Pill, RowIconButton } from "@/components/form-kit";
import { ReadOnlyBanner } from "@/components/read-only-banner";
+import { parseRecurrence } from "@/components/note-sheet";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { shiftVars } from "@/lib/shift-display";
interface NotesListDialogProps {
open: boolean;
@@ -29,6 +24,73 @@ interface NotesListDialogProps {
readOnly?: boolean;
}
+// Plain notes carry no color of their own
+const NOTE_COLOR = "#d97706";
+
+function NoteRow({
+ note,
+ editable,
+ onEdit,
+ onDelete,
+}: {
+ note: CalendarNote;
+ editable: boolean;
+ onEdit: () => void;
+ onDelete: () => void;
+}) {
+ const t = useTranslations();
+ const isEvent = note.type === "event";
+ const Icon = isEvent ? CalendarClock : StickyNote;
+ const [title, ...rest] = note.note.trim().split("\n");
+ const subtitle = rest.join(" ").trim();
+ const color = shiftVars(isEvent ? note.color : NOTE_COLOR);
+
+ const { repeat, interval } = parseRecurrence(note.recurringPattern, note.recurringInterval);
+ const recurrence = !isEvent
+ ? null
+ : repeat === "weeks"
+ ? t("noteSheet.recurrenceWeeks", { count: interval })
+ : repeat === "months"
+ ? t("noteSheet.recurrenceMonths", { count: interval })
+ : repeat === "years"
+ ? t("noteSheet.recurrenceYears", { count: interval })
+ : null;
+
+ const pills = (
+ <>
+ {recurrence && <Pill className="text-[11px]">{recurrence}</Pill>}
+ <span
+ className="shift-chip whitespace-nowrap rounded-full px-[7px] py-0.5 text-[11px] font-semibold"
+ style={color}
+ >
+ {isEvent ? t("noteSheet.typeEvent") : t("noteSheet.typeNote")}
+ </span>
+ </>
+ );
+
+ return (
+ <ListRow className="gap-[11px] px-3 py-[11px]">
+ <span className="shift-rail h-[30px] w-[3px] shrink-0 rounded-full" style={color} />
+ <Icon className="shift-text size-4 shrink-0" style={color} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">{title}</div>
+ {subtitle && (
+ <div className="mt-0.5 truncate text-[12px] text-fg-tertiary">{subtitle}</div>
+ )}
+ {/* Narrow rows move the pills under the text so the title keeps its room */}
+ <div className="mt-1.5 flex flex-wrap gap-1.5 sm:hidden">{pills}</div>
+ </div>
+ <div className="hidden shrink-0 items-center gap-1.5 sm:flex">{pills}</div>
+ {editable && (
+ <div className="-mr-1.5 flex shrink-0 items-center">
+ <RowIconButton icon={Pencil} label={t("noteSheet.editTitle")} onClick={onEdit} />
+ <RowIconButton icon={Trash2} label={t("common.delete")} onClick={onDelete} tone="danger" />
+ </div>
+ )}
+ </ListRow>
+ );
+}
+
export function NotesListDialog({
open,
onOpenChange,
@@ -42,201 +104,71 @@ export function NotesListDialog({
}: NotesListDialogProps) {
const t = useTranslations();
const locale = useLocale();
- const dateLocale = getDateLocale(locale);
const permission = useCalendarPermission(calendarId);
-
- // Determine if dialog should be in read-only mode
const isReadOnly = readOnly || !permission.canEdit;
- const formattedDate = format(date, "EEEE, dd. MMMM yyyy", {
- locale: dateLocale,
- });
-
- const events = notes.filter((n) => n.type === "event");
- const regularNotes = notes.filter((n) => n.type !== "event");
-
- const getRecurringLabel = (note: CalendarNote) => {
- if (!note.recurringPattern || note.recurringPattern === "none") {
- return null;
- }
+ const formattedDate = formatLongDate(date, locale, { year: true });
- if (note.recurringPattern === "custom-weeks") {
- return t("note.recurringEveryWeeks", {
- count: note.recurringInterval || 1,
- });
- }
+ // Events first, then plain notes
+ const entries = [
+ ...notes.filter((n) => n.type === "event"),
+ ...notes.filter((n) => n.type !== "event"),
+ ];
- if (note.recurringPattern === "custom-months") {
- return t("note.recurringEveryMonths", {
- count: note.recurringInterval || 1,
- });
- }
-
- return null;
+ const handleAdd = () => {
+ onOpenChange(false);
+ onAddNew();
};
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-2xl 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("note.typeNote")} & {t("note.typeEvent")}
- </DialogTitle>
- <DialogDescription className="text-sm text-muted-foreground">
- {formattedDate}
- </DialogDescription>
- </DialogHeader>
-
- {/* Read-Only Banner */}
- {isReadOnly && (
- <div className="px-6 pt-6">
- <ReadOnlyBanner message={t("guest.cannotEdit")} />
- </div>
- )}
-
- <div className="space-y-6 overflow-y-auto flex-1 p-6">
- {/* Events Section */}
- {events.length > 0 && (
- <div className="space-y-3">
- <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
- {t("note.typeEvent")} ({events.length})
- </h3>
- <div className="space-y-2">
- {events.map((event) => (
- <div
- key={event.id}
- className="p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
- style={{
- borderLeftColor: event.color || "#3b82f6",
- borderLeftWidth: 4,
- }}
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <div
- className="w-1 h-4 rounded-full"
- style={{
- backgroundColor: event.color || "#3b82f6",
- }}
- />
- <h4 className="font-semibold text-base truncate">
- {event.note}
- </h4>
- {getRecurringLabel(event) && (
- <Badge
- variant="secondary"
- className="text-xs shrink-0"
- >
- {getRecurringLabel(event)}
- </Badge>
- )}
- </div>
- </div>
- {!isReadOnly && (
- <div className="flex gap-1.5 shrink-0 ml-auto">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onEditNote(event)}
- className="h-8 w-8 hover:bg-background/50"
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onDeleteNote(event.id)}
- className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- )}
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* Notes Section */}
- {regularNotes.length > 0 && (
- <div className="space-y-3">
- <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
- {t("note.typeNote")} ({regularNotes.length})
- </h3>
- <div className="space-y-2">
- {regularNotes.map((note) => (
- <div
- key={note.id}
- className="p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex-1 min-w-0">
- <p className="text-sm text-foreground whitespace-pre-wrap break-words">
- {note.note}
- </p>
- </div>
- {!isReadOnly && (
- <div className="flex gap-1.5 shrink-0 ml-auto">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onEditNote(note)}
- className="h-8 w-8"
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => onDeleteNote(note.id)}
- className="h-8 w-8 hover:bg-destructive/10 hover:text-destructive"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- )}
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* Empty State */}
- {notes.length === 0 && (
- <div className="text-center py-12 text-muted-foreground">
- <Calendar className="h-12 w-12 mx-auto mb-3 opacity-30" />
- <p className="text-sm">{t("note.noEntries")}</p>
- </div>
- )}
- </div>
-
- {/* Footer with Add Button */}
- <div className="flex justify-between items-center gap-3 p-6 pt-4 border-t border-border/50 bg-gradient-to-r from-muted/20 via-muted/10 to-transparent">
- <Button
- variant="outline"
- onClick={() => onOpenChange(false)}
- className="border-border/50"
- >
- {t("common.cancel")}
- </Button>
- {!isReadOnly && (
- <Button
- onClick={() => {
- onOpenChange(false);
- onAddNew();
- }}
- className="bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"
- >
- <Plus className="h-4 w-4 mr-2" />
- {t("common.add")}
- </Button>
- )}
- </div>
- </DialogContent>
- </Dialog>
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("noteSheet.listTitle")}
+ description={`${formattedDate} · ${t("noteSheet.entryCount", { count: notes.length })}`}
+ width="md"
+ bodyClassName="flex flex-col gap-[9px] py-4"
+ footer={
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.close")}
+ </Button>
+ }
+ >
+ {isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
+
+ {entries.length === 0 && (
+ <p className="py-6 text-center text-[13px] text-fg-tertiary">{t("note.noEntries")}</p>
+ )}
+
+ {entries.map((note) => (
+ <NoteRow
+ key={note.id}
+ note={note}
+ editable={!isReadOnly}
+ onEdit={() => onEditNote(note)}
+ onDelete={() => onDeleteNote(note.id)}
+ />
+ ))}
+
+ {!isReadOnly && (
+ <button
+ type="button"
+ onClick={handleAdd}
+ className="flex items-center justify-center gap-2 rounded-[10px] border border-dashed border-control p-[11px] text-[13.5px] font-medium text-fg-secondary transition-colors hover:bg-surface-panel"
+ >
+ <Plus className="size-4" />
+ {entries.length > 0 ? t("noteSheet.addAnother") : t("noteSheet.createAction")}
+ </button>
+ )}
+
+ <InfoNote icon={Keyboard} className="mt-2">
+ {t("noteSheet.shortcutHint")}
+ </InfoNote>
+ </PanelDialog>
);
}
diff --git a/components/panel-dialog.tsx b/components/panel-dialog.tsx
new file mode 100644
index 0000000..01eed44
--- /dev/null
+++ b/components/panel-dialog.tsx
@@ -0,0 +1,239 @@
+"use client";
+
+import { ReactNode, useEffect } from "react";
+import { useTranslations } from "next-intl";
+import { X } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Drawer,
+ DrawerContent,
+ DrawerDescription,
+ DrawerTitle,
+} from "@/components/ui/drawer";
+import { useKeyboardInset } from "@/hooks/useKeyboardInset";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { cn } from "@/lib/utils";
+
+const WIDTHS = {
+ sm: "sm:max-w-[420px]",
+ md: "sm:max-w-[480px]",
+ lg: "sm:max-w-[640px]",
+ xl: "sm:max-w-[840px]",
+};
+
+export type PanelWidth = keyof typeof WIDTHS;
+
+/** Air kept between the focused field and the keyboard edge */
+const FIELD_MARGIN = 20;
+/** Rounded top corners stay visible even on a full-height phone sheet */
+const SHEET_TOP_GAP = 12;
+
+/**
+ * Scrolls the panel body only. Scrolling the document instead would drag the
+ * fixed sheet along and push the field back out of view.
+ */
+function revealInPanel(field: HTMLElement) {
+ const scroller = field.closest<HTMLElement>("[data-panel-scroll]");
+ if (!scroller) return;
+
+ const target = field.getBoundingClientRect();
+ const box = scroller.getBoundingClientRect();
+ const below = target.bottom + FIELD_MARGIN - box.bottom;
+ const above = box.top - (target.top - FIELD_MARGIN);
+
+ if (below > 0) scroller.scrollTop += below;
+ else if (above > 0) scroller.scrollTop -= above;
+}
+
+/** Waits for the sheet to settle at its new size before measuring the field. */
+function scheduleReveal(field: HTMLElement) {
+ return requestAnimationFrame(() => revealInPanel(field));
+}
+
+/** Scrollable body of a panel; use inside `bare` panels or settings sections. */
+export function PanelBody({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ data-panel-scroll=""
+ className={cn("min-h-0 flex-1 overflow-y-auto px-[22px] py-[18px]", className)}
+ >
+ {children}
+ </div>
+ );
+}
+
+/** Action row pinned to the bottom of a panel. */
+export function PanelFooter({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex shrink-0 items-center gap-2.5 border-t border-line px-[22px] pb-[max(16px,env(safe-area-inset-bottom))] pt-4 lg:pb-4",
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function PanelCloseButton({ onClick }: { onClick: () => void }) {
+ const t = useTranslations();
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={t("common.close")}
+ className="flex size-[34px] shrink-0 items-center justify-center rounded-lg border border-line text-fg-secondary transition-colors hover:bg-surface-panel"
+ >
+ <X className="size-4" />
+ </button>
+ );
+}
+
+export interface PanelDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: ReactNode;
+ description?: ReactNode;
+ /** Shown left of the title, e.g. a status icon */
+ headerLeading?: ReactNode;
+ children: ReactNode;
+ footer?: ReactNode;
+ width?: PanelWidth;
+ bodyClassName?: string;
+ /** Children render their own PanelBody/PanelFooter */
+ bare?: boolean;
+ /** Desktop-only fixed height, for layouts with an inner sidebar */
+ fixedHeight?: string;
+}
+
+/** Design-system panel: a centered dialog on desktop, a bottom sheet on phones. */
+export function PanelDialog({
+ open,
+ onOpenChange,
+ title,
+ description,
+ headerLeading,
+ children,
+ footer,
+ width = "md",
+ bodyClassName,
+ bare = false,
+ fixedHeight,
+}: PanelDialogProps) {
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const keyboard = useKeyboardInset(open && !desktop);
+ const close = () => onOpenChange(false);
+
+ // The sheet has just been resized around the keyboard; bring the field back into view
+ useEffect(() => {
+ if (!keyboard) return;
+ const field = document.activeElement;
+ if (!(field instanceof HTMLElement)) return;
+
+ const frame = scheduleReveal(field);
+ return () => cancelAnimationFrame(frame);
+ }, [keyboard]);
+
+ const content = bare ? (
+ children
+ ) : (
+ <>
+ <PanelBody className={bodyClassName}>{children}</PanelBody>
+ {footer && <PanelFooter>{footer}</PanelFooter>}
+ </>
+ );
+
+ const TitleEl = desktop ? DialogTitle : DrawerTitle;
+ const DescriptionEl = desktop ? DialogDescription : DrawerDescription;
+ const header = (
+ <div
+ className={cn(
+ "flex shrink-0 items-start gap-3 border-b border-line px-[22px]",
+ desktop ? "pb-4 pt-5" : "pb-3.5 pt-1.5"
+ )}
+ >
+ {headerLeading}
+ <div className="min-w-0 flex-1">
+ <TitleEl
+ className={cn(
+ "font-semibold leading-tight tracking-[-0.01em] text-fg-strong",
+ desktop ? "text-[19px]" : "text-[17px]"
+ )}
+ >
+ {title}
+ </TitleEl>
+ <DescriptionEl
+ className={cn("mt-1 text-fg-secondary", desktop ? "text-[13.5px]" : "text-[13px]", !description && "sr-only")}
+ >
+ {description ?? title}
+ </DescriptionEl>
+ </div>
+ <PanelCloseButton onClick={close} />
+ </div>
+ );
+
+ if (desktop) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ showCloseButton={false}
+ className={cn(
+ "flex max-h-[min(860px,calc(100dvh-48px))] flex-col gap-0 overflow-hidden rounded-2xl border-control p-0 shadow-window",
+ WIDTHS[width]
+ )}
+ style={fixedHeight ? { height: fixedHeight } : undefined}
+ >
+ {header}
+ {content}
+ </DialogContent>
+ </Dialog>
+ );
+ }
+
+ return (
+ // repositionInputs off: vaul moves the whole sheet by the keyboard height,
+ // which pushes the header and long bodies off screen. useKeyboardInset
+ // pins the sheet to the visible area instead.
+ <Drawer open={open} onOpenChange={onOpenChange} repositionInputs={false}>
+ <DrawerContent
+ className="rounded-t-[18px] border-line bg-background shadow-sheet data-[vaul-drawer-direction=bottom]:max-h-[calc(100dvh-12px)] data-[vaul-drawer-direction=bottom]:rounded-t-[18px] dark:bg-surface-panel [&>div:first-child]:hidden"
+ style={
+ keyboard
+ ? {
+ bottom: keyboard.bottom,
+ maxHeight: keyboard.viewportHeight - SHEET_TOP_GAP,
+ }
+ : undefined
+ }
+ // Moving between fields while the keyboard is already up changes no viewport
+ onFocusCapture={(event) => {
+ if (keyboard) scheduleReveal(event.target as HTMLElement);
+ }}
+ >
+ <div className="flex shrink-0 justify-center pb-1 pt-2">
+ <span className="h-1 w-[34px] rounded-full bg-control" />
+ </div>
+ {header}
+ {content}
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/components/phone-menu.tsx b/components/phone-menu.tsx
new file mode 100644
index 0000000..f8a6249
--- /dev/null
+++ b/components/phone-menu.tsx
@@ -0,0 +1,434 @@
+"use client";
+
+import { ReactNode, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { useRouter } from "next/navigation";
+import { useTheme } from "next-themes";
+import {
+ ArrowLeft,
+ ChevronRight,
+ Compass,
+ FileText,
+ Languages,
+ Loader2,
+ LogIn,
+ LogOut,
+ ScrollText,
+ Shield,
+ SlidersHorizontal,
+ SunMoon,
+ User,
+ type LucideIcon,
+} from "lucide-react";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { PanelBody, PanelDialog } from "@/components/panel-dialog";
+import { AppearancePicker, useThemeOptions } from "@/components/appearance-picker";
+import { PersonalViewPanel, ViewSettingsState } from "@/components/view-settings-sheet";
+import {
+ CalendarSettingsPanel,
+ SettingsItem,
+ SettingsSection,
+ useCalendarSettings,
+} from "@/components/settings-dialog";
+import { ChangelogDialog } from "@/components/changelog-dialog";
+import { CalendarDiscoverySheet } from "@/components/calendar-discovery-sheet";
+import { setLocaleCookie } from "@/components/app-preferences-menu-items";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { useIsAdmin } from "@/hooks/useAdminAccess";
+import { useVersionInfo } from "@/hooks/useVersionInfo";
+import { useViewSettings } from "@/hooks/useViewSettings";
+import { useSignOut } from "@/hooks/useSignOut";
+import { locales } from "@/lib/locales";
+import { CalendarWithCount } from "@/lib/types";
+import { cn } from "@/lib/utils";
+import { useGuardedAction } from "@/hooks/useDirtyState";
+
+type MenuSection = SettingsSection | "myView" | "appearance" | "language";
+
+/** What the calendar page hands in: the selected calendar and the page's view state. */
+export interface PhoneMenuCalendarContext {
+ calendarId: string | null;
+ viewSettings: ViewSettingsState;
+ onDeleteCalendar: () => void;
+ onSyncComplete: () => void;
+}
+
+interface PhoneMenuProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Calendar page only; elsewhere the sheet shows just the personal and account groups */
+ context?: PhoneMenuCalendarContext;
+}
+
+interface CalendarGroup extends Omit<PhoneMenuCalendarContext, "calendarId"> {
+ calendarId: string;
+ calendar: CalendarWithCount;
+ items: SettingsItem[];
+}
+
+/** Phones: calendar settings, personal preferences and account in one sheet behind the avatar. */
+export function PhoneMenu({ context, ...props }: PhoneMenuProps) {
+ if (context?.calendarId) {
+ return <CalendarPhoneMenu {...props} context={context} calendarId={context.calendarId} />;
+ }
+ return <PhoneMenuSheet {...props} viewSettings={context?.viewSettings} />;
+}
+
+// Calendar hooks live here so pages without a calendar never fetch calendar data
+function CalendarPhoneMenu({
+ context,
+ calendarId,
+ ...props
+}: Omit<PhoneMenuProps, "context"> & { context: PhoneMenuCalendarContext; calendarId: string }) {
+ const { calendar, items } = useCalendarSettings(calendarId);
+ return (
+ <PhoneMenuSheet
+ {...props}
+ viewSettings={context.viewSettings}
+ calendarGroup={calendar ? { ...context, calendarId, calendar, items } : undefined}
+ />
+ );
+}
+
+function LanguagePanel() {
+ const t = useTranslations();
+ const current = useLocale();
+ return (
+ <PanelBody>
+ <div className="flex flex-col gap-2">
+ {locales.map((locale) => (
+ <button
+ key={locale}
+ type="button"
+ onClick={() => locale !== current && setLocaleCookie(locale)}
+ className={cn(
+ "flex items-center justify-between rounded-[10px] border-[1.5px] px-3 py-3 text-left text-[14px] font-semibold",
+ locale === current
+ ? "border-brand bg-surface-today text-brand-ink"
+ : "border-line bg-surface-card text-fg-strong"
+ )}
+ >
+ {t(`language.${locale}`)}
+ <span className="font-mono text-[12px] uppercase text-fg-tertiary">{locale}</span>
+ </button>
+ ))}
+ </div>
+ </PanelBody>
+ );
+}
+
+/** Pages without the calendar page's view state load it only when the section opens. */
+function StandalonePersonalViewPanel() {
+ const settings = useViewSettings();
+ if (settings.loading) {
+ return (
+ <PanelBody>
+ <div className="flex justify-center py-10 text-fg-tertiary">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ </PanelBody>
+ );
+ }
+ return <PersonalViewPanel settings={settings} />;
+}
+
+function MenuGroup({
+ label,
+ caption,
+ children,
+}: {
+ label: ReactNode;
+ caption?: string;
+ children: ReactNode;
+}) {
+ return (
+ <section>
+ <div className="mb-2 px-1">
+ <div className="eyebrow flex min-w-0 items-center gap-2">{label}</div>
+ {caption && <p className="mt-0.5 text-[12px] text-fg-tertiary">{caption}</p>}
+ </div>
+ <div className="divide-y divide-line-subtle overflow-hidden rounded-[12px] border border-line bg-surface-card">
+ {children}
+ </div>
+ </section>
+ );
+}
+
+function MenuRow({
+ icon: Icon,
+ title,
+ meta,
+ mono = false,
+ metaTone,
+ danger = false,
+ onClick,
+}: {
+ icon: LucideIcon;
+ title: string;
+ meta?: ReactNode;
+ mono?: boolean;
+ metaTone?: "danger";
+ /** Destructive action: danger colour, no chevron */
+ danger?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="flex min-h-11 w-full items-center gap-3 px-3.5 py-3 text-left"
+ >
+ <Icon className={cn("size-[18px] shrink-0", danger ? "text-danger" : "text-fg-secondary")} />
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate text-[14.5px]",
+ danger ? "font-medium text-danger" : "text-fg-strong"
+ )}
+ >
+ {title}
+ </span>
+ {meta !== undefined && meta !== null && (
+ <span
+ className={cn(
+ "shrink-0",
+ mono ? "font-mono text-[12.5px]" : "text-[13px]",
+ metaTone === "danger" ? "font-semibold text-danger" : "text-fg-tertiary"
+ )}
+ >
+ {meta}
+ </span>
+ )}
+ {!danger && <ChevronRight className="size-4 shrink-0 text-fg-tertiary" />}
+ </button>
+ );
+}
+
+function AppVersion() {
+ return useVersionInfo()?.version ?? null;
+}
+
+function PhoneMenuSheet({
+ open,
+ onOpenChange,
+ viewSettings,
+ calendarGroup,
+}: Omit<PhoneMenuProps, "context"> & {
+ viewSettings?: ViewSettingsState;
+ calendarGroup?: CalendarGroup;
+}) {
+ const t = useTranslations();
+ const handleSignOut = useSignOut();
+ const locale = useLocale();
+ const router = useRouter();
+ const { theme } = useTheme();
+ const themeOptions = useThemeOptions();
+ const { user, isGuest } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+ const isAdmin = useIsAdmin();
+ const [section, setSection] = useState<MenuSection | null>(null);
+ const [dirty, setDirty] = useState(false);
+
+ const [changelogOpen, setChangelogOpen] = useState(false);
+ const [discoveryOpen, setDiscoveryOpen] = useState(false);
+
+ // Every open starts at the list, however the sheet was closed last time
+ const [wasOpen, setWasOpen] = useState(open);
+ if (open !== wasOpen) {
+ setWasOpen(open);
+ if (open) {
+ setSection(null);
+ setDirty(false);
+ }
+ }
+
+ const signedIn = isAuthEnabled && !!user && !isGuest;
+
+ const close = () => {
+ setDirty(false);
+ onOpenChange(false);
+ };
+ // Sections with unsaved input report it; leaving them asks first
+ const { guarded, confirmProps } = useGuardedAction(dirty, () => setDirty(false));
+ const openSection = (id: MenuSection | null) =>
+ guarded(() => {
+ setDirty(false);
+ setSection(id);
+ });
+ const navigate = (href: string) => {
+ close();
+ router.push(href);
+ };
+
+ const calendarItem = calendarGroup?.items.find((item) => item.id === section);
+ let title = t("settings.title");
+ let description: string | undefined;
+ let panel: ReactNode = null;
+ if (section === "myView") {
+ title = t("view.settingsTitle");
+ description =
+ isAuthEnabled && user ? t("view.settingsDescription") : t("view.settingsDescriptionLocal");
+ panel = viewSettings ? (
+ <PersonalViewPanel settings={viewSettings} calendarId={calendarGroup?.calendarId} />
+ ) : (
+ <StandalonePersonalViewPanel />
+ );
+ } else if (section === "appearance") {
+ title = t("appearance.title");
+ panel = (
+ <PanelBody>
+ <AppearancePicker />
+ </PanelBody>
+ );
+ } else if (section === "language") {
+ title = t("appMenu.language");
+ panel = <LanguagePanel />;
+ } else if (calendarGroup && calendarItem) {
+ title = calendarItem.title;
+ description = calendarItem.description;
+ panel = (
+ <CalendarSettingsPanel
+ section={calendarItem.id}
+ calendarId={calendarGroup.calendarId}
+ viewSettings={calendarGroup.viewSettings}
+ onClose={close}
+ onCancel={() => guarded(close)}
+ onDirtyChange={setDirty}
+ onDeleteCalendar={calendarGroup.onDeleteCalendar}
+ onSyncComplete={calendarGroup.onSyncComplete}
+ />
+ );
+ }
+ const inSection = panel !== null;
+
+ const themeTitle = (themeOptions.find((o) => o.value === theme) ?? themeOptions[0]).title;
+ const changelogRow = (
+ <MenuRow
+ icon={ScrollText}
+ title={t("changelog.title")}
+ meta={<AppVersion />}
+ mono
+ onClick={() => setChangelogOpen(true)}
+ />
+ );
+
+ return (
+ <>
+ <PanelDialog
+ bare
+ open={open}
+ onOpenChange={(next) => (next ? onOpenChange(true) : guarded(close))}
+ headerLeading={
+ inSection ? (
+ <button
+ type="button"
+ onClick={() => openSection(null)}
+ aria-label={t("common.previous")}
+ className="-ml-1 flex size-[34px] shrink-0 items-center justify-center rounded-lg text-fg-secondary"
+ >
+ <ArrowLeft className="size-5" />
+ </button>
+ ) : undefined
+ }
+ title={title}
+ description={description}
+ >
+ {inSection ? (
+ <div key={section} className="flex min-h-0 flex-1 flex-col">
+ {panel}
+ </div>
+ ) : (
+ <PanelBody className="bg-surface-panel px-4">
+ <div className="flex flex-col gap-5">
+ {calendarGroup && calendarGroup.items.length > 0 && (
+ <MenuGroup
+ label={
+ <>
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ backgroundColor: calendarGroup.calendar.color }}
+ />
+ <span className="truncate">{calendarGroup.calendar.name}</span>
+ </>
+ }
+ caption={t("settings.description")}
+ >
+ {calendarGroup.items.map((item) => (
+ <MenuRow
+ key={item.id}
+ icon={item.icon}
+ title={item.title}
+ meta={item.meta}
+ mono={typeof item.meta === "number"}
+ metaTone={item.metaTone}
+ onClick={() => openSection(item.id)}
+ />
+ ))}
+ </MenuGroup>
+ )}
+ <MenuGroup label={t("settings.groupPersonal")} caption={t("settings.personalCaption")}>
+ <MenuRow
+ icon={SlidersHorizontal}
+ title={t("appMenu.viewSettings")}
+ onClick={() => openSection("myView")}
+ />
+ <MenuRow
+ icon={SunMoon}
+ title={t("appearance.title")}
+ meta={themeTitle}
+ onClick={() => openSection("appearance")}
+ />
+ <MenuRow
+ icon={Languages}
+ title={t("appMenu.language")}
+ meta={t(`language.${locale}`)}
+ onClick={() => openSection("language")}
+ />
+ </MenuGroup>
+ {signedIn ? (
+ <MenuGroup
+ label={
+ <>
+ <span className="shrink-0">{t("settings.groupAccount")}</span>
+ <span aria-hidden className="shrink-0">·</span>
+ <span className="truncate font-normal normal-case tracking-normal">
+ {user.email}
+ </span>
+ </>
+ }
+ >
+ <MenuRow icon={User} title={t("auth.profile")} onClick={() => navigate("/profile")} />
+ <MenuRow
+ icon={FileText}
+ title={t("activityLog.title")}
+ onClick={() => navigate("/profile?section=activity")}
+ />
+ <MenuRow
+ icon={Compass}
+ title={t("calendar.browseCalendars")}
+ onClick={() => setDiscoveryOpen(true)}
+ />
+ {isAdmin && (
+ <MenuRow icon={Shield} title={t("admin.adminPanel")} onClick={() => navigate("/admin")} />
+ )}
+ {changelogRow}
+ <MenuRow icon={LogOut} title={t("auth.logout")} danger onClick={handleSignOut} />
+ </MenuGroup>
+ ) : (
+ <MenuGroup label={t("settings.groupApp")}>
+ {changelogRow}
+ {isAuthEnabled && (
+ <MenuRow icon={LogIn} title={t("auth.login")} onClick={() => navigate("/login")} />
+ )}
+ </MenuGroup>
+ )}
+ </div>
+ </PanelBody>
+ )}
+ </PanelDialog>
+ <ChangelogDialog open={changelogOpen} onOpenChange={setChangelogOpen} locale={locale} />
+ {signedIn && <CalendarDiscoverySheet open={discoveryOpen} onOpenChange={setDiscoveryOpen} />}
+ <ConfirmationDialog {...confirmProps} />
+ </>
+ );
+}
diff --git a/components/preset-form.tsx b/components/preset-form.tsx
new file mode 100644
index 0000000..2f4f3e0
--- /dev/null
+++ b/components/preset-form.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { Ref, useId } from "react";
+import { useTranslations } from "next-intl";
+import { Input } from "@/components/ui/input";
+import { CheckRow, ColorSwatches, Field, inputClass } from "@/components/form-kit";
+import { ShiftPreset } from "@/lib/db/schema";
+import { DEFAULT_COLOR } from "@/lib/constants";
+import type { PresetFormData } from "@/hooks/usePresets";
+import { cn } from "@/lib/utils";
+
+export const EMPTY_PRESET_FORM: PresetFormData = {
+ title: "",
+ startTime: "09:00",
+ endTime: "17:00",
+ color: DEFAULT_COLOR,
+ notes: "",
+ isSecondary: false,
+ isAllDay: false,
+ hideFromStats: false,
+};
+
+export function presetToFormData(preset: ShiftPreset): PresetFormData {
+ return {
+ title: preset.title,
+ startTime: preset.startTime,
+ endTime: preset.endTime,
+ color: preset.color,
+ notes: preset.notes || "",
+ isSecondary: preset.isSecondary || false,
+ isAllDay: preset.isAllDay || false,
+ hideFromStats: preset.hideFromStats || false,
+ };
+}
+
+export function samePresetForm(a: PresetFormData, b: PresetFormData): boolean {
+ return (Object.keys(a) as (keyof PresetFormData)[]).every((key) => a[key] === b[key]);
+}
+
+
+interface PresetFormCardProps {
+ formId: string;
+ editing: boolean;
+ value: PresetFormData;
+ onChange: (patch: Partial<PresetFormData>) => void;
+ onSubmit: () => void;
+ disabled?: boolean;
+ cardRef?: Ref<HTMLFormElement>;
+ titleRef?: Ref<HTMLInputElement>;
+}
+
+/** "Neue Vorlage" card; the same card edits an existing preset. */
+export function PresetFormCard({
+ formId,
+ editing,
+ value,
+ onChange,
+ onSubmit,
+ disabled,
+ cardRef,
+ titleRef,
+}: PresetFormCardProps) {
+ const t = useTranslations();
+ const id = useId();
+ const fieldClass = cn(inputClass, "bg-surface-card");
+
+ return (
+ <form
+ id={formId}
+ ref={cardRef}
+ onSubmit={(e) => {
+ e.preventDefault();
+ onSubmit();
+ }}
+ className="flex scroll-mt-4 flex-col gap-3 rounded-[11px] border border-line bg-surface-panel p-4"
+ >
+ <div className="text-[14px] font-semibold text-fg-strong">
+ {editing ? t("preset.edit") : t("presetSheet.newPreset")}
+ </div>
+
+ <Field label={t("shift.titleLabel")} htmlFor={`${id}-title`}>
+ <Input
+ id={`${id}-title`}
+ ref={titleRef}
+ value={value.title}
+ onChange={(e) => onChange({ title: e.target.value })}
+ placeholder={t("presetSheet.titlePlaceholder")}
+ className={fieldClass}
+ disabled={disabled}
+ />
+ </Field>
+
+ {!value.isAllDay && (
+ <div className="grid grid-cols-2 gap-2.5">
+ <Field label={t("presetSheet.start")} htmlFor={`${id}-start`}>
+ <Input
+ id={`${id}-start`}
+ type="time"
+ value={value.startTime}
+ onChange={(e) => onChange({ startTime: e.target.value })}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ <Field label={t("presetSheet.end")} htmlFor={`${id}-end`}>
+ <Input
+ id={`${id}-end`}
+ type="time"
+ value={value.endTime}
+ onChange={(e) => onChange({ endTime: e.target.value })}
+ className={cn(fieldClass, "font-mono")}
+ disabled={disabled}
+ />
+ </Field>
+ </div>
+ )}
+
+ <ColorSwatches
+ value={value.color}
+ onChange={(color) => onChange({ color })}
+ allowCustom
+ disabled={disabled}
+ />
+
+ <Field label={t("form.notesLabel")} htmlFor={`${id}-notes`}>
+ <Input
+ id={`${id}-notes`}
+ value={value.notes}
+ onChange={(e) => onChange({ notes: e.target.value })}
+ placeholder={t("form.notesPlaceholder")}
+ className={fieldClass}
+ disabled={disabled}
+ />
+ </Field>
+
+ <div className="flex flex-col gap-2.5 pt-0.5">
+ <CheckRow
+ id={`${id}-allday`}
+ checked={value.isAllDay}
+ onCheckedChange={(isAllDay) => onChange({ isAllDay })}
+ disabled={disabled}
+ >
+ {t("presetSheet.allDay")}
+ </CheckRow>
+ <CheckRow
+ id={`${id}-secondary`}
+ checked={value.isSecondary}
+ onCheckedChange={(isSecondary) => onChange({ isSecondary })}
+ disabled={disabled}
+ hint={t("presetSheet.markAsSecondaryHint")}
+ >
+ {t("presetSheet.markAsSecondary")}
+ </CheckRow>
+ <CheckRow
+ id={`${id}-stats`}
+ checked={value.hideFromStats}
+ onCheckedChange={(hideFromStats) => onChange({ hideFromStats })}
+ disabled={disabled}
+ hint={t("presetSheet.hideFromStatsHint")}
+ >
+ {t("preset.hideFromStats")}
+ </CheckRow>
+ </div>
+ </form>
+ );
+}
diff --git a/components/preset-list.tsx b/components/preset-list.tsx
index 723f431..d226d1d 100644
--- a/components/preset-list.tsx
+++ b/components/preset-list.tsx
@@ -1,286 +1,169 @@
-import React from "react";
-import { motion } from "motion/react";
+"use client";
+
import { useTranslations } from "next-intl";
-import { Button } from "@/components/ui/button";
import {
- Check,
- Plus,
- Settings,
- Settings2,
- ChevronDown,
- ChevronUp,
-} from "lucide-react";
-
+ 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 { GripVertical, Pencil, Trash2 } from "lucide-react";
import { ShiftPreset } from "@/lib/db/schema";
-import { CalendarWithCount } from "@/lib/types";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { getShiftCode, presetTime, shiftVars } from "@/lib/shift-display";
+import { ListRow, Pill, RowIconButton, SectionLabel } from "@/components/form-kit";
+import { cn } from "@/lib/utils";
-interface PresetListProps {
- calendars: CalendarWithCount[];
- calendarId: string;
- presets: ShiftPreset[];
- selectedPresetId?: string;
- onSelectPreset: (presetId: string | undefined) => void;
- onCreateNew?: () => void;
- onManageClick?: () => void;
- onViewSettingsClick?: () => void;
- hidePresetHeader?: boolean;
- onHidePresetHeaderChange?: (hide: boolean) => void;
- hideManageButton?: boolean;
+interface PresetRowActions {
+ readOnly: boolean;
+ editingId: string | null;
+ deletingId: string | null;
+ onEdit: (preset: ShiftPreset) => void;
+ onDelete: (preset: ShiftPreset) => void;
}
-export function PresetList({
- calendarId,
- presets,
- selectedPresetId,
- onSelectPreset,
- onManageClick,
- onViewSettingsClick,
- hidePresetHeader = false,
- onHidePresetHeaderChange,
- hideManageButton = false,
-}: PresetListProps) {
- const t = useTranslations();
- const permission = useCalendarPermission(calendarId);
- const [showSecondary, setShowSecondary] = React.useState(false);
-
- const primaryPresets = presets.filter((p) => !p.isSecondary);
- const secondaryPresets = presets.filter((p) => p.isSecondary);
-
- // Check if current calendar is read-only
- const isReadOnly = !permission.canEdit;
-
- // Presets are now loaded at page level - no skeleton needed here
- // If loading is true, parent should show FullscreenLoader
+interface SortablePresetRowProps extends PresetRowActions {
+ preset: ShiftPreset;
+ draggable: boolean;
+}
- if (presets.length === 0) {
- return (
- <div className="border-2 border-dashed rounded-lg p-4 sm:p-6 text-center space-y-2 sm:space-y-3">
- <div className="flex items-center justify-center gap-2 text-muted-foreground">
- <Plus className="h-4 sm:h-5 w-4 sm:w-5" />
- <p className="text-xs sm:text-sm font-medium">
- {t("preset.noPresets")}
- </p>
- </div>
- <p className="text-[10px] sm:text-xs text-muted-foreground max-w-md mx-auto">
- {t("preset.createFirstDescription")}
- </p>
- {!hideManageButton && (
- <Button
- onClick={onManageClick}
- size="sm"
- className="gap-2"
- disabled={!onManageClick}
- >
- <Plus className="h-4 w-4" />
- <span className="text-xs sm:text-sm">
- {t("preset.createYourFirst")}
- </span>
- </Button>
- )}
- </div>
- );
- }
+function SortablePresetRow({
+ preset,
+ draggable,
+ readOnly,
+ editingId,
+ deletingId,
+ onEdit,
+ onDelete,
+}: SortablePresetRowProps) {
+ const t = useTranslations();
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ setActivatorNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: preset.id, disabled: !draggable });
+ const busy = deletingId === preset.id;
return (
- <div className="space-y-2">
- {/* Preset Buttons Row */}
- {!hidePresetHeader && (
- <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">
- {primaryPresets.map((preset) => (
- <PresetButton
- key={preset.id}
- preset={preset}
- isSelected={selectedPresetId === preset.id}
- onSelect={() =>
- onSelectPreset(
- selectedPresetId === preset.id ? undefined : preset.id
- )
- }
- isReadOnly={isReadOnly}
- />
- ))}
- </div>
- )}
-
- {/* Secondary Presets - Collapsible */}
- {!hidePresetHeader && secondaryPresets.length > 0 && (
- <div className="space-y-1.5">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setShowSecondary(!showSecondary)}
- className="gap-1 text-xs text-muted-foreground h-6 px-2"
- >
- {showSecondary ? (
- <ChevronUp className="h-3 w-3" />
- ) : (
- <ChevronDown className="h-3 w-3" />
- )}
- <span>
- {t("preset.secondaryPresets")} ({secondaryPresets.length})
- </span>
- </Button>
- {showSecondary && (
- <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">
- {secondaryPresets.map((preset) => (
- <PresetButton
- key={preset.id}
- preset={preset}
- isSelected={selectedPresetId === preset.id}
- onSelect={() =>
- onSelectPreset(
- selectedPresetId === preset.id ? undefined : preset.id
- )
- }
- compact
- isReadOnly={isReadOnly}
- />
- ))}
- </div>
- )}
- </div>
- )}
-
- {/* Control Buttons Row */}
- <div className="flex items-center gap-1.5 sm:gap-2">
- {!hidePresetHeader && !hideManageButton && (
- <Button
- variant="outline"
- size="sm"
- onClick={onManageClick}
- disabled={!onManageClick}
- className="gap-1.5 text-xs sm:text-sm px-2.5 sm:px-4 h-8 sm:h-9 border-primary/30 hover:border-primary/50 hover:bg-primary/5"
- title={t("preset.manage")}
- >
- <Settings className="h-3.5 sm:h-4 w-3.5 sm:w-4" />
- </Button>
- )}
- <div className="flex-1" />
- {onViewSettingsClick && (
- <Button
- variant="outline"
- size="sm"
- onClick={onViewSettingsClick}
- className="gap-1.5 text-xs sm:text-sm px-2.5 sm:px-4 h-8 sm:h-9 border-primary/30 hover:border-primary/50 hover:bg-primary/5"
- title={t("view.settingsTitle")}
+ <div
+ ref={setNodeRef}
+ style={{
+ transform: CSS.Transform.toString(transform),
+ transition: isDragging ? undefined : transition,
+ }}
+ className={cn("relative", isDragging && "z-10 opacity-60")}
+ >
+ <ListRow
+ highlighted={editingId === preset.id}
+ className={cn("gap-2.5 py-2.5 pr-1.5", draggable ? "pl-1.5" : "pl-3.5")}
+ >
+ {draggable && (
+ <button
+ ref={setActivatorNodeRef}
+ type="button"
+ aria-label={t("presetSheet.dragHandle")}
+ className="-my-1 flex h-8 w-6 shrink-0 cursor-grab touch-none items-center justify-center rounded-md text-fg-tertiary transition-colors hover:bg-surface-sunken active:cursor-grabbing"
+ {...attributes}
+ {...listeners}
>
- <Settings2 className="h-3.5 sm:h-4 w-3.5 sm:w-4" />
- </Button>
+ <GripVertical className="size-4" />
+ </button>
)}
- {onHidePresetHeaderChange && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onHidePresetHeaderChange(!hidePresetHeader)}
- className="h-8 sm:h-9 w-8 sm:w-9 p-0 text-muted-foreground hover:text-foreground"
- title={
- hidePresetHeader
- ? t("preset.showPresets")
- : t("preset.hidePresets")
- }
- >
- {hidePresetHeader ? (
- <ChevronDown className="h-4 w-4" />
- ) : (
- <ChevronUp className="h-4 w-4" />
+ <span
+ className="shift-solid flex size-[22px] shrink-0 items-center justify-center rounded-[6px] text-[11px] font-bold"
+ style={shiftVars(preset.color)}
+ >
+ {getShiftCode(preset.title)}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">
+ {preset.title}
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-1.5">
+ <span className="font-mono text-[12px] text-fg-tertiary">
+ {presetTime(preset, t("presetSheet.allDayShort"))}
+ </span>
+ {preset.isSecondary && <Pill>{t("preset.secondary")}</Pill>}
+ {preset.hideFromStats && (
+ <Pill tone="warning">{t("presetSheet.notInStats")}</Pill>
)}
- </Button>
+ </div>
+ </div>
+ {!readOnly && (
+ <>
+ <RowIconButton
+ icon={Pencil}
+ label={t("preset.edit")}
+ onClick={() => onEdit(preset)}
+ disabled={busy}
+ />
+ <RowIconButton
+ icon={Trash2}
+ tone="danger"
+ label={t("presetSheet.delete")}
+ onClick={() => onDelete(preset)}
+ disabled={busy}
+ />
+ </>
)}
- </div>
+ </ListRow>
</div>
);
}
-interface PresetButtonProps {
- preset: ShiftPreset;
- isSelected: boolean;
- onSelect: () => void;
- compact?: boolean;
- isReadOnly?: boolean;
+interface PresetSectionProps extends PresetRowActions {
+ label: string;
+ presets: ShiftPreset[];
+ onReorder: (next: ShiftPreset[]) => void;
}
-function PresetButton({
- preset,
- isSelected,
- onSelect,
- compact,
- isReadOnly = false,
-}: PresetButtonProps) {
- const t = useTranslations();
+/** One sortable group; primary and secondary presets are reordered separately. */
+export function PresetSection({ label, presets, onReorder, ...actions }: PresetSectionProps) {
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ );
+ const draggable = !actions.readOnly && presets.length > 1;
- if (compact) {
- return (
- <Button
- variant={isSelected ? "default" : "outline"}
- size="sm"
- onClick={isReadOnly ? undefined : onSelect}
- disabled={isReadOnly}
- className="relative text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"
- style={{
- backgroundColor: isSelected ? preset.color : undefined,
- borderColor: preset.color,
- }}
- >
- {isSelected && <Check className="mr-1 h-3 w-3" />}
- <span className="font-medium truncate max-w-[80px] sm:max-w-none">
- {preset.title}
- </span>
- <span className="ml-1 text-[10px] sm:text-xs opacity-70">
- {preset.isAllDay ? (
- <span>{t("shift.allDay")}</span>
- ) : (
- <>
- <span className="sm:hidden">{preset.startTime}</span>
- <span className="hidden sm:inline">
- {preset.startTime} - {preset.endTime}
- </span>
- </>
- )}
- </span>
- </Button>
- );
- }
+ const handleDragEnd = ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ const oldIndex = presets.findIndex((p) => p.id === active.id);
+ const newIndex = presets.findIndex((p) => p.id === over.id);
+ if (oldIndex < 0 || newIndex < 0) return;
+ onReorder(arrayMove(presets, oldIndex, newIndex));
+ };
return (
- <motion.div
- whileTap={{ scale: 0.95 }}
- initial={{ opacity: 0, scale: 0.9 }}
- animate={{ opacity: 1, scale: 1 }}
- >
- <Button
- variant={isSelected ? "default" : "outline"}
- size="sm"
- onClick={isReadOnly ? undefined : onSelect}
- disabled={isReadOnly}
- className="relative text-[11px] sm:text-sm px-2 sm:px-4 h-8 sm:h-10 rounded-full font-semibold transition-all"
- style={{
- backgroundColor: isSelected ? preset.color : undefined,
- borderColor: preset.color,
- borderWidth: "2px",
- }}
- >
- {isSelected && (
- <Check className="mr-1 sm:mr-1.5 h-3 sm:h-3.5 w-3 sm:w-3.5" />
- )}
- <span className="truncate max-w-[80px] sm:max-w-none">
- {preset.title}
- </span>
- <span className="ml-1 sm:ml-1.5 text-[9px] sm:text-xs opacity-80">
- {preset.isAllDay ? (
- <span>{t("shift.allDay")}</span>
- ) : (
- <>
- <span className="sm:hidden">
- {preset.startTime.substring(0, 5)}
- </span>
- <span className="hidden sm:inline">
- {preset.startTime} - {preset.endTime}
- </span>
- </>
- )}
- </span>
- </Button>
- </motion.div>
+ <section>
+ <SectionLabel>{label}</SectionLabel>
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+ <SortableContext items={presets.map((p) => p.id)} strategy={verticalListSortingStrategy}>
+ <div className="flex flex-col gap-2">
+ {presets.map((preset) => (
+ <SortablePresetRow
+ key={preset.id}
+ preset={preset}
+ draggable={draggable}
+ {...actions}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ </section>
);
}
diff --git a/components/preset-manage-sheet.tsx b/components/preset-manage-sheet.tsx
index 9411285..9bd0a24 100644
--- a/components/preset-manage-sheet.tsx
+++ b/components/preset-manage-sheet.tsx
@@ -1,841 +1,242 @@
"use client";
-import { useState, useEffect, memo, useRef } from "react";
+import { useId, useMemo, useRef, useState } 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 { Loader2 } from "lucide-react";
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 { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { PanelBody, PanelDialog, PanelFooter } from "@/components/panel-dialog";
import { ReadOnlyBanner } from "@/components/read-only-banner";
-import { useDirtyState } from "@/hooks/useDirtyState";
-import { usePresets } from "@/hooks/usePresets";
+import { PresetSection } from "@/components/preset-list";
+import {
+ EMPTY_PRESET_FORM,
+ PresetFormCard,
+ presetToFormData,
+ samePresetForm,
+} from "@/components/preset-form";
+import { ShiftPreset } from "@/lib/db/schema";
+import { usePresets, type PresetFormData } from "@/hooks/usePresets";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { useReportDirty } from "@/hooks/useDirtyState";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
-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;
+interface PresetsPanelProps {
calendarId: string;
- presets: ShiftPreset[];
- onPresetsChange?: () => void; // Now optional - React Query handles refetching
+ onClose: () => void;
readOnly?: boolean;
+ /** Called after every successful mutation, for callers holding their own copy of the presets. */
+ onPresetsChange?: () => void;
+ /** Lets the surrounding frame guard its own close button against unsaved form input. */
+ onDirtyChange?: (dirty: boolean) => 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;
- isReadOnly?: boolean;
-}
-
-const SortablePresetItem = memo(function SortablePresetItem({
- preset,
- isDeleting,
- onEdit,
- onDelete,
- t,
- showDragHandle = true,
- isReadOnly = false,
-}: 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">
- {!isReadOnly && (
- <>
- <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,
+export function PresetsPanel({
calendarId,
- presets,
+ onClose,
readOnly = false,
-}: PresetManageSheetProps) {
+ onPresetsChange,
+ onDirtyChange,
+}: PresetsPanelProps) {
const t = useTranslations();
-
const permission = useCalendarPermission(calendarId);
-
- // Determine if sheet should be in read-only mode
+ const desktop = useMediaQuery(DESKTOP_QUERY, false);
const isReadOnly = readOnly || !permission.canEdit;
+ const { presets, loading, createPreset, updatePreset, deletePreset, reorderPresets } =
+ usePresets(calendarId);
- 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 [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
- const [orderedPrimaryPresets, setOrderedPrimaryPresets] = useState<
- ShiftPreset[]
- >([]);
- const [orderedSecondaryPresets, setOrderedSecondaryPresets] = useState<
- ShiftPreset[]
- >([]);
- const initialFormDataRef = useRef<PresetFormData | null>(null);
-
- // Use the unified usePresets hook with mutations
- const {
- createPreset: createPresetMutation,
- updatePreset: updatePresetMutation,
- deletePreset: deletePresetMutation,
- reorderPresets: reorderPresetsMutation,
- } = usePresets(calendarId);
-
- // Initialize ordered presets
- useEffect(() => {
- if (open) {
- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
- }
- }, [presets, open]);
+ const formId = useId();
+ const formRef = useRef<HTMLFormElement>(null);
+ const titleRef = useRef<HTMLInputElement>(null);
- 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);
+ const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);
+ const [formData, setFormData] = useState<PresetFormData>(EMPTY_PRESET_FORM);
+ const [baseline, setBaseline] = useState<PresetFormData>(EMPTY_PRESET_FORM);
+ const [isSaving, setIsSaving] = useState(false);
+ const [deletingId, setDeletingId] = useState<string | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<ShiftPreset | null>(null);
+ const [pendingDiscard, setPendingDiscard] = useState<(() => void) | null>(null);
+ // Holds the dropped order until the reorder request settles, so rows don't snap back.
+ const [pendingOrder, setPendingOrder] = useState<string[] | null>(null);
+
+ const isDirty = !isReadOnly && !samePresetForm(formData, baseline);
+ const canSave = !isSaving && formData.title.trim() !== "" && (!editingPreset || isDirty);
+
+ useReportDirty(isDirty, onDirtyChange);
+
+ const ordered = useMemo(() => {
+ if (!pendingOrder) return presets;
+ const rank = new Map(pendingOrder.map((id, index) => [id, index]));
+ const last = pendingOrder.length;
+ return [...presets].sort((a, b) => (rank.get(a.id) ?? last) - (rank.get(b.id) ?? last));
+ }, [presets, pendingOrder]);
+ const primary = ordered.filter((p) => !p.isSecondary);
+ const secondary = ordered.filter((p) => p.isSecondary);
- // Save new order to backend
- await savePresetOrder([...newOrderedPrimary, ...orderedSecondaryPresets]);
+ const resetForm = () => {
+ setEditingPreset(null);
+ setFormData(EMPTY_PRESET_FORM);
+ setBaseline(EMPTY_PRESET_FORM);
};
- 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]);
+ // Runs the action directly, or after the user agreed to drop unsaved input.
+ const guardDiscard = (action: () => void) => {
+ if (isDirty) setPendingDiscard(() => action);
+ else action();
};
- const savePresetOrder = async (allPresets: ShiftPreset[]) => {
- const presetOrders = allPresets.map((preset, index) => ({
- id: preset.id,
- order: index,
- }));
-
- const success = await reorderPresetsMutation(presetOrders);
- if (!success) {
- // Revert order on error
- setOrderedPrimaryPresets(presets.filter((p) => !p.isSecondary));
- setOrderedSecondaryPresets(presets.filter((p) => p.isSecondary));
- }
+ const saveOrder = async (next: ShiftPreset[]) => {
+ const ids = next.map((p) => p.id);
+ setPendingOrder(ids);
+ const success = await reorderPresets(ids.map((id, order) => ({ id, order })));
+ setPendingOrder((current) => (current === ids ? null : current));
+ if (success) onPresetsChange?.();
};
- // 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);
+ const handleSave = async () => {
+ if (!canSave) return;
+ setIsSaving(true);
try {
- let success = false;
-
- if (editingPreset) {
- success = await updatePresetMutation(editingPreset.id, formData);
- } else {
- success = await createPresetMutation(formData);
- }
-
+ const success = editingPreset
+ ? await updatePreset(editingPreset.id, formData)
+ : await createPreset(formData);
if (success) {
- setEditingPreset(null);
- setShowAddForm(false);
- setFormData({
- title: "",
- startTime: "09:00",
- endTime: "17:00",
- color: PRESET_COLORS[0].value,
- notes: "",
- isSecondary: false,
- isAllDay: false,
- hideFromStats: false,
- });
+ resetForm();
+ onPresetsChange?.();
}
} finally {
- setIsLoading(false);
+ setIsSaving(false);
}
};
- const handleDeleteClick = (presetId: string) => {
- setDeleteTargetId(presetId);
- setShowDeleteConfirm(true);
- };
-
const handleDeleteConfirm = async () => {
- if (!deleteTargetId) return;
-
- setIsDeleting(deleteTargetId);
- setShowDeleteConfirm(false);
-
+ const target = deleteTarget;
+ if (!target) return;
+ setDeleteTarget(null);
+ setDeletingId(target.id);
try {
- const success = await deletePresetMutation(deleteTargetId);
+ const success = await deletePreset(target.id);
if (success) {
- // If we're editing the deleted preset, close the edit form
- if (editingPreset?.id === deleteTargetId) {
- setEditingPreset(null);
- }
+ if (editingPreset?.id === target.id) resetForm();
+ onPresetsChange?.();
}
} finally {
- setIsDeleting(null);
- setDeleteTargetId(null);
+ setDeletingId(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,
+ if (editingPreset?.id === preset.id) return;
+ guardDiscard(() => {
+ const data = presetToFormData(preset);
+ setEditingPreset(preset);
+ setFormData(data);
+ setBaseline(data);
+ requestAnimationFrame(() => {
+ formRef.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
+ // Focusing on a phone would pop the keyboard over the form
+ if (desktop) titleRef.current?.focus({ preventScroll: true });
+ });
});
- 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 handleCancel = () => {
+ if (editingPreset) resetForm();
+ else guardDiscard(onClose);
};
- 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({
- 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,
- });
+ const rowActions = {
+ readOnly: isReadOnly,
+ editingId: editingPreset?.id ?? null,
+ deletingId,
+ onEdit: startEdit,
+ onDelete: setDeleteTarget,
};
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>
+ <PanelBody className="flex flex-col gap-4">
+ {isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
- {/* Read-Only Banner */}
- {isReadOnly && (
- <div className="px-6 pt-6">
- <ReadOnlyBanner message={t("guest.cannotEdit")} />
+ {presets.length === 0 &&
+ (loading ? (
+ <div className="flex justify-center py-6 text-fg-tertiary">
+ <Loader2 className="size-5 animate-spin" />
</div>
- )}
-
- <div className="flex-1 overflow-y-auto px-6 py-6 space-y-3">
- {/* Empty state when no presets exist */}
- {presets.length === 0 && !showAddForm && !editingPreset && (
- <p className="text-center text-muted-foreground py-8">
- {t("preset.noPresets")}
- </p>
- )}
-
- {/* 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={handleDeleteClick}
- t={t}
- showDragHandle={orderedPrimaryPresets.length > 1}
- isReadOnly={isReadOnly}
- />
- ))}
- </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={handleDeleteClick}
- t={t}
- showDragHandle={orderedSecondaryPresets.length > 1}
- isReadOnly={isReadOnly}
- />
- ))}
- </div>
- </SortableContext>
- </DndContext>
- </div>
- )}
-
- {/* Show edited preset */}
- {editingPreset && (
- <div className="space-y-3">
- <SortablePresetItem
- preset={editingPreset}
- isDeleting={isDeleting === editingPreset.id}
- onEdit={startEdit}
- onDelete={handleDeleteClick}
- t={t}
- showDragHandle={false}
- isReadOnly={isReadOnly}
- />
- </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>
+ ) : (
+ <p className="rounded-[11px] border border-dashed border-control px-4 py-5 text-center text-[13px] text-fg-tertiary">
+ {t("preset.noPresets")}
+ </p>
+ ))}
+
+ {primary.length > 0 && (
+ <PresetSection
+ label={t("presetSheet.primary")}
+ presets={primary}
+ onReorder={(next) => saveOrder([...next, ...secondary])}
+ {...rowActions}
+ />
+ )}
+ {secondary.length > 0 && (
+ <PresetSection
+ label={t("presetSheet.secondarySection")}
+ presets={secondary}
+ onReorder={(next) => saveOrder([...primary, ...next])}
+ {...rowActions}
+ />
+ )}
- {/* Footer: Always visible Add or Save button */}
- {!showAddForm && !editingPreset && !isReadOnly && (
- <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>
- )}
- {!isReadOnly && (showAddForm || editingPreset) && (
- <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>
+ {!isReadOnly && (
+ <PresetFormCard
+ formId={formId}
+ editing={!!editingPreset}
+ value={formData}
+ onChange={(patch) => setFormData((current) => ({ ...current, ...patch }))}
+ onSubmit={handleSave}
+ disabled={isSaving}
+ cardRef={formRef}
+ titleRef={titleRef}
+ />
+ )}
+ </PanelBody>
+
+ {!isReadOnly && (
+ <PanelFooter>
+ <Button
+ type="button"
+ variant="outline"
+ className="h-10 flex-1 font-semibold"
+ onClick={handleCancel}
+ disabled={isSaving}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="submit"
+ form={formId}
+ className="h-10 flex-1 font-semibold"
+ disabled={!canSave}
+ >
+ {isSaving ? t("common.saving") : t("presetSheet.save")}
+ </Button>
+ </PanelFooter>
+ )}
<ConfirmationDialog
- open={showConfirmDialog}
- onOpenChange={setShowConfirmDialog}
- onConfirm={handleConfirmClose}
- title={t("common.unsavedChanges")}
- description={t("common.unsavedChangesDescription")}
+ open={!!pendingDiscard}
+ onOpenChange={(open) => !open && setPendingDiscard(null)}
+ onConfirm={() => {
+ const action = pendingDiscard;
+ setPendingDiscard(null);
+ resetForm();
+ action?.();
+ }}
/>
<ConfirmationDialog
- open={showDeleteConfirm}
- onOpenChange={setShowDeleteConfirm}
+ open={!!deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(null)}
onConfirm={handleDeleteConfirm}
- title={t("preset.preset") + " " + t("common.delete")}
+ title={t("presetSheet.delete")}
description={t("preset.deleteConfirm")}
cancelText={t("common.cancel")}
confirmText={t("common.delete")}
@@ -844,3 +245,57 @@ export function PresetManageSheet({
</>
);
}
+
+interface PresetManageSheetProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string;
+ onPresetsChange?: () => void;
+ readOnly?: boolean;
+}
+
+export function PresetManageSheet({
+ open,
+ onOpenChange,
+ calendarId,
+ onPresetsChange,
+ readOnly = false,
+}: PresetManageSheetProps) {
+ const t = useTranslations();
+ const [dirty, setDirty] = useState(false);
+ const [confirmClose, setConfirmClose] = useState(false);
+
+ return (
+ <>
+ <PanelDialog
+ bare
+ open={open}
+ onOpenChange={(next) => {
+ if (next) onOpenChange(true);
+ else if (dirty) setConfirmClose(true);
+ else onOpenChange(false);
+ }}
+ title={t("presetSheet.title")}
+ description={t("presetSheet.description")}
+ >
+ <PresetsPanel
+ key={calendarId}
+ calendarId={calendarId}
+ onClose={() => onOpenChange(false)}
+ readOnly={readOnly}
+ onPresetsChange={onPresetsChange}
+ onDirtyChange={setDirty}
+ />
+ </PanelDialog>
+
+ <ConfirmationDialog
+ open={confirmClose}
+ onOpenChange={setConfirmClose}
+ onConfirm={() => {
+ setConfirmClose(false);
+ onOpenChange(false);
+ }}
+ />
+ </>
+ );
+}
diff --git a/components/preset-select.tsx b/components/preset-select.tsx
index 2def59f..4c8d62f 100644
--- a/components/preset-select.tsx
+++ b/components/preset-select.tsx
@@ -1,20 +1,21 @@
import { useTranslations } from "next-intl";
-import { Label } from "@/components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+import { Field } from "@/components/form-kit";
import { ShiftPreset } from "@/lib/db/schema";
+import { cn } from "@/lib/utils";
+import { shiftVars } from "@/lib/shift-display";
interface PresetSelectProps {
presets: ShiftPreset[];
+ /** Id of the applied preset, `null` for a free entry */
+ value: string | null;
onPresetSelect: (preset: ShiftPreset) => void;
+ onClear: () => void;
}
-export function PresetSelect({ presets, onPresetSelect }: PresetSelectProps) {
+const chipClass =
+ "flex h-8 items-center gap-2 rounded-lg border px-3 text-[13px] font-medium transition-colors";
+
+export function PresetSelect({ presets, value, onPresetSelect, onClear }: PresetSelectProps) {
const t = useTranslations();
if (presets.length === 0) {
@@ -22,31 +23,48 @@ export function PresetSelect({ presets, onPresetSelect }: PresetSelectProps) {
}
return (
- <div className="space-y-2.5 p-4 bg-primary/5 border border-primary/20 rounded-xl">
- <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("shift.selectPreset")}
- </Label>
- <Select
- onValueChange={(value) => {
- const preset = presets.find((p) => p.id === value);
- if (preset) onPresetSelect(preset);
- }}
- >
- <SelectTrigger className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80">
- <SelectValue placeholder={t("shift.none")} />
- </SelectTrigger>
- <SelectContent>
- {presets.map((preset) => (
- <SelectItem key={preset.id} value={preset.id}>
- {preset.title}{" "}
- {preset.isAllDay
- ? `(${t("shift.allDay")})`
- : `(${preset.startTime} - ${preset.endTime})`}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
+ <Field label={t("preset.preset")}>
+ <div role="radiogroup" aria-label={t("preset.preset")} className="flex flex-wrap gap-2">
+ {presets.map((preset) => {
+ const selected = preset.id === value;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => onPresetSelect(preset)}
+ className={cn(
+ chipClass,
+ selected
+ ? "border-brand bg-brand-soft font-semibold text-brand-ink"
+ : "border-line bg-surface-card text-fg-body hover:bg-surface-panel"
+ )}
+ >
+ <span
+ className="shift-rail size-[7px] shrink-0 rounded-full"
+ style={shiftVars(preset.color)}
+ />
+ {preset.title}
+ </button>
+ );
+ })}
+ <button
+ type="button"
+ role="radio"
+ aria-checked={value === null}
+ onClick={onClear}
+ className={cn(
+ chipClass,
+ "border-dashed",
+ value === null
+ ? "border-brand bg-brand-soft font-semibold text-brand-ink"
+ : "border-control text-fg-secondary hover:bg-surface-panel"
+ )}
+ >
+ {t("shiftSheet.noPreset")}
+ </button>
+ </div>
+ </Field>
);
}
diff --git a/components/preset-selector.tsx b/components/preset-selector.tsx
deleted file mode 100644
index 3b66030..0000000
--- a/components/preset-selector.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client";
-
-import { ShiftPreset } from "@/lib/db/schema";
-import { CalendarWithCount } from "@/lib/types";
-import { useState } from "react";
-import { PresetList } from "@/components/preset-list";
-import { PresetManageSheet } from "@/components/preset-manage-sheet";
-
-interface PresetSelectorProps {
- calendars: CalendarWithCount[];
- presets: ShiftPreset[];
- selectedPresetId?: string;
- onSelectPreset: (presetId: string | undefined) => void;
- onPresetsChange?: () => void;
- onShiftsChange?: () => void;
- calendarId: string;
- onViewSettingsClick?: () => void;
- loading?: boolean;
- hidePresetHeader?: boolean;
- onHidePresetHeaderChange?: (hide: boolean) => void;
- hideManageButton?: boolean;
-}
-
-export function PresetSelector({
- calendars,
- presets,
- selectedPresetId,
- onSelectPreset,
- onPresetsChange,
- onShiftsChange,
- calendarId,
- onViewSettingsClick,
- hidePresetHeader = false,
- onHidePresetHeaderChange,
- hideManageButton = false,
-}: PresetSelectorProps) {
- const [showManageDialog, setShowManageDialog] = useState(false);
-
- const handleManageClick = () => {
- setShowManageDialog(true);
- };
-
- const handlePresetsChange = () => {
- if (onPresetsChange) onPresetsChange();
- if (onShiftsChange) onShiftsChange();
- };
-
- return (
- <>
- <PresetList
- calendars={calendars}
- calendarId={calendarId}
- presets={presets}
- selectedPresetId={selectedPresetId}
- onSelectPreset={onSelectPreset}
- onCreateNew={handleManageClick}
- onManageClick={handleManageClick}
- onViewSettingsClick={onViewSettingsClick}
- hidePresetHeader={hidePresetHeader}
- onHidePresetHeaderChange={onHidePresetHeaderChange}
- hideManageButton={hideManageButton}
- />
-
- <PresetManageSheet
- open={showManageDialog}
- onOpenChange={setShowManageDialog}
- calendarId={calendarId}
- presets={presets}
- onPresetsChange={handlePresetsChange}
- />
- </>
- );
-}
diff --git a/components/profile/account-layout.tsx b/components/profile/account-layout.tsx
new file mode 100644
index 0000000..b19dc56
--- /dev/null
+++ b/components/profile/account-layout.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { ReactNode } from "react";
+import Link from "next/link";
+import { useTranslations } from "next-intl";
+import { ChevronLeft } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/** Width cap for account section content, so fields don't stretch across wide screens. */
+export const accountContentClass = "w-full max-w-[680px]";
+
+/** Wider cap for sections that hold a table, such as the activity log. */
+export const accountWideContentClass = "w-full max-w-[960px]";
+
+const backClass =
+ "-ml-1.5 flex size-[34px] shrink-0 items-center justify-center rounded-lg text-fg-secondary transition-colors hover:bg-surface-panel";
+
+/** Top bar of the account pages: back arrow, title with subtitle, trailing actions. */
+export function AccountPageHeader({
+ title,
+ subtitle,
+ backHref,
+ onBack,
+ actions,
+ className,
+}: {
+ title: ReactNode;
+ subtitle?: ReactNode;
+ backHref?: string;
+ onBack?: () => void;
+ actions?: ReactNode;
+ className?: string;
+}) {
+ const t = useTranslations();
+ const icon = <ChevronLeft className="size-[19px]" />;
+
+ return (
+ <header
+ className={cn(
+ "flex shrink-0 items-center gap-3 border-b border-line bg-background px-4 py-3.5 lg:px-[22px] lg:py-4",
+ className
+ )}
+ >
+ {onBack ? (
+ <button type="button" onClick={onBack} aria-label={t("common.previous")} className={backClass}>
+ {icon}
+ </button>
+ ) : (
+ <Link href={backHref ?? "/"} aria-label={t("common.previous")} className={backClass}>
+ {icon}
+ </Link>
+ )}
+ <div className="min-w-0 flex-1">
+ <h1 className="truncate text-[19px] font-semibold leading-tight tracking-[-0.01em] text-fg-strong">
+ {title}
+ </h1>
+ {subtitle && <p className="mt-0.5 truncate text-[13.5px] text-fg-secondary">{subtitle}</p>}
+ </div>
+ {actions && <div className="flex shrink-0 items-center gap-2">{actions}</div>}
+ </header>
+ );
+}
+
+/** Title row inside a section, with an optional action on the right. */
+export function SectionHeading({
+ title,
+ description,
+ action,
+ className,
+}: {
+ title: ReactNode;
+ description?: ReactNode;
+ action?: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div className={cn("flex flex-wrap items-center gap-3", className)}>
+ <div className="min-w-0 flex-1">
+ <h2 className="text-[15px] font-semibold text-fg-strong">{title}</h2>
+ {description && <p className="mt-0.5 text-[13px] text-fg-secondary">{description}</p>}
+ </div>
+ {action}
+ </div>
+ );
+}
diff --git a/components/profile/activity-filters.tsx b/components/profile/activity-filters.tsx
new file mode 100644
index 0000000..a080851
--- /dev/null
+++ b/components/profile/activity-filters.tsx
@@ -0,0 +1,274 @@
+"use client";
+
+import { ReactNode, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { Search, SlidersHorizontal, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { ChoiceChips, Field, inputClass } from "@/components/form-kit";
+import { PanelDialog } from "@/components/panel-dialog";
+import type { UnifiedActivityLog } from "@/hooks/useActivityLogs";
+import { parseLocalDate } from "@/lib/date-utils";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+type LogType = UnifiedActivityLog["type"];
+type LogSeverity = UnifiedActivityLog["severity"];
+
+export interface ActivityFilterValues {
+ type: "all" | LogType;
+ severity: "all" | LogSeverity;
+ startDate: string;
+ endDate: string;
+}
+
+export const EMPTY_ACTIVITY_FILTERS: ActivityFilterValues = {
+ type: "all",
+ severity: "all",
+ startDate: "",
+ endDate: "",
+};
+
+const TYPES: LogType[] = ["auth", "calendar", "sync", "security"];
+const SEVERITIES: LogSeverity[] = ["info", "warning", "error", "critical"];
+
+export function countActivityFilters(filters: ActivityFilterValues) {
+ return [
+ filters.type !== "all",
+ filters.severity !== "all",
+ !!(filters.startDate || filters.endDate),
+ ].filter(Boolean).length;
+}
+
+export function useActivityLabels() {
+ const t = useTranslations();
+ const types: Record<LogType, string> = {
+ auth: t("activityLog.auth"),
+ calendar: t("activityLog.calendar"),
+ sync: t("activityLog.sync"),
+ security: t("activityLog.security"),
+ };
+ const severities: Record<LogSeverity, string> = {
+ info: t("common.severity.info"),
+ warning: t("common.severity.warning"),
+ error: t("common.severity.error"),
+ critical: t("common.severity.critical"),
+ };
+ return { types, severities };
+}
+
+function useRangeLabel(filters: ActivityFilterValues) {
+ const dateLocale = getDateLocale(useLocale());
+ if (!filters.startDate && !filters.endDate) return null;
+ const fmt = (value: string) => format(parseLocalDate(value), "P", { locale: dateLocale });
+ return `${filters.startDate ? fmt(filters.startDate) : "…"} – ${filters.endDate ? fmt(filters.endDate) : "…"}`;
+}
+
+function FilterFields({
+ filters,
+ onChange,
+}: {
+ filters: ActivityFilterValues;
+ onChange: (patch: Partial<ActivityFilterValues>) => void;
+}) {
+ const t = useTranslations();
+ const { types, severities } = useActivityLabels();
+
+ return (
+ <div className="flex flex-col gap-5">
+ <Field label={t("activityLog.eventType")}>
+ <ChoiceChips
+ label={t("activityLog.eventType")}
+ value={filters.type}
+ onChange={(type) => onChange({ type })}
+ options={[
+ { value: "all" as const, label: t("activityLog.allTypes") },
+ ...TYPES.map((value) => ({ value, label: types[value] })),
+ ]}
+ />
+ </Field>
+ <Field label={t("common.labels.severity")}>
+ <ChoiceChips
+ label={t("common.labels.severity")}
+ value={filters.severity}
+ onChange={(severity) => onChange({ severity })}
+ options={[
+ { value: "all" as const, label: t("common.filters.allSeverities") },
+ ...SEVERITIES.map((value) => ({ value, label: severities[value] })),
+ ]}
+ />
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field label={t("common.labels.startDate")} htmlFor="activity-start">
+ <Input
+ id="activity-start"
+ type="date"
+ value={filters.startDate}
+ max={filters.endDate || undefined}
+ onChange={(e) => onChange({ startDate: e.target.value })}
+ className={cn(inputClass, "font-mono text-[13px]")}
+ />
+ </Field>
+ <Field label={t("common.labels.endDate")} htmlFor="activity-end">
+ <Input
+ id="activity-end"
+ type="date"
+ value={filters.endDate}
+ min={filters.startDate || undefined}
+ onChange={(e) => onChange({ endDate: e.target.value })}
+ className={cn(inputClass, "font-mono text-[13px]")}
+ />
+ </Field>
+ </div>
+ </div>
+ );
+}
+
+function ActiveFilterChip({ label, children, onRemove }: { label: string; children?: ReactNode; onRemove: () => void }) {
+ const t = useTranslations();
+ return (
+ <button
+ type="button"
+ onClick={onRemove}
+ aria-label={t("common.filters.remove", { filter: label })}
+ className="flex h-9 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-brand bg-brand-soft pl-3 pr-2 text-[12.5px] font-semibold text-brand-ink lg:h-8"
+ >
+ {children ?? label}
+ <X className="size-3.5" />
+ </button>
+ );
+}
+
+/**
+ * Search plus a filter button: a popover on desktop, a bottom sheet on phones.
+ * Active filters show as removable chips next to the total count.
+ */
+export function ActivityToolbar({
+ desktop,
+ search,
+ onSearchChange,
+ filters,
+ onChange,
+ onClear,
+ total,
+}: {
+ desktop: boolean;
+ search: string;
+ onSearchChange: (value: string) => void;
+ filters: ActivityFilterValues;
+ onChange: (patch: Partial<ActivityFilterValues>) => void;
+ onClear: () => void;
+ /** `null` while the first page loads */
+ total: number | null;
+}) {
+ const t = useTranslations();
+ const { types, severities } = useActivityLabels();
+ const rangeLabel = useRangeLabel(filters);
+ const [sheetOpen, setSheetOpen] = useState(false);
+ const count = countActivityFilters(filters);
+ const anyActive = count > 0 || !!search;
+
+ const trigger = (
+ <button
+ type="button"
+ onClick={desktop ? undefined : () => setSheetOpen(true)}
+ className={cn(
+ "flex h-11 shrink-0 items-center gap-2 rounded-[9px] border px-3.5 text-[13.5px] font-medium transition-colors hover:bg-surface-panel lg:h-[38px]",
+ count > 0 ? "border-brand bg-brand-soft text-brand-ink" : "border-line bg-surface-card text-fg-body"
+ )}
+ >
+ <SlidersHorizontal className="size-4" />
+ {t("common.filters.title")}
+ {count > 0 && (
+ <span className="flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-brand px-1 font-mono text-[11px] font-medium text-white">
+ {count}
+ </span>
+ )}
+ </button>
+ );
+
+ return (
+ <div className="flex flex-col gap-2.5">
+ <div className="flex items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-fg-tertiary" />
+ <Input
+ value={search}
+ onChange={(e) => onSearchChange(e.target.value)}
+ placeholder={t("activityLog.searchPlaceholder")}
+ aria-label={t("activityLog.searchPlaceholder")}
+ className="h-11 rounded-[9px] pl-9 text-[14px] lg:h-[38px] lg:text-[13.5px]"
+ />
+ </div>
+ {desktop ? (
+ <Popover>
+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ <PopoverContent align="end" className="w-[400px] rounded-[12px] border-line bg-background p-4">
+ <FilterFields filters={filters} onChange={onChange} />
+ {anyActive && (
+ <Button variant="ghost" size="sm" onClick={onClear} className="mt-3 h-8 px-2 text-fg-secondary">
+ <X className="size-4" />
+ {t("common.filters.clearFilters")}
+ </Button>
+ )}
+ </PopoverContent>
+ </Popover>
+ ) : (
+ trigger
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ {filters.type !== "all" && (
+ <ActiveFilterChip label={types[filters.type]} onRemove={() => onChange({ type: "all" })} />
+ )}
+ {filters.severity !== "all" && (
+ <ActiveFilterChip label={severities[filters.severity]} onRemove={() => onChange({ severity: "all" })} />
+ )}
+ {rangeLabel && (
+ <ActiveFilterChip label={rangeLabel} onRemove={() => onChange({ startDate: "", endDate: "" })}>
+ <span className="font-mono font-medium">{rangeLabel}</span>
+ </ActiveFilterChip>
+ )}
+ {anyActive && (
+ <Button variant="ghost" onClick={onClear} className="h-9 gap-1.5 px-2.5 text-[13px] text-fg-secondary lg:h-8">
+ <X className="size-4" />
+ {t("common.filters.clearFilters")}
+ </Button>
+ )}
+ {total !== null && (
+ <span className="ml-auto text-[12.5px] text-fg-tertiary">
+ {t("activityLog.totalLogs", { count: total })}
+ </span>
+ )}
+ </div>
+
+ {!desktop && (
+ <PanelDialog
+ open={sheetOpen}
+ onOpenChange={setSheetOpen}
+ title={t("common.filters.title")}
+ footer={
+ <>
+ <Button
+ variant="outline"
+ onClick={onClear}
+ disabled={!anyActive}
+ className="h-11 flex-1 font-semibold"
+ >
+ {t("common.filters.clearFilters")}
+ </Button>
+ <Button onClick={() => setSheetOpen(false)} className="h-11 flex-1 font-semibold">
+ {t("common.filters.done")}
+ </Button>
+ </>
+ }
+ >
+ <FilterFields filters={filters} onChange={onChange} />
+ </PanelDialog>
+ )}
+ </div>
+ );
+}
diff --git a/components/profile/activity-section.tsx b/components/profile/activity-section.tsx
new file mode 100644
index 0000000..10cf41e
--- /dev/null
+++ b/components/profile/activity-section.tsx
@@ -0,0 +1,416 @@
+"use client";
+
+import { Fragment, useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Trash2, TriangleAlert } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { Pill } from "@/components/form-kit";
+import { PanelBody } from "@/components/panel-dialog";
+import { StatusBanner } from "@/components/status-banner";
+import { accountWideContentClass, SectionHeading } from "@/components/profile/account-layout";
+import {
+ ActivityToolbar,
+ countActivityFilters,
+ EMPTY_ACTIVITY_FILTERS,
+ useActivityLabels,
+ type ActivityFilterValues,
+} from "@/components/profile/activity-filters";
+import { useActivityLogs, type UnifiedActivityLog } from "@/hooks/useActivityLogs";
+import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+type SortColumn = "timestamp" | "type" | "severity";
+
+const PAGE_SIZE = 50;
+const SEVERITY_ORDER = { info: 0, warning: 1, error: 2, critical: 3 };
+const SEVERITY_TONE = {
+ info: "neutral",
+ warning: "warning",
+ error: "danger",
+ critical: "danger",
+} as const;
+
+function ActionCode({ action }: { action: string }) {
+ return (
+ <code className="inline-block max-w-full truncate rounded-md bg-surface-sunken px-1.5 py-0.5 align-middle font-mono text-[12px] font-medium text-fg-body">
+ {action}
+ </code>
+ );
+}
+
+function LogDetails({ log, surface }: { log: UnifiedActivityLog; surface: string }) {
+ const t = useTranslations();
+ return (
+ <div className="flex flex-col gap-2">
+ {log.resourceType && (
+ <div className="min-w-0 text-[12.5px] text-fg-secondary">
+ <span className="font-semibold text-fg-body">{t("activityLog.resource")}:</span> {log.resourceType}
+ {log.resourceId && (
+ <span className="ml-1.5 break-all font-mono text-[12px] text-fg-tertiary">{log.resourceId}</span>
+ )}
+ </div>
+ )}
+ <div className="eyebrow">{t("activityLog.details")}</div>
+ {log.metadata ? (
+ <pre
+ className={cn(
+ "max-h-72 max-w-full overflow-auto whitespace-pre-wrap break-words rounded-[9px] border border-line p-3 font-mono text-[12px] leading-relaxed text-fg-body",
+ surface
+ )}
+ >
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ ) : (
+ <p className="text-[13px] text-fg-tertiary">{t("activityLog.noMetadata")}</p>
+ )}
+ </div>
+ );
+}
+
+/** Merged audit and sync log of the signed-in user, with filters, sorting and pagination. */
+export function ActivitySection() {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const { types, severities } = useActivityLabels();
+
+ const search = useDebouncedSearch(500);
+ const [filterValues, setFilterValues] = useState<ActivityFilterValues>(EMPTY_ACTIVITY_FILTERS);
+ // Every filter or search change starts again on the first page
+ const listKey = [search.query, filterValues.type, filterValues.severity, filterValues.startDate, filterValues.endDate].join("|");
+ const [page, setPage] = useResettableState(listKey, 0);
+ const [sortColumn, setSortColumn] = useState<SortColumn>("timestamp");
+ const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
+ const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
+ const [clearDialogOpen, setClearDialogOpen] = useState(false);
+
+ const filters = useMemo(
+ () => ({
+ type: filterValues.type !== "all" ? filterValues.type : undefined,
+ severity: filterValues.severity !== "all" ? filterValues.severity : undefined,
+ search: search.query || undefined,
+ startDate: filterValues.startDate || undefined,
+ endDate: filterValues.endDate || undefined,
+ }),
+ [filterValues, search.query]
+ );
+ const pagination = useMemo(() => ({ limit: PAGE_SIZE, offset: page * PAGE_SIZE }), [page]);
+
+ const { logs, total, isLoading, isPlaceholderData, error, clearLogs } = useActivityLogs(filters, pagination);
+
+ const hasActiveFilters = countActivityFilters(filterValues) > 0 || !!search.input;
+ const hasMore = (page + 1) * PAGE_SIZE < total;
+
+ const updateFilters = (patch: Partial<ActivityFilterValues>) => {
+ setFilterValues((prev) => ({ ...prev, ...patch }));
+ };
+
+ const clearFilters = () => {
+ setFilterValues(EMPTY_ACTIVITY_FILTERS);
+ search.setInput("");
+ };
+
+ const toggleRow = (logId: string) => {
+ setExpandedRows((prev) => {
+ const next = new Set(prev);
+ if (next.has(logId)) next.delete(logId);
+ else next.add(logId);
+ return next;
+ });
+ };
+
+ const handleSort = (column: SortColumn) => {
+ if (sortColumn === column) {
+ setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
+ } else {
+ setSortColumn(column);
+ setSortDirection("desc");
+ }
+ };
+
+ const handleClearAll = async () => {
+ setClearDialogOpen(false);
+ if (await clearLogs()) setPage(0);
+ };
+
+ // Sorting only reorders the loaded page; the API always returns newest first
+ const sortedLogs = useMemo(
+ () =>
+ [...logs].sort((a, b) => {
+ let comparison = 0;
+ switch (sortColumn) {
+ case "timestamp":
+ comparison = a.timestamp.getTime() - b.timestamp.getTime();
+ break;
+ case "type":
+ comparison = a.type.localeCompare(b.type);
+ break;
+ case "severity":
+ comparison = (SEVERITY_ORDER[a.severity] ?? 0) - (SEVERITY_ORDER[b.severity] ?? 0);
+ break;
+ }
+ return sortDirection === "asc" ? comparison : -comparison;
+ }),
+ [logs, sortColumn, sortDirection]
+ );
+
+ const formatTimestamp = (timestamp: Date) =>
+ timestamp instanceof Date && !isNaN(timestamp.getTime()) ? (
+ <>
+ {format(timestamp, "PP", { locale: dateLocale })}{" "}
+ <span className="text-fg-tertiary">{format(timestamp, "HH:mm:ss", { locale: dateLocale })}</span>
+ </>
+ ) : (
+ "—"
+ );
+
+ const severityPill = (severity: UnifiedActivityLog["severity"]) => (
+ <Pill tone={SEVERITY_TONE[severity] ?? "neutral"}>{severities[severity] ?? severity}</Pill>
+ );
+
+ const sortHeader = (column: SortColumn, label: string) => {
+ const sorted = sortColumn === column;
+ const SortIcon = sortDirection === "asc" ? ChevronUp : ChevronDown;
+ return (
+ <th
+ className="px-3 py-2.5 font-normal"
+ aria-sort={sorted ? (sortDirection === "asc" ? "ascending" : "descending") : undefined}
+ >
+ <button
+ type="button"
+ onClick={() => handleSort(column)}
+ className="eyebrow flex items-center gap-1 transition-colors hover:text-fg-strong"
+ >
+ {label}
+ {sorted && <SortIcon className="size-3.5" />}
+ </button>
+ </th>
+ );
+ };
+
+ const paginationFooter = (
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <span className="text-[13px] text-fg-secondary">
+ {t("activityLog.showingResults", {
+ start: page * PAGE_SIZE + 1,
+ end: Math.min((page + 1) * PAGE_SIZE, total),
+ total,
+ })}
+ </span>
+ {total > PAGE_SIZE && (
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-11 font-semibold lg:h-8"
+ onClick={() => setPage((prev) => Math.max(0, prev - 1))}
+ disabled={page === 0}
+ >
+ <ChevronLeft className="size-4" />
+ {t("common.previous")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-11 font-semibold lg:h-8"
+ onClick={() => setPage((prev) => prev + 1)}
+ disabled={!hasMore}
+ >
+ {t("common.next")}
+ <ChevronRight className="size-4" />
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+
+ const renderTable = () => (
+ <div className="overflow-hidden rounded-[12px] border border-line bg-surface-card">
+ <div className="overflow-x-auto">
+ <table className="w-full text-left">
+ <thead className="bg-surface-panel">
+ <tr className="border-b border-line">
+ <th className="w-10 px-3 py-2.5">
+ <span className="sr-only">{t("activityLog.details")}</span>
+ </th>
+ {sortHeader("timestamp", t("common.labels.time"))}
+ {sortHeader("type", t("activityLog.eventType"))}
+ <th className="eyebrow px-3 py-2.5">{t("common.labels.action")}</th>
+ {/* Below xl the resource moves into the expanded details */}
+ <th className="eyebrow hidden px-3 py-2.5 xl:table-cell">{t("activityLog.resource")}</th>
+ {sortHeader("severity", t("common.labels.severity"))}
+ </tr>
+ </thead>
+ <tbody className="[&>tr:last-child]:border-b-0">
+ {sortedLogs.map((log) => {
+ const expanded = expandedRows.has(log.id);
+ return (
+ <Fragment key={log.id}>
+ <tr
+ className={cn(
+ "cursor-pointer border-b border-line-subtle transition-colors hover:bg-surface-panel",
+ expanded && "bg-surface-panel"
+ )}
+ onClick={() => toggleRow(log.id)}
+ >
+ <td className="px-3 py-3">
+ <button
+ type="button"
+ aria-expanded={expanded}
+ aria-label={t("activityLog.details")}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleRow(log.id);
+ }}
+ className="flex size-6 items-center justify-center rounded-md text-fg-tertiary hover:text-fg-strong"
+ >
+ <ChevronRight className={cn("size-4 transition-transform", expanded && "rotate-90")} />
+ </button>
+ </td>
+ <td className="whitespace-nowrap px-3 py-3 font-mono text-[12.5px] text-fg-body">
+ {formatTimestamp(log.timestamp)}
+ </td>
+ <td className="whitespace-nowrap px-3 py-3 text-[13px] text-fg-body">
+ {types[log.type] ?? log.type}
+ </td>
+ <td className="max-w-[260px] px-3 py-3">
+ <ActionCode action={log.action} />
+ </td>
+ <td className="hidden px-3 py-3 text-[13px] text-fg-secondary xl:table-cell">
+ {log.resourceType ? (
+ <>
+ {log.resourceType}
+ {log.resourceId && (
+ <span className="block max-w-[180px] truncate font-mono text-[11.5px] text-fg-tertiary">
+ {log.resourceId}
+ </span>
+ )}
+ </>
+ ) : (
+ <span className="text-fg-faint">—</span>
+ )}
+ </td>
+ <td className="px-3 py-3">{severityPill(log.severity)}</td>
+ </tr>
+ {expanded && (
+ <tr className="border-b border-line-subtle bg-surface-panel">
+ <td colSpan={6} className="px-4 pb-4 pt-1">
+ <LogDetails log={log} surface="bg-surface-card" />
+ </td>
+ </tr>
+ )}
+ </Fragment>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ <div className="border-t border-line bg-surface-panel px-4 py-3">{paginationFooter}</div>
+ </div>
+ );
+
+ const renderCards = () => (
+ <div className="flex flex-col gap-2.5">
+ {sortedLogs.map((log) => {
+ const expanded = expandedRows.has(log.id);
+ return (
+ <div key={log.id} className="overflow-hidden rounded-[12px] border border-line bg-surface-card">
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => toggleRow(log.id)}
+ className="flex w-full flex-col gap-1.5 px-3.5 py-3 text-left"
+ >
+ <span className="flex w-full items-center gap-2">
+ <span className="min-w-0 flex-1">
+ <ActionCode action={log.action} />
+ </span>
+ {severityPill(log.severity)}
+ <ChevronRight
+ className={cn("size-4 shrink-0 text-fg-tertiary transition-transform", expanded && "rotate-90")}
+ />
+ </span>
+ <span className="truncate text-[13.5px] text-fg-body">
+ {types[log.type] ?? log.type}
+ {log.resourceType && <span className="text-fg-secondary"> · {log.resourceType}</span>}
+ </span>
+ <span className="font-mono text-[12px] text-fg-tertiary">{formatTimestamp(log.timestamp)}</span>
+ </button>
+ {expanded && (
+ <div className="border-t border-line-subtle px-3.5 pb-3.5 pt-3">
+ <LogDetails log={log} surface="bg-surface-panel" />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ <div className="pt-1">{paginationFooter}</div>
+ </div>
+ );
+
+ const placeholderClass =
+ "rounded-[12px] border border-dashed border-control px-4 py-12 text-center text-[13.5px] text-fg-tertiary";
+
+ return (
+ <PanelBody>
+ <div className={cn(accountWideContentClass, "flex flex-col gap-4")}>
+ <SectionHeading
+ title={t("activityLog.heading")}
+ description={t("activityLog.description")}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-11 font-semibold text-danger hover:bg-danger-soft hover:text-danger lg:h-[34px]"
+ onClick={() => setClearDialogOpen(true)}
+ // Clearing ignores the filters, so only an unfiltered empty log disables it
+ disabled={total === 0 && !hasActiveFilters}
+ >
+ <Trash2 className="size-[15px]" />
+ {t("activityLog.clearAll")}
+ </Button>
+ }
+ />
+
+ <ActivityToolbar
+ desktop={desktop}
+ search={search.input}
+ onSearchChange={search.setInput}
+ filters={filterValues}
+ onChange={updateFilters}
+ onClear={clearFilters}
+ total={isLoading && logs.length === 0 ? null : total}
+ />
+
+ {isLoading && logs.length === 0 ? (
+ <div className={placeholderClass}>{t("common.loading")}</div>
+ ) : error ? (
+ <StatusBanner tone="danger" icon={TriangleAlert} title={t("common.error")}>
+ {error.message || String(error)}
+ </StatusBanner>
+ ) : logs.length === 0 ? (
+ <div className={placeholderClass}>
+ {hasActiveFilters ? t("common.noResults") : t("activityLog.noLogs")}
+ </div>
+ ) : (
+ <div className={cn(isPlaceholderData && "opacity-60")}>{desktop ? renderTable() : renderCards()}</div>
+ )}
+ </div>
+
+ <ConfirmationDialog
+ open={clearDialogOpen}
+ onOpenChange={setClearDialogOpen}
+ onConfirm={handleClearAll}
+ title={t("activityLog.clearAll")}
+ description={t("activityLog.confirmClear")}
+ confirmText={t("common.delete")}
+ cancelText={t("common.cancel")}
+ confirmVariant="destructive"
+ />
+ </PanelBody>
+ );
+}
diff --git a/components/profile/connected-accounts.tsx b/components/profile/connected-accounts.tsx
new file mode 100644
index 0000000..45e86cc
--- /dev/null
+++ b/components/profile/connected-accounts.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { ComponentType } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { KeyRound, Link2, Mail } from "lucide-react";
+import { ListRow, Pill } from "@/components/form-kit";
+import { PanelBody } from "@/components/panel-dialog";
+import { DiscordIcon, GitHubIcon, GoogleIcon } from "@/components/auth-provider-icons";
+import { accountContentClass, SectionHeading } from "@/components/profile/account-layout";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import type { useConnectedAccounts } from "@/hooks/useConnectedAccounts";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+export type ConnectedAccount = ReturnType<typeof useConnectedAccounts>["accounts"][number];
+
+type ProviderIcon = ComponentType<{ className?: string }>;
+
+/** Display name and mark for a better-auth provider id. */
+export function useProviderInfo() {
+ const t = useTranslations();
+ const { oidc } = useAuthFeatures();
+
+ return (provider: string): { label: string; icon: ProviderIcon } => {
+ switch (provider) {
+ case "credential":
+ return { label: t("auth.emailPasswordAuth"), icon: Mail };
+ case "google":
+ return { label: t("auth.provider.google"), icon: GoogleIcon };
+ case "github":
+ return { label: t("auth.provider.github"), icon: GitHubIcon };
+ case "discord":
+ return { label: t("auth.provider.discord"), icon: DiscordIcon };
+ case "custom-oidc":
+ return { label: oidc.name || t("auth.provider.customOidc"), icon: KeyRound };
+ default:
+ return { label: provider.charAt(0).toUpperCase() + provider.slice(1), icon: Link2 };
+ }
+ };
+}
+
+function ConnectedAccountRow({
+ account,
+ detailed = false,
+}: {
+ account: ConnectedAccount;
+ detailed?: boolean;
+}) {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const { label, icon: Icon } = useProviderInfo()(account.provider);
+
+ return (
+ <ListRow className={cn(!detailed && "rounded-[10px] py-2.5")}>
+ <Icon className="size-[17px] shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] text-fg-strong">{label}</div>
+ {detailed && account.createdAt && (
+ <div className="mt-0.5 truncate font-mono text-[12px] text-fg-tertiary">
+ {t("profile.connectedSince", {
+ date: format(account.createdAt, "PP", { locale: dateLocale }),
+ })}
+ </div>
+ )}
+ </div>
+ <Pill tone="success">{t("common.status.active")}</Pill>
+ </ListRow>
+ );
+}
+
+export function ConnectedAccountList({
+ accounts,
+ detailed,
+}: {
+ accounts: ConnectedAccount[];
+ detailed?: boolean;
+}) {
+ const t = useTranslations();
+
+ if (accounts.length === 0) {
+ return (
+ <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">
+ {t("auth.noConnectedAccounts")}
+ </p>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ {accounts.map((account) => (
+ <ConnectedAccountRow key={account.id} account={account} detailed={detailed} />
+ ))}
+ </div>
+ );
+}
+
+export function ConnectedAccountsSection({ accounts }: { accounts: ConnectedAccount[] }) {
+ const t = useTranslations();
+
+ return (
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-4")}>
+ <SectionHeading title={t("profile.accountsTitle")} description={t("profile.accountsHint")} />
+ <ConnectedAccountList accounts={accounts} detailed />
+ </div>
+ </PanelBody>
+ );
+}
diff --git a/components/profile/danger-section.tsx b/components/profile/danger-section.tsx
new file mode 100644
index 0000000..a7bf366
--- /dev/null
+++ b/components/profile/danger-section.tsx
@@ -0,0 +1,131 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { LogOut, TriangleAlert } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { DangerZone, Field, inputClass, ListRow } from "@/components/form-kit";
+import { PanelBody } from "@/components/panel-dialog";
+import { accountContentClass } from "@/components/profile/account-layout";
+import { useSignOut } from "@/hooks/useSignOut";
+import { signOut } from "@/lib/auth/client";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
+import { cn } from "@/lib/utils";
+
+export function DangerSection({ hasPasswordAuth }: { hasPasswordAuth: boolean }) {
+ const t = useTranslations();
+ const router = useRouter();
+ const handleSignOut = useSignOut();
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [deletePassword, setDeletePassword] = useState("");
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ const handleDeleteAccount = async () => {
+ setIsDeleting(true);
+ try {
+ // Custom endpoint so foreign keys are cleaned up before the user row goes
+ const response = await fetch("/api/auth/delete-account", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: hasPasswordAuth ? JSON.stringify({ password: deletePassword }) : undefined,
+ });
+
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ toast.error(data.error || t("common.error"));
+ return;
+ }
+
+ toast.success(t("auth.accountDeleted"));
+ setShowDeleteDialog(false);
+ setDeletePassword("");
+
+ await signOut();
+ router.replace("/");
+ } catch (error) {
+ console.error("Account deletion error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsDeleting(false);
+ }
+ };
+
+ return (
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-3")}>
+ <ListRow>
+ <LogOut className="size-[18px] shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="text-[14px] font-semibold text-fg-strong">{t("auth.logout")}</div>
+ <div className="text-[13px] text-fg-secondary">{t("auth.logoutDescription")}</div>
+ </div>
+ <Button variant="outline" size="sm" className="h-9 shrink-0 font-semibold" onClick={handleSignOut}>
+ {t("auth.logout")}
+ </Button>
+ </ListRow>
+
+ <DangerZone
+ icon={TriangleAlert}
+ title={t("auth.deleteAccount")}
+ description={
+ hasPasswordAuth
+ ? `${t("profile.deleteImpact")} ${t("profile.deleteNeedsPassword")}`
+ : t("profile.deleteImpact")
+ }
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-9 border-danger-line bg-surface-card font-semibold text-danger hover:bg-danger-soft hover:text-danger"
+ onClick={() => setShowDeleteDialog(true)}
+ >
+ {t("common.delete")}
+ </Button>
+ }
+ />
+ </div>
+
+ <ConfirmationDialog
+ open={showDeleteDialog}
+ onOpenChange={(open) => {
+ setShowDeleteDialog(open);
+ if (!open) setDeletePassword("");
+ }}
+ onConfirm={handleDeleteAccount}
+ title={t("auth.deleteAccount")}
+ description={t("auth.deleteAccountConfirm")}
+ confirmText={isDeleting ? t("common.loading") : t("auth.deleteAccount")}
+ confirmVariant="destructive"
+ confirmDisabled={isDeleting || (hasPasswordAuth && !deletePassword)}
+ >
+ {hasPasswordAuth && (
+ <Field label={t("auth.confirmPasswordLabel")} htmlFor="delete-password">
+ <Input
+ id="delete-password"
+ type="password"
+ autoComplete="current-password"
+ value={deletePassword}
+ onChange={(e) => setDeletePassword(e.target.value)}
+ disabled={isDeleting}
+ placeholder={t("auth.enterPassword")}
+ className={inputClass}
+ />
+ </Field>
+ )}
+ </ConfirmationDialog>
+ </PanelBody>
+ );
+}
diff --git a/components/profile/password-section.tsx b/components/profile/password-section.tsx
new file mode 100644
index 0000000..24ead82
--- /dev/null
+++ b/components/profile/password-section.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Field, inputClass } from "@/components/form-kit";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { accountContentClass } from "@/components/profile/account-layout";
+import { usePasswordForm } from "@/hooks/useProfileForm";
+import { cn } from "@/lib/utils";
+
+export function PasswordSection() {
+ const t = useTranslations();
+ const form = usePasswordForm();
+
+ return (
+ <form
+ className="flex min-h-0 flex-1 flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.submit();
+ }}
+ >
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-[18px]")}>
+ <Field label={t("auth.currentPassword")} htmlFor="current-password">
+ <Input
+ id="current-password"
+ type="password"
+ autoComplete="current-password"
+ value={form.currentPassword}
+ onChange={(e) => form.setCurrentPassword(e.target.value)}
+ disabled={form.isChanging}
+ className={inputClass}
+ />
+ </Field>
+ <div className="h-px shrink-0 bg-line" />
+ <Field label={t("common.labels.newPassword")} htmlFor="new-password">
+ <Input
+ id="new-password"
+ type="password"
+ autoComplete="new-password"
+ minLength={8}
+ value={form.newPassword}
+ onChange={(e) => form.setNewPassword(e.target.value)}
+ disabled={form.isChanging}
+ className={inputClass}
+ />
+ </Field>
+ <Field label={t("common.labels.confirmPassword")} htmlFor="confirm-new-password">
+ <Input
+ id="confirm-new-password"
+ type="password"
+ autoComplete="new-password"
+ minLength={8}
+ value={form.confirmPassword}
+ onChange={(e) => form.setConfirmPassword(e.target.value)}
+ disabled={form.isChanging}
+ className={inputClass}
+ />
+ </Field>
+ </div>
+ </PanelBody>
+ <PanelFooter>
+ <div className={cn(accountContentClass, "flex items-center gap-2.5")}>
+ <p className="hidden min-w-0 flex-1 text-[13px] text-fg-secondary lg:block">
+ {t("profile.passwordNote")}
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={!form.isDirty || form.isChanging}
+ onClick={form.reset}
+ >
+ {t("profile.discard")}
+ </Button>
+ <Button
+ type="submit"
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={form.isChanging}
+ >
+ {form.isChanging ? t("common.saving") : t("auth.changePassword")}
+ </Button>
+ </div>
+ </PanelFooter>
+ </form>
+ );
+}
diff --git a/components/profile/profile-details-section.tsx b/components/profile/profile-details-section.tsx
new file mode 100644
index 0000000..b532622
--- /dev/null
+++ b/components/profile/profile-details-section.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useRef } from "react";
+import { useTranslations } from "next-intl";
+import { Info, Upload, User } from "lucide-react";
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Field, InfoNote, inputClass, SectionLabel } from "@/components/form-kit";
+import { PanelBody, PanelFooter } from "@/components/panel-dialog";
+import { accountContentClass } from "@/components/profile/account-layout";
+import {
+ ConnectedAccountList,
+ type ConnectedAccount,
+} from "@/components/profile/connected-accounts";
+import type { ProfileForm } from "@/hooks/useProfileForm";
+import { cn, getUserInitials } from "@/lib/utils";
+
+const readOnlyInput = "read-only:bg-surface-panel read-only:text-fg-secondary";
+
+/**
+ * Screen 11b. Only accounts with password auth may edit name, e-mail and
+ * avatar; OAuth users see their provider's data read-only.
+ */
+export function ProfileDetailsSection({
+ form,
+ canEdit,
+ accounts,
+}: {
+ form: ProfileForm;
+ canEdit: boolean;
+ accounts: ConnectedAccount[];
+}) {
+ const t = useTranslations();
+ const fileInput = useRef<HTMLInputElement>(null);
+ const busy = form.isSaving || form.isUploadingAvatar;
+
+ return (
+ <form
+ className="flex min-h-0 flex-1 flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.save();
+ }}
+ >
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-[18px]")}>
+ <div className="flex items-center gap-4">
+ <Avatar className="size-16">
+ <AvatarImage src={form.image ?? undefined} alt="" className="object-cover" />
+ <AvatarFallback className="bg-brand-soft text-[20px] font-semibold text-brand-ink">
+ {form.name ? getUserInitials({ name: form.name }) : <User className="size-6" />}
+ </AvatarFallback>
+ </Avatar>
+ {canEdit && (
+ <div className="flex min-w-0 flex-col gap-[7px]">
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-[34px] font-semibold"
+ disabled={busy}
+ onClick={() => fileInput.current?.click()}
+ >
+ <Upload className="size-[15px]" />
+ {t("profile.chooseImage")}
+ </Button>
+ {form.image && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-[34px] font-medium text-danger hover:bg-danger-soft hover:text-danger"
+ disabled={busy}
+ onClick={form.removeAvatar}
+ >
+ {t("profile.removeImage")}
+ </Button>
+ )}
+ </div>
+ <span className="text-[12px] text-fg-tertiary">{t("auth.avatarHint")}</span>
+ <input
+ ref={fileInput}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ aria-label={t("auth.profilePicture")}
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) form.selectAvatar(file);
+ // Allows picking the same file again after removing it
+ e.target.value = "";
+ }}
+ />
+ </div>
+ )}
+ </div>
+
+ <Field label={t("common.labels.name")} htmlFor="profile-name">
+ <Input
+ id="profile-name"
+ value={form.name}
+ onChange={(e) => form.setName(e.target.value)}
+ readOnly={!canEdit}
+ disabled={busy}
+ autoComplete="name"
+ required
+ className={cn(inputClass, readOnlyInput)}
+ />
+ </Field>
+ <Field label={t("common.labels.email")} htmlFor="profile-email">
+ <Input
+ id="profile-email"
+ type="email"
+ value={form.email}
+ onChange={(e) => form.setEmail(e.target.value)}
+ readOnly={!canEdit}
+ disabled={busy}
+ autoComplete="email"
+ required
+ className={cn(inputClass, readOnlyInput)}
+ />
+ </Field>
+ {!canEdit && <InfoNote icon={Info}>{t("profile.managedByProvider")}</InfoNote>}
+
+ <div className="h-px shrink-0 bg-line" />
+
+ <section>
+ <SectionLabel>{t("common.auth.connectedAccounts")}</SectionLabel>
+ <ConnectedAccountList accounts={accounts} />
+ </section>
+ </div>
+ </PanelBody>
+
+ {canEdit && (
+ <PanelFooter>
+ <div className={cn(accountContentClass, "flex items-center gap-2.5")}>
+ <p className="hidden min-w-0 flex-1 text-[13px] text-fg-secondary lg:block">
+ {t("profile.appliesEverywhere")}
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={!form.isDirty || busy}
+ onClick={form.discard}
+ >
+ {t("profile.discard")}
+ </Button>
+ <Button
+ type="submit"
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={!form.isDirty || busy}
+ >
+ {form.isUploadingAvatar
+ ? t("auth.uploadingImage")
+ : form.isSaving
+ ? t("common.saving")
+ : t("common.save")}
+ </Button>
+ </div>
+ </PanelFooter>
+ )}
+ </form>
+ );
+}
diff --git a/components/profile/sessions-section.tsx b/components/profile/sessions-section.tsx
new file mode 100644
index 0000000..48c32a1
--- /dev/null
+++ b/components/profile/sessions-section.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { formatDistanceToNow } from "date-fns";
+import { UAParser } from "ua-parser-js";
+import { LogOut, Monitor, MonitorSmartphone, Smartphone, Tablet } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { ListRow, Pill } from "@/components/form-kit";
+import { PanelBody } from "@/components/panel-dialog";
+import { accountContentClass, SectionHeading } from "@/components/profile/account-layout";
+import type { SessionWithDevice } from "@/hooks/useSessions";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+function parseUserAgent(userAgent: string | null | undefined) {
+ if (!userAgent) return { browser: null, os: null, icon: MonitorSmartphone };
+
+ const result = new UAParser(userAgent).getResult();
+ const os = result.os.name
+ ? `${result.os.name}${result.os.version ? ` ${result.os.version}` : ""}`
+ : null;
+
+ let icon = MonitorSmartphone;
+ if (result.device.type === "mobile") icon = Smartphone;
+ else if (result.device.type === "tablet") icon = Tablet;
+ // Desktop browsers report no device type
+ else if (result.device.type === undefined && result.os.name) icon = Monitor;
+
+ return { browser: result.browser.name ?? null, os, icon };
+}
+
+function SessionRow({
+ session,
+ isCurrent,
+ revoking,
+ onRevoke,
+}: {
+ session: SessionWithDevice;
+ isCurrent: boolean;
+ revoking: boolean;
+ onRevoke: () => void;
+}) {
+ const t = useTranslations();
+ const dateLocale = getDateLocale(useLocale());
+ const device = parseUserAgent(session.userAgent);
+ const Icon = device.icon;
+
+ const lastActive = isCurrent
+ ? t("profile.activeNow")
+ : formatDistanceToNow(new Date(session.updatedAt), { addSuffix: true, locale: dateLocale });
+ const meta = [session.ipAddress, lastActive].filter(Boolean).join(" · ");
+
+ return (
+ <ListRow className="py-[11px]">
+ <Icon className="size-[18px] shrink-0 text-fg-secondary" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[14px] font-semibold text-fg-strong">
+ {device.browser ?? t("profile.unknownBrowser")} · {device.os ?? t("profile.unknownOs")}
+ </div>
+ <div className="mt-0.5 truncate font-mono text-[12px] text-fg-tertiary">{meta}</div>
+ </div>
+ {isCurrent ? (
+ <Pill tone="success">{t("profile.thisDevice")}</Pill>
+ ) : (
+ <button
+ type="button"
+ onClick={onRevoke}
+ disabled={revoking}
+ className="shrink-0 rounded-md px-2 py-1 text-[13px] font-medium text-danger transition-colors hover:bg-danger-soft disabled:opacity-50"
+ >
+ {t("auth.logout")}
+ </button>
+ )}
+ </ListRow>
+ );
+}
+
+/** Screen 11c: signed-in devices, each revocable except the current one. */
+export function SessionsSection({
+ sessions,
+ currentSessionId,
+ revokeAllSessions,
+ revokeSession,
+}: {
+ sessions: SessionWithDevice[];
+ currentSessionId: string | undefined;
+ revokeAllSessions: () => Promise<{ success: boolean; error?: string; revokedCount?: number }>;
+ revokeSession: (token: string) => Promise<{ success: boolean; error?: string }>;
+}) {
+ const t = useTranslations();
+ const [revokingToken, setRevokingToken] = useState<string | null>(null);
+ const [revokingAll, setRevokingAll] = useState(false);
+
+ const sorted = [...sessions].sort((a, b) => {
+ if (a.id === currentSessionId) return -1;
+ if (b.id === currentSessionId) return 1;
+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
+ });
+
+ const handleRevokeAll = async () => {
+ setRevokingAll(true);
+ const result = await revokeAllSessions();
+ setRevokingAll(false);
+
+ if (result.success) {
+ toast.success(t("auth.sessionsRevokedCount", { count: result.revokedCount || 0 }));
+ } else {
+ toast.error(result.error || t("common.error"));
+ }
+ };
+
+ const handleRevoke = async (token: string) => {
+ setRevokingToken(token);
+ const result = await revokeSession(token);
+ setRevokingToken(null);
+
+ if (result.success) {
+ toast.success(t("profile.sessionRevoked"));
+ } else {
+ toast.error(result.error || t("common.error"));
+ }
+ };
+
+ return (
+ <PanelBody>
+ <div className={cn(accountContentClass, "flex flex-col gap-4")}>
+ <SectionHeading
+ title={t("profile.sessionsTitle")}
+ description={t("profile.sessionsHint")}
+ action={
+ sessions.length > 1 && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-[34px] font-semibold"
+ disabled={revokingAll}
+ onClick={handleRevokeAll}
+ >
+ <LogOut className="size-[15px]" />
+ {t("profile.signOutOthers")}
+ </Button>
+ )
+ }
+ />
+ {sorted.length === 0 ? (
+ <p className="rounded-[11px] border border-dashed border-control px-3.5 py-3 text-center text-[13px] text-fg-tertiary">
+ {t("auth.noActiveSessions")}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-2.5">
+ {sorted.map((session) => (
+ <SessionRow
+ key={session.id}
+ session={session}
+ isCurrent={session.id === currentSessionId}
+ revoking={revokingToken === session.token}
+ onRevoke={() => handleRevoke(session.token)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </PanelBody>
+ );
+}
diff --git a/components/read-only-banner.tsx b/components/read-only-banner.tsx
index c3702e3..572b011 100644
--- a/components/read-only-banner.tsx
+++ b/components/read-only-banner.tsx
@@ -1,32 +1,17 @@
"use client";
-import { Eye, Lock } from "lucide-react";
-import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Eye } from "lucide-react";
+import { StatusBanner } from "@/components/status-banner";
interface ReadOnlyBannerProps {
+ title?: string;
message?: string;
- variant?: "default" | "compact";
}
-export function ReadOnlyBanner({
- message,
- variant = "default",
-}: ReadOnlyBannerProps) {
- if (variant === "compact") {
- return (
- <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-900/50 rounded-md p-2 flex items-center gap-2">
- <Eye className="h-4 w-4 text-blue-600 dark:text-blue-400 shrink-0" />
- <p className="text-xs text-blue-900 dark:text-blue-100">{message}</p>
- </div>
- );
- }
-
+export function ReadOnlyBanner({ title, message }: ReadOnlyBannerProps) {
return (
- <Alert className="bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900/50">
- <Lock className="h-4 w-4 text-blue-600 dark:text-blue-400" />
- <AlertDescription className="text-sm text-blue-900 dark:text-blue-100">
- {message}
- </AlertDescription>
- </Alert>
+ <StatusBanner tone="warning" icon={Eye} title={title}>
+ {message}
+ </StatusBanner>
);
}
diff --git a/components/segmented-control.tsx b/components/segmented-control.tsx
new file mode 100644
index 0000000..050bef7
--- /dev/null
+++ b/components/segmented-control.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+
+interface SegmentedControlProps<T extends string> {
+ value: T;
+ onChange: (value: T) => void;
+ options: { value: T; label: string; badge?: React.ReactNode }[];
+ label: string;
+ size?: "md" | "lg";
+ className?: string;
+}
+
+/** Track with at most three segments; the active one is lifted onto a card surface. */
+export function SegmentedControl<T extends string>({
+ value,
+ onChange,
+ options,
+ label,
+ size = "md",
+ className,
+}: SegmentedControlProps<T>) {
+ return (
+ <div
+ role="tablist"
+ aria-label={label}
+ className={cn("flex rounded-[10px] bg-surface-sunken p-[3px]", className)}
+ >
+ {options.map((option) => {
+ const active = option.value === value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => onChange(option.value)}
+ className={cn(
+ "flex flex-1 items-center justify-center gap-1.5 rounded-lg font-medium transition-colors",
+ size === "lg" ? "h-[34px] text-[13.5px]" : "h-[30px] text-[13px]",
+ active
+ ? "bg-surface-card font-semibold text-fg-strong shadow-segment dark:bg-control"
+ : "text-fg-secondary hover:text-fg-strong"
+ )}
+ >
+ {option.label}
+ {option.badge}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/components/settings-dialog.tsx b/components/settings-dialog.tsx
new file mode 100644
index 0000000..56e4a85
--- /dev/null
+++ b/components/settings-dialog.tsx
@@ -0,0 +1,428 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Bell,
+ Download,
+ Layers,
+ Palette,
+ RefreshCw,
+ SlidersHorizontal,
+ TriangleAlert,
+ Users,
+ type LucideIcon,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { PanelBody, PanelDialog, PanelFooter } from "@/components/panel-dialog";
+import { ColorSwatches, DangerZone, Field, inputClass } from "@/components/form-kit";
+import { ExportPanel } from "@/components/export-dialog";
+import { CalendarViewPanel, ViewSettingsState } from "@/components/view-settings-sheet";
+import { PresetsPanel } from "@/components/preset-manage-sheet";
+import { ExternalSyncPanel } from "@/components/external-sync-manage-sheet";
+import { SyncNotificationsPanel } from "@/components/sync-notification-dialog";
+import { SharingPanel } from "@/components/calendar-share-management-sheet";
+import { isUsableToken } from "@/components/calendar-token-list";
+import { useCalendars } from "@/hooks/useCalendars";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { usePresets } from "@/hooks/usePresets";
+import { useShifts } from "@/hooks/useShifts";
+import { useExternalSync } from "@/hooks/useExternalSync";
+import { useCalendarTokens } from "@/hooks/useCalendarTokens";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { cn } from "@/lib/utils";
+import { useGuardedAction, useReportDirty } from "@/hooks/useDirtyState";
+
+export type SettingsSection =
+ | "general"
+ | "presets"
+ | "external"
+ | "sharing"
+ | "export"
+ | "view"
+ | "notifications";
+
+export interface SettingsItem {
+ id: SettingsSection;
+ icon: LucideIcon;
+ title: string;
+ description?: string;
+ /** Short value on the phone row */
+ meta?: string | number;
+ metaTone?: "danger";
+}
+
+interface SettingsDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string | null;
+ viewSettings: ViewSettingsState;
+ onDeleteCalendar: () => void;
+ onSyncComplete: () => void;
+}
+
+function GeneralPanel({
+ calendarId,
+ onClose,
+ onCancel,
+ onDeleteCalendar,
+ onDirtyChange,
+}: {
+ calendarId: string;
+ onClose: () => void;
+ onCancel: () => void;
+ onDeleteCalendar: () => void;
+ onDirtyChange: (dirty: boolean) => void;
+}) {
+ const t = useTranslations();
+ const { calendars, updateCalendar } = useCalendars();
+ const { canDelete } = useCalendarPermission(calendarId);
+ const { shifts } = useShifts(calendarId);
+ const calendar = calendars.find((c) => c.id === calendarId);
+ const [name, setName] = useState(calendar?.name ?? "");
+ const [color, setColor] = useState(calendar?.color ?? "");
+ const [saving, setSaving] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const dirty = !!calendar && (name !== calendar.name || color !== calendar.color);
+
+ useReportDirty(dirty, onDirtyChange);
+
+ const save = async () => {
+ if (!calendar) return;
+ setSaving(true);
+ try {
+ // Only the changed keys: the optimistic patch spreads this over the cached
+ // calendar, so an explicit `undefined` would blank the field until the
+ // server responds.
+ await updateCalendar(calendarId, {
+ ...(name !== calendar.name && { name: name.trim() }),
+ ...(color !== calendar.color && { color }),
+ });
+ onClose();
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <>
+ <PanelBody>
+ <div className="flex flex-col gap-5">
+ <Field label={t("common.labels.name")} htmlFor="calendar-name">
+ <Input
+ id="calendar-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ className={inputClass}
+ />
+ </Field>
+ <Field label={t("form.colorLabel")}>
+ <ColorSwatches value={color} onChange={setColor} allowCustom />
+ </Field>
+ {canDelete && (
+ <div className="border-t border-line pt-5">
+ <DangerZone
+ icon={TriangleAlert}
+ title={t("calendar.deleteCalendar")}
+ description={t("settings.deleteImpact", { count: shifts.length })}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-9 border-danger-line bg-surface-card font-semibold text-danger hover:bg-danger-soft hover:text-danger"
+ onClick={() => setConfirmDelete(true)}
+ >
+ {t("common.delete")}
+ </Button>
+ }
+ />
+ </div>
+ )}
+ </div>
+ </PanelBody>
+ <PanelFooter>
+ <p className="hidden min-w-0 flex-1 text-[13px] text-fg-secondary lg:block">
+ {t("settings.appliesToAll")}
+ </p>
+ <Button variant="outline" className="h-10 flex-1 font-semibold lg:flex-none lg:px-4" onClick={onCancel}>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={!dirty || !name.trim() || saving}
+ onClick={save}
+ >
+ {saving ? t("common.saving") : t("common.save")}
+ </Button>
+ </PanelFooter>
+ <ConfirmationDialog
+ open={confirmDelete}
+ onOpenChange={setConfirmDelete}
+ title={t("calendar.deleteCalendar")}
+ description={t("calendar.deleteWarning")}
+ confirmText={t("common.delete")}
+ confirmVariant="destructive"
+ onConfirm={() => {
+ setConfirmDelete(false);
+ onDeleteCalendar();
+ onClose();
+ }}
+ />
+ </>
+ );
+}
+
+/** The calendar's settings sections the current user may open, in display order. */
+export function useCalendarSettings(calendarId: string | null) {
+ const t = useTranslations();
+ const { calendars } = useCalendars();
+ const calendar = calendars.find((c) => c.id === calendarId);
+ const permission = useCalendarPermission(calendarId);
+ const { isAuthEnabled } = useAuthFeatures();
+ const { presets } = usePresets(calendarId ?? undefined);
+ const { externalSyncs, hasSyncErrors } = useExternalSync(
+ permission.canManage ? calendarId : null
+ );
+ const { tokens } = useCalendarTokens(permission.canShare ? calendarId : null);
+
+ const items: SettingsItem[] = [];
+ if (!calendar) return { calendar, items };
+ if (permission.canManage)
+ items.push({
+ id: "general",
+ icon: Palette,
+ title: t("settings.general"),
+ description: t("settings.generalHint"),
+ });
+ if (permission.canEdit)
+ items.push({
+ id: "presets",
+ icon: Layers,
+ title: t("settings.presets"),
+ description: t("settings.presetsHint", { count: presets.length }),
+ meta: presets.length,
+ });
+ if (permission.canManage)
+ items.push({
+ id: "external",
+ icon: RefreshCw,
+ title: t("settings.external"),
+ description: t("settings.externalHint", { count: externalSyncs.length }),
+ meta: externalSyncs.length,
+ });
+ if (isAuthEnabled && permission.canShare)
+ items.push({
+ id: "sharing",
+ icon: Users,
+ title: t("settings.sharing"),
+ description: t("settings.sharingHint", { count: tokens.filter(isUsableToken).length }),
+ });
+ items.push(
+ {
+ id: "export",
+ icon: Download,
+ title: t("settings.export"),
+ description: t("settings.exportHint"),
+ },
+ {
+ id: "view",
+ icon: SlidersHorizontal,
+ title: t("settings.view"),
+ description: t("settings.viewHint"),
+ meta: calendar.viewSettings ? t("settings.viewOn") : t("settings.viewOff"),
+ },
+ {
+ id: "notifications",
+ icon: Bell,
+ title: t("settings.notifications"),
+ description: hasSyncErrors ? t("settings.notificationsError") : t("settings.notificationsHint"),
+ meta: hasSyncErrors ? t("common.error") : undefined,
+ metaTone: hasSyncErrors ? "danger" : undefined,
+ }
+ );
+ return { calendar, items };
+}
+
+export interface CalendarSettingsPanelProps {
+ section: SettingsSection;
+ calendarId: string;
+ viewSettings: ViewSettingsState;
+ /** Closes without asking, e.g. after saving */
+ onClose: () => void;
+ /** Closes, asking first when there are unsaved changes */
+ onCancel: () => void;
+ onDirtyChange: (dirty: boolean) => void;
+ onDeleteCalendar: () => void;
+ onSyncComplete: () => void;
+}
+
+/** One calendar settings section, shared by the desktop dialog and the phone menu. */
+export function CalendarSettingsPanel({
+ section,
+ calendarId,
+ viewSettings,
+ onClose,
+ onCancel,
+ onDirtyChange,
+ onDeleteCalendar,
+ onSyncComplete,
+}: CalendarSettingsPanelProps) {
+ switch (section) {
+ case "general":
+ return (
+ <GeneralPanel
+ key={calendarId}
+ calendarId={calendarId}
+ onClose={onClose}
+ onCancel={onCancel}
+ onDeleteCalendar={onDeleteCalendar}
+ onDirtyChange={onDirtyChange}
+ />
+ );
+ case "presets":
+ return <PresetsPanel calendarId={calendarId} onClose={onClose} onDirtyChange={onDirtyChange} />;
+ case "external":
+ return (
+ <ExternalSyncPanel
+ calendarId={calendarId}
+ onClose={onClose}
+ onSyncComplete={onSyncComplete}
+ onDirtyChange={onDirtyChange}
+ />
+ );
+ case "sharing":
+ return <SharingPanel calendarId={calendarId} onClose={onCancel} onDirtyChange={onDirtyChange} />;
+ case "export":
+ return <ExportPanel calendarId={calendarId} onClose={onClose} />;
+ case "view":
+ return (
+ <CalendarViewPanel
+ key={calendarId}
+ calendarId={calendarId}
+ personal={viewSettings.personal}
+ onClose={onClose}
+ onCancel={onCancel}
+ onDirtyChange={onDirtyChange}
+ />
+ );
+ case "notifications":
+ return <SyncNotificationsPanel calendarId={calendarId} onClose={onClose} />;
+ }
+}
+
+/** Desktop calendar settings; phones reach the same sections through the phone menu. */
+export function SettingsDialog({
+ open,
+ onOpenChange,
+ calendarId,
+ viewSettings,
+ onDeleteCalendar,
+ onSyncComplete,
+}: SettingsDialogProps) {
+ const t = useTranslations();
+ const { calendar, items } = useCalendarSettings(calendarId);
+ const [section, setSection] = useState<SettingsSection | null>(null);
+ const [dirty, setDirty] = useState(false);
+
+ const close = () => {
+ setDirty(false);
+ onOpenChange(false);
+ };
+ // Panels with unsaved input report it; leaving them asks first
+ const { guarded, confirmProps } = useGuardedAction(dirty, () => setDirty(false));
+ const openSection = (id: SettingsSection) =>
+ guarded(() => {
+ setDirty(false);
+ setSection(id);
+ });
+ const requestClose = (next: boolean) => {
+ if (next) onOpenChange(true);
+ else guarded(close);
+ };
+
+ const active = items.some((i) => i.id === section) ? section : items[0]?.id;
+
+ return (
+ <>
+ <PanelDialog
+ bare
+ open={open}
+ onOpenChange={requestClose}
+ width="xl"
+ fixedHeight="min(640px, calc(100dvh - 48px))"
+ title={
+ <span className="flex items-center gap-2.5">
+ {calendar && (
+ <span className="size-2.5 rounded-full" style={{ backgroundColor: calendar.color }} />
+ )}
+ {calendar?.name ?? t("settings.title")}
+ </span>
+ }
+ description={t("settings.description")}
+ >
+ <div className="flex min-h-0 flex-1">
+ <nav className="flex w-[278px] shrink-0 flex-col gap-1 overflow-y-auto border-r border-line bg-surface-panel p-2.5">
+ {items.map((item) => {
+ const selected = item.id === active;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => openSection(item.id)}
+ aria-current={selected ? "page" : undefined}
+ className={cn(
+ "flex items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",
+ selected
+ ? "bg-brand-soft shadow-[inset_2px_0_0_var(--brand)]"
+ : "hover:bg-surface-sunken"
+ )}
+ >
+ <item.icon
+ className={cn("mt-0.5 size-4 shrink-0", selected ? "text-brand-ink" : "text-fg-secondary")}
+ />
+ <span className="min-w-0">
+ <span
+ className={cn(
+ "block text-[13.5px] font-semibold",
+ selected ? "text-brand-ink" : "text-fg-body"
+ )}
+ >
+ {item.title}
+ </span>
+ {item.description && (
+ <span
+ className={cn(
+ "block text-[12px]",
+ selected ? "text-brand-ink/80" : "text-fg-tertiary"
+ )}
+ >
+ {item.description}
+ </span>
+ )}
+ </span>
+ </button>
+ );
+ })}
+ </nav>
+ <div key={active} className="flex min-w-0 flex-1 flex-col">
+ {active && calendarId && (
+ <CalendarSettingsPanel
+ section={active}
+ calendarId={calendarId}
+ viewSettings={viewSettings}
+ onClose={close}
+ onCancel={() => requestClose(false)}
+ onDirtyChange={setDirty}
+ onDeleteCalendar={onDeleteCalendar}
+ onSyncComplete={onSyncComplete}
+ />
+ )}
+ </div>
+ </div>
+ </PanelDialog>
+ <ConfirmationDialog {...confirmProps} />
+ </>
+ );
+}
diff --git a/components/shift-card.tsx b/components/shift-card.tsx
deleted file mode 100644
index 8be1c10..0000000
--- a/components/shift-card.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { ShiftWithCalendar } from "@/lib/types";
-import { Card } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Trash2, Pencil } from "lucide-react";
-import { motion } from "motion/react";
-
-interface ShiftCardProps {
- shift: ShiftWithCalendar;
- onDelete?: (id: string) => void;
- onEdit?: (shift: ShiftWithCalendar) => void;
-}
-
-export function ShiftCard({ shift, onDelete, onEdit }: ShiftCardProps) {
- const t = useTranslations();
-
- const isEditable = onEdit && !shift.externalSyncId && !shift.syncedFromExternal;
-
- const handleCardClick = () => {
- if (isEditable) {
- onEdit(shift);
- }
- };
-
- return (
- <motion.div
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, scale: 0.95 }}
- transition={{ duration: 0.2 }}
- layout
- >
- <Card
- className={`p-3 sm:p-4 hover:shadow-lg active:scale-[0.98] transition-all group relative overflow-hidden border-l-4 ${isEditable ? "cursor-pointer" : ""
- }`}
- style={{ borderLeftColor: shift.color || "#3b82f6" }}
- onClick={handleCardClick}
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm sm:text-base truncate">
- {shift.title}
- </h3>
- <div className="flex items-center gap-2 text-xs sm:text-sm text-muted-foreground mt-1">
- {shift.isAllDay ? (
- <span className="font-medium">{t("shift.allDay")}</span>
- ) : (
- <>
- <span className="font-medium">{shift.startTime}</span>
- <span className="opacity-50">→</span>
- <span className="font-medium">{shift.endTime}</span>
- </>
- )}
- </div>
- {shift.notes && (
- <p className="text-xs sm:text-sm text-muted-foreground mt-2 line-clamp-2 leading-relaxed">
- {shift.notes}
- </p>
- )}
- </div>
- <div className="flex items-center gap-1">
- {isEditable && (
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8 sm:h-9 sm:w-9 transition-all text-muted-foreground hover:text-foreground hover:bg-muted flex-shrink-0 rounded-full"
- onClick={(e) => {
- e.stopPropagation();
- onEdit(shift);
- }}
- >
- <Pencil className="h-4 w-4" />
- </Button>
- )}
- {!shift.externalSyncId && !shift.syncedFromExternal && onDelete && (
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8 sm:h-9 sm:w-9 transition-all text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 flex-shrink-0 rounded-full"
- onClick={(e) => {
- e.stopPropagation();
- onDelete(shift.id);
- }}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- )}
- </div>
- </div>
- <div
- className="absolute inset-0 opacity-[0.05] pointer-events-none"
- style={{ backgroundColor: shift.color || "#3b82f6" }}
- />
- </Card>
- </motion.div>
- );
-}
-
diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsx
index 2d3dcf8..f3d65d4 100644
--- a/components/shift-form-fields.tsx
+++ b/components/shift-form-fields.tsx
@@ -1,12 +1,19 @@
-import { motion } from "motion/react";
-import { useTranslations } from "next-intl";
+import { useLocale, useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
-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 {
+ CheckRow,
+ ColorSwatches,
+ Field,
+ inputClass,
+ textareaClass,
+} from "@/components/form-kit";
import { ShiftFormData } from "@/components/shift-sheet";
-import { PRESET_COLORS } from "@/lib/constants";
+import { useAutoFocusRef } from "@/hooks/useAutoFocus";
+import { DEFAULT_COLOR } from "@/lib/constants";
+import { calculateShiftDuration } from "@/lib/date-utils";
+import { formatHours } from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
interface ShiftFormFieldsProps {
formData: ShiftFormData;
@@ -16,11 +23,11 @@ interface ShiftFormFieldsProps {
presetName: string;
onPresetNameChange: (value: string) => void;
isEditing: boolean;
- onBlur?: () => void;
- showSaved?: boolean;
readOnly?: boolean;
}
+const TIME_PATTERN = /^\d{2}:\d{2}$/;
+
export function ShiftFormFields({
formData,
onFormDataChange,
@@ -29,182 +36,129 @@ export function ShiftFormFields({
presetName,
onPresetNameChange,
isEditing,
- onBlur,
readOnly = false,
}: ShiftFormFieldsProps) {
const t = useTranslations();
+ const locale = useLocale();
+ const titleRef = useAutoFocusRef<HTMLInputElement>(!readOnly);
- return (
- <div className="space-y-5">
- <div className="space-y-2.5">
- <Label
- htmlFor="date"
- 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.date")}
- </Label>
- <Input
- id="date"
- type="date"
- value={formData.date}
- onChange={(e) =>
- onFormDataChange({ ...formData, date: e.target.value })
- }
- onBlur={onBlur}
- disabled={readOnly}
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
- />
- </div>
+ const validTimes =
+ !formData.isAllDay &&
+ TIME_PATTERN.test(formData.startTime) &&
+ TIME_PATTERN.test(formData.endTime);
+ const duration = validTimes
+ ? formatHours(calculateShiftDuration(formData.startTime, formData.endTime), locale)
+ : "–";
+ const timesDisabled = readOnly || formData.isAllDay;
- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">
- <Checkbox
- id="allDay"
- checked={formData.isAllDay}
- onCheckedChange={(checked) => {
- onFormDataChange({ ...formData, isAllDay: !!checked });
- setTimeout(() => onBlur?.(), 10);
- }}
- disabled={readOnly}
- />
- <Label htmlFor="allDay" className="text-sm font-medium cursor-pointer">
- {t("shift.allDayShift")}
- </Label>
- </div>
+ return (
+ <div className="flex flex-col gap-3 lg:gap-4">
+ {/* Creating uses the day shown in the header; editing may move the shift */}
+ {isEditing && (
+ <Field label={t("shift.date")} htmlFor="date">
+ <Input
+ id="date"
+ type="date"
+ value={formData.date}
+ onChange={(e) => onFormDataChange({ ...formData, date: e.target.value })}
+ disabled={readOnly}
+ className={cn(inputClass, "font-mono")}
+ />
+ </Field>
+ )}
- {!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="startTime" className="text-sm font-medium">
- {t("shift.startTime")}
- </Label>
+ <div className="flex flex-col gap-2.5 lg:gap-3">
+ <div className="flex gap-2.5">
+ <Field label={t("shiftSheet.start")} htmlFor="startTime" className="flex-1">
<Input
id="startTime"
type="time"
value={formData.startTime}
- onChange={(e) =>
- onFormDataChange({ ...formData, startTime: e.target.value })
- }
- onBlur={onBlur}
- disabled={readOnly}
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ onChange={(e) => onFormDataChange({ ...formData, startTime: e.target.value })}
+ disabled={timesDisabled}
+ className={cn(inputClass, "font-mono")}
/>
- </div>
- <div className="space-y-2">
- <Label htmlFor="endTime" className="text-sm font-medium">
- {t("shift.endTime")}
- </Label>
+ </Field>
+ <Field label={t("shiftSheet.end")} htmlFor="endTime" className="flex-1">
<Input
id="endTime"
type="time"
value={formData.endTime}
- onChange={(e) =>
- onFormDataChange({ ...formData, endTime: e.target.value })
- }
- onBlur={onBlur}
- disabled={readOnly}
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"
+ onChange={(e) => onFormDataChange({ ...formData, endTime: e.target.value })}
+ disabled={timesDisabled}
+ className={cn(inputClass, "font-mono")}
/>
- </div>
- </motion.div>
- )}
+ </Field>
+ <Field label={t("shiftSheet.duration")} className="w-[74px] shrink-0">
+ <output
+ aria-live="polite"
+ className="flex h-10 items-center justify-center rounded-[9px] bg-surface-sunken font-mono text-[14px] font-medium text-fg-body"
+ >
+ {duration}
+ </output>
+ </Field>
+ </div>
- <div className="space-y-2.5">
- <Label
- htmlFor="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>
+ <CheckRow
+ id="allDay"
+ label={t("shiftSheet.allDay")}
+ checked={!!formData.isAllDay}
+ onCheckedChange={(checked) => onFormDataChange({ ...formData, isAllDay: checked })}
+ disabled={readOnly}
+ />
+ </div>
+
+ <Field label={t("shift.titleLabel")} htmlFor="title">
<Input
id="title"
placeholder={t("shift.titlePlaceholder")}
value={formData.title}
- onChange={(e) =>
- onFormDataChange({ ...formData, title: e.target.value })
- }
- onBlur={onBlur}
+ onChange={(e) => onFormDataChange({ ...formData, title: e.target.value })}
disabled={readOnly}
- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"
- autoFocus={!readOnly}
+ className={inputClass}
+ ref={titleRef}
/>
- </div>
+ </Field>
+
+ <Field label={t("form.colorLabel")}>
+ <ColorSwatches
+ value={formData.color || DEFAULT_COLOR}
+ onChange={(color) => onFormDataChange({ ...formData, color })}
+ allowCustom
+ disabled={readOnly}
+ />
+ </Field>
- <div className="space-y-2.5">
- <Label
- htmlFor="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>
+ <Field label={t("calendarView.note")} htmlFor="notes" optional>
<Textarea
id="notes"
placeholder={t("form.notesPlaceholder")}
value={formData.notes}
- onChange={(e) =>
- onFormDataChange({ ...formData, notes: e.target.value })
- }
- onBlur={onBlur}
+ onChange={(e) => onFormDataChange({ ...formData, notes: e.target.value })}
disabled={readOnly}
rows={3}
- className="border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 resize-none"
+ className={cn(textareaClass, "min-h-16")}
/>
- </div>
-
- <ColorPicker
- color={formData.color || "#3b82f6"}
- onChange={(color) => onFormDataChange({ ...formData, color })}
- label={t("form.colorLabel")}
- presetColors={PRESET_COLORS}
- disabled={readOnly}
- />
+ </Field>
- {/* Auto-Save as Preset */}
{!isEditing && !readOnly && (
- <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="savePreset"
- checked={saveAsPreset}
- onCheckedChange={(checked) =>
- onSaveAsPresetChange(checked as boolean)
- }
- />
- <Label
- htmlFor="savePreset"
- 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("preset.saveAsPreset")}
- </Label>
- </div>
+ <div className="flex flex-col gap-2.5 lg:gap-3">
+ <CheckRow
+ id="savePreset"
+ label={t("preset.saveAsPreset")}
+ checked={saveAsPreset}
+ onCheckedChange={onSaveAsPresetChange}
+ />
{saveAsPreset && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="space-y-2 pt-1"
- >
- <Label htmlFor="presetName" className="text-sm">
- {t("preset.presetName")}
- </Label>
+ <Field label={t("preset.presetName")} htmlFor="presetName">
<Input
id="presetName"
placeholder={t("preset.presetNamePlaceholder")}
value={presetName}
onChange={(e) => onPresetNameChange(e.target.value)}
- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"
+ className={inputClass}
/>
- </motion.div>
+ </Field>
)}
</div>
)}
diff --git a/components/shift-sheet.tsx b/components/shift-sheet.tsx
index 163dadf..5189b14 100644
--- a/components/shift-sheet.tsx
+++ b/components/shift-sheet.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useState, useEffect, useRef } from "react";
-import { useTranslations } from "next-intl";
+import { useMemo, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
import { BaseSheet } from "@/components/ui/base-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormFields } from "@/components/shift-form-fields";
@@ -9,7 +9,7 @@ import { PresetSelect } from "@/components/preset-select";
import { ReadOnlyBanner } from "@/components/read-only-banner";
import { useShiftForm } from "@/hooks/useShiftForm";
import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-import { formatDateToLocal } from "@/lib/date-utils";
+import { formatDateToLocal, formatLongDate, parseLocalDate } from "@/lib/date-utils";
interface ShiftSheetProps {
open: boolean;
@@ -33,6 +33,19 @@ export interface ShiftFormData {
isAllDay?: boolean;
}
+// presetId is left out: the form never changes it and does not load it
+function snapshot(data: ShiftFormData) {
+ return JSON.stringify({
+ date: data.date,
+ startTime: data.startTime,
+ endTime: data.endTime,
+ title: data.title,
+ notes: data.notes || "",
+ color: data.color,
+ isAllDay: data.isAllDay || false,
+ });
+}
+
export function ShiftSheet({
open,
onOpenChange,
@@ -44,9 +57,9 @@ export function ShiftSheet({
readOnly = false,
}: ShiftSheetProps) {
const t = useTranslations();
+ const locale = useLocale();
const permission = useCalendarPermission(calendarId);
const [isSaving, setIsSaving] = useState(false);
- const initialFormDataRef = useRef<string | null>(null);
// Determine if sheet should be in read-only mode
const isReadOnly = readOnly || !permission.canEdit;
@@ -60,49 +73,39 @@ export function ShiftSheet({
presetName,
setPresetName,
applyPreset,
+ clearPreset,
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 [selectedPresetId, setSelectedPresetId] = useState<string | null>(null);
+ const [wasOpen, setWasOpen] = useState(open);
+ if (open !== wasOpen) {
+ setWasOpen(open);
+ if (open) setSelectedPresetId(null);
+ }
+
+ const initialSnapshot = useMemo(
+ () =>
+ shift
+ ? snapshot({
+ 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,
+ })
+ : null,
+ [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;
+ if (shift && initialSnapshot) {
+ return snapshot(formData) !== initialSnapshot;
}
// For new shifts, check if user has entered any data
@@ -145,35 +148,45 @@ export function ShiftSheet({
}
};
- const handlePresetSelect = async (
- preset: Parameters<typeof applyPreset>[0]
- ) => {
+ const handlePresetSelect = (preset: Parameters<typeof applyPreset>[0]) => {
+ setSelectedPresetId(preset.id);
applyPreset(preset);
};
+ const handlePresetClear = () => {
+ if (selectedPresetId === null) return;
+ setSelectedPresetId(null);
+ clearPreset();
+ };
+
+ const dateLabel = /^\d{4}-\d{2}-\d{2}$/.test(formData.date)
+ ? formatLongDate(parseLocalDate(formData.date), locale, { year: true })
+ : undefined;
+
return (
<BaseSheet
open={open}
onOpenChange={onOpenChange}
title={shift ? t("shift.edit") : t("shift.create")}
- description={
- shift ? t("shift.editDescription") : t("shift.createDescription")
- }
+ description={dateLabel}
showSaveButton={!isReadOnly}
showCancelButton
onSave={handleSave}
isSaving={isSaving}
saveDisabled={!formData.title.trim() || (shift && !hasChanges())}
+ saveLabel={shift ? undefined : t("shiftSheet.createAction")}
hasUnsavedChanges={!isReadOnly && hasChanges()}
- maxWidth="md"
>
- <div className="space-y-5">
- {/* Read-only banner */}
+ <div className="flex flex-col gap-3 lg:gap-4">
{isReadOnly && <ReadOnlyBanner message={t("guest.cannotEdit")} />}
- {/* Preset Selection */}
{!shift && !isReadOnly && (
- <PresetSelect presets={presets} onPresetSelect={handlePresetSelect} />
+ <PresetSelect
+ presets={presets}
+ value={selectedPresetId}
+ onPresetSelect={handlePresetSelect}
+ onClear={handlePresetClear}
+ />
)}
<ShiftFormFields
diff --git a/components/shift-stats.tsx b/components/shift-stats.tsx
index 238dabc..5b8e8df 100644
--- a/components/shift-stats.tsx
+++ b/components/shift-stats.tsx
@@ -1,17 +1,18 @@
"use client";
-import { useState, useEffect } from "react";
-import { useTranslations } from "next-intl";
-import { Button } from "@/components/ui/button";
-import {
- BarChart3,
- ChevronDown,
- ChevronUp,
- PieChart,
- Radar as RadarIcon,
-} from "lucide-react";
-import { formatDuration } from "@/lib/date-utils";
+import { useState, useMemo } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { useTheme } from "next-themes";
+import { Loader2 } from "lucide-react";
import { useShiftStats } from "@/hooks/useShiftStats";
+import { useShifts } from "@/hooks/useShifts";
+import { usePresets } from "@/hooks/usePresets";
+import { SegmentedControl } from "@/components/segmented-control";
+import { ChoiceChips } from "@/components/form-kit";
+import { useMediaQuery } from "@/hooks/useMediaQuery";
+import { formatHours } from "@/lib/shift-display";
+import { countFreeDays } from "@/lib/free-days";
+import { cn } from "@/lib/utils";
import {
PieChart as RechartsPieChart,
Pie,
@@ -31,30 +32,23 @@ import {
Radar,
} from "recharts";
-// Hook for responsive radius that's SSR-safe
-function useResponsiveRadius() {
- const [radius, setRadius] = useState(120); // Safe default for SSR
-
- useEffect(() => {
- if (typeof window === "undefined") return;
-
- const updateRadius = () => {
- setRadius(window.innerWidth < 640 ? 80 : 120);
- };
-
- // Set initial value
- updateRadius();
-
- // Add resize listener
- window.addEventListener("resize", updateRadius);
-
- // Cleanup
- return () => window.removeEventListener("resize", updateRadius);
- }, []);
-
- return radius;
+/** Mirrors the dark-mode lightening of `.shift-rail`, which SVG fills can't inherit. */
+function lightenForDark(color: string): string {
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color);
+ if (!match) return color;
+ const hex =
+ match[1].length === 3
+ ? match[1].split("").map((c) => c + c).join("")
+ : match[1];
+ const mix = (i: number) =>
+ Math.round(parseInt(hex.slice(i, i + 2), 16) * 0.72 + 255 * 0.28)
+ .toString(16)
+ .padStart(2, "0");
+ return `#${mix(0)}${mix(2)}${mix(4)}`;
}
+const tick = { fontSize: 12, fill: "var(--fg-tertiary)" };
+
// CustomTooltip component - declared outside to avoid recreation on each render
const CustomTooltip = ({
active,
@@ -71,15 +65,18 @@ const CustomTooltip = ({
}) => {
if (active && payload && payload.length) {
return (
- <div className="bg-card/95 backdrop-blur-sm border border-border rounded-lg p-3 shadow-lg">
- <p className="font-semibold text-sm mb-1">
+ <div className="rounded-lg border border-line bg-surface-card px-3 py-2 shadow-md">
+ <p className="mb-1 text-[12.5px] font-semibold text-fg-strong">
{payload[0].payload.fullName || payload[0].name}
</p>
{payload.map((entry) => (
- <p key={entry.name} className="text-xs text-muted-foreground">
- <span style={{ color: entry.color }}>{entry.name}:</span>{" "}
- {entry.value}
- {entry.name === "hours" || entry.dataKey === "hours" ? "h" : ""}
+ <p key={entry.name} className="flex items-center gap-1.5 text-[12px] text-fg-secondary">
+ <span className="size-2 rounded-full" style={{ backgroundColor: entry.color }} />
+ {entry.name}:{" "}
+ <span className="font-mono text-fg-strong">
+ {entry.value}
+ {entry.name === "hours" || entry.dataKey === "hours" ? "h" : ""}
+ </span>
</p>
))}
</div>
@@ -88,56 +85,79 @@ const CustomTooltip = ({
return null;
};
+function KpiTile({ label, value }: { label: string; value: React.ReactNode }) {
+ return (
+ <div className="rounded-lg border border-line bg-surface-card px-3 py-2.5">
+ <div className="text-[11.5px] text-fg-tertiary">{label}</div>
+ <div className="mt-1 font-mono text-[21px] font-medium text-fg-strong">{value}</div>
+ </div>
+ );
+}
+
+function Swatch({ color }: { color: string }) {
+ return (
+ <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: color }} />
+ );
+}
+
interface ShiftStatsProps {
calendarId: string | undefined;
currentDate: Date;
}
type ViewMode = "overview" | "pie" | "bar" | "radar";
+type Period = "week" | "month" | "year";
-const CHART_COLORS = [
- "#3b82f6", // primary blue
- "#8b5cf6", // purple
- "#ec4899", // pink
- "#f59e0b", // amber
- "#10b981", // green
- "#06b6d4", // cyan
- "#f97316", // orange
- "#6366f1", // indigo
- "#14b8a6", // teal
- "#a855f7", // violet
- "#ef4444", // red
- "#22c55e", // lime
-];
-
+/** Period statistics with charts; the surrounding dialog provides the frame. */
export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {
const t = useTranslations();
- const [period, setPeriod] = useState<"week" | "month" | "year">("month");
+ const locale = useLocale();
+ const { resolvedTheme } = useTheme();
+ const [period, setPeriod] = useState<Period>("month");
const [viewMode, setViewMode] = useState<ViewMode>("overview");
- const [isExpanded, setIsExpanded] = useState(true);
- const outerRadius = useResponsiveRadius();
+ const outerRadius = useMediaQuery("(min-width: 640px)", true) ? 120 : 80;
const { stats, loading } = useShiftStats({
calendarId,
currentDate,
period,
});
+ const { shifts } = useShifts(calendarId);
+ const { presets } = usePresets(calendarId);
- if (!calendarId) return null;
-
- const totalShifts = stats?.totalShifts || 0;
- const totalMinutes = stats?.totalMinutes || 0;
+ // The stats API groups by title without colors, so borrow them from loaded shifts and presets
+ const colorByTitle = useMemo(() => {
+ const dark = resolvedTheme === "dark";
+ const known = new Map<string, string>();
+ for (const shift of shifts) {
+ if (!known.has(shift.title)) known.set(shift.title, shift.color);
+ }
+ for (const preset of presets) {
+ if (!known.has(preset.title)) known.set(preset.title, preset.color);
+ }
+ const colors = new Map<string, string>();
+ Object.keys(stats?.stats ?? {}).forEach((title, index) => {
+ const color = known.get(title);
+ colors.set(
+ title,
+ color ? (dark ? lightenForDark(color) : color) : `var(--chart-${(index % 5) + 1})`
+ );
+ });
+ return colors;
+ }, [stats, shifts, presets, resolvedTheme]);
// Prepare data for charts
- const pieData = stats
+ const pieData = useMemo(() =>
+ stats
? Object.entries(stats.stats).map(([title, data]) => ({
name: title,
value: data.count,
hours: Math.round((data.totalMinutes / 60) * 10) / 10,
}))
- : [];
+ : [], [stats]);
- const barData = stats
+ const barData = useMemo(() =>
+ stats
? Object.entries(stats.stats)
.map(([title, data]) => ({
name: title.length > 15 ? title.substring(0, 15) + "..." : title,
@@ -146,10 +166,11 @@ export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {
hours: Math.round((data.totalMinutes / 60) * 10) / 10,
}))
.sort((a, b) => b.shifts - a.shifts)
- : [];
+ : [], [stats]);
// Prepare data for radar chart (top shift types by hours)
- const radarData = stats
+ const radarData = useMemo(() =>
+ stats
? Object.entries(stats.stats)
.sort(([, a], [, b]) => b.totalMinutes - a.totalMinutes)
.slice(0, 6) // Top 6 shift types
@@ -162,409 +183,278 @@ export function ShiftStats({ calendarId, currentDate }: ShiftStatsProps) {
? Math.round((data.totalMinutes / data.count / 60) * 10) / 10
: 0,
}))
- : [];
+ : [], [stats]);
+
+
+ if (!calendarId) return null;
+
+ const colorFor = (title: string) => colorByTitle.get(title) ?? "var(--chart-1)";
+ const totalShifts = stats?.totalShifts || 0;
+ const totalMinutes = stats?.totalMinutes || 0;
+ const hasData = !!stats && Object.keys(stats.stats).length > 0;
+ const freeDays = stats ? countFreeDays(stats) : null;
return (
- <div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">
- {/* Header */}
- <button
- onClick={() => setIsExpanded(!isExpanded)}
- className="w-full px-3 sm:px-4 py-3 sm:py-3.5 flex items-center justify-between hover:bg-primary/5 transition-all"
- >
- <div className="flex items-center gap-2.5">
- <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/20">
- <BarChart3 className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />
- </div>
- <h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- {t("stats.title")}
- </h3>
+ <div className="flex flex-col gap-4">
+ <SegmentedControl
+ value={period}
+ onChange={setPeriod}
+ label={t("stats.title")}
+ options={[
+ { value: "week", label: t("stats.week") },
+ { value: "month", label: t("stats.month") },
+ { value: "year", label: t("stats.year") },
+ ]}
+ />
+
+ {hasData && (
+ <ChoiceChips
+ value={viewMode}
+ onChange={setViewMode}
+ label={t("stats.title")}
+ options={[
+ { value: "overview", label: t("stats.overview") },
+ { value: "pie", label: t("stats.distribution") },
+ { value: "bar", label: t("stats.comparison") },
+ { value: "radar", label: t("stats.radar") },
+ ]}
+ />
+ )}
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="size-6 animate-spin text-fg-tertiary" />
</div>
- <div className="flex items-center gap-2">
- {!isExpanded && stats && totalShifts > 0 && (
+ ) : stats && hasData ? (
+ <>
+ {viewMode === "overview" && (
<>
- <div className="px-2.5 py-1 bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30 rounded-lg">
- <span className="font-bold text-primary text-xs sm:text-sm">
- {totalShifts}
- </span>
+ {/* Without timed shifts only four tiles remain, so keep them on one row */}
+ <div
+ className={cn(
+ "grid grid-cols-2 gap-2",
+ stats.maxDuration > 0 ? "sm:grid-cols-3" : "sm:grid-cols-4"
+ )}
+ >
+ <KpiTile label={t("stats.totalShifts")} value={totalShifts} />
+ <KpiTile label={t("stats.totalHours")} value={formatHours(totalMinutes, locale)} />
+ <KpiTile
+ label={t("stats.avgPerShift")}
+ value={formatHours(stats.avgMinutesPerShift, locale)}
+ />
+ <KpiTile label={t("calendarView.kpiFreeDays")} value={freeDays ?? "–"} />
+ {stats.minDuration > 0 && (
+ <KpiTile
+ label={t("stats.shortestShift")}
+ value={formatHours(stats.minDuration, locale)}
+ />
+ )}
+ {stats.maxDuration > 0 && (
+ <KpiTile
+ label={t("stats.longestShift")}
+ value={formatHours(stats.maxDuration, locale)}
+ />
+ )}
</div>
- {totalMinutes > 0 && (
- <div className="px-2.5 py-1 bg-gradient-to-r from-primary/20 to-primary/10 border border-primary/30 rounded-lg">
- <span className="font-bold text-primary text-xs sm:text-sm">
- {formatDuration(totalMinutes)}
- </span>
- </div>
- )}
- </>
- )}
- {isExpanded ? (
- <ChevronUp className="h-4 w-4 text-muted-foreground" />
- ) : (
- <ChevronDown className="h-4 w-4 text-muted-foreground" />
- )}
- </div>
- </button>
-
- {/* Content */}
- {isExpanded && (
- <div className="px-3 sm:px-4 pb-3 sm:pb-4 space-y-4 border-t border-border/30 bg-muted/20">
- {/* Period Selector */}
- <div className="flex gap-2 pt-4">
- <Button
- variant={period === "week" ? "default" : "outline"}
- size="sm"
- onClick={() => setPeriod("week")}
- className="flex-1 sm:flex-none h-9 transition-all shadow-sm"
- >
- {t("stats.week")}
- </Button>
- <Button
- variant={period === "month" ? "default" : "outline"}
- size="sm"
- onClick={() => setPeriod("month")}
- className="flex-1 sm:flex-none h-9 transition-all shadow-sm"
- >
- {t("stats.month")}
- </Button>
- <Button
- variant={period === "year" ? "default" : "outline"}
- size="sm"
- onClick={() => setPeriod("year")}
- className="flex-1 sm:flex-none h-9 transition-all shadow-sm"
- >
- {t("stats.year")}
- </Button>
- </div>
- {/* View Mode Selector */}
- {stats && Object.keys(stats.stats).length > 0 && (
- <div className="grid grid-cols-2 sm:flex gap-2">
- <Button
- variant={viewMode === "overview" ? "default" : "outline"}
- size="sm"
- onClick={() => setViewMode("overview")}
- className="sm:flex-none h-8 text-xs transition-all"
- >
- <BarChart3 className="h-3.5 w-3.5 mr-1.5" />
- {t("stats.overview")}
- </Button>
- <Button
- variant={viewMode === "pie" ? "default" : "outline"}
- size="sm"
- onClick={() => setViewMode("pie")}
- className="sm:flex-none h-8 text-xs transition-all"
- >
- <PieChart className="h-3.5 w-3.5 mr-1.5" />
- {t("stats.distribution")}
- </Button>
- <Button
- variant={viewMode === "bar" ? "default" : "outline"}
- size="sm"
- onClick={() => setViewMode("bar")}
- className="sm:flex-none h-8 text-xs transition-all"
- >
- <BarChart3 className="h-3.5 w-3.5 mr-1.5" />
- {t("stats.comparison")}
- </Button>
- <Button
- variant={viewMode === "radar" ? "default" : "outline"}
- size="sm"
- onClick={() => setViewMode("radar")}
- className="sm:flex-none h-8 text-xs transition-all"
- >
- <RadarIcon className="h-3.5 w-3.5 mr-1.5" />
- {t("stats.radar")}
- </Button>
- </div>
+ <div className="flex flex-col gap-2">
+ <div className="eyebrow">{t("stats.byType")}</div>
+ {Object.entries(stats.stats)
+ .sort(([, a], [, b]) => b.count - a.count)
+ .map(([title, data]) => (
+ <div key={title} className="flex items-center gap-[9px]">
+ <span
+ className="size-2 shrink-0 rounded-full"
+ style={{ backgroundColor: colorFor(title) }}
+ />
+ <span className="min-w-0 flex-1 truncate text-[13px] text-fg-body">
+ {title}
+ </span>
+ <span className="h-1 w-20 shrink-0 overflow-hidden rounded-full bg-line-grid sm:w-32">
+ <span
+ className="block h-full rounded-full"
+ style={{
+ backgroundColor: colorFor(title),
+ width: `${totalShifts ? (data.count / totalShifts) * 100 : 0}%`,
+ }}
+ />
+ </span>
+ <span className="w-7 shrink-0 text-right font-mono text-[12px] text-fg-strong">
+ {data.count}
+ </span>
+ <span className="w-12 shrink-0 text-right font-mono text-[12px] text-fg-tertiary">
+ {data.totalMinutes > 0 ? formatHours(data.totalMinutes, locale) : "–"}
+ </span>
+ </div>
+ ))}
+ </div>
+ </>
)}
- {/* Stats Display */}
- {loading ? (
- <div className="text-center py-8 text-sm text-muted-foreground">
- {t("common.loading")}
- </div>
- ) : stats && Object.keys(stats.stats).length > 0 ? (
- <div className="space-y-3.5">
- {/* Overview Mode - Enhanced Cards */}
- {viewMode === "overview" && (
- <>
- {/* Summary Statistics Grid */}
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
- <div className="p-3 rounded-lg bg-gradient-to-br from-primary/10 via-primary/5 to-transparent border border-primary/20">
- <div className="text-[10px] text-muted-foreground font-medium mb-1">
- {t("stats.totalShifts")}
- </div>
- <div className="text-xl font-bold bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent">
- {totalShifts}
- </div>
- </div>
- <div className="p-3 rounded-lg bg-gradient-to-br from-primary/10 via-primary/5 to-transparent border border-primary/20">
- <div className="text-[10px] text-muted-foreground font-medium mb-1">
- {t("stats.totalHours")}
- </div>
- <div className="text-xl font-bold bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent">
- {formatDuration(totalMinutes)}
- </div>
- </div>
- <div className="p-3 rounded-lg bg-gradient-to-br from-card via-card/80 to-card/60 border border-border/40">
- <div className="text-[10px] text-muted-foreground font-medium mb-1">
- {t("stats.avgPerShift")}
+ {viewMode === "pie" && (
+ <div className="flex flex-col gap-3">
+ <div className="h-[300px] min-h-[300px] sm:h-[380px]">
+ <ResponsiveContainer width="100%" height="100%" minHeight={300}>
+ <RechartsPieChart>
+ <Pie
+ data={pieData}
+ cx="50%"
+ cy="50%"
+ labelLine={false}
+ label={({ name, percent }) =>
+ `${name}: ${((percent ?? 0) * 100).toFixed(0)}%`
+ }
+ outerRadius={outerRadius}
+ stroke="var(--background)"
+ dataKey="value"
+ animationBegin={0}
+ animationDuration={800}
+ >
+ {pieData.map((entry) => (
+ <Cell key={entry.name} fill={colorFor(entry.name)} />
+ ))}
+ </Pie>
+ <Tooltip content={<CustomTooltip />} />
+ </RechartsPieChart>
+ </ResponsiveContainer>
+ </div>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ {pieData.map((entry) => (
+ <div
+ key={entry.name}
+ className="flex items-center gap-2 rounded-lg border border-line bg-surface-card px-2.5 py-2"
+ >
+ <Swatch color={colorFor(entry.name)} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12.5px] font-medium text-fg-body">
+ {entry.name}
</div>
- <div className="text-xl font-bold text-foreground">
- {formatDuration(stats.avgMinutesPerShift)}
+ <div className="font-mono text-[11px] text-fg-tertiary">
+ {entry.value} × {entry.hours}h
</div>
</div>
</div>
+ ))}
+ </div>
+ </div>
+ )}
- {/* Additional Metrics */}
- <div className="grid grid-cols-2 gap-2">
- {stats.minDuration > 0 && (
- <div className="p-3 rounded-lg bg-gradient-to-br from-card via-card/80 to-card/60 border border-border/40">
- <div className="text-[10px] text-muted-foreground font-medium mb-1">
- {t("stats.shortestShift")}
- </div>
- <div className="text-lg font-bold text-foreground">
- {formatDuration(stats.minDuration)}
- </div>
- </div>
- )}
- {stats.maxDuration > 0 && (
- <div className="p-3 rounded-lg bg-gradient-to-br from-card via-card/80 to-card/60 border border-border/40">
- <div className="text-[10px] text-muted-foreground font-medium mb-1">
- {t("stats.longestShift")}
- </div>
- <div className="text-lg font-bold text-foreground">
- {formatDuration(stats.maxDuration)}
- </div>
- </div>
- )}
- </div>
-
- {/* Individual Shift Types List */}
- <div className="space-y-2">
- <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
- {t("stats.byType")}
- </h4>
- {Object.entries(stats.stats)
- .sort(([, a], [, b]) => b.count - a.count)
- .map(([title, data]) => (
- <div
- key={title}
- className="group relative p-3 rounded-lg bg-gradient-to-br from-card via-card/80 to-card/60 border border-border/40 hover:border-primary/30 hover:shadow-md hover:shadow-primary/5 transition-all duration-200"
- >
- <div className="flex justify-between items-center gap-3">
- <span className="text-sm font-semibold truncate flex-shrink min-w-0 group-hover:text-primary transition-colors">
- {title}
- </span>
- <div className="flex items-center gap-3 flex-shrink-0">
- <div className="w-24 sm:w-32 h-2 bg-muted/50 rounded-full overflow-hidden border border-border/20 shadow-inner">
- <div
- className="h-full bg-gradient-to-r from-primary via-primary/90 to-primary/80 transition-all duration-300 shadow-sm"
- style={{
- width: `${
- (data.count / totalShifts) * 100
- }%`,
- }}
- />
- </div>
- <div className="min-w-[2.5rem] px-2 py-1 rounded-md bg-primary/10 border border-primary/20">
- <span className="font-bold text-sm text-primary text-center block">
- {data.count}
- </span>
- </div>
- {data.totalMinutes > 0 && (
- <div className="min-w-[3rem] sm:min-w-[3.5rem] px-2 py-1 rounded-md bg-primary/10 border border-primary/20">
- <span className="font-semibold text-xs sm:text-sm text-primary text-center block">
- {formatDuration(data.totalMinutes)}
- </span>
- </div>
- )}
- </div>
- </div>
- </div>
+ {viewMode === "bar" && (
+ <div className="flex flex-col gap-2">
+ <div className="h-[350px] min-h-[350px] sm:h-[420px]">
+ <ResponsiveContainer width="100%" height="100%" minHeight={350}>
+ <BarChart data={barData}>
+ <CartesianGrid strokeDasharray="3 3" stroke="var(--line)" vertical={false} />
+ <XAxis
+ dataKey="name"
+ tick={tick}
+ tickLine={false}
+ axisLine={{ stroke: "var(--line)" }}
+ angle={-45}
+ textAnchor="end"
+ height={80}
+ />
+ <YAxis tick={tick} tickLine={false} axisLine={false} />
+ <Tooltip content={<CustomTooltip />} cursor={{ fill: "var(--surface-sunken)" }} />
+ <Bar
+ dataKey="shifts"
+ name={t("common.shifts")}
+ radius={[4, 4, 0, 0]}
+ animationDuration={1000}
+ >
+ {barData.map((entry) => (
+ <Cell key={entry.fullName} fill={colorFor(entry.fullName)} />
))}
- </div>
- </>
- )}
-
- {/* Pie Chart Mode */}
- {viewMode === "pie" && (
- <div className="space-y-3">
- <div className="h-[300px] sm:h-[400px] min-h-[300px]">
- <ResponsiveContainer
- width="100%"
- height="100%"
- minHeight={300}
+ </Bar>
+ <Bar
+ dataKey="hours"
+ name={t("stats.hours")}
+ radius={[4, 4, 0, 0]}
+ animationDuration={1000}
>
- <RechartsPieChart>
- <Pie
- data={pieData}
- cx="50%"
- cy="50%"
- labelLine={false}
- label={({ name, percent }) =>
- `${name}: ${((percent ?? 0) * 100).toFixed(0)}%`
- }
- outerRadius={outerRadius}
- fill="#8884d8"
- dataKey="value"
- animationBegin={0}
- animationDuration={800}
- >
- {pieData.map((_, index) => (
- <Cell
- key={`cell-${index}`}
- fill={CHART_COLORS[index % CHART_COLORS.length]}
- />
- ))}
- </Pie>
- <Tooltip content={<CustomTooltip />} />
- </RechartsPieChart>
- </ResponsiveContainer>
- </div>
- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
- {pieData.map((entry, index) => (
- <div
- key={entry.name}
- className="flex items-center gap-2 p-2 rounded-lg bg-card/50 border border-border/30 hover:bg-card/70 hover:border-primary/30 transition-all"
- >
- <div
- className="w-3 h-3 rounded-sm flex-shrink-0"
- style={{
- backgroundColor:
- CHART_COLORS[index % CHART_COLORS.length],
- }}
+ {barData.map((entry) => (
+ <Cell
+ key={entry.fullName}
+ fill={colorFor(entry.fullName)}
+ fillOpacity={0.4}
/>
- <div className="flex-1 min-w-0">
- <div className="text-xs font-medium truncate">
- {entry.name}
- </div>
- <div className="text-[10px] text-muted-foreground">
- {entry.value} × {entry.hours}h
- </div>
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
+ ))}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ {/* Bars take each type's color, so the legend explains solid vs. faded */}
+ <div className="flex items-center justify-center gap-4 text-[12px] text-fg-secondary">
+ <span className="flex items-center gap-1.5">
+ <span className="size-2.5 rounded-[3px] bg-fg-secondary" />
+ {t("common.shifts")}
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span className="size-2.5 rounded-[3px] bg-fg-secondary/40" />
+ {t("stats.hours")}
+ </span>
+ </div>
+ </div>
+ )}
- {/* Bar Chart Mode */}
- {viewMode === "bar" && (
- <div className="h-[350px] sm:h-[450px] min-h-[350px]">
- <ResponsiveContainer
- width="100%"
- height="100%"
- minHeight={350}
+ {viewMode === "radar" && radarData.length > 0 && (
+ <div className="flex flex-col gap-3">
+ <div className="h-[350px] min-h-[350px] sm:h-[420px]">
+ <ResponsiveContainer width="100%" height="100%" minHeight={350}>
+ <RadarChart data={radarData}>
+ <PolarGrid stroke="var(--line)" />
+ <PolarAngleAxis
+ dataKey="type"
+ tick={{ fontSize: 11, fill: "var(--fg-secondary)" }}
+ />
+ <PolarRadiusAxis angle={90} domain={[0, "auto"]} tick={{ ...tick, fontSize: 10 }} />
+ <Radar
+ name={t("stats.totalHours")}
+ dataKey="hours"
+ stroke="var(--chart-1)"
+ fill="var(--chart-1)"
+ fillOpacity={0.45}
+ animationDuration={1000}
+ />
+ <Radar
+ name={t("stats.avgHoursPerShift")}
+ dataKey="avgHours"
+ stroke="var(--chart-2)"
+ fill="var(--chart-2)"
+ fillOpacity={0.35}
+ animationDuration={1000}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ <Legend wrapperStyle={{ fontSize: 12 }} />
+ </RadarChart>
+ </ResponsiveContainer>
+ </div>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
+ {radarData.map((entry) => (
+ <div
+ key={entry.fullName}
+ className="flex items-center gap-2 rounded-lg border border-line bg-surface-card px-2.5 py-2"
>
- <BarChart data={barData}>
- <CartesianGrid strokeDasharray="3 3" opacity={0.1} />
- <XAxis
- dataKey="name"
- tick={{ fontSize: 12 }}
- angle={-45}
- textAnchor="end"
- height={80}
- />
- <YAxis tick={{ fontSize: 12 }} />
- <Tooltip content={<CustomTooltip />} />
- <Legend />
- <Bar
- dataKey="shifts"
- fill={CHART_COLORS[0]}
- name={t("common.shifts")}
- radius={[4, 4, 0, 0]}
- animationDuration={1000}
- />
- <Bar
- dataKey="hours"
- fill={CHART_COLORS[1]}
- name={t("stats.hours")}
- radius={[4, 4, 0, 0]}
- animationDuration={1000}
- />
- </BarChart>
- </ResponsiveContainer>
- </div>
- )}
-
- {/* Radar Chart - Performance metrics for top shift types */}
- {viewMode === "radar" && radarData.length > 0 && (
- <div className="space-y-3">
- <div className="h-[350px] sm:h-[450px] min-h-[350px]">
- <ResponsiveContainer
- width="100%"
- height="100%"
- minHeight={350}
- >
- <RadarChart data={radarData}>
- <PolarGrid stroke={CHART_COLORS[0]} opacity={0.2} />
- <PolarAngleAxis
- dataKey="type"
- tick={{ fontSize: 11, fill: "currentColor" }}
- />
- <PolarRadiusAxis
- angle={90}
- domain={[0, "auto"]}
- tick={{ fontSize: 10 }}
- />
- <Radar
- name={t("stats.totalHours")}
- dataKey="hours"
- stroke={CHART_COLORS[0]}
- fill={CHART_COLORS[0]}
- fillOpacity={0.6}
- animationDuration={1000}
- />
- <Radar
- name={t("stats.avgHoursPerShift")}
- dataKey="avgHours"
- stroke={CHART_COLORS[2]}
- fill={CHART_COLORS[2]}
- fillOpacity={0.4}
- animationDuration={1000}
- />
- <Tooltip content={<CustomTooltip />} />
- <Legend />
- </RadarChart>
- </ResponsiveContainer>
- </div>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
- {radarData.map((entry) => (
- <div
- key={entry.fullName}
- className="flex items-center gap-2 p-2 rounded-lg bg-card/50 border border-border/30"
- >
- <div
- className="w-3 h-3 rounded-sm flex-shrink-0"
- style={{
- backgroundColor: CHART_COLORS[0],
- }}
- />
- <div className="flex-1 min-w-0">
- <div className="text-xs font-medium truncate">
- {entry.fullName}
- </div>
- <div className="text-[10px] text-muted-foreground">
- {entry.shifts} × ⌀{entry.avgHours}h
- </div>
- </div>
+ <Swatch color={colorFor(entry.fullName)} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12.5px] font-medium text-fg-body">
+ {entry.fullName}
</div>
- ))}
- </div>
- <div className="p-3 rounded-lg bg-muted/30 border border-border/30">
- <p className="text-xs text-muted-foreground text-center">
- {t("stats.radarDescription")}
- </p>
+ <div className="font-mono text-[11px] text-fg-tertiary">
+ {entry.shifts} × ⌀{entry.avgHours}h
+ </div>
+ </div>
</div>
- </div>
- )}
+ ))}
+ </div>
+ <p className="rounded-[10px] border border-line bg-surface-panel px-3 py-2.5 text-center text-[12px] text-fg-secondary">
+ {t("stats.radarDescription")}
+ </p>
</div>
- ) : (
- <p className="text-sm text-muted-foreground py-6 text-center">
- {t("stats.noData")}
- </p>
)}
- </div>
+ </>
+ ) : (
+ <p className="py-10 text-center text-[13px] text-fg-tertiary">{t("stats.noData")}</p>
)}
</div>
);
diff --git a/components/shifts-list.tsx b/components/shifts-list.tsx
deleted file mode 100644
index fbbb763..0000000
--- a/components/shifts-list.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { useState } from "react";
-import { motion, AnimatePresence } from "motion/react";
-import { format } from "date-fns";
-import { useTranslations, useLocale } from "next-intl";
-import { getDateLocale } from "@/lib/locales";
-import { ShiftWithCalendar } from "@/lib/types";
-import { ShiftCard } from "@/components/shift-card";
-import { ChevronUp, ChevronDown, Calendar as CalendarIcon } from "lucide-react";
-import { useCalendarPermission } from "@/hooks/useCalendarPermission";
-
-interface ShiftsListProps {
- shifts: ShiftWithCalendar[];
- currentDate: Date;
- onDeleteShift?: (id: string) => void;
- onEditShift?: (shift: ShiftWithCalendar) => void;
- calendarId?: string; // Optional: if provided, uses this for permission check instead of first shift's calendarId
-}
-
-export function ShiftsList({
- shifts,
- currentDate,
- onDeleteShift,
- onEditShift,
- calendarId: propCalendarId,
-}: ShiftsListProps) {
- const t = useTranslations();
- const locale = useLocale();
- const dateLocale = getDateLocale(locale);
- const [showShiftsSection, setShowShiftsSection] = useState(false);
-
- // Get calendar ID from props or first shift
- const calendarId = propCalendarId || shifts[0]?.calendarId;
- const { canEdit } = useCalendarPermission(calendarId);
-
- const shiftsInMonth = shifts.filter((shift) => {
- if (!shift.date) return false;
- const shiftDate = shift.date as Date;
- return (
- shiftDate.getMonth() === currentDate.getMonth() &&
- shiftDate.getFullYear() === currentDate.getFullYear()
- );
- });
-
- const groupedShifts = shiftsInMonth
- .sort(
- (a, b) =>
- (a.date ? (a.date as Date).getTime() : 0) -
- (b.date ? (b.date as Date).getTime() : 0)
- )
- .reduce((acc, shift) => {
- const dateKey = shift.date
- ? format(shift.date as Date, "yyyy-MM-dd")
- : "unknown";
- if (!acc[dateKey]) acc[dateKey] = [];
- acc[dateKey].push(shift);
- return acc;
- }, {} as Record<string, ShiftWithCalendar[]>);
-
- return (
- <div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">
- <button
- onClick={() => setShowShiftsSection(!showShiftsSection)}
- className="w-full px-3 sm:px-4 py-3 sm:py-3.5 flex items-center justify-between hover:bg-primary/5 transition-all"
- >
- <div className="flex items-center gap-2.5">
- <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/20">
- <CalendarIcon className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />
- </div>
- <h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">
- {t("common.shifts")}
- </h3>
- </div>
- <div className="flex items-center gap-3">
- {!showShiftsSection && shiftsInMonth.length > 0 && (
- <div className="px-3 py-1.5 bg-primary/10 rounded-full">
- <span className="font-semibold text-primary text-xs sm:text-sm">
- {shiftsInMonth.length}
- </span>
- </div>
- )}
- {showShiftsSection ? (
- <ChevronUp className="h-4 w-4 text-muted-foreground" />
- ) : (
- <ChevronDown className="h-4 w-4 text-muted-foreground" />
- )}
- </div>
- </button>
-
- {showShiftsSection && (
- <div className="border-t border-border/30 bg-muted/20 p-3 sm:p-4">
- {shiftsInMonth.length === 0 ? (
- <motion.div
- className="border-2 border-dashed border-border/50 rounded-xl p-10 sm:p-14 text-center space-y-4 sm:space-y-5"
- initial={{ opacity: 0, scale: 0.95 }}
- animate={{ opacity: 1, scale: 1 }}
- transition={{ duration: 0.3 }}
- >
- <motion.div
- className="flex justify-center"
- initial={{ scale: 0 }}
- animate={{ scale: 1 }}
- transition={{
- delay: 0.1,
- type: "spring",
- stiffness: 200,
- }}
- >
- <div className="h-16 w-16 sm:h-20 sm:w-20 rounded-full bg-gradient-to-br from-primary/20 to-primary/10 flex items-center justify-center shadow-lg">
- <CalendarIcon className="h-8 w-8 sm:h-10 sm:w-10 text-primary/70" />
- </div>
- </motion.div>
- <div className="space-y-2 sm:space-y-2.5">
- <h4 className="font-bold text-lg sm:text-xl text-foreground/90">
- {t("shift.noShiftsInMonth", {
- default: "No shifts this month",
- })}
- </h4>
- <p className="text-sm sm:text-base text-muted-foreground max-w-md mx-auto leading-relaxed">
- {t("shift.noShiftsInMonthDescription", {
- default:
- "Add shifts by clicking on days in the calendar above.",
- })}
- </p>
- </div>
- </motion.div>
- ) : (
- <AnimatePresence mode="popLayout">
- <motion.div
- className="space-y-3 sm:space-y-4"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ staggerChildren: 0.05 }}
- >
- {Object.entries(groupedShifts).map(
- ([dateKey, dayShifts], index) => (
- <motion.div
- key={dateKey}
- className="border border-border/50 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-all bg-gradient-to-b from-card via-card to-muted/20"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: index * 0.05 }}
- layout
- >
- <div className="bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-4 sm:px-5 py-2.5 sm:py-3 border-b border-border/30">
- <div className="flex items-center justify-between">
- <div className="font-bold text-sm sm:text-base flex items-center gap-2">
- <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>
- {dayShifts[0].date &&
- format(
- dayShifts[0].date as Date,
- "EEEE, MMMM d, yyyy",
- { locale: dateLocale }
- )}
- </div>
- <div className="text-xs sm:text-sm px-2.5 py-1 bg-primary/15 text-primary rounded-full font-semibold shadow-sm">
- {dayShifts.length}{" "}
- {dayShifts.length === 1
- ? t("shift.shift_one")
- : t("common.shifts")}
- </div>
- </div>
- </div>
- <div className="p-3 sm:p-4 grid gap-2 sm:gap-3 sm:grid-cols-2">
- {dayShifts.map((shift) => (
- <ShiftCard
- key={shift.id}
- shift={shift}
- onDelete={canEdit ? onDeleteShift : undefined}
- onEdit={canEdit ? onEditShift : undefined}
- />
- ))}
- </div>
- </motion.div>
- )
- )}
- </motion.div>
- </AnimatePresence>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/components/shifts-overview-dialog.tsx b/components/shifts-overview-dialog.tsx
index 616af77..106e09e 100644
--- a/components/shifts-overview-dialog.tsx
+++ b/components/shifts-overview-dialog.tsx
@@ -1,19 +1,11 @@
"use client";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/ui/dialog";
+import { useLocale, useTranslations } from "next-intl";
+import { formatLongDate } from "@/lib/date-utils";
+import { PanelDialog } from "@/components/panel-dialog";
+import { ShiftDetailRow } from "@/components/day-detail";
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, Pencil } from "lucide-react";
+import { formatHours, getShiftMinutes } from "@/lib/shift-display";
interface ShiftsOverviewDialogProps {
open: boolean;
@@ -22,6 +14,8 @@ interface ShiftsOverviewDialogProps {
shifts: ShiftWithCalendar[];
onDeleteShift?: (shiftId: string) => void;
onEditShift?: (shift: ShiftWithCalendar) => void;
+ /** Viewer's edit permission on the calendar the shifts belong to */
+ canEdit: boolean;
}
export function ShiftsOverviewDialog({
@@ -31,110 +25,48 @@ export function ShiftsOverviewDialog({
shifts,
onDeleteShift,
onEditShift,
+ canEdit,
}: 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,
- });
-
- const handleShiftClick = (shift: ShiftWithCalendar) => {
- if (onEditShift && !shift.externalSyncId && !shift.syncedFromExternal) {
- onOpenChange(false); // Close dialog first
- onEditShift(shift);
- }
- };
+ const formattedDate = formatLongDate(date, locale, { year: true });
+ const minutes = shifts.reduce((sum, s) => sum + getShiftMinutes(s), 0);
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 transition-all ${onEditShift && !shift.externalSyncId && !shift.syncedFromExternal
- ? "hover:bg-muted/40 cursor-pointer"
- : "hover:bg-muted/30"
- }`}
- style={{ borderLeftColor: shift.color, borderLeftWidth: 4 }}
- onClick={() => handleShiftClick(shift)}
- >
- <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>
- <div className="flex items-center gap-1">
- {onEditShift && !shift.externalSyncId && !shift.syncedFromExternal && (
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground hover:bg-muted"
- onClick={(e) => {
- e.stopPropagation();
- onOpenChange(false);
- onEditShift(shift);
- }}
- >
- <Pencil className="h-4 w-4" />
- </Button>
- )}
- {onDeleteShift && !shift.externalSyncId && !shift.syncedFromExternal && (
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
- onClick={(e) => {
- e.stopPropagation();
- onDeleteShift(shift.id);
- }}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- )}
- </div>
- </div>
- ))
- )}
+ <PanelDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={formattedDate}
+ description={
+ t("calendarView.shiftCount", { count: shifts.length }) +
+ (minutes > 0 ? ` · ${formatHours(minutes, locale)}` : "")
+ }
+ width="md"
+ >
+ {shifts.length === 0 ? (
+ <p className="py-6 text-center text-[13px] text-fg-tertiary">
+ {t("calendarView.dayEmpty")}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-1.5">
+ {shifts.map((shift) => (
+ <ShiftDetailRow
+ key={shift.id}
+ shift={shift}
+ canEdit={canEdit && !!onEditShift && !!onDeleteShift}
+ actions="menu"
+ onEdit={(s) => {
+ onOpenChange(false);
+ onEditShift?.(s);
+ }}
+ onDelete={(s) => onDeleteShift?.(s.id)}
+ />
+ ))}
</div>
- </DialogContent>
- </Dialog>
+ )}
+ </PanelDialog>
);
}
diff --git a/components/stamp-dock.tsx b/components/stamp-dock.tsx
new file mode 100644
index 0000000..e579440
--- /dev/null
+++ b/components/stamp-dock.tsx
@@ -0,0 +1,432 @@
+"use client";
+
+import { ComponentProps, useState } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Check,
+ ChevronDown,
+ ChevronUp,
+ Ellipsis,
+ Hand,
+ Plus,
+ SlidersHorizontal,
+} from "lucide-react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { ShiftPreset } from "@/lib/db/schema";
+import { getShiftCode, presetTime, shiftVars } from "@/lib/shift-display";
+import { cn } from "@/lib/utils";
+
+export function splitStampPresets(presets: ShiftPreset[]) {
+ return {
+ primary: presets.filter((p) => !p.isSecondary),
+ secondary: presets.filter((p) => p.isSecondary),
+ };
+}
+
+/** Presets that get their own chip and number key 1–9; secondary ones sit under "Weitere". */
+export function orderStampPresets(presets: ShiftPreset[]): ShiftPreset[] {
+ return splitStampPresets(presets).primary;
+}
+
+type MoreVariant = "dock" | "compare" | "bar";
+
+interface MoreChipProps extends ComponentProps<"button"> {
+ variant: MoreVariant;
+ count: number;
+ /** The armed secondary preset; the chip shows it in place so the row keeps its layout. */
+ active: ShiftPreset | undefined;
+ open: boolean;
+}
+
+function MoreChip({ variant, count, active, open, className, ...props }: MoreChipProps) {
+ const t = useTranslations();
+ const label = (
+ <span className="whitespace-nowrap">
+ {t("preset.secondary")}
+ <span className="opacity-60"> · </span>
+ <span className="font-mono">{count}</span>
+ </span>
+ );
+
+ if (variant === "bar") {
+ const Chevron = open ? ChevronDown : ChevronUp;
+ return (
+ <button
+ type="button"
+ aria-expanded={open}
+ {...props}
+ className={cn(
+ "flex h-12 shrink-0 items-center gap-2.5 rounded-[10px] border py-1.5 pl-2 pr-2.5 text-left transition-colors",
+ active
+ ? "border-brand bg-brand-soft"
+ : open
+ ? "border-control bg-surface-sunken"
+ : "border-line bg-surface-card",
+ className
+ )}
+ >
+ {active ? (
+ <>
+ <span
+ className="shift-solid flex size-[22px] shrink-0 items-center justify-center rounded-[5px] text-[11px] font-bold"
+ style={shiftVars(active.color)}
+ >
+ {getShiftCode(active.title)}
+ </span>
+ <span className="min-w-0">
+ <span className="block max-w-[140px] truncate text-[13px] font-semibold text-brand-ink">
+ {active.title}
+ </span>
+ <span className="block font-mono text-[11.5px] text-brand-ink">
+ {presetTime(active, t("shift.allDayShift"))}
+ </span>
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="flex size-[22px] shrink-0 items-center justify-center rounded-[5px] bg-surface-sunken text-fg-secondary">
+ <Ellipsis className="size-3.5" />
+ </span>
+ <span className="text-[13px] font-semibold text-fg-strong">{label}</span>
+ </>
+ )}
+ <Chevron className={cn("size-4 shrink-0", active ? "text-brand-ink" : "text-fg-tertiary")} />
+ </button>
+ );
+ }
+
+ const dock = variant === "dock";
+ const Chevron = dock ? ChevronUp : ChevronDown;
+ const tone = dock
+ ? active
+ ? "bg-brand text-white"
+ : cn("text-dock-ink hover:bg-white/10", open && "bg-white/10")
+ : active
+ ? "border-brand bg-brand-soft text-brand-ink"
+ : cn(
+ "border-line bg-surface-card text-fg-body hover:bg-surface-panel",
+ open && "bg-surface-panel"
+ );
+ return (
+ <button
+ type="button"
+ {...props}
+ className={cn(
+ "flex shrink-0 items-center gap-[7px] px-2.5 text-[12.5px] font-medium transition-colors",
+ dock ? "h-[30px] rounded-lg" : "h-7 rounded-[7px] border",
+ tone,
+ className
+ )}
+ >
+ {active ? (
+ <>
+ <span className="size-[7px] shrink-0 rounded-full" style={{ backgroundColor: active.color }} />
+ <span className="max-w-[140px] truncate">{active.title}</span>
+ </>
+ ) : (
+ label
+ )}
+ <Chevron className="-mr-0.5 size-3.5 shrink-0 opacity-70" />
+ </button>
+ );
+}
+
+/** Secondary presets as rows; picking the armed one disarms it. */
+function SecondaryPresetList({
+ presets,
+ selectedPresetId,
+ onPick,
+ touch = false,
+}: {
+ presets: ShiftPreset[];
+ selectedPresetId: string | undefined;
+ onPick: (id: string | undefined) => void;
+ touch?: boolean;
+}) {
+ const t = useTranslations();
+ return (
+ <div className="flex flex-col gap-px">
+ {presets.map((preset) => {
+ const active = preset.id === selectedPresetId;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ aria-pressed={active}
+ onClick={() => onPick(active ? undefined : preset.id)}
+ className={cn(
+ "flex items-center gap-2.5 rounded-[8px] px-2.5 text-left outline-none transition-colors",
+ touch ? "h-11 text-[14px]" : "h-9 text-[13px]",
+ active
+ ? "bg-brand-soft text-brand-ink"
+ : "text-fg-body hover:bg-surface-sunken focus-visible:bg-surface-sunken"
+ )}
+ >
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: preset.color }} />
+ <span className="min-w-0 flex-1 truncate font-medium">{preset.title}</span>
+ <span
+ className={cn(
+ "shrink-0 font-mono text-[12px]",
+ active ? "text-brand-ink" : "text-fg-tertiary"
+ )}
+ >
+ {presetTime(preset, t("presetSheet.allDayShort"))}
+ </span>
+ <Check className={cn("size-3.5 shrink-0", !active && "invisible")} />
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+interface MorePresetsProps {
+ /** Secondary presets only. */
+ presets: ShiftPreset[];
+ selectedPresetId: string | undefined;
+ onSelectPreset: (id: string | undefined) => void;
+}
+
+/** Trailing "Weitere · N" chip that opens the secondary presets in a popover. */
+export function MorePresets({
+ variant,
+ presets,
+ selectedPresetId,
+ onSelectPreset,
+}: MorePresetsProps & { variant: "dock" | "compare" }) {
+ const [open, setOpen] = useState(false);
+ if (presets.length === 0) return null;
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <MoreChip
+ variant={variant}
+ count={presets.length}
+ active={presets.find((p) => p.id === selectedPresetId)}
+ open={open}
+ />
+ </PopoverTrigger>
+ <PopoverContent
+ side={variant === "dock" ? "top" : "bottom"}
+ align={variant === "dock" ? "end" : "start"}
+ sideOffset={8}
+ collisionPadding={12}
+ className="w-[260px] rounded-[12px] border-line bg-surface-card p-1"
+ >
+ <SecondaryPresetList
+ presets={presets}
+ selectedPresetId={selectedPresetId}
+ onPick={(id) => {
+ onSelectPreset(id);
+ setOpen(false);
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+interface StampProps {
+ presets: ShiftPreset[];
+ selectedPresetId: string | undefined;
+ onSelectPreset: (id: string | undefined) => void;
+ onManage: () => void;
+}
+
+export function StampDock({ presets, selectedPresetId, onSelectPreset, onManage }: StampProps) {
+ const t = useTranslations();
+ const { primary, secondary } = splitStampPresets(presets);
+
+ return (
+ <div
+ role="toolbar"
+ aria-label={t("calendarView.stamp")}
+ className="absolute bottom-5 left-1/2 z-20 flex max-w-[calc(100%-36px)] -translate-x-1/2 items-center gap-1.5 rounded-xl border border-transparent bg-dock p-1.5 shadow-dock dark:border-dock-line"
+ >
+ <span className="shrink-0 pl-2 pr-1.5 text-[11px] font-semibold uppercase tracking-[0.06em] text-fg-faint dark:text-fg-tertiary">
+ {t("calendarView.stamp")}
+ </span>
+ <div className="flex min-w-0 items-center gap-1.5 overflow-x-auto [scrollbar-width:none]">
+ {presets.length === 0 && (
+ <button
+ type="button"
+ onClick={onManage}
+ className="flex h-[30px] shrink-0 items-center gap-1.5 rounded-lg px-2.5 text-[12.5px] font-medium text-dock-ink hover:bg-white/10"
+ >
+ <Plus className="size-3.5" />
+ {t("calendarView.createPreset")}
+ </button>
+ )}
+ {primary.map((preset, index) => {
+ const active = preset.id === selectedPresetId;
+ const key = index < 9 ? String(index + 1) : null;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ aria-pressed={active}
+ onClick={() => onSelectPreset(active ? undefined : preset.id)}
+ title={
+ preset.isAllDay
+ ? preset.title
+ : `${preset.title} · ${preset.startTime}–${preset.endTime}`
+ }
+ className={cn(
+ "flex h-[30px] shrink-0 items-center gap-[7px] rounded-lg px-2.5 text-[12.5px] font-medium transition-colors",
+ active ? "bg-brand text-white" : "text-dock-ink hover:bg-white/10"
+ )}
+ >
+ <span
+ className="size-[7px] shrink-0 rounded-full"
+ style={{ backgroundColor: preset.color }}
+ />
+ <span className="max-w-[140px] truncate">{preset.title}</span>
+ {key && (
+ <kbd
+ className={cn(
+ "rounded-[4px] bg-white/18 px-1 py-px font-mono text-[10px] font-normal",
+ active ? "text-white" : "text-dock-ink"
+ )}
+ >
+ {key}
+ </kbd>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ <MorePresets
+ variant="dock"
+ presets={secondary}
+ selectedPresetId={selectedPresetId}
+ onSelectPreset={onSelectPreset}
+ />
+ <div className="mx-0.5 h-[22px] w-px shrink-0 bg-dock-line" />
+ <button
+ type="button"
+ onClick={onManage}
+ title={t("calendarView.managePresets")}
+ aria-label={t("calendarView.managePresets")}
+ className="flex size-[30px] shrink-0 items-center justify-center rounded-lg text-fg-faint transition-colors hover:bg-white/10 hover:text-white"
+ >
+ <SlidersHorizontal className="size-[15px]" />
+ </button>
+ </div>
+ );
+}
+
+export function MobilePresetBar({
+ presets,
+ selectedPresetId,
+ onSelectPreset,
+ onManage,
+}: StampProps) {
+ const t = useTranslations();
+ const [moreOpen, setMoreOpen] = useState(false);
+ const { primary, secondary } = splitStampPresets(presets);
+ const active = presets.find((p) => p.id === selectedPresetId);
+ const activeSecondary = active?.isSecondary ? active : undefined;
+ // Otherwise the list would pop up by itself once a preset is marked secondary again
+ if (moreOpen && secondary.length === 0) setMoreOpen(false);
+
+ return (
+ <div className="border-t border-line bg-surface-panel">
+ {moreOpen && (
+ <div className="px-3 pt-2.5">
+ <div className="rounded-[10px] border border-line bg-surface-card p-1">
+ <SecondaryPresetList
+ touch
+ presets={secondary}
+ selectedPresetId={selectedPresetId}
+ onPick={(id) => {
+ onSelectPreset(id);
+ setMoreOpen(false);
+ }}
+ />
+ </div>
+ </div>
+ )}
+ <div className="flex items-center gap-2 py-2.5 pl-3 pr-3">
+ <div className="flex min-w-0 flex-1 gap-2 overflow-x-auto pb-0.5 [scrollbar-width:thin]">
+ {presets.length === 0 && (
+ <button
+ type="button"
+ onClick={onManage}
+ className="flex h-12 shrink-0 items-center gap-2 rounded-[10px] border border-dashed border-control px-3 text-[13px] font-medium text-fg-secondary"
+ >
+ <Plus className="size-4" />
+ {t("calendarView.createPreset")}
+ </button>
+ )}
+ {primary.map((preset) => {
+ const on = preset.id === selectedPresetId;
+ return (
+ <button
+ key={preset.id}
+ type="button"
+ aria-pressed={on}
+ onClick={() => onSelectPreset(on ? undefined : preset.id)}
+ className={cn(
+ "flex h-12 shrink-0 items-center gap-2.5 rounded-[10px] border py-1.5 pl-2 pr-3 text-left transition-colors",
+ on
+ ? "border-brand bg-brand-soft"
+ : "border-line bg-surface-card"
+ )}
+ >
+ <span
+ className="shift-solid flex size-[22px] shrink-0 items-center justify-center rounded-[5px] text-[11px] font-bold"
+ style={shiftVars(preset.color)}
+ >
+ {getShiftCode(preset.title)}
+ </span>
+ <span className="min-w-0">
+ <span
+ className={cn(
+ "block max-w-[140px] truncate text-[13px] font-semibold",
+ on ? "text-brand-ink" : "text-fg-strong"
+ )}
+ >
+ {preset.title}
+ </span>
+ <span
+ className={cn(
+ "block font-mono text-[11.5px]",
+ on ? "text-brand-ink" : "text-fg-tertiary"
+ )}
+ >
+ {presetTime(preset, t("shift.allDayShift"))}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ {secondary.length > 0 && (
+ <MoreChip
+ variant="bar"
+ count={secondary.length}
+ active={activeSecondary}
+ open={moreOpen}
+ onClick={() => setMoreOpen((current) => !current)}
+ />
+ )}
+ </div>
+ </div>
+ {active && (
+ <div className="flex items-center gap-2 px-4 pb-2.5 text-[12px] leading-snug text-fg-secondary">
+ <Hand className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1">
+ {t("calendarView.stampHint", { title: active.title })}
+ </span>
+ <button
+ type="button"
+ onClick={onManage}
+ className="shrink-0 font-semibold text-brand-ink"
+ >
+ {t("calendarView.manage")}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/components/status-banner.tsx b/components/status-banner.tsx
new file mode 100644
index 0000000..de3e59d
--- /dev/null
+++ b/components/status-banner.tsx
@@ -0,0 +1,61 @@
+import { ReactNode } from "react";
+import { type LucideIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+const TONES = {
+ warning: {
+ box: "border-warning-line bg-warning-surface",
+ icon: "text-warning",
+ title: "text-warning-title",
+ body: "text-warning",
+ },
+ danger: {
+ box: "border-danger-line bg-danger-surface",
+ icon: "text-danger",
+ title: "text-danger",
+ body: "text-danger-body",
+ },
+ info: {
+ box: "border-line bg-surface-panel",
+ icon: "text-fg-secondary",
+ title: "text-fg-strong",
+ body: "text-fg-secondary",
+ },
+} as const;
+
+interface StatusBannerProps {
+ tone: keyof typeof TONES;
+ icon: LucideIcon;
+ title?: ReactNode;
+ children?: ReactNode;
+ action?: ReactNode;
+ className?: string;
+}
+
+export function StatusBanner({
+ tone,
+ icon: Icon,
+ title,
+ children,
+ action,
+ className,
+}: StatusBannerProps) {
+ const styles = TONES[tone];
+ return (
+ <div
+ role={tone === "info" ? "note" : "status"}
+ className={cn(
+ "flex items-start gap-2.5 rounded-[11px] border px-[13px] py-[11px]",
+ styles.box,
+ className
+ )}
+ >
+ <Icon className={cn("mt-px size-4 shrink-0", styles.icon)} />
+ <div className="min-w-0 flex-1 text-[12.5px] leading-relaxed">
+ {title && <div className={cn("text-[13px] font-semibold", styles.title)}>{title}</div>}
+ {children && <div className={styles.body}>{children}</div>}
+ </div>
+ {action && <div className="shrink-0 self-center">{action}</div>}
+ </div>
+ );
+}
diff --git a/components/sync-notification-dialog.tsx b/components/sync-notification-dialog.tsx
index 6a5838f..fced648 100644
--- a/components/sync-notification-dialog.tsx
+++ b/components/sync-notification-dialog.tsx
@@ -3,38 +3,20 @@
import { useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
+import { CheckCheck, RefreshCw, Trash2, User } from "lucide-react";
+import { toast } from "sonner";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
import { Button } from "@/components/ui/button";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
+import { PanelBody, PanelDialog, PanelFooter } from "@/components/panel-dialog";
+import { SegmentedControl } from "@/components/segmented-control";
+import { ListRow, Pill } from "@/components/form-kit";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
import { SyncLog } from "@/lib/db/schema";
import { queryKeys } from "@/lib/query-keys";
-import {
- CheckCircle2,
- XCircle,
- Clock,
- RefreshCw,
- User,
- Trash2,
- CheckCheck,
-} from "lucide-react";
-import { toast } from "sonner";
+import { cn } from "@/lib/utils";
+
+type LogFilter = "all" | "success" | "error";
-/**
- * Fetch sync logs from API
- */
async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {
const params = new URLSearchParams({ calendarId, limit: "20" });
const response = await fetch(`/api/sync-logs?${params}`);
@@ -46,35 +28,29 @@ async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {
return await response.json();
}
-interface SyncNotificationDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- calendarId: string | null;
+interface SyncNotificationsPanelProps {
+ calendarId: string;
+ onClose: () => void;
onErrorsMarkedRead?: () => void;
}
-export function SyncNotificationDialog({
- open,
- onOpenChange,
+export function SyncNotificationsPanel({
calendarId,
+ onClose,
onErrorsMarkedRead,
-}: SyncNotificationDialogProps) {
+}: SyncNotificationsPanelProps) {
const t = useTranslations();
- const locale = useLocale();
const queryClient = useQueryClient();
- const [filter, setFilter] = useState<"all" | "success" | "error">("all");
+ const [filter, setFilter] = useState<LogFilter>("all");
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
- // Fetch sync logs with React Query polling
- const { data: logs = [], isLoading: loading } = useQuery({
- queryKey: queryKeys.externalSyncs.logs(calendarId!),
- queryFn: () => fetchSyncLogsApi(calendarId!),
- enabled: !!calendarId && open,
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: false, // Only poll when dialog is open
+ const { data: logs = [], isLoading } = useQuery({
+ queryKey: queryKeys.externalSyncs.logs(calendarId),
+ queryFn: () => fetchSyncLogsApi(calendarId),
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
+ refetchIntervalInBackground: false,
});
- // Delete all logs mutation
const deleteMutation = useMutation({
mutationFn: async () => {
const response = await fetch(`/api/sync-logs?calendarId=${calendarId}`, {
@@ -87,21 +63,14 @@ export function SyncNotificationDialog({
}
},
onSuccess: () => {
- queryClient.invalidateQueries({
- queryKey: queryKeys.externalSyncs.logs(calendarId!),
- });
- toast.success(
- t("common.deleted", { item: t("syncNotifications.title") })
- );
+ queryClient.invalidateQueries({ queryKey: queryKeys.externalSyncs.logs(calendarId) });
+ toast.success(t("common.deleted", { item: t("syncNotifications.title") }));
},
onError: () => {
- toast.error(
- t("common.deleteError", { item: t("syncNotifications.title") })
- );
+ toast.error(t("common.deleteError", { item: t("syncNotifications.title") }));
},
});
- // Mark errors as read mutation
const markReadMutation = useMutation({
mutationFn: async () => {
const response = await fetch(
@@ -117,222 +86,84 @@ export function SyncNotificationDialog({
}
},
onSuccess: () => {
- queryClient.invalidateQueries({
- queryKey: queryKeys.externalSyncs.logs(calendarId!),
- });
+ queryClient.invalidateQueries({ queryKey: queryKeys.externalSyncs.logs(calendarId) });
toast.success(t("syncNotifications.markedAsRead"));
onErrorsMarkedRead?.();
},
onError: () => {
- toast.error(
- t("common.updateError", { item: t("syncNotifications.title") })
- );
+ toast.error(t("common.updateError", { item: t("syncNotifications.title") }));
},
});
- const formatDateTime = (date: Date) => {
- return new Intl.DateTimeFormat(locale, {
- day: "2-digit",
- month: "2-digit",
- year: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- }).format(new Date(date));
- };
-
- const getStatusIcon = (status: string) => {
- if (status === "success") {
- return <CheckCircle2 className="h-5 w-5 text-green-600" />;
- }
- return <XCircle className="h-5 w-5 text-red-600" />;
- };
-
- const getSyncTypeIcon = (syncType: string) => {
- if (syncType === "auto") {
- return <RefreshCw className="h-4 w-4" />;
- }
- return <User className="h-4 w-4" />;
- };
-
- const hasChanges = (log: SyncLog) => {
- return (
- log.shiftsCreated > 0 || log.shiftsUpdated > 0 || log.shiftsDeleted > 0
- );
- };
-
- const handleDeleteLogs = () => {
- setShowDeleteConfirm(false);
- deleteMutation.mutate();
- };
-
- const handleMarkErrorsAsRead = () => {
- markReadMutation.mutate();
- };
-
- const filteredLogs = logs.filter((log) => {
- if (filter === "all") return true;
- return log.status === filter;
- });
+ const hasUnreadErrors = logs.some((log) => log.status === "error" && !log.isRead);
+ const filteredLogs = filter === "all" ? logs : logs.filter((log) => log.status === filter);
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("syncNotifications.title")}
- </DialogTitle>
- </DialogHeader>
+ <PanelBody>
+ <div className="flex flex-col gap-3.5">
+ <SegmentedControl<LogFilter>
+ label={t("syncNotifications.title")}
+ value={filter}
+ onChange={setFilter}
+ options={[
+ { value: "all", label: t("syncNotifications.filterAll") },
+ { value: "success", label: t("syncNotifications.filterSuccess") },
+ { value: "error", label: t("syncNotifications.filterError") },
+ ]}
+ />
- {/* Filter and Actions */}
- <div className="flex flex-wrap gap-2 items-center pb-4 border-b border-border/50 px-6 pt-6">
- <Select
- value={filter}
- onValueChange={(v: typeof filter) => setFilter(v)}
- >
- <SelectTrigger className="w-[140px]">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">
- {t("syncNotifications.filterAll")}
- </SelectItem>
- <SelectItem value="success">
- {t("syncNotifications.filterSuccess")}
- </SelectItem>
- <SelectItem value="error">
- {t("syncNotifications.filterError")}
- </SelectItem>
- </SelectContent>
- </Select>
- <div className="flex gap-2 ml-auto">
- {logs.some((log) => log.status === "error" && !log.isRead) && (
- <Button
- variant="outline"
- size="sm"
- onClick={handleMarkErrorsAsRead}
- disabled={markReadMutation.isPending}
- >
- <CheckCheck className="h-4 w-4 mr-2" />
- {t("syncNotifications.markAsRead")}
- </Button>
- )}
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowDeleteConfirm(true)}
- disabled={deleteMutation.isPending || logs.length === 0}
- >
- <Trash2 className="h-4 w-4 mr-2" />
- {t("syncNotifications.deleteAll")}
- </Button>
+ {isLoading ? (
+ <p className="py-8 text-center text-[13px] text-fg-tertiary">{t("common.loading")}</p>
+ ) : filteredLogs.length === 0 ? (
+ <p className="rounded-[11px] border border-dashed border-control px-4 py-8 text-center text-[13px] text-fg-tertiary">
+ {logs.length === 0
+ ? t("syncNotifications.noLogs")
+ : t("syncNotifications.noLogsFiltered")}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {filteredLogs.map((log) => (
+ <SyncLogRow key={log.id} log={log} />
+ ))}
</div>
- </div>
+ )}
+ </div>
+ </PanelBody>
- <div className="space-y-4 overflow-y-auto flex-1 px-6 pb-6">
- {loading ? (
- <div className="text-center py-8 text-muted-foreground">
- {t("common.loading")}
- </div>
- ) : filteredLogs.length === 0 ? (
- <div className="text-center py-8 text-muted-foreground">
- {logs.length === 0
- ? t("syncNotifications.noLogs")
- : t("syncNotifications.noLogsFiltered")}
- </div>
- ) : (
- filteredLogs.map((log) => (
- <div
- key={log.id}
- className="border rounded-lg p-4 space-y-3 hover:bg-accent/50 transition-colors"
- >
- {/* Header with status and sync type */}
- <div className="flex items-start justify-between">
- <div className="flex items-center gap-2">
- {getStatusIcon(log.status)}
- <div>
- <div className="font-medium flex items-center gap-2">
- {log.externalSyncName}
- {log.isRead && log.status === "error" && (
- <span className="text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
- {t("syncNotifications.read")}
- </span>
- )}
- </div>
- <div className="text-sm text-muted-foreground flex items-center gap-1.5">
- <Clock className="h-3.5 w-3.5" />
- {formatDateTime(log.syncedAt)}
- </div>
- </div>
- </div>
- <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
- {getSyncTypeIcon(log.syncType)}
- <span>
- {log.syncType === "auto"
- ? t("syncNotifications.syncTypeAuto")
- : t("syncNotifications.syncTypeManual")}
- </span>
- </div>
- </div>
-
- {/* Status and changes */}
- {log.status === "success" ? (
- <div>
- {hasChanges(log) ? (
- <div className="flex flex-wrap gap-3 text-sm">
- {log.shiftsCreated > 0 && (
- <div className="flex items-center gap-1.5 text-green-700">
- <span className="font-medium">
- {t("common.createdCount", {
- count: log.shiftsCreated,
- })}
- </span>
- </div>
- )}
- {log.shiftsUpdated > 0 && (
- <div className="flex items-center gap-1.5 text-blue-700">
- <span className="font-medium">
- {t("common.updatedCount", {
- count: log.shiftsUpdated,
- })}
- </span>
- </div>
- )}
- {log.shiftsDeleted > 0 && (
- <div className="flex items-center gap-1.5 text-orange-700">
- <span className="font-medium">
- {t("common.deletedCount", {
- count: log.shiftsDeleted,
- })}
- </span>
- </div>
- )}
- </div>
- ) : (
- <div className="text-sm text-muted-foreground">
- {t("syncNotifications.noChanges")}
- </div>
- )}
- </div>
- ) : (
- <div className="text-sm text-red-100 bg-red-950/90 p-3 rounded border border-red-800">
- <div className="font-medium mb-1">
- {t("syncNotifications.errorMessage")}:
- </div>
- <div className="text-red-200">{log.errorMessage}</div>
- </div>
- )}
- </div>
- ))
- )}
- </div>
- </DialogContent>
- </Dialog>
+ <PanelFooter>
+ <Button
+ variant="outline"
+ className="h-10 flex-1 font-semibold text-danger hover:text-danger"
+ onClick={() => setShowDeleteConfirm(true)}
+ disabled={deleteMutation.isPending || logs.length === 0}
+ >
+ <Trash2 className="size-4" />
+ {t("syncNotifications.deleteAll")}
+ </Button>
+ {hasUnreadErrors ? (
+ <Button
+ className="h-10 flex-1 font-semibold"
+ onClick={() => markReadMutation.mutate()}
+ disabled={markReadMutation.isPending}
+ >
+ <CheckCheck className="size-4" />
+ {t("syncNotifications.markAsRead")}
+ </Button>
+ ) : (
+ <Button variant="outline" className="h-10 flex-1 font-semibold" onClick={onClose}>
+ {t("common.close")}
+ </Button>
+ )}
+ </PanelFooter>
<ConfirmationDialog
open={showDeleteConfirm}
onOpenChange={setShowDeleteConfirm}
- onConfirm={handleDeleteLogs}
+ onConfirm={() => {
+ setShowDeleteConfirm(false);
+ deleteMutation.mutate();
+ }}
title={t("syncNotifications.title") + " " + t("common.delete")}
description={t("syncNotifications.deleteConfirm")}
cancelText={t("common.cancel")}
@@ -342,3 +173,103 @@ export function SyncNotificationDialog({
</>
);
}
+
+function SyncLogRow({ log }: { log: SyncLog }) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const ok = log.status === "success";
+ const auto = log.syncType === "auto";
+ const TypeIcon = auto ? RefreshCw : User;
+ const counts = [
+ { count: log.shiftsCreated, label: t("common.createdCount", { count: log.shiftsCreated }), tone: "text-success" },
+ { count: log.shiftsUpdated, label: t("common.updatedCount", { count: log.shiftsUpdated }), tone: "text-brand-ink" },
+ { count: log.shiftsDeleted, label: t("common.deletedCount", { count: log.shiftsDeleted }), tone: "text-warning" },
+ ];
+ const changed = counts.some((c) => c.count > 0);
+
+ return (
+ <ListRow className={cn("items-start px-[13px]", log.isRead && !ok && "opacity-75")}>
+ <span
+ className={cn("mt-0.5 h-[34px] w-1 shrink-0 rounded-full", ok ? "bg-success" : "bg-danger")}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="min-w-0 flex-1 truncate text-[14px] font-semibold text-fg-strong">
+ {log.externalSyncName}
+ </span>
+ {log.isRead && !ok && <Pill>{t("syncNotifications.read")}</Pill>}
+ <Pill tone={ok ? "success" : "danger"}>
+ {ok ? t("syncLog.statusSuccess") : t("syncNotifications.statusError")}
+ </Pill>
+ </div>
+ <div className="mt-[3px] flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] text-fg-tertiary">
+ <span className="font-mono">
+ {new Intl.DateTimeFormat(locale, {
+ day: "2-digit",
+ month: "2-digit",
+ year: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(log.syncedAt))}
+ </span>
+ <span aria-hidden>·</span>
+ <span className="inline-flex items-center gap-1">
+ <TypeIcon className="size-3" />
+ {auto ? t("syncNotifications.syncTypeAuto") : t("syncNotifications.syncTypeManual")}
+ </span>
+ </div>
+ {ok ? (
+ changed ? (
+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 font-mono text-[12px] font-medium">
+ {counts.map((c) => (
+ <span key={c.label} className={c.count > 0 ? c.tone : "text-fg-faint"}>
+ {c.label}
+ </span>
+ ))}
+ </div>
+ ) : (
+ <p className="mt-2 text-[12px] text-fg-tertiary">{t("syncNotifications.noChanges")}</p>
+ )
+ ) : (
+ <p className="mt-2 break-words rounded-lg border border-danger-line bg-danger-surface px-2.5 py-2 text-[12.5px] leading-snug text-danger-body">
+ {log.errorMessage || t("syncNotifications.statusError")}
+ </p>
+ )}
+ </div>
+ </ListRow>
+ );
+}
+
+interface SyncNotificationDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ calendarId: string | null;
+ onErrorsMarkedRead?: () => void;
+}
+
+export function SyncNotificationDialog({
+ open,
+ onOpenChange,
+ calendarId,
+ onErrorsMarkedRead,
+}: SyncNotificationDialogProps) {
+ const t = useTranslations();
+
+ return (
+ <PanelDialog
+ bare
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("syncNotifications.title")}
+ description={t("syncLog.description")}
+ >
+ {calendarId && (
+ <SyncNotificationsPanel
+ calendarId={calendarId}
+ onClose={() => onOpenChange(false)}
+ onErrorsMarkedRead={onErrorsMarkedRead}
+ />
+ )}
+ </PanelDialog>
+ );
+}
diff --git a/components/theme-switcher.tsx b/components/theme-switcher.tsx
deleted file mode 100644
index 0d0ec38..0000000
--- a/components/theme-switcher.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-"use client";
-
-import { useState, useLayoutEffect } from "react";
-import { useTheme } from "next-themes";
-import { useTranslations } from "next-intl";
-import { Moon, Sun } from "lucide-react";
-import { Button } from "@/components/ui/button";
-
-export function ThemeSwitcher() {
- const { theme, setTheme } = useTheme();
- const t = useTranslations();
- const [mounted, setMounted] = useState(false);
-
- // Set mounted after initial render to avoid hydration mismatch
- // This is a legitimate pattern for SSR hydration - calling setState in useLayoutEffect
- // is the recommended approach to avoid hydration mismatches in client components.
- useLayoutEffect(() => {
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setMounted(true);
- }, []);
-
- const toggleTheme = () => {
- setTheme(theme === "dark" ? "light" : "dark");
- };
-
- // Render placeholder with same dimensions during SSR
- if (!mounted) {
- return (
- <Button variant="ghost" size="icon" className="h-9 w-9" disabled>
- <div className="h-4 w-4" />
- <span className="sr-only">Toggle theme</span>
- </Button>
- );
- }
-
- return (
- <Button
- variant="ghost"
- size="icon"
- onClick={toggleTheme}
- className="h-9 w-9"
- title={
- theme === "dark" ? t("theme.switchToLight") : t("theme.switchToDark")
- }
- >
- {theme === "dark" ? (
- <Sun className="h-4 w-4" />
- ) : (
- <Moon className="h-4 w-4" />
- )}
- <span className="sr-only">
- {theme === "dark" ? t("theme.switchToLight") : t("theme.switchToDark")}
- </span>
- </Button>
- );
-}
diff --git a/components/themed-toaster.tsx b/components/themed-toaster.tsx
index a2b4125..79e6c0d 100644
--- a/components/themed-toaster.tsx
+++ b/components/themed-toaster.tsx
@@ -8,15 +8,20 @@ export function ThemedToaster() {
return (
<Toaster
- position="bottom-left"
- richColors
+ position="top-center"
closeButton
theme={theme as "light" | "dark" | "system"}
toastOptions={{
- className: "text-sm",
- style: {
- padding: "12px 16px",
+ classNames: {
+ toast:
+ "!rounded-[11px] !border !border-line !bg-popover !text-fg-strong !shadow-window !text-[13px] !font-sans",
+ description: "!text-fg-secondary",
+ success: "[&_[data-icon]]:!text-success-dot",
+ error: "!border-danger-line !bg-danger-surface [&_[data-icon]]:!text-danger",
+ warning: "!border-warning-line !bg-warning-surface [&_[data-icon]]:!text-warning",
+ closeButton: "!border-line !bg-popover !text-fg-tertiary",
},
+ style: { padding: "12px 14px" },
}}
/>
);
diff --git a/components/ui/base-sheet.tsx b/components/ui/base-sheet.tsx
index 8d9f644..eb3cf9c 100644
--- a/components/ui/base-sheet.tsx
+++ b/components/ui/base-sheet.tsx
@@ -1,17 +1,10 @@
"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 { Button } from "@/components/ui/button";
import { ConfirmationDialog } from "@/components/ui/confirmation-dialog";
+import { PanelDialog, PanelWidth } from "@/components/panel-dialog";
import { useDirtyState } from "@/hooks/useDirtyState";
interface BaseSheetProps {
@@ -28,16 +21,10 @@ interface BaseSheetProps {
saveDisabled?: boolean;
saveLabel?: string;
hasUnsavedChanges?: boolean;
- maxWidth?: "sm" | "md" | "lg" | "xl";
+ width?: PanelWidth;
}
-const maxWidthClasses = {
- sm: "sm:max-w-[480px]",
- md: "sm:max-w-[600px]",
- lg: "sm:max-w-[700px]",
- xl: "sm:max-w-[800px]",
-};
-
+/** Form panel with cancel/save footer and an unsaved-changes guard. */
export function BaseSheet({
open,
onOpenChange,
@@ -52,85 +39,55 @@ export function BaseSheet({
saveDisabled = false,
saveLabel,
hasUnsavedChanges = false,
- maxWidth = "md",
+ width = "md",
}: BaseSheetProps) {
const t = useTranslations();
- const {
- handleClose,
- showConfirmDialog,
- setShowConfirmDialog,
- handleConfirmClose,
- } = useDirtyState({
- onClose: onOpenChange,
- hasChanges: () => hasUnsavedChanges,
- });
+ const { handleClose, showConfirmDialog, setShowConfirmDialog, handleConfirmClose } =
+ useDirtyState({
+ onClose: onOpenChange,
+ hasChanges: () => hasUnsavedChanges,
+ });
- const handleSave = async () => {
- if (onSave) {
- await onSave();
- }
- };
-
- const handleCancelClick = () => {
- handleClose();
- };
+ const defaultFooter =
+ showSaveButton || showCancelButton ? (
+ <>
+ {showCancelButton && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => handleClose()}
+ disabled={isSaving}
+ className="h-10 flex-1 font-semibold"
+ >
+ {t("common.cancel")}
+ </Button>
+ )}
+ {showSaveButton && (
+ <Button
+ type="button"
+ onClick={() => onSave?.()}
+ disabled={saveDisabled || isSaving}
+ className="h-10 flex-1 font-semibold"
+ >
+ {isSaving ? t("common.saving") : saveLabel || t("common.save")}
+ </Button>
+ )}
+ </>
+ ) : undefined;
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")
- : saveLabel || t("common.save")}
- </Button>
- )}
- </div>
- )}
- </SheetFooter>
- )}
- </SheetContent>
- </Sheet>
+ <PanelDialog
+ open={open}
+ onOpenChange={(next) => (next ? onOpenChange(true) : handleClose())}
+ title={title}
+ description={description}
+ width={width}
+ footer={footer ?? defaultFooter}
+ >
+ {children}
+ </PanelDialog>
<ConfirmationDialog
open={showConfirmDialog}
diff --git a/components/ui/confirmation-dialog.tsx b/components/ui/confirmation-dialog.tsx
index c07a771..f29fbbe 100644
--- a/components/ui/confirmation-dialog.tsx
+++ b/components/ui/confirmation-dialog.tsx
@@ -6,11 +6,10 @@ import {
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useTranslations } from "next-intl";
+import { cn } from "@/lib/utils";
interface ConfirmationDialogProps {
open: boolean;
@@ -25,6 +24,9 @@ interface ConfirmationDialogProps {
children?: React.ReactNode;
}
+// Long labels push the confirm button onto its own row instead of overflowing
+const footerButton = "h-10 flex-[1_1_9rem] font-semibold";
+
export function ConfirmationDialog({
open,
onOpenChange,
@@ -41,32 +43,32 @@ export function ConfirmationDialog({
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
+ <AlertDialogContent className="gap-0 overflow-hidden rounded-2xl border-control p-0 shadow-window sm:max-w-[420px]">
+ <div className="px-[22px] pb-4 pt-5">
+ <AlertDialogTitle className="text-[19px] font-semibold leading-tight tracking-[-0.01em] text-fg-strong">
{title || t("common.unsavedChanges")}
</AlertDialogTitle>
- <AlertDialogDescription>
+ <AlertDialogDescription className="mt-1.5 text-[13.5px] leading-relaxed text-fg-secondary">
{description || t("common.unsavedChangesDescription")}
</AlertDialogDescription>
- </AlertDialogHeader>
- {children}
- <AlertDialogFooter>
- <AlertDialogCancel>
+ </div>
+ {children && <div className="px-[22px] pb-4">{children}</div>}
+ <div className="flex flex-wrap items-center gap-2.5 border-t border-line px-[22px] py-4">
+ <AlertDialogCancel className={footerButton}>
{cancelText || t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
onClick={onConfirm}
disabled={confirmDisabled}
- className={
- confirmVariant === "destructive"
- ? "bg-destructive text-destructive-foreground hover:bg-destructive/90"
- : ""
- }
+ className={cn(
+ footerButton,
+ confirmVariant === "destructive" &&
+ "bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive/60"
+ )}
>
{confirmText || t("common.closeWithoutSaving")}
</AlertDialogAction>
- </AlertDialogFooter>
+ </div>
</AlertDialogContent>
</AlertDialog>
);
diff --git a/components/ui/drawer.tsx b/components/ui/drawer.tsx
new file mode 100644
index 0000000..ad3080e
--- /dev/null
+++ b/components/ui/drawer.tsx
@@ -0,0 +1,134 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "@/lib/utils"
+import { Drawer as DrawerPrimitive } from "vaul"
+
+function Drawer({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
+ return <DrawerPrimitive.Root data-slot="drawer" {...props} />
+}
+
+function DrawerTrigger({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
+ return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
+}
+
+function DrawerPortal({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
+ return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
+}
+
+function DrawerClose({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
+ return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
+}
+
+function DrawerOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
+ return (
+ <DrawerPrimitive.Overlay
+ data-slot="drawer-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DrawerContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
+ return (
+ <DrawerPortal data-slot="drawer-portal">
+ <DrawerOverlay />
+ <DrawerPrimitive.Content
+ data-slot="drawer-content"
+ className={cn(
+ "group/drawer-content fixed z-50 flex h-auto flex-col bg-background",
+ "data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
+ "data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
+ "data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
+ "data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
+ className
+ )}
+ {...props}
+ >
+ <div className="mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
+ {children}
+ </DrawerPrimitive.Content>
+ </DrawerPortal>
+ )
+}
+
+function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-header"
+ className={cn(
+ "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function DrawerTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
+ return (
+ <DrawerPrimitive.Title
+ data-slot="drawer-title"
+ className={cn("font-semibold text-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+function DrawerDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
+ return (
+ <DrawerPrimitive.Description
+ data-slot="drawer-description"
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Drawer,
+ DrawerPortal,
+ DrawerOverlay,
+ DrawerTrigger,
+ DrawerClose,
+ DrawerContent,
+ DrawerHeader,
+ DrawerFooter,
+ DrawerTitle,
+ DrawerDescription,
+}
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
index 96733a2..dcd1df3 100644
--- a/components/user-menu.tsx
+++ b/components/user-menu.tsx
@@ -1,10 +1,11 @@
"use client";
import { useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
-import { useTranslations } from "next-intl";
+import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
-import { signOut } from "@/lib/auth/client";
+import { useSignOut } from "@/hooks/useSignOut";
import {
DropdownMenu,
DropdownMenuContent,
@@ -15,125 +16,201 @@ import {
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
-import { User, LogOut, Users, FileText, Shield } from "lucide-react";
-import { toast } from "sonner";
+import {
+ User,
+ LogOut,
+ Compass,
+ FileText,
+ Settings,
+ Shield,
+ SlidersHorizontal,
+} from "lucide-react";
import { CalendarDiscoverySheet } from "@/components/calendar-discovery-sheet";
+import { ChangelogDialog } from "@/components/changelog-dialog";
+import { AppPreferencesMenuItems } from "@/components/app-preferences-menu-items";
+import { PhoneMenu } from "@/components/phone-menu";
import { useIsAdmin } from "@/hooks/useAdminAccess";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+import { getUserInitials } from "@/lib/utils";
+
+interface MenuProps {
+ onOpenViewSettings?: () => void;
+ /** Phones: opens the page's own settings sheet instead of the built-in one */
+ onOpenPhoneMenu?: () => void;
+}
-/**
- * User menu dropdown for authenticated users
- *
- * Shows:
- * - User avatar and name
- * - Profile link
- * - Activity Log link
- * - Admin Panel link (if user is admin)
- * - Browse Calendars
- * - Sign out button
- */
-export function UserMenu() {
+/** Avatar menu for signed-in users: a dropdown on desktop, the settings sheet on phones. */
+export function UserMenu({ onOpenViewSettings, onOpenPhoneMenu }: MenuProps) {
const t = useTranslations();
+ const handleSignOut = useSignOut();
+ const locale = useLocale();
const router = useRouter();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
const { user, isAuthenticated, isLoading } = useAuth();
const isAdmin = useIsAdmin();
const [discoveryOpen, setDiscoveryOpen] = useState(false);
+ const [changelogOpen, setChangelogOpen] = useState(false);
+ const [phoneMenuOpen, setPhoneMenuOpen] = useState(false);
if (isLoading || !isAuthenticated || !user) {
return null;
}
- const handleSignOut = async () => {
- try {
- await signOut({
- fetchOptions: {
- onSuccess: () => {
- toast.success(t("auth.logoutSuccess"));
- },
- },
- });
- // Always redirect to login after sign out, regardless of auth method
- router.replace("/login");
- } catch (error) {
- console.error("Sign out error:", error);
- toast.error(t("common.error"));
- }
- };
-
- // Generate initials from name
- const getInitials = (name: string) => {
- return name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
- };
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- className="h-10 w-10 sm:h-8 sm:w-8 rounded-full"
+ if (!desktop) {
+ // Gear for settings; the corner avatar says the account lives there too
+ return (
+ <>
+ <button
+ type="button"
+ onClick={onOpenPhoneMenu ?? (() => setPhoneMenuOpen(true))}
+ className="relative flex size-9 shrink-0 items-center justify-center rounded-lg border border-line text-fg-secondary"
+ aria-label={t("appMenu.settingsAndAccount")}
>
- <Avatar className="h-10 w-10 sm:h-8 sm:w-8">
- <AvatarImage src={user.image || undefined} alt={user.name || ""} />
- <AvatarFallback className="bg-primary/10 text-primary text-xs font-semibold">
- {user.name ? (
- getInitials(user.name)
- ) : (
- <User className="h-4 w-4" />
- )}
+ <Settings className="size-4" />
+ <Avatar className="absolute -bottom-1.5 -right-1.5 size-[18px] ring-2 ring-background">
+ <AvatarImage src={user.image || undefined} alt="" />
+ <AvatarFallback className="bg-fg-secondary text-[9px] font-semibold text-background">
+ {user.name ? getUserInitials(user).slice(0, 1) : <User className="size-2.5" />}
</AvatarFallback>
</Avatar>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-56">
- <DropdownMenuLabel className="font-normal">
- <div className="flex flex-col space-y-1">
- <p className="text-sm font-medium leading-none">{user.name}</p>
- <p className="text-xs leading-none text-muted-foreground">
- {user.email}
+ </button>
+ {!onOpenPhoneMenu && <PhoneMenu open={phoneMenuOpen} onOpenChange={setPhoneMenuOpen} />}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className="shrink-0 rounded-full"
+ aria-label={t("appMenu.account")}
+ >
+ <Avatar className="size-8">
+ <AvatarImage src={user.image || undefined} alt={user.name || ""} />
+ <AvatarFallback className="bg-line text-[12px] font-semibold text-fg-body">
+ {user.name ? getUserInitials(user) : <User className="h-4 w-4" />}
+ </AvatarFallback>
+ </Avatar>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-60">
+ <DropdownMenuLabel className="font-normal">
+ <p className="truncate text-sm font-semibold text-fg-strong">
+ {user.name}
</p>
- </div>
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => router.replace("/profile")}>
- <User className="mr-2 h-4 w-4" />
- {t("auth.profile")}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => router.replace("/profile/activity")}>
- <FileText className="mr-2 h-4 w-4" />
- {t("activityLog.title")}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setDiscoveryOpen(true)}>
- <Users className="mr-2 h-4 w-4" />
- {t("calendar.browseCalendars")}
- </DropdownMenuItem>
- {isAdmin && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => router.replace("/admin")}>
+ <p className="truncate text-xs text-fg-tertiary">{user.email}</p>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => router.push("/profile")}>
+ <User className="mr-2 h-4 w-4" />
+ {t("auth.profile")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => router.push("/profile?section=activity")}>
+ <FileText className="mr-2 h-4 w-4" />
+ {t("activityLog.title")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setDiscoveryOpen(true)}>
+ <Compass className="mr-2 h-4 w-4" />
+ {t("calendar.browseCalendars")}
+ </DropdownMenuItem>
+ {isAdmin && (
+ <DropdownMenuItem onClick={() => router.push("/admin")}>
<Shield className="mr-2 h-4 w-4" />
{t("admin.adminPanel")}
</DropdownMenuItem>
- </>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={handleSignOut}
- className="text-destructive focus:text-destructive"
+ )}
+ <DropdownMenuSeparator />
+ <AppPreferencesMenuItems
+ onOpenChangelog={() => setChangelogOpen(true)}
+ onOpenViewSettings={onOpenViewSettings}
+ />
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={handleSignOut}
+ className="text-danger focus:text-danger"
+ >
+ <LogOut className="mr-2 h-4 w-4" />
+ {t("auth.logout")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <CalendarDiscoverySheet open={discoveryOpen} onOpenChange={setDiscoveryOpen} />
+ <ChangelogDialog
+ open={changelogOpen}
+ onOpenChange={setChangelogOpen}
+ locale={locale}
+ />
+ </>
+ );
+}
+
+/** Guests and auth-less instances still need appearance, language and changelog. */
+export function GuestMenu({
+ showLogin,
+ loginOnPhone = true,
+ onOpenViewSettings,
+ onOpenPhoneMenu,
+}: MenuProps & { showLogin: boolean; loginOnPhone?: boolean }) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const [changelogOpen, setChangelogOpen] = useState(false);
+ const [phoneMenuOpen, setPhoneMenuOpen] = useState(false);
+
+ const loginButton = showLogin && (
+ <Button asChild size="sm" className="h-9 font-semibold lg:h-8">
+ <Link href="/login">{t("auth.login")}</Link>
+ </Button>
+ );
+
+ if (!desktop) {
+ return (
+ <>
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-9 rounded-lg"
+ aria-label={t("settings.title")}
+ onClick={onOpenPhoneMenu ?? (() => setPhoneMenuOpen(true))}
>
- <LogOut className="mr-2 h-4 w-4" />
- {t("auth.logout")}
- </DropdownMenuItem>
- </DropdownMenuContent>
+ <Settings className="h-4 w-4 text-fg-secondary" />
+ </Button>
+ {loginOnPhone && loginButton}
+ {!onOpenPhoneMenu && <PhoneMenu open={phoneMenuOpen} onOpenChange={setPhoneMenuOpen} />}
+ </>
+ );
+ }
- <CalendarDiscoverySheet
- open={discoveryOpen}
- onOpenChange={setDiscoveryOpen}
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ className="size-9 rounded-lg lg:size-8"
+ aria-label={t("appMenu.preferences")}
+ >
+ <SlidersHorizontal className="h-4 w-4 text-fg-secondary" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <AppPreferencesMenuItems
+ onOpenChangelog={() => setChangelogOpen(true)}
+ onOpenViewSettings={onOpenViewSettings}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {loginButton}
+ <ChangelogDialog
+ open={changelogOpen}
+ onOpenChange={setChangelogOpen}
+ locale={locale}
/>
- </DropdownMenu>
+ </>
);
}
diff --git a/components/view-settings-sheet.tsx b/components/view-settings-sheet.tsx
index 6f339d1..7830f4b 100644
--- a/components/view-settings-sheet.tsx
+++ b/components/view-settings-sheet.tsx
@@ -1,463 +1,461 @@
"use client";
+import { useId, useState } from "react";
import { useTranslations } from "next-intl";
+import { Info, Loader2, Lock, UserRound } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { PanelBody, PanelDialog, PanelFooter } from "@/components/panel-dialog";
import {
- 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";
+ ChoiceChips,
+ ColorSwatches,
+ Field,
+ InfoNote,
+ SectionLabel,
+ ToggleRow,
+} from "@/components/form-kit";
+import { useViewSettings } from "@/hooks/useViewSettings";
+import { useCalendars } from "@/hooks/useCalendars";
+import { useCalendarPermission } from "@/hooks/useCalendarPermission";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import {
- Maximize2,
- FileText,
- Infinity,
- ArrowUpDown,
- Highlighter,
-} from "lucide-react";
-import { PRESET_COLORS } from "@/lib/constants";
+ CalendarViewSettings,
+ PersonalViewSettings,
+ calendarViewSettingsEqual,
+ sanitizeCalendarViewSettings,
+} from "@/lib/view-settings";
+import { cn } from "@/lib/utils";
+import { useReportDirty } from "@/hooks/useDirtyState";
-interface ViewSettingsSheetProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- shiftsPerDay: number | null;
- externalShiftsPerDay: number | null;
- showShiftNotes: boolean;
- showFullTitles: boolean;
- shiftSortType: "startTime" | "createdAt" | "title";
- shiftSortOrder: "asc" | "desc";
- combinedSortMode: boolean;
- highlightWeekends: boolean;
- highlightedWeekdays: number[];
- highlightColor: string;
- onShiftsPerDayChange: (count: number | null) => void;
- onExternalShiftsPerDayChange: (count: number | null) => void;
- onShowShiftNotesChange: (show: boolean) => void;
- onShowFullTitlesChange: (show: boolean) => void;
- onShiftSortTypeChange: (type: "startTime" | "createdAt" | "title") => void;
- onShiftSortOrderChange: (order: "asc" | "desc") => void;
- onCombinedSortModeChange: (combined: boolean) => void;
- onHighlightWeekendsChange: (highlight: boolean) => void;
- onHighlightedWeekdaysChange: (days: number[]) => void;
- onHighlightColorChange: (color: string) => void;
+export type ViewSettingsState = ReturnType<typeof useViewSettings>;
+
+type LimitValue = "1" | "2" | "3" | "auto";
+const LIMITS: LimitValue[] = ["1", "2", "3", "auto"];
+
+// Handoff rule: locked controls keep their contrast and only lose the fill
+const LOCKED_FIELDS =
+ "[&_button:disabled]:cursor-not-allowed [&_button:disabled]:opacity-100 [&_[role=radio][aria-checked=true]:disabled]:bg-transparent [&_[role=switch]:disabled]:border-control [&_[role=switch]:disabled]:bg-surface-sunken";
+
+function toLimit(value: number | null): LimitValue {
+ if (value === null) return "auto";
+ return (LIMITS.includes(String(value) as LimitValue) ? String(value) : "auto") as LimitValue;
}
-export function ViewSettingsSheet({
- open,
- onOpenChange,
- shiftsPerDay,
- externalShiftsPerDay,
- showShiftNotes,
- showFullTitles,
- shiftSortType,
- shiftSortOrder,
- combinedSortMode,
- highlightWeekends,
- highlightedWeekdays,
- highlightColor,
- onShiftsPerDayChange,
- onExternalShiftsPerDayChange,
- onShowShiftNotesChange,
- onShowFullTitlesChange,
- onShiftSortTypeChange,
- onShiftSortOrderChange,
- onCombinedSortModeChange,
- onHighlightWeekendsChange,
- onHighlightedWeekdaysChange,
- onHighlightColorChange,
-}: ViewSettingsSheetProps) {
+function LimitControl({
+ value,
+ onChange,
+ label,
+ disabled,
+}: {
+ value: number | null;
+ onChange: (value: number | null) => void;
+ label: string;
+ disabled?: boolean;
+}) {
const t = useTranslations();
-
return (
- <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")}
- </SheetTitle>
- <SheetDescription className="text-sm text-muted-foreground">
- {t("view.settingsDescription")}
- </SheetDescription>
- </SheetHeader>
+ <div
+ role="radiogroup"
+ aria-label={label}
+ className={cn(
+ "flex rounded-[9px] p-[3px]",
+ disabled ? "ring-1 ring-inset ring-line" : "bg-surface-sunken"
+ )}
+ >
+ {LIMITS.map((limit) => {
+ const active = toLimit(value) === limit;
+ return (
+ <button
+ key={limit}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={disabled}
+ onClick={() => onChange(limit === "auto" ? null : Number(limit))}
+ className={cn(
+ "h-7 min-w-8 rounded-md px-2 font-mono text-[12.5px] font-medium",
+ active
+ ? disabled
+ ? "font-semibold text-fg-strong ring-1 ring-inset ring-control"
+ : "bg-surface-card font-semibold text-fg-strong shadow-segment dark:bg-control"
+ : "text-fg-secondary"
+ )}
+ >
+ {limit === "auto" ? t("view.limitAuto") : limit}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
- <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">
- <div className="flex items-center gap-2">
- <Maximize2 className="h-4 w-4 text-primary" />
- <Label className="text-sm font-semibold">
- {t("view.shiftsPerDay")}
- </Label>
- </div>
- <div className="flex items-center gap-2 px-3 py-1.5 bg-primary/10 rounded-lg border border-primary/20">
- {shiftsPerDay === null ? (
- <>
- <Infinity className="h-4 w-4 text-primary" />
- <span className="text-sm font-semibold text-primary">
- {t("view.showAll")}
- </span>
- </>
- ) : (
- <span className="text-sm font-semibold text-primary">
- {shiftsPerDay}
- </span>
- )}
- </div>
- </div>
- <div className="space-y-3">
- <Slider
- value={[shiftsPerDay === null ? 11 : shiftsPerDay]}
- onValueChange={(value: number[]) =>
- onShiftsPerDayChange(value[0] === 11 ? null : value[0])
- }
- min={1}
- max={11}
- step={1}
- className="w-full"
- />
- <div className="flex justify-between text-xs text-muted-foreground px-1">
- <span>1</span>
- <span>{t("view.showAll")}</span>
- </div>
- </div>
- <p className="text-xs text-muted-foreground">
- {t("view.shiftsPerDayHint")}
- </p>
- </div>
+/** Field UI shared by the personal view and a calendar's own view. */
+function ViewFields({
+ value,
+ onChange,
+ disabled = false,
+ stampBar,
+}: {
+ value: CalendarViewSettings;
+ onChange: (patch: Partial<CalendarViewSettings>) => void;
+ disabled?: boolean;
+ /** Only the personal view carries the stamp-bar toggle */
+ stampBar?: { checked: boolean; onChange: (checked: boolean) => void };
+}) {
+ const t = useTranslations();
+ const id = useId();
+ const desktop = useMediaQuery(DESKTOP_QUERY, true);
+ const weekdays = [
+ { day: 1, label: t("view.monday") },
+ { day: 2, label: t("view.tuesday") },
+ { day: 3, label: t("view.wednesday") },
+ { day: 4, label: t("view.thursday") },
+ { day: 5, label: t("view.friday") },
+ { day: 6, label: t("view.saturday") },
+ { day: 0, label: t("view.sunday") },
+ ];
+ const days = value.highlightedWeekdays;
- {/* External Shifts per Day */}
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Maximize2 className="h-4 w-4 text-primary" />
- <Label className="text-sm font-semibold">
- {t("view.externalShiftsPerDay")}
- </Label>
- </div>
- <div className="flex items-center gap-2 px-3 py-1.5 bg-primary/10 rounded-lg border border-primary/20">
- {externalShiftsPerDay === null ? (
- <>
- <Infinity className="h-4 w-4 text-primary" />
- <span className="text-sm font-semibold text-primary">
- {t("view.showAll")}
- </span>
- </>
- ) : (
- <span className="text-sm font-semibold text-primary">
- {externalShiftsPerDay}
- </span>
- )}
- </div>
- </div>
- <div className="space-y-3">
- <Slider
- value={[
- externalShiftsPerDay === null ? 11 : externalShiftsPerDay,
- ]}
- onValueChange={(value: number[]) =>
- onExternalShiftsPerDayChange(
- value[0] === 11 ? null : value[0]
- )
- }
- min={1}
- max={11}
- step={1}
- className="w-full"
- />
- <div className="flex justify-between text-xs text-muted-foreground px-1">
- <span>1</span>
- <span>{t("view.showAll")}</span>
- </div>
+ return (
+ <div className={cn("flex flex-col gap-6", disabled && LOCKED_FIELDS)}>
+ <section className="flex flex-col gap-3">
+ <SectionLabel className="mb-0">{t("view.density")}</SectionLabel>
+ <div className="flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ <div className="text-[14px] font-semibold text-fg-strong">{t("view.shiftsPerDay")}</div>
+ <div className="text-[12.5px] text-fg-secondary">{t("view.shiftsPerDayHint")}</div>
+ </div>
+ <LimitControl
+ label={t("view.shiftsPerDay")}
+ value={value.shiftsPerDay}
+ onChange={(shiftsPerDay) => onChange({ shiftsPerDay })}
+ disabled={disabled}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ <div className="text-[14px] font-semibold text-fg-strong">
+ {t("view.externalShiftsPerDay")}
</div>
- <p className="text-xs text-muted-foreground">
+ <div className="text-[12.5px] text-fg-secondary">
{t("view.externalShiftsPerDayHint")}
- </p>
- </div>
-
- {/* Shift Sorting */}
- <div className="space-y-4">
- <div className="flex items-center gap-2">
- <ArrowUpDown className="h-4 w-4 text-primary" />
- <Label className="text-sm font-semibold">
- {t("view.sortOptions")}
- </Label>
</div>
- <div className="space-y-3 pl-6 border-l-2 border-border/50">
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">
- {t("view.sortBy")}
- </Label>
- <Select
- value={shiftSortType}
- onValueChange={onShiftSortTypeChange}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="startTime">
- {t("view.sortByStartTime")}
- </SelectItem>
- <SelectItem value="createdAt">
- {t("view.sortByCreatedAt")}
- </SelectItem>
- <SelectItem value="title">
- {t("view.sortByTitle")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
+ </div>
+ <LimitControl
+ label={t("view.externalShiftsPerDay")}
+ value={value.externalShiftsPerDay}
+ onChange={(externalShiftsPerDay) => onChange({ externalShiftsPerDay })}
+ disabled={disabled}
+ />
+ </div>
+ {/* Phone cells have no room for a second line, so the toggle would do nothing there */}
+ {desktop && (
+ <ToggleRow
+ id={`${id}-notes`}
+ title={t("view.showNotes")}
+ description={t("view.showNotesHint")}
+ checked={value.showShiftNotes}
+ onCheckedChange={(showShiftNotes) => onChange({ showShiftNotes })}
+ disabled={disabled}
+ />
+ )}
+ {stampBar && (
+ <ToggleRow
+ id={`${id}-dock`}
+ title={t("view.showPresetBar")}
+ description={t("view.showPresetBarHint")}
+ checked={stampBar.checked}
+ onCheckedChange={stampBar.onChange}
+ disabled={disabled}
+ />
+ )}
+ </section>
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">
- {t("view.sortOrder")}
- </Label>
- <Select
- value={shiftSortOrder}
- onValueChange={onShiftSortOrderChange}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="asc">
- {t("view.sortOrderAsc")}
- </SelectItem>
- <SelectItem value="desc">
- {t("view.sortOrderDesc")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
+ <section className="flex flex-col gap-3 border-t border-line pt-5">
+ <SectionLabel className="mb-0">{t("view.sortOptions")}</SectionLabel>
+ <Field label={t("view.sortBy")}>
+ <ChoiceChips
+ value={value.sortType}
+ onChange={(sortType) => onChange({ sortType })}
+ disabled={disabled}
+ options={[
+ { value: "startTime", label: t("view.sortByStartTime") },
+ { value: "createdAt", label: t("view.sortByCreatedAt") },
+ { value: "title", label: t("view.sortByTitle") },
+ ]}
+ />
+ </Field>
+ <Field label={t("view.sortOrder")}>
+ <ChoiceChips
+ value={value.sortOrder}
+ onChange={(sortOrder) => onChange({ sortOrder })}
+ disabled={disabled}
+ options={[
+ { value: "asc", label: t("view.sortOrderAsc") },
+ { value: "desc", label: t("view.sortOrderDesc") },
+ ]}
+ />
+ </Field>
+ <ToggleRow
+ id={`${id}-combined`}
+ title={t("view.combinedSort")}
+ description={t("view.combinedSortHint")}
+ checked={value.combinedSort}
+ onCheckedChange={(combinedSort) => onChange({ combinedSort })}
+ disabled={disabled}
+ />
+ </section>
- <div className="flex items-start gap-3 pt-2">
- <Checkbox
- id="combined-sort"
- checked={combinedSortMode}
- onCheckedChange={(checked: boolean) =>
- onCombinedSortModeChange(checked)
+ <section className="flex flex-col gap-3 border-t border-line pt-5">
+ <SectionLabel className="mb-0">{t("view.dayHighlighting")}</SectionLabel>
+ <ToggleRow
+ id={`${id}-weekends`}
+ title={t("view.highlightWeekends")}
+ description={t("view.highlightWeekendsHint")}
+ checked={days.includes(0) && days.includes(6)}
+ onCheckedChange={(checked) =>
+ onChange({
+ highlightedWeekdays: checked
+ ? Array.from(new Set([...days, 0, 6]))
+ : days.filter((d) => d !== 0 && d !== 6),
+ })
+ }
+ disabled={disabled}
+ />
+ <Field label={t("view.customWeekdays")} hint={t("view.customWeekdaysHint")}>
+ <div className="grid grid-cols-7 gap-1.5">
+ {weekdays.map(({ day, label }) => {
+ const selected = days.includes(day);
+ return (
+ <button
+ key={day}
+ type="button"
+ aria-pressed={selected}
+ title={label}
+ disabled={disabled}
+ onClick={() =>
+ onChange({
+ highlightedWeekdays: selected
+ ? days.filter((d) => d !== day)
+ : [...days, day],
+ })
}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-1">
- <Label
- htmlFor="combined-sort"
- className="text-sm font-medium cursor-pointer"
- >
- {t("view.combinedSort")}
- </Label>
- <p className="text-xs text-muted-foreground">
- {t("view.combinedSortHint")}
- </p>
- </div>
- </div>
- </div>
+ className={cn(
+ "h-9 rounded-lg border text-[12.5px] font-semibold",
+ selected ? "border-brand text-brand-ink" : "border-line text-fg-secondary",
+ !disabled && (selected ? "bg-brand-soft" : "bg-surface-card")
+ )}
+ >
+ {label.slice(0, 2)}
+ </button>
+ );
+ })}
</div>
+ </Field>
+ <Field label={t("view.highlightColor")}>
+ <ColorSwatches
+ size="sm"
+ value={value.highlightColor}
+ onChange={(highlightColor) => onChange({ highlightColor })}
+ disabled={disabled}
+ />
+ </Field>
+ </section>
+ </div>
+ );
+}
- {/* Show Shift Notes */}
- <div className="space-y-3">
- <div className="flex items-center gap-2">
- <FileText className="h-4 w-4 text-primary" />
- <Label className="text-sm font-semibold">
- {t("view.displayOptions")}
- </Label>
- </div>
- <div className="space-y-3 pl-6 border-l-2 border-border/50">
- <div className="flex items-start gap-3">
- <Checkbox
- id="show-notes"
- checked={showShiftNotes}
- onCheckedChange={(checked: boolean) =>
- onShowShiftNotesChange(checked)
- }
- className="mt-0.5"
- />
- <div className="flex-1 space-y-1">
- <Label
- htmlFor="show-notes"
- className="text-sm font-medium cursor-pointer"
- >
- {t("view.showNotes")}
- </Label>
- <p className="text-xs text-muted-foreground">
- {t("view.showNotesHint")}
- </p>
- </div>
- </div>
+interface CalendarViewPanelProps {
+ calendarId: string;
+ personal: PersonalViewSettings;
+ onClose: () => void;
+ onCancel: () => void;
+ onDirtyChange: (dirty: boolean) => void;
+}
- {/* Show Full Titles */}
- <div className="flex items-start gap-3">
- <Checkbox
- id="show-full-titles"
- checked={showFullTitles}
- onCheckedChange={(checked: boolean) =>
- onShowFullTitlesChange(checked)
- }
- className="mt-0.5"
- />
- <div className="flex-1 space-y-1">
- <Label
- htmlFor="show-full-titles"
- className="text-sm font-medium cursor-pointer"
- >
- {t("view.showFullTitles")}
- </Label>
- <p className="text-xs text-muted-foreground">
- {t("view.showFullTitlesHint")}
- </p>
- </div>
- </div>
- </div>
- </div>
+/**
+ * Settings section for a calendar's own view. Off by default; while off,
+ * everyone with access sees their personal view instead.
+ */
+export function CalendarViewPanel(props: CalendarViewPanelProps) {
+ const { loading } = useCalendars();
- {/* Day Highlighting */}
- <div className="space-y-4">
- <div className="flex items-center gap-2">
- <Highlighter className="h-4 w-4 text-primary" />
- <Label className="text-sm font-semibold">
- {t("view.dayHighlighting")}
- </Label>
- </div>
- <div className="space-y-4 pl-6 border-l-2 border-border/50">
- {/* Quick Toggle: Weekends */}
- <div className="flex items-start gap-3">
- <Checkbox
- id="highlight-weekends"
- checked={highlightWeekends}
- onCheckedChange={(checked: boolean) => {
- onHighlightWeekendsChange(checked);
- if (checked) {
- // Add Saturday (6) and Sunday (0) to existing weekdays
- const newDays = Array.from(
- new Set([...highlightedWeekdays, 0, 6])
- ).sort((a, b) => a - b);
- onHighlightedWeekdaysChange(newDays);
- } else {
- // Remove Saturday and Sunday, keep other weekdays
- const filtered = highlightedWeekdays.filter(
- (d) => d !== 0 && d !== 6
- );
- onHighlightedWeekdaysChange(filtered);
- }
- }}
- className="mt-0.5"
- />
- <div className="flex-1 space-y-1">
- <Label
- htmlFor="highlight-weekends"
- className="text-sm font-medium cursor-pointer"
- >
- {t("view.highlightWeekends")}
- </Label>
- <p className="text-xs text-muted-foreground">
- {t("view.highlightWeekendsHint")}
- </p>
- </div>
- </div>
+ // The body snapshots the saved view once, so it must not mount before the
+ // calendar is cached: it would read "off" and let a Save clear the pinned
+ // view for everyone with access.
+ if (loading) {
+ return (
+ <PanelBody>
+ <div className="flex justify-center py-6 text-fg-tertiary">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ </PanelBody>
+ );
+ }
- {/* Custom Weekdays */}
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">
- {t("view.customWeekdays")}
- </Label>
- <div className="grid grid-cols-7 gap-1">
- {[
- { day: 1, label: t("view.monday") },
- { day: 2, label: t("view.tuesday") },
- { day: 3, label: t("view.wednesday") },
- { day: 4, label: t("view.thursday") },
- { day: 5, label: t("view.friday") },
- { day: 6, label: t("view.saturday") },
- { day: 0, label: t("view.sunday") },
- ].map(({ day, label }) => {
- const isSelected = highlightedWeekdays.includes(day);
- return (
- <button
- key={day}
- type="button"
- onClick={() => {
- const newDays = isSelected
- ? highlightedWeekdays.filter((d) => d !== day)
- : [...highlightedWeekdays, day];
- onHighlightedWeekdaysChange(newDays);
+ return <CalendarViewPanelBody {...props} />;
+}
- // Update weekends toggle state
- const hasWeekends =
- newDays.includes(0) && newDays.includes(6);
- if (hasWeekends !== highlightWeekends) {
- onHighlightWeekendsChange(hasWeekends);
- }
- }}
- className={`
- px-1 py-2 text-xs font-medium rounded-md transition-all border-2
- ${
- isSelected
- ? "bg-primary/20 border-primary text-primary"
- : "bg-muted/30 border-border/30 text-muted-foreground hover:bg-muted/50"
- }
- `}
- title={label}
- >
- {label.substring(0, 2)}
- </button>
- );
- })}
- </div>
- <p className="text-xs text-muted-foreground">
- {t("view.customWeekdaysHint")}
- </p>
- </div>
+function CalendarViewPanelBody({
+ calendarId,
+ personal,
+ onClose,
+ onCancel,
+ onDirtyChange,
+}: CalendarViewPanelProps) {
+ const t = useTranslations();
+ const id = useId();
+ const { calendars, updateCalendar } = useCalendars();
+ const { canManage } = useCalendarPermission(calendarId);
+ const calendar = calendars.find((c) => c.id === calendarId);
+ const saved = calendar?.viewSettings ? sanitizeCalendarViewSettings(calendar.viewSettings) : null;
+ const personalFields = sanitizeCalendarViewSettings(personal);
- {/* Highlight Color */}
- <div className="space-y-2">
- <Label className="text-xs text-muted-foreground">
- {t("view.highlightColor")}
- </Label>
- <div className="grid grid-cols-4 gap-2">
- {PRESET_COLORS.map((color) => (
- <button
- key={color.value}
- type="button"
- onClick={() => onHighlightColorChange(color.value)}
- className={`
- h-10 rounded-lg border-2 transition-all
- ${
- highlightColor === color.value
- ? "border-foreground ring-2 ring-foreground/20 scale-105"
- : "border-border/30 hover:border-border"
- }
- `}
- style={{
- backgroundColor: `${color.value}20`,
- }}
- title={color.name}
- >
- <div
- className="h-4 w-4 rounded-full mx-auto"
- style={{ backgroundColor: color.value }}
- />
- </button>
- ))}
- </div>
- </div>
- </div>
+ const [enabled, setEnabled] = useState(!!saved);
+ const [draft, setDraft] = useState<CalendarViewSettings>(() => saved ?? personalFields);
+ const [saving, setSaving] = useState(false);
+
+ const dirty =
+ !!calendar &&
+ canManage &&
+ (enabled !== !!saved || (!!saved && enabled && !calendarViewSettingsEqual(draft, saved)));
+
+ useReportDirty(dirty, onDirtyChange);
+
+ const toggle = (on: boolean) => {
+ // Turning it on starts from the saved view, or from the personal one the first time
+ if (on) setDraft(saved ?? personalFields);
+ setEnabled(on);
+ };
+
+ const save = async () => {
+ setSaving(true);
+ try {
+ await updateCalendar(calendarId, { viewSettings: enabled ? draft : null });
+ onClose();
+ } catch {
+ // updateCalendar already reported the error
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const editable = canManage && enabled;
+ const shown = canManage ? (enabled ? draft : personalFields) : (saved ?? personalFields);
+ const ownView = canManage ? enabled : !!saved;
+
+ return (
+ <>
+ <PanelBody>
+ <div className="flex flex-col gap-5">
+ <div className={cn("flex flex-col gap-3", !canManage && LOCKED_FIELDS)}>
+ <ToggleRow
+ id={`${id}-own`}
+ title={t("view.calendarOwn")}
+ description={t("view.calendarOwnHint")}
+ checked={ownView}
+ onCheckedChange={toggle}
+ disabled={!canManage}
+ />
+ {ownView && !canManage && (
+ <InfoNote icon={Lock}>{t("view.calendarLocked")}</InfoNote>
+ )}
+ {!ownView && <InfoNote icon={UserRound}>{t("view.calendarOffNote")}</InfoNote>}
+ </div>
+ <div className="border-t border-line pt-5">
+ <ViewFields
+ value={shown}
+ onChange={(patch) => setDraft((prev) => ({ ...prev, ...patch }))}
+ disabled={!editable}
+ />
</div>
</div>
- </SheetContent>
- </Sheet>
+ </PanelBody>
+ {canManage && (
+ <PanelFooter>
+ <p className="hidden min-w-0 flex-1 text-[13px] text-fg-secondary lg:block">
+ {t("settings.appliesToAll")}
+ </p>
+ <Button
+ variant="outline"
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ onClick={onCancel}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ className="h-10 flex-1 font-semibold lg:flex-none lg:px-4"
+ disabled={!dirty || saving}
+ onClick={save}
+ >
+ {saving ? t("common.saving") : t("common.save")}
+ </Button>
+ </PanelFooter>
+ )}
+ </>
+ );
+}
+
+/** Body of "Meine Ansicht"; changes apply immediately. */
+export function PersonalViewPanel({
+ settings,
+ calendarId,
+}: {
+ settings: ViewSettingsState;
+ /** Selected calendar, to point out when its own view takes precedence */
+ calendarId?: string | null;
+}) {
+ const t = useTranslations();
+ const { calendars } = useCalendars();
+ const calendar = calendarId ? calendars.find((c) => c.id === calendarId) : undefined;
+ const { personal, updatePersonal } = settings;
+
+ return (
+ <PanelBody>
+ <div className="flex flex-col gap-5">
+ {calendar?.viewSettings && (
+ <InfoNote icon={Info}>
+ {t("view.overriddenByCalendar", { calendar: calendar.name })}
+ </InfoNote>
+ )}
+ <ViewFields
+ value={personal}
+ onChange={updatePersonal}
+ stampBar={{
+ checked: personal.showStampBar,
+ onChange: (showStampBar) => updatePersonal({ showStampBar }),
+ }}
+ />
+ </div>
+ </PanelBody>
+ );
+}
+
+/** "Meine Ansicht": the personal view, applied to every calendar without its own view. */
+export function ViewSettingsSheet({
+ open,
+ onOpenChange,
+ settings,
+ calendarId,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ settings: ViewSettingsState;
+ calendarId?: string | null;
+}) {
+ const t = useTranslations();
+ return (
+ <PanelDialog
+ bare
+ open={open}
+ onOpenChange={onOpenChange}
+ title={t("view.settingsTitle")}
+ description={
+ settings.storedInAccount
+ ? t("view.settingsDescription")
+ : t("view.settingsDescriptionLocal")
+ }
+ >
+ <PersonalViewPanel settings={settings} calendarId={calendarId} />
+ </PanelDialog>
);
}
diff --git a/demo/README.md b/demo/README.md
deleted file mode 100644
index dac4c38..0000000
--- a/demo/README.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# Demo Folder
-
-⚠️ **WARNING: This folder is for DEMO purposes only!**
-
-This directory contains scripts and snapshots specifically designed for creating and managing the BetterShift demo environment. **Do NOT use these scripts on production data** as they will reset/overwrite your database.
-
-## Contents
-
-### Scripts
-
-- **`create-snapshot.sh`** - Creates a snapshot of the current database state for demo purposes
-- **`reset-demo.sh`** - Resets the database to the demo snapshot state
-
-### What This Folder Is For
-
-This folder helps maintain a consistent demo environment by:
-
-- Capturing a pre-configured database state with sample data
-- Quickly resetting to that state for demos or testing
-- Ensuring reproducible demo scenarios
-
-## Usage
-
-### Creating a Demo Snapshot
-
-```bash
-./demo/create-snapshot.sh
-```
-
-This will create a snapshot of your current database in the demo folder.
-
-### Resetting to Demo State
-
-```bash
-./demo/reset-demo.sh
-```
-
-This will **overwrite your current database** with the demo snapshot.
-
-### Automated Demo Reset with Cron
-
-For automated demo environments (e.g., public demos), you can set up a cron job to automatically reset the database at regular intervals.
-
-**Example: Reset every hour**
-
-```bash
-# Edit your crontab
-crontab -e
-
-# Add this line to reset every hour at minute 0
-0 * * * * cd /path/to/bettershift && ./demo/reset-demo.sh >> /var/log/bettershift-demo-reset.log 2>&1
-```
-
-**Example: Reset every 30 minutes**
-
-```bash
-# Add this line to reset twice per hour
-*/30 * * * * cd /path/to/bettershift && ./demo/reset-demo.sh >> /var/log/bettershift-demo-reset.log 2>&1
-```
-
-**Example: Reset daily at 2 AM**
-
-```bash
-# Add this line to reset once per day
-0 2 * * * cd /path/to/bettershift && ./demo/reset-demo.sh >> /var/log/bettershift-demo-reset.log 2>&1
-```
-
-**Important for Cron Setup:**
-
-- Replace `/path/to/bettershift` with your actual project path
-- Ensure the cron user has permission to run the script
-- The script requires `sudo` permissions for file operations
-- Check logs at `/var/log/bettershift-demo-reset.log` for errors
-- Consider using `flock` to prevent overlapping executions:
- ```bash
- */30 * * * * flock -n /tmp/demo-reset.lock -c "cd /path/to/bettershift && ./demo/reset-demo.sh" >> /var/log/bettershift-demo-reset.log 2>&1
- ```
-
-## Important Notes
-
-- ⛔ **Never run these scripts on production databases**
-- 🎯 This folder is exclusively for demo/testing environments
-- 💾 The snapshot file is not tracked in git (see `.gitignore`)
-- 🔄 Always backup your data before running reset scripts
-
-## For Production Use
-
-If you need to backup or restore production data, use proper backup tools and strategies instead of these demo scripts. Consider:
-
-- Database backup solutions (SQLite `.backup` command)
-- File-based backups with proper versioning
-- Automated backup schedules
-- Secure off-site storage
diff --git a/demo/create-snapshot.sh b/demo/create-snapshot.sh
deleted file mode 100755
index 7594da8..0000000
--- a/demo/create-snapshot.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/bin/bash
-# Create initial database snapshot for demo resets
-# Run this once to capture the current database state
-
-set -e
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
-DB_PATH="${PROJECT_DIR}/data/sqlite.db"
-SNAPSHOT_PATH="${PROJECT_DIR}/data/demo-snapshot.db"
-
-echo "========================================="
-echo "Create Demo Snapshot"
-echo "========================================="
-
-# Check if database exists
-if [ ! -f "$DB_PATH" ]; then
- echo "Error: Database not found at: $DB_PATH"
- echo "Please ensure your application is running and has a database."
- exit 1
-fi
-
-# Create snapshot
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] Creating snapshot from current database..."
-sudo cp "$DB_PATH" "$SNAPSHOT_PATH"
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✓ Snapshot created: $SNAPSHOT_PATH"
-
-echo ""
-echo "========================================="
-echo "✅ Snapshot created successfully!"
-echo "========================================="
-echo ""
-echo "You can now run ./demo/reset-demo.sh to restore to this state."
-echo ""
diff --git a/demo/reset-demo.sh b/demo/reset-demo.sh
deleted file mode 100755
index c4d95cf..0000000
--- a/demo/reset-demo.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-# Standalone demo reset script for BetterShift
-# Resets the database to the initial snapshot state
-# Works with Docker containers - handles permissions correctly
-
-set -e
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
-CONTAINER_NAME="${CONTAINER_NAME:-bettershift}"
-DB_PATH="${PROJECT_DIR}/data/sqlite.db"
-SNAPSHOT_PATH="${PROJECT_DIR}/data/demo-snapshot.db"
-
-echo "========================================="
-echo "BetterShift Demo Reset"
-echo "========================================="
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting database reset..."
-
-# Check if snapshot exists
-if [ ! -f "$SNAPSHOT_PATH" ]; then
- echo "Error: Demo snapshot not found at: $SNAPSHOT_PATH"
- echo "Please run: ./demo/create-snapshot.sh first"
- exit 1
-fi
-
-# Stop container temporarily to avoid conflicts
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] Stopping container..."
-if ! (cd "$PROJECT_DIR" && docker compose stop "$CONTAINER_NAME"); then
- echo "Error: Failed to stop container"
- exit 1
-fi
-
-# Remove current database and restore from snapshot
-sudo rm -f "$DB_PATH"
-sudo cp "$SNAPSHOT_PATH" "$DB_PATH"
-sudo chown $(stat -c '%u:%g' "$PROJECT_DIR/data") "$DB_PATH"
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✓ Database restored from snapshot"
-
-# Start container again
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting container..."
-(cd "$PROJECT_DIR" && docker compose start "$CONTAINER_NAME")
-
-# Wait for container to be healthy
-echo "[$(date '+%Y-%m-%d %H:%M:%S')] Waiting for container to be ready..."
-timeout 60 sh -c "cd '$PROJECT_DIR' && until docker compose ps '$CONTAINER_NAME' | grep -q '(healthy)'; do sleep 2; done" || echo "Warning: Container may not be fully healthy"
-
-echo ""
-echo "========================================="
-echo "✅ Database reset complete!"
-echo "========================================="
-echo ""
diff --git a/docker-compose.yml b/docker-compose.yml
index 38ec925..1bbf097 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -11,5 +11,6 @@ services:
- "3000:3000"
volumes:
- ./data:/app/data
+ - ./uploads:/app/public/uploads
env_file:
- .env
diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh
index 3d80440..1dad434 100755
--- a/docker-entrypoint.sh
+++ b/docker-entrypoint.sh
@@ -5,14 +5,22 @@
set -e
+# Mirrors lib/db/db-path.mjs's resolveDatabasePath(): DATABASE_URL wins, else
+# the default under /app/data. A custom DATABASE_URL needs its own directory
+# chowned, not the hardcoded default -- otherwise db:migrate still fails as
+# "node" even though this script ran.
+db_path="${DATABASE_URL#file:}"
+db_path="${db_path:-/app/data/sqlite.db}"
+db_dir="$(dirname "$db_path")"
+
# Already non-root: nothing to drop to, and no privilege to chown with. Both
# paths ship owned by "node"; any other uid needs the host side sorted out.
if [ "$(id -u)" != "0" ]; then
- mkdir -p /app/data /app/public/uploads 2>/dev/null || true
+ mkdir -p "$db_dir" /app/public/uploads 2>/dev/null || true
exec "$@"
fi
-for dir in /app/data /app/public/uploads; do
+for dir in "$db_dir" /app/public/uploads; do
mkdir -p "$dir"
owner="$(stat -c '%u:%g' "$dir")"
if [ "$owner" != "$(id -u node):$(id -g node)" ]; then
diff --git a/docs/ADMIN_PANEL.md b/docs/ADMIN_PANEL.md
index 70ac256..4f8857b 100644
--- a/docs/ADMIN_PANEL.md
+++ b/docs/ADMIN_PANEL.md
@@ -5,11 +5,12 @@ This guide covers the admin panel features in BetterShift, including user manage
## Table of Contents
1. [Overview](#overview)
-2. [Roles and Permissions](#roles-and-permissions)
-3. [User Management](#user-management)
-4. [Calendar Management](#calendar-management)
-5. [Audit Logs](#audit-logs)
-6. [Rate Limiting](#rate-limiting)
+2. [Dashboard](#dashboard)
+3. [Roles and Permissions](#roles-and-permissions)
+4. [User Management](#user-management)
+5. [Calendar Management](#calendar-management)
+6. [Audit Logs](#audit-logs)
+7. [Rate Limiting](#rate-limiting)
---
@@ -25,6 +26,26 @@ The admin panel is available at `/admin` and provides system-wide management cap
Or navigate directly to `/admin`.
+### Navigation
+
+- **Desktop**: a sidebar on the left links to Dashboard, Users, Calendars, and Audit Logs.
+- **Phone**: the same four areas are reached through a bottom tab bar instead of a sidebar.
+- Viewing or editing a single user or calendar opens as a side panel over the current list, not as a separate page — the list stays where you left it underneath.
+
+---
+
+## Dashboard
+
+Location: `/admin` (the page you land on when opening the admin panel)
+
+The dashboard exists so you can tell at a glance whether anything needs attention, without opening every section.
+
+- **Header**: instance version, build date, and commit hash, with an update indicator that links to the GitHub release when a newer version is available.
+- **Attention banners**: shown here directly rather than buried in a section — an orphaned-calendars warning (links straight to `/admin/calendars`) and an available-update notice.
+- **Recent Activity**: admin actions and security events combined into one feed (the same entries as [Audit Logs](#audit-logs)), each with a severity indicator, a plain-language description, and a relative timestamp. "View all" links to `/admin/logs`.
+- **Scope**: one list with total users (by role), total calendars (orphaned count called out separately), total shifts, active shares (by user vs. token), and events in the last 7 days — this replaced an earlier grid of separate stat cards.
+- **Jump links**: below Scope, direct links to Users, Calendars, and Audit Logs. On phones, use the bottom tab bar for this instead.
+
---
## Roles and Permissions
diff --git a/docs/AUTH_SETUP.md b/docs/AUTH_SETUP.md
index dd541f9..9552c1f 100644
--- a/docs/AUTH_SETUP.md
+++ b/docs/AUTH_SETUP.md
@@ -250,6 +250,17 @@ Rate-limited endpoints return these headers:
- `X-RateLimit-Remaining`: Requests remaining in window
- `X-RateLimit-Reset`: Unix timestamp when limit resets
+### Behind a Reverse Proxy
+
+Login and registration limits are keyed by IP address. Behind Cloudflare, Caddy, nginx, or any other reverse proxy, set `TRUSTED_PROXY_HEADER` so the real visitor IP is used instead of your proxy's own address — otherwise every visitor is lumped into the same bucket, which defeats the limit entirely.
+
+```bash
+TRUSTED_PROXY_HEADER=CF-Connecting-IP # behind Cloudflare
+TRUSTED_PROXY_HEADER=X-Real-IP # behind Caddy/nginx/Traefik on their own
+```
+
+See `.env.example` (section "Reverse Proxy") for the full set of options.
+
---
## Troubleshooting
diff --git a/docs/MIGRATION_AUTH_TOGGLE.md b/docs/ENABLING_AUTH.md
similarity index 98%
rename from docs/MIGRATION_AUTH_TOGGLE.md
rename to docs/ENABLING_AUTH.md
index 2d19986..0cd13e7 100644
--- a/docs/MIGRATION_AUTH_TOGGLE.md
+++ b/docs/ENABLING_AUTH.md
@@ -101,7 +101,7 @@ The first registered user automatically becomes **superadmin** with full adminis
After logging in as superadmin:
1. Go to `/admin/calendars`
-2. Orphaned calendars appear at the top with a red "Orphaned" badge
+2. Orphaned calendars appear at the top with an "Orphaned" badge
3. For each orphaned calendar:
- Click the action menu
- Select "Transfer Ownership"
diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md
index 2eb14b6..92cbc21 100644
--- a/docs/PERMISSIONS.md
+++ b/docs/PERMISSIONS.md
@@ -58,10 +58,10 @@ BetterShift uses a four-level permission hierarchy for calendars:
Owners and admins can share calendars with other registered users:
1. Open the calendar settings
-2. Go to "Sharing" section
+2. Go to the "Sharing" section, "People" tab
3. Search for users by name or email
4. Select permission level (admin, write, or read)
-5. Click "Share"
+5. Click "Invite"
### Managing Shares
@@ -84,18 +84,17 @@ From calendar settings, you can:
## Access Tokens (Share Links)
-Access tokens provide a way to share calendars via a URL, without requiring the recipient to have an account.
+Access tokens provide a way to share calendars via a URL. With `ALLOW_GUEST_ACCESS=true` the recipient needs no account; otherwise they sign in first and the token applies afterwards.
### Creating Access Tokens
1. Open calendar settings
-2. Navigate to "Access Tokens" section
-3. Click "Create Token"
-4. Configure:
+2. Go to the "Sharing" section, "Links" tab
+3. Configure:
- **Name**: Description for your reference
- **Permission**: read or write
- **Expiration**: Optional expiry date
-5. Copy the generated link
+4. Click "Create link" and copy it; the token is shown only once
### Token Properties
@@ -117,20 +116,20 @@ Access tokens provide a way to share calendars via a URL, without requiring the
### Security Considerations
- Tokens are stored in cookies after first validation
-- Users with tokens can access the calendar without logging in
+- Users with tokens can access the calendar without logging in when `ALLOW_GUEST_ACCESS=true`
- Treat share links like passwords - anyone with the link has access
- Set expiration dates for temporary access
- Monitor usage in token management
### Token vs. User Sharing
-| Aspect | Access Token | User Sharing |
-| ------------------------ | ----------------------- | ------------------ |
-| Requires account | No | Yes |
-| Trackable per-user | No | Yes |
-| Revocable per-person | No (revoke token) | Yes |
-| Can set admin permission | No | Yes |
-| Best for | Public/temporary access | Team collaboration |
+| Aspect | Access Token | User Sharing |
+| ------------------------ | --------------------------- | ------------------ |
+| Requires account | Only if guest access is off | Yes |
+| Trackable per-user | No | Yes |
+| Revocable per-person | No (revoke token) | Yes |
+| Can set admin permission | No | Yes |
+| Best for | Public/temporary access | Team collaboration |
---
@@ -141,7 +140,9 @@ Guest access allows unauthenticated users to view or edit calendars without any
### Configuration
1. Enable globally: Set `ALLOW_GUEST_ACCESS=true` in environment
-2. Enable per-calendar: Set "Guest Permission" in calendar settings
+2. Enable per-calendar: Set public access in calendar settings, "Sharing" section, "Public" tab
+
+The per-calendar level applies to visitors without an account only while `ALLOW_GUEST_ACCESS=true`; otherwise they are sent to the login page. Signed-in users get it through [Calendar Discovery](#calendar-discovery), whatever the flag says. Access links work even with public access set to `none`, but with `ALLOW_GUEST_ACCESS=false` a recipient without a session is sent to the login page first; the link's grant applies once they sign in.
### Guest Permission Levels
@@ -165,12 +166,12 @@ Guest access allows unauthenticated users to view or edit calendars without any
## Calendar Discovery
-When guest access is enabled and calendars are set to allow guests, authenticated users can discover and subscribe to public calendars.
+Signed-in users can discover and subscribe to any calendar whose public access is `read` or `write`. This does not depend on `ALLOW_GUEST_ACCESS`, which only governs visitors without an account.
### Finding Public Calendars
1. Click your profile menu
-2. Select "Browse Calendars"
+2. Select "Shared Calendars"
3. View available public calendars
4. Click "Subscribe" to add to your calendar list
@@ -197,8 +198,8 @@ When a user accesses a calendar, BetterShift resolves permissions in this order:
1. **Owner check**: Is user the calendar owner? → `owner`
2. **Share check**: Is user explicitly shared? → Use share permission
-3. **Subscription check**: Is user subscribed to public calendar? → Use guest permission
-4. **Token check**: Valid access token in cookie? → Use token permission
+3. **Token check**: Valid access token in cookie? → Use token permission
+4. **Subscription check**: Is user subscribed to public calendar? → Use guest permission
5. **Guest check**: Guest access enabled + calendar allows guests? → Use guest permission
6. **No access**: None of the above → Access denied
@@ -213,4 +214,4 @@ The first matching rule determines the permission level.
3. **Set token expiration**: Don't leave tokens valid indefinitely
4. **Review shares periodically**: Remove access that's no longer needed
5. **Use read permission by default**: Only grant write when editing is required
-6. **Consider guest access carefully**: Public calendars are visible to everyone
+6. **Consider public access carefully**: Public calendars are open to every signed-in user, and to everyone when `ALLOW_GUEST_ACCESS=true`
diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md
new file mode 100644
index 0000000..1cb512a
--- /dev/null
+++ b/docs/UPGRADING.md
@@ -0,0 +1,154 @@
+<!--
+Maintainer note: this file collects breaking changes across releases, newest first.
+
+When a release has breaking changes, add a new section above the previous one:
+
+ ## X.Y.Z (from previous version)
+
+ Reuse the same subsections, each suffixed with the version so anchors stay
+ unique across releases instead of colliding (GitHub would otherwise render
+ the second "Breaking Changes" heading in the file as "#breaking-changes-1"):
+
+ ### Before You Start (X.Y.Z)
+ ### Breaking Changes (X.Y.Z)
+ ### Upgrade Steps (X.Y.Z)
+ ### FAQ (X.Y.Z)
+ ### Rollback (X.Y.Z)
+
+ Add the version to the list below. A release with no breaking changes
+ doesn't need a full section — a one-line entry in the list is enough.
+-->
+
+# Upgrade Guide
+
+Breaking changes between BetterShift releases and the steps to get through them. Find the version you're upgrading from below.
+
+## Versions
+
+- [3.0.0](#300-from-22x) — from `2.2.x`
+
+---
+
+## 3.0.0 (from 2.2.x)
+
+BetterShift 3.0.0 is the redesign release — a new visual design across the calendar, admin panel and sign-in flow — bundled with a handful of infrastructure changes that need action from every self-hosted instance coming from `2.2.x`.
+
+### Before You Start (3.0.0)
+
+**Prerequisites**
+
+- A BetterShift instance running `2.2.0` or `2.2.1`
+- Read access to your `.env` file and, for Docker, your `docker-compose.yml` / `docker run` command
+- Database backup (recommended)
+
+```bash
+# SQLite database location (default)
+cp ./data/sqlite.db ./data/sqlite.db.backup
+
+# Or if using Docker
+docker cp bettershift:/app/data/sqlite.db ./sqlite.db.backup
+```
+
+The only schema change in this release is additive (a new `user_preferences` table and a nullable `calendars.view_settings` column, for the personal/per-calendar view settings feature) — `npm run db:migrate` handles it, no manual data work is needed.
+
+### Breaking Changes (3.0.0)
+
+#### 1. ARM Docker images are no longer built
+
+Releases up to and including `v2.2.1` were published for both `linux/amd64` and `linux/arm64`. Starting with `v3.0.0`, only `linux/amd64` images are built, to keep the image small (the same change also cut the image from 1.01GB to 203MB).
+
+| Your setup | Action |
+| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| Raspberry Pi, Ampere, or another native arm64 server | Stay on `v2.2.1` — it will not receive further updates |
+| Apple Silicon Mac via Docker Desktop | Same as above, unless you're fine running `amd64` under emulation (slower, not recommended for production) |
+| `linux/amd64` server (the common case) | No action |
+
+#### 2. The real client IP behind a reverse proxy must now be configured explicitly
+
+Previous versions used the `@supercharge/request-ip` package, which auto-detected several proxy headers (including Cloudflare's `CF-Connecting-IP`) without configuration. That library is gone; IP detection is now controlled by a single `TRUSTED_PROXY_HEADER` variable, because auto-detection could be fooled by a client sending a fake header of its own.
+
+Rate limiting and audit-log entries are keyed off this address, so getting it wrong doesn't break the app — it silently attributes every visitor to the wrong IP (usually your proxy's own address), which weakens rate limiting and makes the audit log useless for tracing abuse.
+
+Add to `.env`:
+
+| Your setup | Set `TRUSTED_PROXY_HEADER` to |
+| -------------------------------------------------------------- | ------------------------------------------------------------------ |
+| Cloudflare in front (with or without Caddy/nginx behind it) | `CF-Connecting-IP` |
+| Caddy, nginx, or Traefik directly in front | `X-Real-IP` |
+| No reverse proxy — app exposed directly | `none` |
+| Exactly one reverse proxy, header name unknown | leave unset (falls back to the last `X-Forwarded-For` entry) |
+
+If you were previously behind Cloudflare and didn't need to configure anything for correct IPs, you need to add this now.
+
+#### 3. Stricter Content-Security-Policy — an escape hatch if it breaks your setup
+
+`v2.2.x` shipped `script-src 'self' 'unsafe-inline' 'unsafe-eval'` in production — any inline or externally injected script was allowed. `v3.0.0` switches to a per-request nonce with `'strict-dynamic'` and drops `'unsafe-eval'` outside development. This is new in `v3.0.0`, not a setting you could have touched before.
+
+The stricter policy can block a same-origin script that a reverse proxy injects into the page without your app's nonce — Cloudflare's Rocket Loader is the known case. If the app fails to load or hydrate after upgrading (a blank page, or a page that never becomes interactive) and you use Rocket Loader or a similar script-rewriting proxy feature, set:
+
+```bash
+CSP_STRICT_DYNAMIC_BYPASS=true
+```
+
+This falls back to the old, permissive `'self' 'unsafe-inline'` policy for scripts. If you don't hit this symptom, no action is needed.
+
+#### 4. Avatar uploads need a second Docker volume
+
+Uploaded profile pictures live at `/app/public/uploads` inside the container. Until now, only `/app/data` was mounted, so avatars were silently lost every time the container was recreated. Add the second mount **before** upgrading:
+
+```diff
+ volumes:
+ - ./data:/app/data
++ - ./uploads:/app/public/uploads
+```
+
+(or `-v ./uploads:/app/public/uploads` for a plain `docker run`). Avatars lost before this fix cannot be recovered from the database; only newly uploaded ones will persist once the mount is in place.
+
+#### 5. Node.js 22+ is required for source installs
+
+Only relevant if you run `npm install` / `npm run build` directly on a host rather than using the Docker image (which already bundles Node 24). Update your local Node.js version before installing.
+
+#### 6. `AUTH_ENABLED` behavior when unset was fixed
+
+The client and server previously disagreed on the default when `AUTH_ENABLED` was left unset: the server treated it as enabled, the client's UI treated it as disabled. This is now consistent (both default to enabled). If your `.env` already sets `AUTH_ENABLED` explicitly, this doesn't affect you; if it was left unset, we recommend setting it explicitly to whatever you intend, so a future default change can't surprise you again.
+
+#### 7. better-auth was updated (1.4.7 → 1.6.30)
+
+If you use a custom OIDC provider, sign in again after upgrading and confirm it still works. See [Authentication Setup](AUTH_SETUP.md) if you need to adjust the configuration.
+
+### Upgrade Steps (3.0.0)
+
+1. **Back up your database** (see [Before You Start](#before-you-start-300)).
+2. **Update `.env`** for the items in [Breaking Changes](#breaking-changes-300) that apply to you: `TRUSTED_PROXY_HEADER`, and an explicit `AUTH_ENABLED`. Keep `CSP_STRICT_DYNAMIC_BYPASS` in mind only if step 6 below turns up a blank page.
+3. **Add the `uploads` volume mount** to your `docker-compose.yml` or `docker run` command.
+4. **Pull the new image** (`ghcr.io/pantelx/bettershift:latest` or `:3.0.0`) — skip this step and stay on `v2.2.1` if you're on ARM hardware.
+5. **Restart the container** (or `npm run build && npm run db:migrate && npm start` from source). The migration runs automatically on container start.
+6. **Verify**: sign in still works (including OAuth/OIDC if configured), a newly uploaded avatar survives a container restart, and new audit-log entries show real visitor IPs rather than your proxy's address.
+
+### FAQ (3.0.0)
+
+**I don't use a reverse proxy — do I need to set `TRUSTED_PROXY_HEADER`?**
+
+No, but setting it to `none` makes the intent explicit and is slightly more defensive than leaving it unset.
+
+**I'm on ARM hardware. What are my options?**
+
+Stay on `v2.2.1`. It won't receive further updates, but there's no forced-upgrade pressure — running it indefinitely is fine if ARM support matters more than new features.
+
+**The app shows a blank page / never finishes loading after upgrading.**
+
+This is almost always the CSP change interacting with a script-injecting reverse-proxy feature (Cloudflare Rocket Loader is the common case). Set `CSP_STRICT_DYNAMIC_BYPASS=true` and restart.
+
+**My avatars are gone after upgrading.**
+
+Anything uploaded before you added the `./uploads:/app/public/uploads` volume mount was never persisted to disk and can't be recovered. Add the mount (see [Breaking Change 4](#4-avatar-uploads-need-a-second-docker-volume)) so it doesn't happen again.
+
+**Do I need to touch the database manually?**
+
+No. `npm run db:migrate` (or the Docker entrypoint, which runs it automatically) only adds a new table and a new nullable column — no existing data is changed.
+
+### Rollback (3.0.0)
+
+1. Re-deploy the `v2.2.1` image tag (or your previous version).
+2. The `v3.0.0` migration is additive, so an older version simply ignores the new table/column — no database rollback is needed.
+3. `TRUSTED_PROXY_HEADER` and `CSP_STRICT_DYNAMIC_BYPASS` can stay in your `.env` — `v2.2.1` doesn't read either and ignores them.
diff --git a/drizzle.config.ts b/drizzle.config.ts
index 4a5880d..210aa9f 100644
--- a/drizzle.config.ts
+++ b/drizzle.config.ts
@@ -1,11 +1,12 @@
import "dotenv/config";
import { defineConfig } from "drizzle-kit";
+import { resolveDatabasePath } from "./lib/db/db-path.mjs";
export default defineConfig({
out: "./drizzle",
schema: "./lib/db/schema.ts",
dialect: "sqlite",
dbCredentials: {
- url: process.env.DATABASE_URL || "./data/sqlite.db",
+ url: resolveDatabasePath(),
},
});
diff --git a/drizzle/0014_long_the_liberteens.sql b/drizzle/0014_long_the_liberteens.sql
new file mode 100644
index 0000000..348ab1f
--- /dev/null
+++ b/drizzle/0014_long_the_liberteens.sql
@@ -0,0 +1,8 @@
+CREATE TABLE `user_preferences` (
+ `user_id` text PRIMARY KEY NOT NULL,
+ `view_settings` text,
+ `updated_at` integer DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+ALTER TABLE `calendars` ADD `view_settings` text;
\ No newline at end of file
diff --git a/drizzle/meta/0014_snapshot.json b/drizzle/meta/0014_snapshot.json
new file mode 100644
index 0000000..018bf96
--- /dev/null
+++ b/drizzle/meta/0014_snapshot.json
@@ -0,0 +1,1680 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "af48f9e4-d5e2-4cd2-a283-0b41d0e35cd1",
+ "prevId": "15a997db-247d-452f-8243-0146dfca9d63",
+ "tables": {
+ "account": {
+ "name": "account",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "audit_logs": {
+ "name": "audit_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'info'"
+ },
+ "is_user_visible": {
+ "name": "is_user_visible",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "audit_logs_userId_timestamp_idx": {
+ "name": "audit_logs_userId_timestamp_idx",
+ "columns": [
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_action_timestamp_idx": {
+ "name": "audit_logs_action_timestamp_idx",
+ "columns": [
+ "action",
+ "timestamp"
+ ],
+ "isUnique": false
+ },
+ "audit_logs_userVisible_userId_timestamp_idx": {
+ "name": "audit_logs_userVisible_userId_timestamp_idx",
+ "columns": [
+ "is_user_visible",
+ "user_id",
+ "timestamp"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "audit_logs_user_id_user_id_fk": {
+ "name": "audit_logs_user_id_user_id_fk",
+ "tableFrom": "audit_logs",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_access_tokens": {
+ "name": "calendar_access_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'read'"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage_count": {
+ "name": "usage_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "calendar_access_tokens_token_unique": {
+ "name": "calendar_access_tokens_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "calendar_access_tokens_token_idx": {
+ "name": "calendar_access_tokens_token_idx",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_calendarId_isActive_idx": {
+ "name": "calendar_access_tokens_calendarId_isActive_idx",
+ "columns": [
+ "calendar_id",
+ "is_active"
+ ],
+ "isUnique": false
+ },
+ "calendar_access_tokens_createdBy_idx": {
+ "name": "calendar_access_tokens_createdBy_idx",
+ "columns": [
+ "created_by"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_access_tokens_calendar_id_calendars_id_fk": {
+ "name": "calendar_access_tokens_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_access_tokens_created_by_user_id_fk": {
+ "name": "calendar_access_tokens_created_by_user_id_fk",
+ "tableFrom": "calendar_access_tokens",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_notes": {
+ "name": "calendar_notes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'note'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recurring_pattern": {
+ "name": "recurring_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "recurring_interval": {
+ "name": "recurring_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "calendar_notes_calendar_id_calendars_id_fk": {
+ "name": "calendar_notes_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendar_shares": {
+ "name": "calendar_shares",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "permission": {
+ "name": "permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'read'"
+ },
+ "shared_by": {
+ "name": "shared_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendar_shares_calendarId_idx": {
+ "name": "calendar_shares_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "calendar_shares_userId_idx": {
+ "name": "calendar_shares_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendar_shares_calendar_id_calendars_id_fk": {
+ "name": "calendar_shares_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_user_id_user_id_fk": {
+ "name": "calendar_shares_user_id_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_shares_shared_by_user_id_fk": {
+ "name": "calendar_shares_shared_by_user_id_fk",
+ "tableFrom": "calendar_shares",
+ "tableTo": "user",
+ "columnsFrom": [
+ "shared_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendars": {
+ "name": "calendars",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "guest_permission": {
+ "name": "guest_permission",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'none'"
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "calendars_ownerId_idx": {
+ "name": "calendars_ownerId_idx",
+ "columns": [
+ "owner_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "calendars_owner_id_user_id_fk": {
+ "name": "calendars_owner_id_user_id_fk",
+ "tableFrom": "calendars",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_syncs": {
+ "name": "external_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'icloud'"
+ },
+ "calendar_url": {
+ "name": "calendar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "display_mode": {
+ "name": "display_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "auto_sync_interval": {
+ "name": "auto_sync_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "is_one_time_import": {
+ "name": "is_one_time_import",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "external_syncs_calendar_id_calendars_id_fk": {
+ "name": "external_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "external_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impersonated_by": {
+ "name": "impersonated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "columns": [
+ "token"
+ ],
+ "isUnique": true
+ },
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_presets": {
+ "name": "shift_presets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shift_presets_calendar_id_calendars_id_fk": {
+ "name": "shift_presets_calendar_id_calendars_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shifts": {
+ "name": "shifts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "external_event_id": {
+ "name": "external_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_external": {
+ "name": "synced_from_external",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shifts_calendar_id_calendars_id_fk": {
+ "name": "shifts_calendar_id_calendars_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_preset_id_shift_presets_id_fk": {
+ "name": "shifts_preset_id_shift_presets_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "shifts_external_sync_id_external_syncs_id_fk": {
+ "name": "shifts_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sync_logs": {
+ "name": "sync_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_id": {
+ "name": "external_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_sync_name": {
+ "name": "external_sync_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shifts_created": {
+ "name": "shifts_created",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_updated": {
+ "name": "shifts_updated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "shifts_deleted": {
+ "name": "shifts_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "sync_type": {
+ "name": "sync_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'auto'"
+ },
+ "is_read": {
+ "name": "is_read",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "synced_at": {
+ "name": "synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sync_logs_calendar_id_calendars_id_fk": {
+ "name": "sync_logs_calendar_id_calendars_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sync_logs_external_sync_id_external_syncs_id_fk": {
+ "name": "sync_logs_external_sync_id_external_syncs_id_fk",
+ "tableFrom": "sync_logs",
+ "tableTo": "external_syncs",
+ "columnsFrom": [
+ "external_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "ban_reason": {
+ "name": "ban_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ban_expires": {
+ "name": "ban_expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_calendar_subscriptions": {
+ "name": "user_calendar_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'subscribed'"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'guest'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "user_calendar_subscriptions_userId_idx": {
+ "name": "user_calendar_subscriptions_userId_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_calendarId_idx": {
+ "name": "user_calendar_subscriptions_calendarId_idx",
+ "columns": [
+ "calendar_id"
+ ],
+ "isUnique": false
+ },
+ "user_calendar_subscriptions_status_idx": {
+ "name": "user_calendar_subscriptions_status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "user_calendar_subscriptions_user_id_user_id_fk": {
+ "name": "user_calendar_subscriptions_user_id_user_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_calendar_subscriptions_calendar_id_calendars_id_fk": {
+ "name": "user_calendar_subscriptions_calendar_id_calendars_id_fk",
+ "tableFrom": "user_calendar_subscriptions",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_preferences": {
+ "name": "user_preferences",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "view_settings": {
+ "name": "view_settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_preferences_user_id_user_id_fk": {
+ "name": "user_preferences_user_id_user_id_fk",
+ "tableFrom": "user_preferences",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "verification": {
+ "name": "verification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsecond') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 71f3ff7..1135b61 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -99,6 +99,13 @@
"when": 1767124870128,
"tag": "0013_first_phantom_reporter",
"breakpoints": true
+ },
+ {
+ "idx": 14,
+ "version": "6",
+ "when": 1789142634528,
+ "tag": "0014_long_the_liberteens",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/eslint.config.mjs b/eslint.config.mjs
index e9b8125..fb7d519 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -14,37 +14,10 @@ const eslintConfig = defineConfig([
"out/**",
"build/**",
"next-env.d.ts",
+ // Gitignored scratch space (design handoffs, local scripts). CI never sees
+ // it, so linting it only ever breaks `npm test` on a working copy.
+ ".LOCAL/**",
]),
- {
- // eslint-plugin-react-hooks v7 added three compiler-based rules that flag
- // pre-existing patterns across the dialog/sheet components and the page
- // routes. They are real findings, but fixing them touches component logic
- // that is out of scope for this maintenance sweep, so they are demoted to
- // warnings to keep CI actionable. The list is deliberately explicit rather
- // than repo-wide: a new violation in any other file still fails the build,
- // and the list shrinks as these files are reworked — tracked as follow-up
- // work. Note that the rule engine stops after the first diagnosis per
- // function, so fixing one finding can uncover others in the same file.
- files: [
- "app/admin/page.tsx",
- "app/login/page.tsx",
- "app/page.tsx",
- "app/profile/page.tsx",
- "app/register/page.tsx",
- "components/admin/calendar-edit-sheet.tsx",
- "components/changelog-dialog.tsx",
- "components/export-dialog.tsx",
- "components/external-sync-manage-sheet.tsx",
- "components/note-sheet.tsx",
- "components/preset-manage-sheet.tsx",
- "components/shift-sheet.tsx",
- ],
- rules: {
- "react-hooks/set-state-in-effect": "warn",
- "react-hooks/refs": "warn",
- "react-hooks/immutability": "warn",
- },
- },
]);
export default eslintConfig;
diff --git a/hooks/useAccessLinkForm.ts b/hooks/useAccessLinkForm.ts
new file mode 100644
index 0000000..102cfdc
--- /dev/null
+++ b/hooks/useAccessLinkForm.ts
@@ -0,0 +1,100 @@
+"use client";
+
+import { useState } from "react";
+import { useCalendarTokens } from "@/hooks/useCalendarTokens";
+
+export type LinkValidity = "1" | "7" | "30" | "never";
+export type LinkPermission = "read" | "write";
+
+export interface CreatedAccessLink {
+ token: string;
+ link: string;
+ name: string;
+ permission: LinkPermission;
+ validity: LinkValidity;
+}
+
+const VALIDITY_DAYS: Record<LinkValidity, number | null> = {
+ "1": 1,
+ "7": 7,
+ "30": 30,
+ never: null,
+};
+
+function expiryFor(validity: LinkValidity): Date | null {
+ const days = VALIDITY_DAYS[validity];
+ if (days === null) return null;
+ const date = new Date();
+ date.setDate(date.getDate() + days);
+ return date;
+}
+
+const DEFAULT_VALIDITY: LinkValidity = "7";
+
+/** Form state for creating an access link; the full token is only available right after creation. */
+export function useAccessLinkForm(calendarId: string) {
+ const { createToken, getShareLink } = useCalendarTokens(calendarId);
+
+ const [name, setName] = useState("");
+ const [permission, setPermission] = useState<LinkPermission>("read");
+ const [validity, setValidityState] = useState<LinkValidity>(DEFAULT_VALIDITY);
+ const [expiresAt, setExpiresAt] = useState<Date | null>(() =>
+ expiryFor(DEFAULT_VALIDITY)
+ );
+ const [creating, setCreating] = useState(false);
+ const [created, setCreated] = useState<CreatedAccessLink | null>(null);
+
+ // A created link counts as saved; the one-time token view is not unsaved input.
+ const dirty =
+ !created &&
+ (name.trim() !== "" || permission !== "read" || validity !== DEFAULT_VALIDITY);
+
+ const setValidity = (value: LinkValidity) => {
+ setValidityState(value);
+ setExpiresAt(expiryFor(value));
+ };
+
+ const create = async () => {
+ setCreating(true);
+ // Recomputed so a form left open for a while still gets the full period.
+ const expiry = expiryFor(validity);
+ const result = await createToken({
+ name: name.trim() || undefined,
+ permission,
+ expiresAt: expiry?.toISOString() ?? null,
+ });
+ setCreating(false);
+
+ if (result?.token) {
+ setCreated({
+ token: result.token,
+ link: getShareLink(result.token),
+ name: name.trim(),
+ permission,
+ validity,
+ });
+ }
+ };
+
+ const reset = () => {
+ setName("");
+ setPermission("read");
+ setValidity(DEFAULT_VALIDITY);
+ setCreated(null);
+ };
+
+ return {
+ name,
+ setName,
+ permission,
+ setPermission,
+ validity,
+ setValidity,
+ expiresAt,
+ dirty,
+ creating,
+ created,
+ create,
+ reset,
+ };
+}
diff --git a/hooks/useActivityLogs.ts b/hooks/useActivityLogs.ts
index d7275c1..789e136 100644
--- a/hooks/useActivityLogs.ts
+++ b/hooks/useActivityLogs.ts
@@ -1,10 +1,10 @@
"use client";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { keepPreviousData, useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
/**
* Activity Log Types
@@ -129,13 +129,15 @@ export function useActivityLogs(
const {
data: logsData,
isLoading,
+ isPlaceholderData,
error,
refetch,
} = useQuery({
queryKey: queryKeys.activityLogs({ filters, pagination, t }),
queryFn: () => fetchActivityLogsApi(filters, pagination, t),
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true, // Continue polling in background
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
+ // Keeps the current page visible while the next page or filter loads
+ placeholderData: keepPreviousData,
});
// Clear logs mutation
@@ -143,7 +145,7 @@ export function useActivityLogs(
mutationFn: () => clearLogsApi(t),
onSuccess: () => {
toast.success(t("common.deleted", { item: t("activityLog.title") }));
- queryClient.invalidateQueries({ queryKey: ["activity-logs"] });
+ queryClient.invalidateQueries({ queryKey: queryKeys.activityLogsAll });
},
onError: (err) => {
toast.error(
@@ -161,6 +163,7 @@ export function useActivityLogs(
limit: logsData?.limit || pagination.limit,
offset: logsData?.offset || pagination.offset,
isLoading,
+ isPlaceholderData,
error,
// Functions
diff --git a/hooks/useAdminAuditLogs.ts b/hooks/useAdminAuditLogs.ts
index 24edd4d..02ee1ee 100644
--- a/hooks/useAdminAuditLogs.ts
+++ b/hooks/useAdminAuditLogs.ts
@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
/**
* Audit Log Types
@@ -179,6 +179,8 @@ export function useAdminAuditLogs(
filters: AuditLogFilters = {},
sort: AuditLogSort = { field: "timestamp", direction: "desc" },
pagination: AuditLogPagination = { limit: 25, offset: 0 },
+ /** Callers that only need the delete actions skip the polling list query */
+ { listEnabled = true }: { listEnabled?: boolean } = {},
) {
const t = useTranslations();
const queryClient = useQueryClient();
@@ -192,8 +194,8 @@ export function useAdminAuditLogs(
} = useQuery({
queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination, t }),
queryFn: () => fetchAuditLogsApi(filters, sort, pagination, t),
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true, // Continue polling in background
+ enabled: listEnabled,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
// Delete audit logs by IDs mutation
@@ -237,8 +239,8 @@ export function useAdminAuditLogs(
toast.success(t("common.deletedCount", { count: data.deletedCount }));
},
onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "audit-logs"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.auditLogsAll });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });
},
});
@@ -256,8 +258,8 @@ export function useAdminAuditLogs(
toast.success(t("common.deletedCount", { count: data.deletedCount }));
},
onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "audit-logs"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.auditLogsAll });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });
},
});
@@ -267,7 +269,7 @@ export function useAdminAuditLogs(
total: logsData?.total || 0,
limit: logsData?.limit || pagination.limit,
offset: logsData?.offset || pagination.offset,
- isLoading,
+ isLoading: isLoading || deleteByIdsMutation.isPending || deleteByDateMutation.isPending,
error,
// Functions
diff --git a/hooks/useAdminCalendars.ts b/hooks/useAdminCalendars.ts
index 10fce71..3b4595c 100644
--- a/hooks/useAdminCalendars.ts
+++ b/hooks/useAdminCalendars.ts
@@ -1,10 +1,28 @@
"use client";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import {
+ AdminRequestError,
+ toSearchParams,
+ type AdminListResponse,
+ type CalendarListCounts,
+ type CalendarListParams,
+} from "@/lib/admin-list";
+import {
+ patchListPages,
+ restoreListPages,
+ run,
+ useAdminErrorToast,
+} from "@/hooks/useAdminList";
/**
* Calendar Owner Info
@@ -59,95 +77,34 @@ export interface CalendarDetails extends AdminCalendar {
}>;
}
-/**
- * Calendar Filters
- */
-export interface CalendarFilters {
- search?: string;
- status?: "all" | "orphaned" | "with-owner";
-}
-
-/**
- * Calendar Sort Options
- */
-export interface CalendarSort {
- field: "name" | "createdAt" | "owner" | "shiftsCount";
- direction: "asc" | "desc";
-}
-
-/**
- * Calendars List Response
- */
-export interface CalendarsListResponse {
- calendars: AdminCalendar[];
- total: number;
- orphanedCount: number;
-}
+export type CalendarsListResponse = AdminListResponse<AdminCalendar, CalendarListCounts>;
-/**
- * Fetch calendars list from API
- */
-async function fetchCalendarsApi(
- filters: CalendarFilters | undefined,
- sort: CalendarSort | undefined,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- t: ReturnType<typeof useTranslations>,
+/** One page of calendars; omitted params fall back to the API defaults. */
+async function fetchAdminCalendars(
+ params: Partial<CalendarListParams>,
): Promise<CalendarsListResponse> {
- const params = new URLSearchParams();
-
- if (filters?.search) {
- params.set("search", filters.search);
- }
- if (filters?.status && filters.status !== "all") {
- params.set("status", filters.status);
- }
-
- if (sort?.field) {
- params.set("sortBy", sort.field);
- }
- if (sort?.direction) {
- params.set("sortDirection", sort.direction);
- }
-
- const response = await fetch(`/api/admin/calendars?${params}`);
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || "Failed to fetch calendars");
- }
+ const response = await fetch(`/api/admin/calendars?${toSearchParams(params)}`);
+ if (!response.ok) throw new AdminRequestError(response.status);
const data = await response.json();
-
- // Parse dates
- const calendars = data.calendars.map((cal: AdminCalendar) => ({
- ...cal,
- createdAt: new Date(cal.createdAt),
- updatedAt: new Date(cal.updatedAt),
- }));
-
return {
- calendars,
- total: data.total,
- orphanedCount: data.orphanedCount,
+ ...data,
+ items: data.items.map((cal: AdminCalendar) => ({
+ ...cal,
+ createdAt: new Date(cal.createdAt),
+ updatedAt: new Date(cal.updatedAt),
+ })),
};
}
-/**
- * Fetch calendar details from API
- */
-async function fetchCalendarDetailsApi(
+export async function fetchAdminCalendarDetails(
calendarId: string,
): Promise<CalendarDetails> {
const response = await fetch(`/api/admin/calendars/${calendarId}`);
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || "Failed to fetch calendar details");
- }
+ if (!response.ok) throw new AdminRequestError(response.status);
const data = await response.json();
- // Parse dates
return {
...data,
createdAt: new Date(data.createdAt),
@@ -166,7 +123,7 @@ async function fetchCalendarDetailsApi(
*/
async function updateCalendarApi(
calendarId: string,
- updates: { name?: string; color?: string; guestPermission?: string },
+ updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] },
): Promise<void> {
const response = await fetch(`/api/admin/calendars/${calendarId}`, {
method: "PATCH",
@@ -255,140 +212,91 @@ async function bulkTransferCalendarsApi(
}
/**
- * Admin Calendars Management Hook
- *
- * Provides functions for managing calendars in the admin panel.
- * Uses React Query for automatic polling and cache management.
- *
- * Features:
- * - Fetch calendars with filtering and sorting
- * - Get calendar details
- * - Update calendar information
- * - Delete calendars (single and bulk)
- * - Transfer calendar ownership (single and bulk)
- * - Optimistic updates for instant UI feedback
- * - Error handling with toast notifications
- * - Automatic cache invalidation
- *
- * @param filters - Calendar filters (search, status)
- * @param sort - Sort options (field, direction)
- * @returns Object with calendar data and management functions
+ * One page of the admin calendar list, filtered, sorted and paginated by the API.
+ * The previous page stays visible while the next one loads.
*/
-export function useAdminCalendars(
- filters?: CalendarFilters,
- sort?: CalendarSort,
-) {
+export function useAdminCalendars(params: CalendarListParams) {
const t = useTranslations();
- const queryClient = useQueryClient();
+ const { data, isLoading, isPlaceholderData, error } = useQuery({
+ queryKey: queryKeys.admin.calendars.list(params),
+ queryFn: () => fetchAdminCalendars(params),
+ placeholderData: keepPreviousData,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
+ });
- // Fetch calendars list with polling
- const {
- data: calendarsData,
- isLoading,
+ useAdminErrorToast(
error,
- refetch,
- } = useQuery({
- queryKey: queryKeys.admin.calendars({ filters, sort, t }),
- queryFn: () => fetchCalendarsApi(filters, sort, t),
- refetchInterval: REFETCH_INTERVAL,
- });
+ "admin-calendars-error",
+ t("common.fetchError", { item: t("admin.calendarsMenu") }),
+ );
+
+ return {
+ calendars: data?.items ?? [],
+ total: data?.total ?? 0,
+ counts: data?.counts ?? null,
+ // See useAdminUsers: the served page is only authoritative for the current request
+ page: isPlaceholderData ? params.page : (data?.page ?? params.page),
+ isLoading,
+ isPlaceholderData,
+ };
+}
+
+/**
+ * Calendar mutations for the admin panel. Edits and deletions are applied
+ * optimistically to every cached page of the calendar list.
+ */
+export function useAdminCalendarActions() {
+ const t = useTranslations();
+ const queryClient = useQueryClient();
+
+ const patchCalendars = (patch: (calendars: AdminCalendar[]) => AdminCalendar[]) =>
+ patchListPages<AdminCalendar>(queryClient, queryKeys.admin.calendars.lists, patch);
+
+ const onSettled = () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.calendars.all });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });
+ };
- // Update calendar mutation
const updateMutation = useMutation({
mutationFn: ({
calendarId,
updates,
}: {
calendarId: string;
- updates: { name?: string; color?: string; guestPermission?: string };
+ updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] };
}) => updateCalendarApi(calendarId, updates),
- onMutate: async ({ calendarId, updates }) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.calendars({ filters, sort }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- (old: CalendarsListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- calendars: old.calendars.map((cal) =>
- cal.id === calendarId ? { ...cal, ...updates } : cal,
- ),
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async ({ calendarId, updates }) => ({
+ snapshot: await patchCalendars((calendars) =>
+ calendars.map((cal) => (cal.id === calendarId ? { ...cal, ...updates } : cal)),
+ ),
+ }),
onError: (err, variables, context) => {
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- context?.previous,
- );
- toast.error(
- t("common.updateError", { item: t("common.labels.calendar") }),
- );
+ restoreListPages(queryClient, context?.snapshot);
+ toast.error(t("common.updateError", { item: t("common.labels.calendar") }));
},
onSuccess: () => {
toast.success(t("common.updated", { item: t("common.labels.calendar") }));
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Delete calendar mutation
const deleteMutation = useMutation({
mutationFn: (calendarId: string) => deleteCalendarApi(calendarId),
- onMutate: async (calendarId) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.calendars({ filters, sort }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- (old: CalendarsListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- calendars: old.calendars.filter((cal) => cal.id !== calendarId),
- total: old.total - 1,
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async (calendarId) => ({
+ snapshot: await patchCalendars((calendars) =>
+ calendars.filter((cal) => cal.id !== calendarId),
+ ),
+ }),
onError: (err, calendarId, context) => {
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- context?.previous,
- );
- toast.error(
- t("common.deleteError", { item: t("common.labels.calendar") }),
- );
+ restoreListPages(queryClient, context?.snapshot);
+ toast.error(t("common.deleteError", { item: t("common.labels.calendar") }));
},
onSuccess: () => {
toast.success(t("common.deleted", { item: t("common.labels.calendar") }));
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Transfer calendar mutation
const transferMutation = useMutation({
mutationFn: ({
calendarId,
@@ -398,70 +306,31 @@ export function useAdminCalendars(
newOwnerId: string;
}) => transferCalendarApi(calendarId, newOwnerId),
onError: () => {
- toast.error(
- t("common.transferError", { item: t("common.labels.calendar") }),
- );
+ toast.error(t("common.transferError", { item: t("common.labels.calendar") }));
},
onSuccess: () => {
- toast.success(
- t("common.transferred", { item: t("common.labels.calendar") }),
- );
- },
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
+ toast.success(t("common.transferred", { item: t("common.labels.calendar") }));
},
+ onSettled,
});
- // Bulk delete mutation
const bulkDeleteMutation = useMutation({
mutationFn: (calendarIds: string[]) => bulkDeleteCalendarsApi(calendarIds),
- onMutate: async (calendarIds) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.calendars({ filters, sort }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- (old: CalendarsListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- calendars: old.calendars.filter(
- (cal) => !calendarIds.includes(cal.id),
- ),
- total: old.total - calendarIds.length,
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async (calendarIds) => ({
+ snapshot: await patchCalendars((calendars) =>
+ calendars.filter((cal) => !calendarIds.includes(cal.id)),
+ ),
+ }),
onError: (err, calendarIds, context) => {
- queryClient.setQueryData(
- queryKeys.admin.calendars({ filters, sort }),
- context?.previous,
- );
- toast.error(
- t("common.deleteError", { item: t("common.labels.calendar") }),
- );
+ restoreListPages(queryClient, context?.snapshot);
+ toast.error(t("common.deleteError", { item: t("common.labels.calendar") }));
},
onSuccess: (data) => {
- toast.success(
- t("admin.calendars.calendarsDeleted", { count: data.deletedCount }),
- );
- },
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
+ toast.success(t("admin.calendars.calendarsDeleted", { count: data.deletedCount }));
},
+ onSettled,
});
- // Bulk transfer mutation
const bulkTransferMutation = useMutation({
mutationFn: ({
calendarIds,
@@ -471,83 +340,29 @@ export function useAdminCalendars(
newOwnerId: string;
}) => bulkTransferCalendarsApi(calendarIds, newOwnerId),
onError: () => {
- toast.error(
- t("common.transferError", { item: t("common.labels.calendar") }),
- );
+ toast.error(t("common.transferError", { item: t("common.labels.calendar") }));
},
onSuccess: (data) => {
toast.success(
- t("admin.calendars.calendarsTransferred", {
- count: data.transferredCount,
- }),
+ t("admin.calendars.calendarsTransferred", { count: data.transferredCount }),
);
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "calendars"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
return {
- // Data
- calendars: calendarsData?.calendars || [],
- total: calendarsData?.total || 0,
- orphanedCount: calendarsData?.orphanedCount || 0,
- isLoading,
- error,
-
- // Functions
- refetch,
- fetchCalendarDetails: (calendarId: string) =>
- fetchCalendarDetailsApi(calendarId),
- updateCalendar: async (
+ isUpdating: updateMutation.isPending,
+ isTransferring: transferMutation.isPending || bulkTransferMutation.isPending,
+ updateCalendar: (
calendarId: string,
- updates: { name?: string; color?: string; guestPermission?: string },
- ): Promise<boolean> => {
- try {
- await updateMutation.mutateAsync({ calendarId, updates });
- return true;
- } catch {
- return false;
- }
- },
- deleteCalendar: async (calendarId: string): Promise<boolean> => {
- try {
- await deleteMutation.mutateAsync(calendarId);
- return true;
- } catch {
- return false;
- }
- },
- transferCalendar: async (
- calendarId: string,
- newOwnerId: string,
- ): Promise<boolean> => {
- try {
- await transferMutation.mutateAsync({ calendarId, newOwnerId });
- return true;
- } catch {
- return false;
- }
- },
- bulkDeleteCalendars: async (calendarIds: string[]): Promise<boolean> => {
- try {
- await bulkDeleteMutation.mutateAsync(calendarIds);
- return true;
- } catch {
- return false;
- }
- },
- bulkTransferCalendars: async (
- calendarIds: string[],
- newOwnerId: string,
- ): Promise<boolean> => {
- try {
- await bulkTransferMutation.mutateAsync({ calendarIds, newOwnerId });
- return true;
- } catch {
- return false;
- }
- },
+ updates: { name?: string; color?: string; guestPermission?: AdminCalendar["guestPermission"] },
+ ) => run(updateMutation.mutateAsync, { calendarId, updates }),
+ deleteCalendar: (calendarId: string) => run(deleteMutation.mutateAsync, calendarId),
+ transferCalendar: (calendarId: string, newOwnerId: string) =>
+ run(transferMutation.mutateAsync, { calendarId, newOwnerId }),
+ bulkDeleteCalendars: (calendarIds: string[]) =>
+ run(bulkDeleteMutation.mutateAsync, calendarIds),
+ bulkTransferCalendars: (calendarIds: string[], newOwnerId: string) =>
+ run(bulkTransferMutation.mutateAsync, { calendarIds, newOwnerId }),
};
}
diff --git a/hooks/useAdminList.ts b/hooks/useAdminList.ts
new file mode 100644
index 0000000..b449f2d
--- /dev/null
+++ b/hooks/useAdminList.ts
@@ -0,0 +1,100 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { QueryClient, QueryKey } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+import { AdminRequestError, type AdminListResponse } from "@/lib/admin-list";
+
+/** Search input whose committed `query` trails the typed `input` by `delay` ms. */
+export function useDebouncedSearch(delay = 300) {
+ const [input, setInputState] = useState("");
+ const [query, setQuery] = useState("");
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+
+ useEffect(() => () => clearTimeout(timer.current), []);
+
+ const setInput = useCallback(
+ (value: string) => {
+ setInputState(value);
+ clearTimeout(timer.current);
+ timer.current = setTimeout(() => setQuery(value.trim()), delay);
+ },
+ [delay]
+ );
+
+ return { input, query, setInput };
+}
+
+/** Runs a mutation and reports success as a boolean instead of throwing. */
+export async function run<V>(
+ mutate: (variables: V) => Promise<unknown>,
+ variables: V
+): Promise<boolean> {
+ try {
+ await mutate(variables);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** State that falls back to `initial` whenever `resetKey` changes, without an effect. */
+export function useResettableState<T>(resetKey: string, initial: T) {
+ const [state, setState] = useState({ key: resetKey, value: initial });
+ const value = state.key === resetKey ? state.value : initial;
+
+ const set = useCallback(
+ (next: T | ((prev: T) => T)) =>
+ setState((prev) => {
+ const current = prev.key === resetKey ? prev.value : initial;
+ return {
+ key: resetKey,
+ value: typeof next === "function" ? (next as (prev: T) => T)(current) : next,
+ };
+ }),
+ [resetKey, initial]
+ );
+
+ return [value, set] as const;
+}
+
+/**
+ * Shows a query error once, however many components observe the query.
+ * `id` lets sonner replace instead of stack toasts from sibling observers.
+ */
+export function useAdminErrorToast(error: Error | null, id: string, fallback: string) {
+ const t = useTranslations();
+ const message =
+ error instanceof AdminRequestError && error.status === 403
+ ? t("admin.accessDenied")
+ : error
+ ? fallback
+ : null;
+
+ useEffect(() => {
+ if (message) toast.error(message, { id });
+ }, [message, id]);
+}
+
+type ListSnapshot = Array<[QueryKey, unknown]>;
+
+/** Cancels, snapshots and patches every cached page of a list for an optimistic update. */
+export async function patchListPages<T>(
+ queryClient: QueryClient,
+ queryKey: QueryKey,
+ patch: (items: T[]) => T[]
+): Promise<ListSnapshot> {
+ await queryClient.cancelQueries({ queryKey });
+ const snapshot = queryClient.getQueriesData({ queryKey });
+ queryClient.setQueriesData<AdminListResponse<T, unknown>>({ queryKey }, (old) => {
+ if (!old) return old;
+ const items = patch(old.items);
+ return { ...old, items, total: old.total - (old.items.length - items.length) };
+ });
+ return snapshot;
+}
+
+export function restoreListPages(queryClient: QueryClient, snapshot: ListSnapshot | undefined) {
+ snapshot?.forEach(([key, data]) => queryClient.setQueryData(key, data));
+}
diff --git a/hooks/useAdminStats.ts b/hooks/useAdminStats.ts
index b697939..f77667f 100644
--- a/hooks/useAdminStats.ts
+++ b/hooks/useAdminStats.ts
@@ -1,15 +1,23 @@
"use client";
import { useQuery } from "@tanstack/react-query";
-import { useEffect, useRef } from "react";
-import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import { AdminRequestError } from "@/lib/admin-list";
+import { useAdminErrorToast } from "@/hooks/useAdminList";
+
+export interface AdminActivityLog {
+ id: string;
+ action: string;
+ resourceType: string | null;
+ resourceId: string | null;
+ userId: string | null;
+ metadata: unknown;
+ severity: string;
+ timestamp: Date;
+}
-/**
- * Admin Stats Type Definitions
- */
export interface AdminStats {
users: {
superadmin: number;
@@ -18,6 +26,7 @@ export interface AdminStats {
total: number;
};
calendars: {
+ /** Calendars with an owner; orphaned ones are counted separately */
total: number;
orphaned: number;
};
@@ -30,109 +39,52 @@ export interface AdminStats {
total: number;
};
activity: {
+ /** Audit entries of the last 7 days */
recent: number;
- logs: Array<{
- id: string;
- action: string;
- resourceType: string | null;
- resourceId: string | null;
- userId: string | null;
- severity: string;
- timestamp: Date;
- }>;
+ /** Admin actions and security events, the scope of `logs` */
+ total: number;
+ logs: AdminActivityLog[];
+ };
+ auditLogs: {
+ total: number;
};
}
-interface AuditLogResponse {
- id: string;
- action: string;
- resourceType: string | null;
- resourceId: string | null;
- userId: string | null;
- severity: string;
- timestamp: string | Date;
-}
-
-/**
- * Fetch admin stats from API
- */
-async function fetchAdminStatsApi(
- t: ReturnType<typeof useTranslations>,
-): Promise<AdminStats> {
- const response = await fetch("/api/admin/stats", {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- });
-
- if (!response.ok) {
- if (response.status === 403) {
- throw new Error(t("admin.accessDenied"));
- }
- throw new Error(t("admin.statsFetchError"));
- }
+async function fetchAdminStats(): Promise<AdminStats> {
+ const response = await fetch("/api/admin/stats");
+ if (!response.ok) throw new AdminRequestError(response.status);
const data = await response.json();
-
- // Parse timestamp strings to Date objects
- if (data.activity?.logs) {
- data.activity.logs = data.activity.logs.map((log: AuditLogResponse) => ({
- ...log,
- timestamp: new Date(log.timestamp),
- }));
- }
-
- return data;
+ return {
+ ...data,
+ activity: {
+ ...data.activity,
+ logs: data.activity.logs.map((log: AdminActivityLog & { timestamp: string }) => ({
+ ...log,
+ timestamp: new Date(log.timestamp),
+ })),
+ },
+ };
}
/**
- * Admin Statistics Hook
- *
- * Fetches and manages system-wide statistics for admin dashboard.
- * Uses React Query for automatic polling and cache management.
- *
- * Features:
- * - Automatic 5-second polling for live updates
- * - Error handling with toast notifications
- * - Smart caching and background refetching
- * - Loading state management
- *
- * @returns Object with stats data, loading state, error, and refetch function
+ * System-wide statistics for the dashboard and sidebar, polled. Several components
+ * observe the same query; a failure still shows a single toast.
*/
-export function useAdminStats(): {
- stats: AdminStats | null;
- isLoading: boolean;
- error: Error | null;
- refetch: () => void;
-} {
+export function useAdminStats() {
const t = useTranslations();
- const lastErrorMessage = useRef<string | null>(null);
-
- const {
- data: stats = null,
- isLoading,
- error,
- refetch,
- } = useQuery({
- queryKey: queryKeys.admin.stats({ t }),
- queryFn: () => fetchAdminStatsApi(t),
- refetchInterval: REFETCH_INTERVAL,
+ const { data, isLoading, error, refetch } = useQuery({
+ queryKey: queryKeys.admin.stats,
+ queryFn: fetchAdminStats,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
- useEffect(() => {
- if (error && error.message !== lastErrorMessage.current) {
- toast.error(error.message);
- lastErrorMessage.current = error.message;
- } else if (!error) {
- lastErrorMessage.current = null;
- }
- }, [error]);
+ useAdminErrorToast(error, "admin-stats-error", t("admin.statsFetchError"));
return {
- stats,
+ stats: data ?? null,
isLoading,
- error: error as Error | null,
+ error,
refetch,
};
}
diff --git a/hooks/useAdminUsers.ts b/hooks/useAdminUsers.ts
index 7e2b4e7..99d8503 100644
--- a/hooks/useAdminUsers.ts
+++ b/hooks/useAdminUsers.ts
@@ -1,11 +1,29 @@
"use client";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
import type { User } from "@/lib/auth";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import {
+ AdminRequestError,
+ toSearchParams,
+ type AdminListResponse,
+ type UserListCounts,
+ type UserListParams,
+} from "@/lib/admin-list";
+import {
+ patchListPages,
+ restoreListPages,
+ run,
+ useAdminErrorToast,
+} from "@/hooks/useAdminList";
/**
* Extended User Type with Admin-specific fields
@@ -42,122 +60,35 @@ export interface UserDetails extends AdminUser {
}>;
}
-/**
- * User Filters
- */
-export interface UserFilters {
- search?: string;
- role?: "all" | "superadmin" | "admin" | "user";
- status?: "all" | "active" | "banned";
-}
-
-/**
- * User Sort Options
- */
-export interface UserSort {
- field: "name" | "email" | "createdAt" | "role";
- direction: "asc" | "desc";
-}
-
-/**
- * Pagination Options
- */
-export interface Pagination {
- page: number;
- limit: number;
-}
-
-/**
- * Users List Response
- */
-export interface UsersListResponse {
- users: AdminUser[];
- total: number;
- page: number;
- limit: number;
- totalPages: number;
-}
+export type UsersListResponse = AdminListResponse<AdminUser, UserListCounts>;
-/**
- * Fetch users list from API
- */
-async function fetchUsersApi(
- filters: UserFilters,
- sort: UserSort,
- pagination: Pagination,
- t: ReturnType<typeof useTranslations>,
-): Promise<UsersListResponse> {
- const params = new URLSearchParams();
- if (filters.search) params.set("search", filters.search);
- if (filters.role && filters.role !== "all") params.set("role", filters.role);
- if (filters.status && filters.status !== "all") {
- params.set("banned", filters.status === "banned" ? "true" : "false");
- }
- params.set("sortBy", sort.field);
- params.set("sortDir", sort.direction);
- params.set("page", pagination.page.toString());
- params.set("limit", pagination.limit.toString());
-
- const response = await fetch(`/api/admin/users?${params.toString()}`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- });
-
- if (!response.ok) {
- if (response.status === 403) {
- throw new Error(t("admin.accessDenied"));
- }
- throw new Error(t("common.fetchError", { item: t("common.labels.users") }));
- }
-
- const data = await response.json();
-
- // Parse date strings to Date objects
- const users = data.users.map((user: Record<string, unknown>) => ({
- ...user,
+function parseAdminUser(user: Record<string, unknown>): AdminUser {
+ return {
+ ...(user as unknown as AdminUser),
createdAt: new Date(user.createdAt as string),
updatedAt: new Date(user.updatedAt as string),
- lastActivity: user.lastActivity
- ? new Date(user.lastActivity as string)
- : null,
+ lastActivity: user.lastActivity ? new Date(user.lastActivity as string) : null,
banExpires: user.banExpires ? new Date(user.banExpires as string) : null,
- }));
-
- return {
- ...data,
- users,
};
}
-/**
- * Fetch user details from API
- */
-async function fetchUserDetailsApi(
- userId: string,
- t: ReturnType<typeof useTranslations>,
-): Promise<UserDetails> {
- const response = await fetch(`/api/admin/users/${userId}`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- });
+/** One page of users; omitted params fall back to the API defaults. */
+export async function fetchAdminUsers(
+ params: Partial<UserListParams>,
+): Promise<UsersListResponse> {
+ const response = await fetch(`/api/admin/users?${toSearchParams(params)}`);
+ if (!response.ok) throw new AdminRequestError(response.status);
- if (!response.ok) {
- if (response.status === 403) {
- throw new Error(t("admin.accessDenied"));
- }
- if (response.status === 404) {
- throw new Error(t("admin.userNotFound"));
- }
- throw new Error(t("common.fetchError", { item: t("admin.userDetails") }));
- }
+ const data = await response.json();
+ return { ...data, items: data.items.map(parseAdminUser) };
+}
+
+export async function fetchAdminUserDetails(userId: string): Promise<UserDetails> {
+ const response = await fetch(`/api/admin/users/${userId}`);
+ if (!response.ok) throw new AdminRequestError(response.status);
const data = await response.json();
- // Parse date strings to Date objects
return {
...data.user,
createdAt: new Date(data.user.createdAt as string),
@@ -316,48 +247,53 @@ async function resetPasswordApi(
}
/**
- * Admin Users Management Hook
- *
- * Provides functions for managing users in the admin panel.
- * Uses React Query for automatic polling and cache management.
- *
- * Features:
- * - Fetch users with filtering, sorting, and pagination
- * - Get user details
- * - Update user information
- * - Ban/Unban users
- * - Delete users
- * - Reset user passwords
- * - Optimistic updates for instant UI feedback
- * - Error handling with toast notifications
- * - Automatic cache invalidation
- *
- * @param filters - User filters (search, role, status)
- * @param sort - Sort options (field, direction)
- * @param pagination - Pagination options (page, limit)
- * @returns Object with user data and management functions
+ * One page of the admin user list, filtered, sorted and paginated by the API.
+ * The previous page stays visible while the next one loads.
*/
-export function useAdminUsers(
- filters: UserFilters = {},
- sort: UserSort = { field: "createdAt", direction: "desc" },
- pagination: Pagination = { page: 1, limit: 25 },
-) {
+export function useAdminUsers(params: UserListParams) {
const t = useTranslations();
- const queryClient = useQueryClient();
+ const { data, isLoading, isPlaceholderData, error } = useQuery({
+ queryKey: queryKeys.admin.users.list(params),
+ queryFn: () => fetchAdminUsers(params),
+ placeholderData: keepPreviousData,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
+ });
- // Fetch users list with polling
- const {
- data: usersData,
- isLoading,
+ useAdminErrorToast(
error,
- refetch,
- } = useQuery({
- queryKey: queryKeys.admin.users({ filters, sort, pagination, t }),
- queryFn: () => fetchUsersApi(filters, sort, pagination, t),
- refetchInterval: REFETCH_INTERVAL,
- });
+ "admin-users-error",
+ t("common.fetchError", { item: t("common.labels.users") }),
+ );
+
+ return {
+ users: data?.items ?? [],
+ total: data?.total ?? 0,
+ counts: data?.counts ?? null,
+ // While the previous page is still on screen its served number would make the
+ // pager target a page the user already asked for; the clamped one only counts
+ // once it belongs to the request in flight.
+ page: isPlaceholderData ? params.page : (data?.page ?? params.page),
+ isLoading,
+ isPlaceholderData,
+ };
+}
+
+/**
+ * User mutations for the admin panel. Updates are applied optimistically to every
+ * cached page of the user list and rolled back on error.
+ */
+export function useAdminUserActions() {
+ const t = useTranslations();
+ const queryClient = useQueryClient();
+
+ const patchUsers = (patch: (users: AdminUser[]) => AdminUser[]) =>
+ patchListPages<AdminUser>(queryClient, queryKeys.admin.users.lists, patch);
+
+ const onSettled = () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.users.all });
+ queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats });
+ };
- // Update user mutation
const updateMutation = useMutation({
mutationFn: ({
userId,
@@ -366,35 +302,13 @@ export function useAdminUsers(
userId: string;
data: { name?: string; email?: string; role?: string };
}) => updateUserApi(userId, data, t),
- onMutate: async ({ userId, data }) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.users({ filters, sort, pagination }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- (old: UsersListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- users: old.users.map((user) =>
- user.id === userId ? { ...user, ...data } : user,
- ),
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async ({ userId, data }) => ({
+ snapshot: await patchUsers((users) =>
+ users.map((user) => (user.id === userId ? { ...user, ...data } : user)),
+ ),
+ }),
onError: (err, variables, context) => {
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- context?.previous,
- );
+ restoreListPages(queryClient, context?.snapshot);
toast.error(
err instanceof Error
? err.message
@@ -404,14 +318,9 @@ export function useAdminUsers(
onSuccess: () => {
toast.success(t("common.updated", { item: t("common.labels.user") }));
},
- onSettled: () => {
- // Invalidate all user queries
- queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Ban user mutation
const banMutation = useMutation({
mutationFn: ({
userId,
@@ -422,42 +331,17 @@ export function useAdminUsers(
reason: string;
expiresAt?: Date;
}) => banUserApi(userId, reason, expiresAt, t),
- onMutate: async ({ userId, reason, expiresAt }) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.users({ filters, sort, pagination }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- (old: UsersListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- users: old.users.map((user) =>
- user.id === userId
- ? {
- ...user,
- banned: true,
- banReason: reason,
- banExpires: expiresAt || null,
- }
- : user,
- ),
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async ({ userId, reason, expiresAt }) => ({
+ snapshot: await patchUsers((users) =>
+ users.map((user) =>
+ user.id === userId
+ ? { ...user, banned: true, banReason: reason, banExpires: expiresAt || null }
+ : user,
+ ),
+ ),
+ }),
onError: (err, variables, context) => {
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- context?.previous,
- );
+ restoreListPages(queryClient, context?.snapshot);
toast.error(
err instanceof Error
? err.message
@@ -467,46 +351,22 @@ export function useAdminUsers(
onSuccess: () => {
toast.success(t("common.banned", { item: t("common.labels.user") }));
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Unban user mutation
const unbanMutation = useMutation({
mutationFn: (userId: string) => unbanUserApi(userId, t),
- onMutate: async (userId) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.users({ filters, sort, pagination }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- (old: UsersListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- users: old.users.map((user) =>
- user.id === userId
- ? { ...user, banned: false, banReason: null, banExpires: null }
- : user,
- ),
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async (userId) => ({
+ snapshot: await patchUsers((users) =>
+ users.map((user) =>
+ user.id === userId
+ ? { ...user, banned: false, banReason: null, banExpires: null }
+ : user,
+ ),
+ ),
+ }),
onError: (err, userId, context) => {
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- context?.previous,
- );
+ restoreListPages(queryClient, context?.snapshot);
toast.error(
err instanceof Error
? err.message
@@ -516,43 +376,16 @@ export function useAdminUsers(
onSuccess: () => {
toast.success(t("common.unbanned", { item: t("common.labels.user") }));
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Delete user mutation
const deleteMutation = useMutation({
mutationFn: (userId: string) => deleteUserApi(userId, t),
- onMutate: async (userId) => {
- await queryClient.cancelQueries({
- queryKey: queryKeys.admin.users({ filters, sort, pagination }),
- });
- const previous = queryClient.getQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- );
-
- // Optimistic update
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- (old: UsersListResponse | undefined) => {
- if (!old) return old;
- return {
- ...old,
- users: old.users.filter((user) => user.id !== userId),
- total: old.total - 1,
- };
- },
- );
-
- return { previous };
- },
+ onMutate: async (userId) => ({
+ snapshot: await patchUsers((users) => users.filter((user) => user.id !== userId)),
+ }),
onError: (err, userId, context) => {
- queryClient.setQueryData(
- queryKeys.admin.users({ filters, sort, pagination }),
- context?.previous,
- );
+ restoreListPages(queryClient, context?.snapshot);
toast.error(
err instanceof Error
? err.message
@@ -562,13 +395,10 @@ export function useAdminUsers(
onSuccess: () => {
toast.success(t("common.deleted", { item: t("common.labels.user") }));
},
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
- queryClient.invalidateQueries({ queryKey: queryKeys.admin.stats() });
- },
+ onSettled,
});
- // Reset password mutation (no optimistic update needed)
+ // No optimistic update: nothing in the list changes
const resetPasswordMutation = useMutation({
mutationFn: ({
userId,
@@ -588,83 +418,14 @@ export function useAdminUsers(
});
return {
- // Data
- users: usersData?.users || [],
- total: usersData?.total || 0,
- page: usersData?.page || pagination.page,
- limit: usersData?.limit || pagination.limit,
- totalPages: usersData?.totalPages || 1,
- isLoading,
- error,
-
- // Functions
- refetch,
- fetchUserDetails: (userId: string) => fetchUserDetailsApi(userId, t),
- updateUser: async (
- userId: string,
- data: { name?: string; email?: string; role?: string },
- ): Promise<boolean> => {
- try {
- await updateMutation.mutateAsync({ userId, data });
- return true;
- } catch {
- return false;
- }
- },
- banUser: async (
- userId: string,
- reason: string,
- expiresAt?: Date,
- ): Promise<boolean> => {
- try {
- await banMutation.mutateAsync({ userId, reason, expiresAt });
- return true;
- } catch {
- return false;
- }
- },
- unbanUser: async (userId: string): Promise<boolean> => {
- try {
- await unbanMutation.mutateAsync(userId);
- return true;
- } catch {
- return false;
- }
- },
- deleteUser: async (userId: string): Promise<boolean> => {
- try {
- await deleteMutation.mutateAsync(userId);
- return true;
- } catch {
- return false;
- }
- },
- resetPassword: async (
- userId: string,
- newPassword: string,
- ): Promise<boolean> => {
- try {
- await resetPasswordMutation.mutateAsync({ userId, newPassword });
- return true;
- } catch {
- return false;
- }
- },
- fetchUsers: async (
- searchFilters: UserFilters,
- searchSort: UserSort,
- searchPagination: Pagination,
- ): Promise<UsersListResponse | null> => {
- try {
- return await fetchUsersApi(
- searchFilters,
- searchSort,
- searchPagination,
- t,
- );
- } catch {
- return null;
- }
- },
+ isUpdating: updateMutation.isPending,
+ updateUser: (userId: string, data: { name?: string; email?: string; role?: string }) =>
+ run(updateMutation.mutateAsync, { userId, data }),
+ banUser: (userId: string, reason: string, expiresAt?: Date) =>
+ run(banMutation.mutateAsync, { userId, reason, expiresAt }),
+ unbanUser: (userId: string) => run(unbanMutation.mutateAsync, userId),
+ deleteUser: (userId: string) => run(deleteMutation.mutateAsync, userId),
+ resetPassword: (userId: string, newPassword: string) =>
+ run(resetPasswordMutation.mutateAsync, { userId, newPassword }),
};
}
diff --git a/hooks/useAutoFocus.ts b/hooks/useAutoFocus.ts
new file mode 100644
index 0000000..19344df
--- /dev/null
+++ b/hooks/useAutoFocus.ts
@@ -0,0 +1,19 @@
+"use client";
+
+import { useCallback } from "react";
+import { DESKTOP_QUERY, useMediaQuery } from "@/hooks/useMediaQuery";
+
+/**
+ * Ref callback that focuses the field on pointer devices only. On phones an
+ * autofocus pops the on-screen keyboard the moment a sheet opens.
+ */
+export function useAutoFocusRef<T extends HTMLElement>(enabled = true) {
+ const desktop = useMediaQuery(DESKTOP_QUERY, false);
+
+ return useCallback(
+ (element: T | null) => {
+ if (element && enabled && desktop) element.focus();
+ },
+ [enabled, desktop]
+ );
+}
diff --git a/hooks/useCalendarShares.ts b/hooks/useCalendarShares.ts
index 4bdb463..8f86241 100644
--- a/hooks/useCalendarShares.ts
+++ b/hooks/useCalendarShares.ts
@@ -9,6 +9,8 @@ import {
handleRateLimitError,
isRateLimitError,
} from "@/lib/rate-limit-client";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
export interface CalendarShare {
id: string;
@@ -44,7 +46,7 @@ async function fetchSharesApi(calendarId: string): Promise<CalendarShare[]> {
const response = await fetch(`/api/calendars/${calendarId}/shares`);
if (!response.ok) {
- throw new Error("Failed to fetch shares");
+ throw new ApiError("Failed to fetch shares", response.status);
}
const data = await response.json();
@@ -155,11 +157,13 @@ export function useCalendarShares(calendarId: string) {
const [searchResults, setSearchResults] = useState<SearchUser[]>([]);
const [searchLoading, setSearchLoading] = useState(false);
+ const accessible = useIsCalendarAccessible(calendarId);
+
// Fetch shares
const { data: shares = [], isLoading: loading } = useQuery({
queryKey: queryKeys.shares.byCalendar(calendarId),
queryFn: () => fetchSharesApi(calendarId),
- enabled: !!calendarId,
+ enabled: accessible,
});
// Add share mutation
diff --git a/hooks/useCalendarSubscriptions.ts b/hooks/useCalendarSubscriptions.ts
index 7c54edd..ea332c8 100644
--- a/hooks/useCalendarSubscriptions.ts
+++ b/hooks/useCalendarSubscriptions.ts
@@ -4,7 +4,8 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import { ApiError } from "@/lib/api-error";
type CalendarSource = "guest" | "shared";
@@ -46,7 +47,7 @@ async function fetchSubscriptionsApi(): Promise<SubscriptionResponse> {
const response = await fetch("/api/calendars/subscriptions");
if (!response.ok) {
- throw new Error("Failed to fetch calendars");
+ throw new ApiError("Failed to fetch calendars", response.status);
}
return await response.json();
@@ -100,7 +101,11 @@ async function dismissApi(calendarId: string): Promise<void> {
*
* @returns Object with calendar subscription data and management functions
*/
-export function useCalendarSubscriptions() {
+/**
+ * @param enabled - the discovery sheet stays mounted behind every menu, so the
+ * list is only worth fetching while it is actually open.
+ */
+export function useCalendarSubscriptions(enabled = true) {
const t = useTranslations();
const queryClient = useQueryClient();
@@ -112,7 +117,8 @@ export function useCalendarSubscriptions() {
} = useQuery({
queryKey: queryKeys.subscriptions.all,
queryFn: fetchSubscriptionsApi,
- refetchInterval: REFETCH_INTERVAL,
+ enabled,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
const availableCalendars = data?.available ?? [];
diff --git a/hooks/useCalendarTokens.ts b/hooks/useCalendarTokens.ts
index a863776..9fe9b1e 100644
--- a/hooks/useCalendarTokens.ts
+++ b/hooks/useCalendarTokens.ts
@@ -5,7 +5,9 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
export interface CalendarAccessToken {
id: string;
@@ -60,7 +62,7 @@ async function fetchTokensApi(
const response = await fetch(`/api/calendars/${calendarId}/tokens`);
if (!response.ok) {
- throw new Error(`HTTP ${response.status}`);
+ throw new ApiError(`HTTP ${response.status}`, response.status);
}
return await response.json();
@@ -157,6 +159,8 @@ export function useCalendarTokens(calendarId: string | null) {
const queryClient = useQueryClient();
// Fetch tokens
+ const accessible = useIsCalendarAccessible(calendarId);
+
const {
data: tokens = [],
isLoading,
@@ -164,8 +168,8 @@ export function useCalendarTokens(calendarId: string | null) {
} = useQuery({
queryKey: queryKeys.tokens.byCalendar(calendarId!),
queryFn: () => fetchTokensApi(calendarId!),
- enabled: !!calendarId,
- refetchInterval: REFETCH_INTERVAL,
+ enabled: accessible,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
// Create token mutation (NO optimistic update - need real token!)
diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.ts
index d6412ff..397e94b 100644
--- a/hooks/useCalendars.ts
+++ b/hooks/useCalendars.ts
@@ -1,6 +1,12 @@
import { useState, useEffect, useRef } from "react";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ useQuery,
+ useMutation,
+ useQueryClient,
+ useIsMutating,
+} from "@tanstack/react-query";
import { CalendarWithCount } from "@/lib/types";
+import type { CalendarViewSettings } from "@/lib/view-settings";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import {
@@ -8,14 +14,15 @@ import {
handleRateLimitError,
} from "@/lib/rate-limit-client";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import { ApiError } from "@/lib/api-error";
// API functions
async function fetchCalendarsApi(): Promise<CalendarWithCount[]> {
const response = await fetch("/api/calendars");
if (!response.ok) {
- throw new Error(`Failed to fetch calendars: ${response.statusText}`);
+ throw new ApiError(`Failed to fetch calendars: ${response.statusText}`, response.status);
}
const data = await response.json();
@@ -65,6 +72,7 @@ async function updateCalendarApi(
name?: string;
color?: string;
guestPermission?: "none" | "read" | "write";
+ viewSettings?: CalendarViewSettings | null;
}
): Promise<CalendarWithCount> {
const response = await fetch(`/api/calendars/${calendarId}`, {
@@ -126,6 +134,8 @@ export function useCalendars(initialCalendarId?: string | null) {
string | undefined
>();
+ const mutating = useIsMutating();
+
// Capture initialCalendarId on mount to prevent dependency changes
const initialCalendarIdRef = useRef(initialCalendarId);
@@ -134,10 +144,11 @@ export function useCalendars(initialCalendarId?: string | null) {
data: calendars = [],
isLoading,
isFetched,
+ isFetching,
} = useQuery({
queryKey: queryKeys.calendars.all,
queryFn: fetchCalendarsApi,
- refetchInterval: REFETCH_INTERVAL,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
// Auto-select calendar when data loads
@@ -150,6 +161,32 @@ export function useCalendars(initialCalendarId?: string | null) {
}
}, [calendars, selectedCalendar]);
+ // A calendar we just created is known to exist, so no list may rule it out —
+ // a list can always have been read before the insert was visible, whatever the
+ // timestamps say. Held until a list actually carries it, or the user moves on.
+ const createdCalendarId = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ if (createdCalendarId.current !== selectedCalendar) {
+ createdCalendarId.current = undefined;
+ }
+ }, [selectedCalendar]);
+
+ // Access can disappear while the app is open: a dismissed subscription, a
+ // withdrawn share, guestPermission set to none, an expired token. The id would
+ // otherwise stick and every per-calendar query would keep asking for it.
+ useEffect(() => {
+ if (!isFetched || isFetching || !selectedCalendar || mutating > 0) return;
+
+ const present = calendars.some((c) => c.id === selectedCalendar);
+ if (createdCalendarId.current === selectedCalendar) {
+ if (!present) return;
+ createdCalendarId.current = undefined;
+ }
+ if (present) return;
+
+ queueMicrotask(() => setSelectedCalendar(calendars[0]?.id));
+ }, [isFetched, isFetching, mutating, calendars, selectedCalendar]);
+
// Create mutation with optimistic update
const createMutation = useMutation<
CalendarWithCount,
@@ -199,6 +236,7 @@ export function useCalendars(initialCalendarId?: string | null) {
},
onSuccess: (newCalendar) => {
// Update selection with real ID
+ createdCalendarId.current = newCalendar.id;
setSelectedCalendar(newCalendar.id);
toast.success(t("common.created", { item: t("calendar.title") }));
},
@@ -217,6 +255,7 @@ export function useCalendars(initialCalendarId?: string | null) {
name?: string;
color?: string;
guestPermission?: "none" | "read" | "write";
+ viewSettings?: CalendarViewSettings | null;
};
},
UpdateCalendarContext
@@ -340,6 +379,7 @@ export function useCalendars(initialCalendarId?: string | null) {
name?: string;
color?: string;
guestPermission?: "none" | "read" | "write";
+ viewSettings?: CalendarViewSettings | null;
}
) => {
try {
@@ -379,3 +419,26 @@ export function useCalendars(initialCalendarId?: string | null) {
queryClient.invalidateQueries({ queryKey: queryKeys.calendars.all }),
};
}
+
+/**
+ * Predicate for whether per-calendar data may be requested for an id. Unknown
+ * counts as allowed: while the list is still loading an id cannot be ruled out,
+ * and blocking would serialise the first paint behind the calendar request.
+ * Once the list has arrived, an id missing from it means access is gone — the
+ * server would answer 403 for shifts, notes, presets and sync state alike.
+ */
+export function useCalendarAccessFilter(): (calendarId?: string | null) => boolean {
+ const { data: calendars = [], isFetched } = useQuery({
+ queryKey: queryKeys.calendars.all,
+ queryFn: fetchCalendarsApi,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
+ });
+
+ return (calendarId?: string | null) =>
+ !!calendarId && (!isFetched || calendars.some((c) => c.id === calendarId));
+}
+
+/** Single-id form of {@link useCalendarAccessFilter}. */
+export function useIsCalendarAccessible(calendarId?: string | null): boolean {
+ return useCalendarAccessFilter()(calendarId);
+}
diff --git a/hooks/useCompareData.ts b/hooks/useCompareData.ts
index 5ef6ad4..9105e40 100644
--- a/hooks/useCompareData.ts
+++ b/hooks/useCompareData.ts
@@ -10,6 +10,8 @@ import { normalizeNote } from "@/hooks/useNotes";
import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
+import { useCalendarAccessFilter } from "@/hooks/useCalendars";
+import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
// API functions
async function fetchShiftsApi(
@@ -87,13 +89,15 @@ export function useCompareData({
}: UseCompareDataOptions) {
const t = useTranslations();
const queryClient = useQueryClient();
+ const isAccessible = useCalendarAccessFilter();
// Fetch shifts for all calendars
const shiftsQueries = useQueries({
queries: calendarIds.map((id) => ({
queryKey: queryKeys.shifts.byCalendar(id),
queryFn: () => fetchShiftsApi(id),
- enabled: enabled && !!id,
+ enabled: enabled && isAccessible(id),
+ refetchInterval: LIVE_REFETCH_INTERVAL,
})),
});
@@ -102,7 +106,8 @@ export function useCompareData({
queries: calendarIds.map((id) => ({
queryKey: queryKeys.notes.byCalendar(id),
queryFn: () => fetchNotesApi(id),
- enabled: enabled && !!id,
+ enabled: enabled && isAccessible(id),
+ refetchInterval: LIVE_REFETCH_INTERVAL,
})),
});
@@ -111,7 +116,7 @@ export function useCompareData({
queries: calendarIds.map((id) => ({
queryKey: queryKeys.externalSyncs.byCalendar(id),
queryFn: () => fetchExternalSyncsApi(id),
- enabled: enabled && !!id,
+ enabled: enabled && isAccessible(id),
})),
});
@@ -120,7 +125,7 @@ export function useCompareData({
queries: calendarIds.map((id) => ({
queryKey: queryKeys.presets.byCalendar(id),
queryFn: () => fetchPresetsApi(id),
- enabled: enabled && !!id,
+ enabled: enabled && isAccessible(id),
})),
});
@@ -214,13 +219,6 @@ export function useCompareData({
},
});
- // Invalidate notes for a specific calendar (used after note mutations)
- const invalidateNotes = (calendarId: string) => {
- queryClient.invalidateQueries({
- queryKey: queryKeys.notes.byCalendar(calendarId),
- });
- };
-
// Invalidate presets for a specific calendar
const invalidatePresets = (calendarId: string) => {
queryClient.invalidateQueries({
@@ -244,7 +242,6 @@ export function useCompareData({
deleteShift: deleteShiftMutation.mutateAsync,
// Invalidation helpers
- invalidateNotes,
invalidatePresets,
};
}
diff --git a/hooks/useCompareMode.ts b/hooks/useCompareMode.ts
new file mode 100644
index 0000000..7299d50
--- /dev/null
+++ b/hooks/useCompareMode.ts
@@ -0,0 +1,218 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { isSameDay, isSameMonth } from "date-fns";
+import { toast } from "sonner";
+import { useTranslations } from "next-intl";
+import { CalendarWithCount } from "@/lib/types";
+import { useCompareData } from "@/hooks/useCompareData";
+import { formatDateToLocal, toLocalDate } from "@/lib/date-utils";
+
+interface UseCompareModeProps {
+ calendars: CalendarWithCount[];
+ hasLoadedOnce: boolean;
+ selectedCalendar: string | undefined;
+ currentDate: Date;
+ setCurrentDate: (date: Date) => void;
+ selectDay: (day: Date) => void;
+ selectedPresetId: string | undefined;
+}
+
+export function useCompareMode({
+ calendars,
+ hasLoadedOnce,
+ selectedCalendar,
+ currentDate,
+ setCurrentDate,
+ selectDay,
+ selectedPresetId,
+}: UseCompareModeProps) {
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const t = useTranslations();
+
+ const [isCompareMode, setIsCompareMode] = useState(false);
+ const [showCompareSelector, setShowCompareSelector] = useState(false);
+ const [selectedCompareIds, setSelectedCompareIds] = useState<string[]>([]);
+ // Selection before the picker opened, restored on cancel
+ const [compareSnapshot, setCompareSnapshot] = useState<string[]>([]);
+ const [compareTogglingDates, setCompareTogglingDates] = useState<
+ Map<string, Set<string>>
+ >(new Map());
+ const [compareNoteCalendarId, setCompareNoteCalendarId] = useState<
+ string | undefined
+ >();
+
+ const compareData = useCompareData({
+ calendarIds: selectedCompareIds,
+ enabled: isCompareMode,
+ });
+
+ // Load compare mode from URL on initial load
+ useEffect(() => {
+ const compareParam = searchParams.get("compare");
+ if (compareParam && !isCompareMode) {
+ const calendarIds = compareParam.split(",").filter((id) => id.trim());
+ if (calendarIds.length >= 2 && calendarIds.length <= 3) {
+ const validIds = calendarIds.filter((id) =>
+ calendars.some((cal) => cal.id === id)
+ );
+ if (validIds.length >= 2) {
+ // Syncing from the URL (an external source), not from render state.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setSelectedCompareIds(validIds);
+ setIsCompareMode(true);
+ }
+ }
+ } else if (!compareParam && isCompareMode) {
+ setIsCompareMode(false);
+ setSelectedCompareIds([]);
+ setCompareTogglingDates(new Map());
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchParams, calendars]);
+
+ // The effect above only filters while entering compare mode. Access to one of
+ // the columns can be lost afterwards, and compare needs at least two.
+ useEffect(() => {
+ if (!isCompareMode || !hasLoadedOnce) return;
+ const stillAccessible = selectedCompareIds.filter((id) =>
+ calendars.some((cal) => cal.id === id)
+ );
+ if (stillAccessible.length === selectedCompareIds.length) return;
+ queueMicrotask(() => {
+ if (stillAccessible.length >= 2) {
+ setSelectedCompareIds(stillAccessible);
+ } else {
+ setIsCompareMode(false);
+ setSelectedCompareIds([]);
+ setCompareTogglingDates(new Map());
+ }
+ });
+ }, [isCompareMode, hasLoadedOnce, calendars, selectedCompareIds]);
+
+ const handleToggleCompareCalendar = useCallback((calendarId: string) => {
+ setSelectedCompareIds((prev) =>
+ prev.includes(calendarId)
+ ? prev.filter((id) => id !== calendarId)
+ : [...prev, calendarId]
+ );
+ }, []);
+
+ const handleExitCompare = useCallback(() => {
+ setIsCompareMode(false);
+ setSelectedCompareIds([]);
+ setCompareTogglingDates(new Map());
+ router.replace(selectedCalendar ? `/?id=${selectedCalendar}` : `/`, {
+ scroll: false,
+ });
+ }, [router, selectedCalendar]);
+
+ const updateCompareToggling = useCallback(
+ (calendarId: string, dateKey: string, add: boolean) => {
+ setCompareTogglingDates((prev) => {
+ const updated = new Map(prev);
+ const next = new Set(updated.get(calendarId) || []);
+ if (add) next.add(dateKey);
+ else next.delete(dateKey);
+ updated.set(calendarId, next);
+ return updated;
+ });
+ },
+ []
+ );
+
+ const openComparePicker = useCallback(() => {
+ setCompareSnapshot(isCompareMode ? selectedCompareIds : []);
+ setShowCompareSelector(true);
+ }, [isCompareMode, selectedCompareIds]);
+
+ const startCompare = useCallback(() => {
+ setShowCompareSelector(false);
+ setIsCompareMode(true);
+ }, []);
+
+ const cancelComparePicker = useCallback(() => {
+ setShowCompareSelector(false);
+ setSelectedCompareIds(compareSnapshot);
+ }, [compareSnapshot]);
+
+ const handleCompareDayClick = useCallback(
+ async (calendarId: string, date: Date | string) => {
+ const targetDate = toLocalDate(date);
+ selectDay(targetDate);
+ if (!isSameMonth(targetDate, currentDate)) setCurrentDate(targetDate);
+ if (!selectedPresetId) return;
+
+ const calendarPresets = compareData.presetsMap.get(calendarId) || [];
+ const calendarShifts = compareData.shiftsMap.get(calendarId) || [];
+ const preset = calendarPresets.find((p) => p.id === selectedPresetId);
+ if (!preset) return;
+
+ const dateKey = formatDateToLocal(targetDate);
+ if (compareTogglingDates.get(calendarId)?.has(dateKey)) return;
+ updateCompareToggling(calendarId, dateKey, true);
+
+ try {
+ const existingShift = calendarShifts.find(
+ (shift) =>
+ shift.date &&
+ isSameDay(shift.date as Date, targetDate) &&
+ shift.title === preset.title &&
+ shift.startTime === preset.startTime &&
+ shift.endTime === preset.endTime
+ );
+
+ if (existingShift) {
+ await compareData.deleteShift({ calendarId, shiftId: existingShift.id });
+ } else {
+ await compareData.createShift({
+ calendarId,
+ formData: {
+ date: dateKey,
+ startTime: preset.startTime,
+ endTime: preset.endTime,
+ title: preset.title,
+ color: preset.color,
+ notes: preset.notes || "",
+ presetId: preset.id,
+ isAllDay: preset.isAllDay || false,
+ },
+ });
+ }
+ } catch (error) {
+ console.error("Failed to toggle shift:", error);
+ toast.error(t("common.error"));
+ } finally {
+ updateCompareToggling(calendarId, dateKey, false);
+ }
+ },
+ [
+ selectDay,
+ currentDate,
+ setCurrentDate,
+ selectedPresetId,
+ compareData,
+ compareTogglingDates,
+ updateCompareToggling,
+ t,
+ ]
+ );
+
+ return {
+ isCompareMode,
+ showCompareSelector,
+ selectedCompareIds,
+ compareTogglingDates,
+ compareNoteCalendarId,
+ setCompareNoteCalendarId,
+ compareData,
+ handleToggleCompareCalendar,
+ handleExitCompare,
+ openComparePicker,
+ startCompare,
+ cancelComparePicker,
+ handleCompareDayClick,
+ };
+}
diff --git a/hooks/useConnectionStatus.ts b/hooks/useConnectionStatus.ts
index 67a79f4..e4532ab 100644
--- a/hooks/useConnectionStatus.ts
+++ b/hooks/useConnectionStatus.ts
@@ -13,7 +13,7 @@ const DISCONNECT_TOAST_ID = "connection-status-disconnected";
* Shows toast notifications on status changes.
* Returns true if the browser is online and React Query can poll.
*/
-export function useConnectionStatus() {
+export function useConnectionStatus({ toasts = true }: { toasts?: boolean } = {}) {
const t = useTranslations();
const [isOnline, setIsOnline] = useState(() => onlineManager.isOnline());
const hasInitialized = useRef(false);
@@ -32,6 +32,8 @@ export function useConnectionStatus() {
// Show toast notifications on status changes
useEffect(() => {
+ if (!toasts) return;
+
// Skip initial render - don't show toast on page load
if (!hasInitialized.current) {
hasInitialized.current = true;
@@ -60,7 +62,7 @@ export function useConnectionStatus() {
duration: Infinity,
});
}
- }, [isOnline, t]);
+ }, [isOnline, t, toasts]);
return {
isOnline,
diff --git a/hooks/useDaySummary.ts b/hooks/useDaySummary.ts
new file mode 100644
index 0000000..ad89f65
--- /dev/null
+++ b/hooks/useDaySummary.ts
@@ -0,0 +1,84 @@
+"use client";
+
+import { useMemo } from "react";
+import { ShiftWithCalendar } from "@/lib/types";
+import { countFreeDays } from "@/lib/free-days";
+import { CalendarNote } from "@/lib/db/schema";
+import { findNotesForDate } from "@/lib/event-utils";
+import { getDayShifts, sumShiftMinutes } from "@/lib/shift-display";
+import { useShiftStats, ShiftStatsData } from "@/hooks/useShiftStats";
+
+export type StatsPeriod = "week" | "month" | "year";
+
+export interface ShiftTypeStat {
+ title: string;
+ count: number;
+ color: string;
+}
+
+export interface PeriodSummary {
+ stats: ShiftStatsData | null;
+ freeDays: number | null;
+ byType: ShiftTypeStat[];
+ loading: boolean;
+}
+
+/** Everything the desktop inspector and the mobile day sheet show for one day. */
+export function useDayData({
+ selectedDay,
+ shifts,
+ notes,
+}: {
+ selectedDay: Date;
+ shifts: ShiftWithCalendar[];
+ notes: CalendarNote[];
+}) {
+ return useMemo(() => {
+ const dayShifts = getDayShifts(shifts, selectedDay);
+ return {
+ dayShifts,
+ dayNotes: findNotesForDate(notes, selectedDay),
+ totalMinutes: sumShiftMinutes(dayShifts),
+ };
+ }, [selectedDay, shifts, notes]);
+}
+
+/** Period summary built on the existing stats endpoint. */
+export function usePeriodSummary({
+ calendarId,
+ anchorDate,
+ period,
+ shifts,
+}: {
+ calendarId: string | undefined;
+ anchorDate: Date;
+ period: StatsPeriod;
+ shifts: ShiftWithCalendar[];
+}): PeriodSummary {
+ const { stats, loading } = useShiftStats({
+ calendarId,
+ currentDate: anchorDate,
+ period,
+ });
+
+ return useMemo(() => {
+ // The stats API groups by title and carries no color, so borrow it from a loaded shift
+ const colorByTitle = new Map<string, string>();
+ for (const shift of shifts) {
+ if (!colorByTitle.has(shift.title)) colorByTitle.set(shift.title, shift.color);
+ }
+ const byType = stats
+ ? Object.entries(stats.stats)
+ .map(([title, { count }]) => ({
+ title,
+ count,
+ color: colorByTitle.get(title) ?? "var(--brand)",
+ }))
+ .sort((a, b) => b.count - a.count)
+ : [];
+
+ const freeDays = stats ? countFreeDays(stats) : null;
+
+ return { stats, freeDays, byType, loading };
+ }, [stats, loading, shifts]);
+}
diff --git a/hooks/useDialogStates.ts b/hooks/useDialogStates.ts
index a6ee31d..1045ab4 100644
--- a/hooks/useDialogStates.ts
+++ b/hooks/useDialogStates.ts
@@ -7,23 +7,19 @@ export function useDialogStates() {
const [showShiftDialog, setShowShiftDialog] = useState(false);
const [showCalendarSettingsDialog, setShowCalendarSettingsDialog] =
useState(false);
- const [showMobileCalendarDialog, setShowMobileCalendarDialog] =
- useState(false);
- const [showExternalSyncDialog, setShowExternalSyncDialog] = useState(false);
const [showSyncNotificationDialog, setShowSyncNotificationDialog] =
useState(false);
const [showDayShiftsDialog, setShowDayShiftsDialog] = useState(false);
- const [showSyncedShiftsDialog, setShowSyncedShiftsDialog] = useState(false);
const [showViewSettingsDialog, setShowViewSettingsDialog] = useState(false);
const [showNotesListDialog, setShowNotesListDialog] = useState(false);
+ const [showMonthStatsDialog, setShowMonthStatsDialog] = useState(false);
+ const [showMonthShiftsDialog, setShowMonthShiftsDialog] = useState(false);
+ const [showPresetManageDialog, setShowPresetManageDialog] = useState(false);
const [selectedDayDate, setSelectedDayDate] = useState<Date | null>(null);
const [selectedDayShifts, setSelectedDayShifts] = useState<
ShiftWithCalendar[]
>([]);
- const [selectedSyncedShifts, setSelectedSyncedShifts] = useState<
- ShiftWithCalendar[]
- >([]);
const [selectedDayNotes, setSelectedDayNotes] = useState<CalendarNote[]>([]);
return {
@@ -33,26 +29,24 @@ export function useDialogStates() {
setShowShiftDialog,
showCalendarSettingsDialog,
setShowCalendarSettingsDialog,
- showMobileCalendarDialog,
- setShowMobileCalendarDialog,
- showExternalSyncDialog,
- setShowExternalSyncDialog,
showSyncNotificationDialog,
setShowSyncNotificationDialog,
showDayShiftsDialog,
setShowDayShiftsDialog,
- showSyncedShiftsDialog,
- setShowSyncedShiftsDialog,
showViewSettingsDialog,
setShowViewSettingsDialog,
showNotesListDialog,
setShowNotesListDialog,
+ showMonthStatsDialog,
+ setShowMonthStatsDialog,
+ showMonthShiftsDialog,
+ setShowMonthShiftsDialog,
+ showPresetManageDialog,
+ setShowPresetManageDialog,
selectedDayDate,
setSelectedDayDate,
selectedDayShifts,
setSelectedDayShifts,
- selectedSyncedShifts,
- setSelectedSyncedShifts,
selectedDayNotes,
setSelectedDayNotes,
};
diff --git a/hooks/useDirtyState.ts b/hooks/useDirtyState.ts
index b406925..2cdc3cc 100644
--- a/hooks/useDirtyState.ts
+++ b/hooks/useDirtyState.ts
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
interface UseDirtyStateOptions {
onClose: (open: boolean) => void;
@@ -62,3 +62,42 @@ export function useDirtyState({
handleConfirmClose,
};
}
+
+/** Reports a panel's unsaved input to the frame around it, and clears it on unmount. */
+export function useReportDirty(
+ dirty: boolean,
+ onDirtyChange?: (dirty: boolean) => void
+) {
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ return () => onDirtyChange?.(false);
+ }, [dirty, onDirtyChange]);
+}
+
+/**
+ * Defers an action behind a confirmation while there is unsaved input.
+ * Spread `confirmProps` onto a ConfirmationDialog.
+ */
+export function useGuardedAction(dirty: boolean, onDiscard?: () => void) {
+ const [pendingAction, setPendingAction] = useState<(() => void) | null>(null);
+
+ const guarded = (action: () => void) => {
+ if (dirty) setPendingAction(() => action);
+ else action();
+ };
+
+ const confirmProps = {
+ open: pendingAction !== null,
+ onOpenChange: (next: boolean) => {
+ if (!next) setPendingAction(null);
+ },
+ onConfirm: () => {
+ const action = pendingAction;
+ setPendingAction(null);
+ onDiscard?.();
+ action?.();
+ },
+ };
+
+ return { guarded, confirmProps };
+}
diff --git a/hooks/useExternalSync.ts b/hooks/useExternalSync.ts
index 85c39ba..9edd1e2 100644
--- a/hooks/useExternalSync.ts
+++ b/hooks/useExternalSync.ts
@@ -4,7 +4,9 @@ import { useMemo } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ExternalSync, SyncLog } from "@/lib/db/schema";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { BACKGROUND_REFETCH_INTERVAL } from "@/lib/query-client";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
/**
* Fetch external syncs from API
@@ -16,7 +18,7 @@ async function fetchExternalSyncsApi(
const response = await fetch(`/api/external-syncs?${params}`);
if (!response.ok) {
- throw new Error("Failed to fetch external syncs");
+ throw new ApiError("Failed to fetch external syncs", response.status);
}
return await response.json();
@@ -34,7 +36,7 @@ async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {
const response = await fetch(`/api/sync-logs?${params}`);
if (!response.ok) {
- throw new Error("Failed to fetch sync logs");
+ throw new ApiError("Failed to fetch sync logs", response.status);
}
return await response.json();
@@ -58,22 +60,22 @@ async function fetchSyncLogsApi(calendarId: string): Promise<SyncLog[]> {
export function useExternalSync(selectedCalendar: string | null) {
const queryClient = useQueryClient();
+ const accessible = useIsCalendarAccessible(selectedCalendar);
+
// Fetch external syncs
const { data: externalSyncs = [], isLoading: syncsLoading } = useQuery({
queryKey: queryKeys.externalSyncs.byCalendar(selectedCalendar!),
queryFn: () => fetchExternalSyncsApi(selectedCalendar!),
- enabled: !!selectedCalendar,
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true, // Continue polling in background
+ enabled: accessible,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
// Fetch sync logs
const { data: syncLogs = [], isLoading: logsLoading } = useQuery({
queryKey: queryKeys.externalSyncs.logs(selectedCalendar!),
queryFn: () => fetchSyncLogsApi(selectedCalendar!),
- enabled: !!selectedCalendar,
- refetchInterval: REFETCH_INTERVAL,
- refetchIntervalInBackground: true, // Continue polling in background
+ enabled: accessible,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
// Compute error status from logs
@@ -96,6 +98,7 @@ export function useExternalSync(selectedCalendar: string | null) {
return {
externalSyncs,
+ syncLogs,
hasSyncErrors,
loading: syncsLoading || logsLoading,
refetch,
diff --git a/hooks/useExternalSyncForm.ts b/hooks/useExternalSyncForm.ts
new file mode 100644
index 0000000..d83c345
--- /dev/null
+++ b/hooks/useExternalSyncForm.ts
@@ -0,0 +1,78 @@
+import { useCallback, useState } from "react";
+import { ExternalSync } from "@/lib/db/schema";
+import { DEFAULT_COLOR } from "@/lib/constants";
+
+export type SyncDisplayMode = "normal" | "minimal";
+export type SyncImportType = "url" | "file";
+
+export interface ExternalSyncFormValues {
+ name: string;
+ url: string;
+ color: string;
+ displayMode: SyncDisplayMode;
+ autoSyncInterval: number;
+ isHidden: boolean;
+ hideFromStats: boolean;
+ importType: SyncImportType;
+ file: File | null;
+}
+
+/** Minutes accepted by the external-syncs API; 0 means manual. */
+export const AUTO_SYNC_INTERVALS = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
+
+export const EMPTY_SYNC_FORM: ExternalSyncFormValues = {
+ name: "",
+ url: "",
+ color: DEFAULT_COLOR,
+ displayMode: "normal",
+ autoSyncInterval: 0,
+ isHidden: false,
+ hideFromStats: false,
+ importType: "url",
+ file: null,
+};
+
+export function syncToFormValues(sync: ExternalSync): ExternalSyncFormValues {
+ return {
+ ...EMPTY_SYNC_FORM,
+ name: sync.name || "",
+ url: sync.calendarUrl || "",
+ color: sync.color || DEFAULT_COLOR,
+ displayMode: sync.displayMode === "minimal" ? "minimal" : "normal",
+ autoSyncInterval: sync.autoSyncInterval || 0,
+ isHidden: sync.isHidden || false,
+ hideFromStats: sync.hideFromStats || false,
+ };
+}
+
+// The import method alone is not an unsaved change.
+const TRACKED_FIELDS = [
+ "name",
+ "url",
+ "color",
+ "displayMode",
+ "autoSyncInterval",
+ "isHidden",
+ "hideFromStats",
+ "file",
+] as const;
+
+export function useExternalSyncForm() {
+ const [values, setValues] = useState<ExternalSyncFormValues>(EMPTY_SYNC_FORM);
+ const [initial, setInitial] = useState<ExternalSyncFormValues>(EMPTY_SYNC_FORM);
+
+ const setField = useCallback(
+ <K extends keyof ExternalSyncFormValues>(key: K, value: ExternalSyncFormValues[K]) =>
+ setValues((prev) => ({ ...prev, [key]: value })),
+ []
+ );
+
+ const reset = useCallback((next: ExternalSyncFormValues = EMPTY_SYNC_FORM) => {
+ setValues(next);
+ setInitial(next);
+ }, []);
+
+ const isDirty = TRACKED_FIELDS.some((key) => values[key] !== initial[key]);
+
+ return { values, setField, reset, isDirty };
+}
diff --git a/hooks/useExternalSyncPanel.ts b/hooks/useExternalSyncPanel.ts
new file mode 100644
index 0000000..f9992a1
--- /dev/null
+++ b/hooks/useExternalSyncPanel.ts
@@ -0,0 +1,291 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { ExternalSync } from "@/lib/db/schema";
+import { syncToFormValues, useExternalSyncForm } from "@/hooks/useExternalSyncForm";
+import { useExternalSync } from "@/hooks/useExternalSync";
+import { isRateLimitError, handleRateLimitError } from "@/lib/rate-limit-client";
+import { isValidCalendarUrl, detectCalendarSyncType } from "@/lib/external-calendar-utils";
+import { useGuardedAction, useReportDirty } from "@/hooks/useDirtyState";
+
+const MAX_FILE_SIZE = 5 * 1024 * 1024;
+
+type PanelMode = { kind: "list" } | { kind: "add" } | { kind: "edit"; syncId: string };
+
+interface UseExternalSyncPanelProps {
+ calendarId: string;
+ onSyncComplete?: () => void;
+ /** Lets the surrounding frame guard its close button against unsaved changes */
+ onDirtyChange?: (dirty: boolean) => void;
+}
+
+export function useExternalSyncPanel({
+ calendarId,
+ onSyncComplete,
+ onDirtyChange,
+}: UseExternalSyncPanelProps) {
+ const t = useTranslations();
+ const [mode, setMode] = useState<PanelMode>({ kind: "list" });
+ const [isSyncing, setIsSyncing] = useState<string | null>(null);
+ const [isDeleting, setIsDeleting] = useState<string | null>(null);
+ const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const { values, setField, reset, isDirty } = useExternalSyncForm();
+ const itemLabel = t("externalSync.syncTypeCustom");
+
+ const { externalSyncs: syncs, syncLogs, refetch: invalidateSyncs } = useExternalSync(calendarId);
+
+ // Latest unread error per sync; marking logs as read clears it.
+ const syncErrors = useMemo(() => {
+ const errors: Record<string, string> = {};
+ for (const sync of syncs) {
+ const latestError = syncLogs.find(
+ (log) => log.externalSyncId === sync.id && log.status === "error" && !log.isRead
+ );
+ if (latestError) {
+ errors[sync.id] = latestError.errorMessage || t("syncNotifications.statusError");
+ }
+ }
+ return errors;
+ }, [syncs, syncLogs, t]);
+
+ const editingSync =
+ mode.kind === "edit" ? syncs.find((sync) => sync.id === mode.syncId) ?? null : null;
+ const formOpen = mode.kind === "add" || editingSync !== null;
+
+ const hasUnsavedChanges = formOpen && isDirty;
+
+ useReportDirty(hasUnsavedChanges, onDirtyChange);
+
+ const showList = () => {
+ setMode({ kind: "list" });
+ reset();
+ };
+
+ const startAdd = () => {
+ setMode({ kind: "add" });
+ reset();
+ };
+
+ const startEdit = (sync: ExternalSync) => {
+ setMode({ kind: "edit", syncId: sync.id });
+ reset(syncToFormValues(sync));
+ };
+
+ /** Runs `action` right away, or after confirming that unsaved input may be dropped. */
+ const { guarded: guardUnsaved, confirmProps } = useGuardedAction(hasUnsavedChanges);
+
+ const handleSync = async (syncId: string) => {
+ setIsSyncing(syncId);
+ try {
+ const response = await fetch(`/api/external-syncs/${syncId}/sync`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || "Failed to sync calendar");
+ }
+
+ invalidateSyncs();
+ onSyncComplete?.();
+
+ 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 handleAdd = async () => {
+ const name = values.name.trim();
+ const url = values.url.trim();
+ if (!name) return;
+
+ if (values.importType === "file") {
+ if (!values.file) {
+ toast.error(t("validation.fileRequired"));
+ return;
+ }
+ if (values.file.size > MAX_FILE_SIZE) {
+ toast.error(t("validation.fileTooLarge", { maxSize: "5MB" }));
+ return;
+ }
+ } else {
+ if (!url) {
+ toast.error(t("validation.urlRequired"));
+ return;
+ }
+ if (!isValidCalendarUrl(url, detectCalendarSyncType(url))) {
+ toast.error(t("validation.urlInvalid"));
+ return;
+ }
+ // Uploaded files are stored as data URLs and never collide.
+ const exists = syncs.some(
+ (sync) => !sync.isOneTimeImport && sync.calendarUrl.toLowerCase() === url.toLowerCase()
+ );
+ if (exists) {
+ toast.error(t("validation.urlAlreadyExists"));
+ return;
+ }
+ }
+
+ setIsSubmitting(true);
+ try {
+ const icsContent =
+ values.importType === "file" && values.file ? await values.file.text() : undefined;
+
+ const response = await fetch("/api/external-syncs", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ calendarId,
+ name,
+ calendarUrl: url || undefined,
+ color: values.color,
+ displayMode: values.displayMode,
+ autoSyncInterval: values.autoSyncInterval,
+ icsContent,
+ isHidden: values.isHidden,
+ hideFromStats: values.hideFromStats,
+ }),
+ });
+
+ if (response.ok) {
+ const newSync = await response.json();
+ showList();
+ invalidateSyncs();
+ onSyncComplete?.();
+ toast.success(t("common.created", { item: itemLabel }));
+ await handleSync(newSync.id);
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("common.createError", { item: itemLabel }));
+ }
+ } catch (error) {
+ console.error("Failed to create sync:", error);
+ toast.error(t("common.createError", { item: itemLabel }));
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const handleSave = async () => {
+ if (!editingSync) return;
+
+ setIsSubmitting(true);
+ try {
+ const response = await fetch(`/api/external-syncs/${editingSync.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: values.name.trim(),
+ calendarUrl: !editingSync.isOneTimeImport ? values.url.trim() : undefined,
+ color: values.color,
+ displayMode: values.displayMode,
+ autoSyncInterval: values.autoSyncInterval,
+ isHidden: values.isHidden,
+ hideFromStats: values.hideFromStats,
+ }),
+ });
+
+ if (response.ok) {
+ invalidateSyncs();
+ onSyncComplete?.();
+ showList();
+ toast.success(t("common.updated", { item: itemLabel }));
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("common.updateError", { item: itemLabel }));
+ }
+ } catch (error) {
+ console.error("Failed to save sync:", error);
+ toast.error(t("common.updateError", { item: itemLabel }));
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ const confirmDelete = async () => {
+ const syncId = deleteTargetId;
+ if (!syncId) return;
+
+ setIsDeleting(syncId);
+ try {
+ const response = await fetch(`/api/external-syncs/${syncId}`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+
+ if (response.ok) {
+ if (mode.kind === "edit" && mode.syncId === syncId) showList();
+ invalidateSyncs();
+ onSyncComplete?.();
+ toast.success(t("common.deleted", { item: itemLabel }));
+ } else {
+ const data = await response.json();
+ toast.error(data.error || t("common.deleteError", { item: itemLabel }));
+ }
+ } catch (error) {
+ console.error("Error deleting sync:", error);
+ toast.error(t("common.deleteError", { item: itemLabel }));
+ } finally {
+ setIsDeleting(null);
+ setDeleteTargetId(null);
+ }
+ };
+
+ const busy = !!isSyncing || !!isDeleting;
+ const canSubmit =
+ !isSubmitting &&
+ !!values.name.trim() &&
+ (editingSync
+ ? isDirty
+ : values.importType === "file"
+ ? !!values.file
+ : !!values.url.trim());
+
+ return {
+ syncs,
+ syncErrors,
+ editingSync,
+ formOpen,
+ values,
+ setField,
+ isSubmitting,
+ isSyncing,
+ isDeleting,
+ busy,
+ canSubmit,
+ deleteTargetId,
+ setDeleteTargetId,
+ showList,
+ startAdd,
+ startEdit,
+ guardUnsaved,
+ confirmProps,
+ handleSync,
+ handleAdd,
+ handleSave,
+ confirmDelete,
+ };
+}
diff --git a/hooks/useKeyboardInset.ts b/hooks/useKeyboardInset.ts
new file mode 100644
index 0000000..90ffff3
--- /dev/null
+++ b/hooks/useKeyboardInset.ts
@@ -0,0 +1,66 @@
+"use client";
+
+import { useCallback, useRef, useSyncExternalStore } from "react";
+
+export interface KeyboardInset {
+ /** Pixels the on-screen keyboard covers at the bottom of the layout viewport */
+ bottom: number;
+ /** Height that is still visible above the keyboard */
+ viewportHeight: number;
+}
+
+// Below this a shrinking visual viewport is a collapsing browser toolbar, not a keyboard
+const KEYBOARD_MIN_HEIGHT = 120;
+
+function readInset(viewport: VisualViewport): KeyboardInset | null {
+ const bottom = Math.max(
+ 0,
+ window.innerHeight - viewport.height - viewport.offsetTop
+ );
+ if (bottom <= KEYBOARD_MIN_HEIGHT) return null;
+ return { bottom, viewportHeight: viewport.height };
+}
+
+/**
+ * Tracks the on-screen keyboard. iOS only shrinks the visual viewport, so a
+ * `position: fixed` sheet keeps sitting behind the keyboard unless it is pinned
+ * to the visible area itself.
+ */
+export function useKeyboardInset(enabled: boolean): KeyboardInset | null {
+ // useSyncExternalStore compares by identity, so an unchanged reading must
+ // stay the same object. Per instance, not shared across mounted panels.
+ const last = useRef<KeyboardInset | null>(null);
+
+ const subscribe = useCallback(
+ (notify: () => void) => {
+ const viewport = enabled ? window.visualViewport : null;
+ if (!viewport) return () => {};
+
+ viewport.addEventListener("resize", notify);
+ viewport.addEventListener("scroll", notify);
+ return () => {
+ viewport.removeEventListener("resize", notify);
+ viewport.removeEventListener("scroll", notify);
+ };
+ },
+ [enabled]
+ );
+
+ const getSnapshot = useCallback(() => {
+ const viewport = enabled ? window.visualViewport : null;
+ const next = viewport ? readInset(viewport) : null;
+ const prev = last.current;
+ if (
+ next &&
+ prev &&
+ prev.bottom === next.bottom &&
+ prev.viewportHeight === next.viewportHeight
+ ) {
+ return prev;
+ }
+ last.current = next;
+ return next;
+ }, [enabled]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, () => null);
+}
diff --git a/hooks/useMediaQuery.ts b/hooks/useMediaQuery.ts
new file mode 100644
index 0000000..f31f3a7
--- /dev/null
+++ b/hooks/useMediaQuery.ts
@@ -0,0 +1,39 @@
+"use client";
+
+import { useCallback, useSyncExternalStore } from "react";
+
+/** Tailwind's `lg` breakpoint; below it the calendar uses the mobile layout. */
+export const DESKTOP_QUERY = "(min-width: 1024px)";
+
+const noSubscribe = () => () => {};
+
+/** False during SSR and the first render, true afterwards. */
+export function useMounted(): boolean {
+ return useSyncExternalStore(
+ noSubscribe,
+ () => true,
+ () => false
+ );
+}
+
+/** Reads a value that only exists in the browser, without a hydration mismatch. */
+export function useClientValue<T>(read: () => T, serverFallback: T): T {
+ return useSyncExternalStore(noSubscribe, read, () => serverFallback);
+}
+
+export function useMediaQuery(query: string, serverFallback = false): boolean {
+ const subscribe = useCallback(
+ (notify: () => void) => {
+ const media = window.matchMedia(query);
+ media.addEventListener("change", notify);
+ return () => media.removeEventListener("change", notify);
+ },
+ [query]
+ );
+
+ return useSyncExternalStore(
+ subscribe,
+ () => window.matchMedia(query).matches,
+ () => serverFallback
+ );
+}
diff --git a/hooks/useNotes.ts b/hooks/useNotes.ts
index 524b038..345232a 100644
--- a/hooks/useNotes.ts
+++ b/hooks/useNotes.ts
@@ -1,17 +1,16 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { CalendarNote } from "@/lib/db/schema";
-import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
+import { formatDateToLocal, parseLocalDate, toLocalDate } from "@/lib/date-utils";
import { toast } from "sonner";
import { queryKeys } from "@/lib/query-keys";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
+import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
// Helper to convert API response timestamps to Date objects
export function normalizeNote(note: Record<string, unknown>): CalendarNote {
- const dateValue = note.date as string | number | Date;
- const parsedDate =
- typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
- ? parseLocalDate(dateValue)
- : new Date(dateValue);
+ const parsedDate = toLocalDate(note.date as string | number | Date);
return {
...(note as Omit<CalendarNote, "date" | "createdAt" | "updatedAt">),
@@ -37,7 +36,7 @@ async function fetchNotesApi(calendarId: string): Promise<CalendarNote[]> {
const response = await fetch(`/api/notes?${params}`);
if (!response.ok) {
- throw new Error(`Failed to fetch notes: ${response.statusText}`);
+ throw new ApiError(`Failed to fetch notes: ${response.statusText}`, response.status);
}
const data = await response.json();
@@ -118,6 +117,8 @@ export function useNotes(calendarId: string | undefined) {
const t = useTranslations();
const queryClient = useQueryClient();
+ const accessible = useIsCalendarAccessible(calendarId);
+
// Data fetching with React Query
const {
data: notes = [],
@@ -126,7 +127,8 @@ export function useNotes(calendarId: string | undefined) {
} = useQuery({
queryKey: queryKeys.notes.byCalendar(calendarId!),
queryFn: () => fetchNotesApi(calendarId!),
- enabled: !!calendarId,
+ enabled: accessible,
+ refetchInterval: LIVE_REFETCH_INTERVAL,
});
// Create mutation with optimistic update
diff --git a/hooks/usePresets.ts b/hooks/usePresets.ts
index e3a9868..d4c4b80 100644
--- a/hooks/usePresets.ts
+++ b/hooks/usePresets.ts
@@ -3,6 +3,8 @@ import { useTranslations } from "next-intl";
import { ShiftPreset } from "@/lib/db/schema";
import { toast } from "sonner";
import { queryKeys } from "@/lib/query-keys";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
// Form data interface
export interface PresetFormData {
@@ -22,7 +24,7 @@ async function fetchPresetsApi(calendarId: string): Promise<ShiftPreset[]> {
const response = await fetch(`/api/presets?${params}`);
if (!response.ok) {
- throw new Error(`Failed to fetch presets: ${response.statusText}`);
+ throw new ApiError(`Failed to fetch presets: ${response.statusText}`, response.status);
}
return await response.json();
@@ -120,6 +122,8 @@ export function usePresets(calendarId: string | undefined) {
const queryClient = useQueryClient();
const t = useTranslations();
+ const accessible = useIsCalendarAccessible(calendarId);
+
// Query for fetching presets
const {
data: presets = [],
@@ -128,7 +132,7 @@ export function usePresets(calendarId: string | undefined) {
} = useQuery({
queryKey: queryKeys.presets.byCalendar(calendarId!),
queryFn: () => fetchPresetsApi(calendarId!),
- enabled: !!calendarId,
+ enabled: accessible,
});
// Create preset mutation
diff --git a/hooks/useProfileForm.ts b/hooks/useProfileForm.ts
new file mode 100644
index 0000000..787f0df
--- /dev/null
+++ b/hooks/useProfileForm.ts
@@ -0,0 +1,260 @@
+"use client";
+
+import { useState } from "react";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import type { User } from "@/lib/auth";
+import {
+ isRateLimitError,
+ handleRateLimitError,
+} from "@/lib/rate-limit-client";
+
+const MAX_AVATAR_BYTES = 5 * 1024 * 1024;
+
+/**
+ * Name, e-mail and avatar edits of the signed-in user. Drafts stay `null`
+ * until touched, so the fields follow the session user after a refetch.
+ */
+export function useProfileForm(
+ user: User | undefined,
+ refetch: () => Promise<unknown>
+) {
+ const t = useTranslations();
+ const [draftName, setDraftName] = useState<string | null>(null);
+ const [draftEmail, setDraftEmail] = useState<string | null>(null);
+ const [avatarFile, setAvatarFile] = useState<File | null>(null);
+ const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
+ const [avatarRemoved, setAvatarRemoved] = useState(false);
+ const [isSaving, setIsSaving] = useState(false);
+ const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
+
+ const name = draftName ?? user?.name ?? "";
+ const email = draftEmail ?? user?.email ?? "";
+ const image = avatarRemoved ? null : (avatarPreview ?? user?.image ?? null);
+ const isDirty =
+ name !== (user?.name ?? "") ||
+ email !== (user?.email ?? "") ||
+ !!avatarFile ||
+ (avatarRemoved && !!user?.image);
+
+ const discard = () => {
+ setDraftName(null);
+ setDraftEmail(null);
+ setAvatarFile(null);
+ setAvatarPreview(null);
+ setAvatarRemoved(false);
+ };
+
+ const selectAvatar = (file: File) => {
+ if (!file.type.startsWith("image/")) {
+ toast.error(t("auth.invalidImageType"));
+ return;
+ }
+
+ if (file.size > MAX_AVATAR_BYTES) {
+ toast.error(t("auth.imageTooLarge"));
+ return;
+ }
+
+ setAvatarFile(file);
+ setAvatarRemoved(false);
+
+ const reader = new FileReader();
+ reader.onloadend = () => {
+ setAvatarPreview(reader.result as string);
+ };
+ reader.readAsDataURL(file);
+ };
+
+ const removeAvatar = () => {
+ setAvatarFile(null);
+ setAvatarPreview(null);
+ setAvatarRemoved(true);
+ };
+
+ const save = async () => {
+ if (!name.trim()) {
+ toast.error(t("auth.nameRequired"));
+ return;
+ }
+
+ if (!email.trim()) {
+ toast.error(t("auth.emailRequired"));
+ return;
+ }
+
+ setIsSaving(true);
+
+ try {
+ let imageUrl: string | null | undefined = avatarRemoved ? null : user?.image;
+ if (avatarFile) {
+ setIsUploadingAvatar(true);
+ const formData = new FormData();
+ formData.append("file", avatarFile);
+
+ const uploadResponse = await fetch("/api/auth/upload-avatar", {
+ method: "POST",
+ body: formData,
+ });
+
+ if (isRateLimitError(uploadResponse)) {
+ await handleRateLimitError(uploadResponse, t);
+ return;
+ }
+
+ if (!uploadResponse.ok) {
+ toast.error(t("auth.avatarUploadFailed"));
+ return;
+ }
+
+ const uploadData = await uploadResponse.json();
+ imageUrl = uploadData.url;
+ setIsUploadingAvatar(false);
+ }
+
+ const updateResponse = await fetch("/api/auth/update-user", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name, image: imageUrl }),
+ });
+
+ if (isRateLimitError(updateResponse)) {
+ await handleRateLimitError(updateResponse, t);
+ return;
+ }
+
+ if (!updateResponse.ok) {
+ const updateData = await updateResponse.json();
+ toast.error(updateData.error || t("common.error"));
+ return;
+ }
+
+ // E-mail changes apply without verification
+ if (email !== user?.email) {
+ const emailResponse = await fetch("/api/auth/change-email", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ newEmail: email }),
+ });
+
+ if (isRateLimitError(emailResponse)) {
+ await handleRateLimitError(emailResponse, t);
+ return;
+ }
+
+ if (!emailResponse.ok) {
+ const emailData = await emailResponse.json();
+ toast.error(emailData.error || t("common.error"));
+ return;
+ }
+ }
+
+ toast.success(t("auth.profileUpdated"));
+ await refetch();
+ discard();
+ } catch (error) {
+ console.error("Profile update error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsSaving(false);
+ setIsUploadingAvatar(false);
+ }
+ };
+
+ return {
+ name,
+ email,
+ image,
+ isDirty,
+ isSaving,
+ isUploadingAvatar,
+ setName: setDraftName,
+ setEmail: setDraftEmail,
+ selectAvatar,
+ removeAvatar,
+ discard,
+ save,
+ };
+}
+
+export type ProfileForm = ReturnType<typeof useProfileForm>;
+
+export function usePasswordForm() {
+ const t = useTranslations();
+ const [currentPassword, setCurrentPassword] = useState("");
+ const [newPassword, setNewPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [isChanging, setIsChanging] = useState(false);
+
+ const isDirty = !!(currentPassword || newPassword || confirmPassword);
+
+ const reset = () => {
+ setCurrentPassword("");
+ setNewPassword("");
+ setConfirmPassword("");
+ };
+
+ const submit = async () => {
+ if (!currentPassword || !newPassword) {
+ toast.error(t("validation.passwordRequired"));
+ return;
+ }
+
+ if (newPassword.length < 8) {
+ toast.error(t("validation.passwordTooShort"));
+ return;
+ }
+
+ if (newPassword !== confirmPassword) {
+ toast.error(t("validation.passwordsNoMatch"));
+ return;
+ }
+
+ setIsChanging(true);
+
+ try {
+ const response = await fetch("/api/auth/change-password", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ newPassword,
+ currentPassword,
+ revokeOtherSessions: false,
+ }),
+ });
+
+ if (isRateLimitError(response)) {
+ await handleRateLimitError(response, t);
+ return;
+ }
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ toast.error(result.error || t("common.error"));
+ return;
+ }
+
+ toast.success(t("auth.passwordChanged"));
+ reset();
+ } catch (error) {
+ console.error("Password change error:", error);
+ toast.error(t("common.error"));
+ } finally {
+ setIsChanging(false);
+ }
+ };
+
+ return {
+ currentPassword,
+ newPassword,
+ confirmPassword,
+ setCurrentPassword,
+ setNewPassword,
+ setConfirmPassword,
+ isChanging,
+ isDirty,
+ reset,
+ submit,
+ };
+}
diff --git a/hooks/useSessions.ts b/hooks/useSessions.ts
index 196ff4c..1c3169a 100644
--- a/hooks/useSessions.ts
+++ b/hooks/useSessions.ts
@@ -62,7 +62,10 @@ export function useSessions() {
}> => {
try {
// Use Better Auth's built-in revokeOtherSessions
- await authClient.revokeOtherSessions();
+ const { error } = await authClient.revokeOtherSessions();
+ if (error) {
+ throw new Error(error.message || "Failed to revoke sessions");
+ }
// Count sessions before refresh
const beforeCount = sessions.length - 1; // -1 for current session
@@ -80,6 +83,28 @@ export function useSessions() {
}
}, [fetchSessions, sessions.length]);
+ const revokeSession = useCallback(
+ async (token: string): Promise<{ success: boolean; error?: string }> => {
+ try {
+ const { error } = await authClient.revokeSession({ token });
+ if (error) {
+ throw new Error(error.message || "Failed to revoke session");
+ }
+
+ await fetchSessions();
+
+ return { success: true };
+ } catch (err) {
+ console.error("Error revoking session:", err);
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : "Unknown error",
+ };
+ }
+ },
+ [fetchSessions]
+ );
+
useEffect(() => {
let cancelled = false;
@@ -116,5 +141,6 @@ export function useSessions() {
error,
refetch: fetchSessions,
revokeAllSessions,
+ revokeSession,
};
}
diff --git a/hooks/useShiftActions.ts b/hooks/useShiftActions.ts
index 8b71f71..fe8570f 100644
--- a/hooks/useShiftActions.ts
+++ b/hooks/useShiftActions.ts
@@ -3,7 +3,7 @@ import { isSameDay } from "date-fns";
import { ShiftFormData } from "@/components/shift-sheet";
import { ShiftWithCalendar } from "@/lib/types";
import { ShiftPreset } from "@/lib/db/schema";
-import { formatDateToLocal, parseLocalDate } from "@/lib/date-utils";
+import { formatDateToLocal, toLocalDate } from "@/lib/date-utils";
interface UseShiftActionsProps {
shifts: ShiftWithCalendar[];
@@ -56,10 +56,7 @@ export function useShiftActions({
const preset = presets.find((p) => p.id === selectedPresetId);
if (!preset) return;
- const targetDate =
- typeof date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(date)
- ? parseLocalDate(date)
- : new Date(date);
+ const targetDate = toLocalDate(date);
const dateKey = formatDateToLocal(targetDate);
if (togglingDatesRef.current.has(dateKey)) return;
diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.ts
index fc4ce7e..8c41fa7 100644
--- a/hooks/useShiftForm.ts
+++ b/hooks/useShiftForm.ts
@@ -4,6 +4,7 @@ import { ShiftPreset } from "@/lib/db/schema";
import { ShiftWithCalendar } from "@/lib/types";
import { formatDateToLocal } from "@/lib/date-utils";
import { usePresets } from "@/hooks/usePresets";
+import { DEFAULT_COLOR } from "@/lib/constants";
interface UseShiftFormOptions {
open: boolean;
@@ -29,7 +30,7 @@ export function useShiftForm({
endTime: shift?.endTime || "17:00",
title: shift?.title || "",
notes: shift?.notes || "",
- color: shift?.color || "#3b82f6",
+ color: shift?.color || DEFAULT_COLOR,
isAllDay: false,
});
@@ -45,7 +46,7 @@ export function useShiftForm({
title: presetName,
startTime: shiftData.startTime,
endTime: shiftData.endTime,
- color: shiftData.color || "#3b82f6",
+ color: shiftData.color || DEFAULT_COLOR,
notes: shiftData.notes || "",
isAllDay: shiftData.isAllDay || false,
isSecondary: false,
@@ -67,6 +68,19 @@ export function useShiftForm({
});
};
+ /** Drops the values a preset filled in, keeping the date. */
+ const clearPreset = () => {
+ setFormData({
+ ...formData,
+ startTime: "09:00",
+ endTime: "17:00",
+ title: "",
+ notes: "",
+ color: DEFAULT_COLOR,
+ isAllDay: false,
+ });
+ };
+
const resetForm = () => {
setFormData({
date: selectedDate
@@ -76,7 +90,7 @@ export function useShiftForm({
endTime: "17:00",
title: "",
notes: "",
- color: "#3b82f6",
+ color: DEFAULT_COLOR,
isAllDay: false,
});
setPresetName("");
@@ -103,7 +117,7 @@ export function useShiftForm({
endTime: shift?.endTime || "17:00",
title: shift?.title || "",
notes: shift?.notes || "",
- color: shift?.color || "#3b82f6",
+ color: shift?.color || DEFAULT_COLOR,
isAllDay: shift?.isAllDay || false,
};
@@ -135,6 +149,7 @@ export function useShiftForm({
presetName,
setPresetName,
applyPreset,
+ clearPreset,
saveAsPresetHandler,
resetForm,
};
diff --git a/hooks/useShiftStats.ts b/hooks/useShiftStats.ts
index 45d62cc..e1774a5 100644
--- a/hooks/useShiftStats.ts
+++ b/hooks/useShiftStats.ts
@@ -2,8 +2,10 @@
import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/lib/query-keys";
-import { REFETCH_INTERVAL } from "@/lib/query-client";
+import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
import { formatDateToLocal } from "@/lib/date-utils";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
export interface ShiftStatsData {
period: string;
@@ -44,7 +46,7 @@ async function fetchShiftStatsApi(
const response = await fetch(`/api/shifts/stats?${params}`);
if (!response.ok) {
- throw new Error("Failed to fetch shift statistics");
+ throw new ApiError("Failed to fetch shift statistics", response.status);
}
return await response.json();
@@ -71,6 +73,8 @@ export function useShiftStats({
currentDate,
period,
}: UseShiftStatsOptions) {
+ const accessible = useIsCalendarAccessible(calendarId);
+
const {
data: stats = null,
isLoading: loading,
@@ -82,8 +86,8 @@ export function useShiftStats({
formatDateToLocal(currentDate)
),
queryFn: () => fetchShiftStatsApi(calendarId!, period, currentDate),
- enabled: !!calendarId,
- refetchInterval: REFETCH_INTERVAL,
+ enabled: accessible,
+ refetchInterval: LIVE_REFETCH_INTERVAL,
});
return {
diff --git a/hooks/useShifts.ts b/hooks/useShifts.ts
index 73aa80b..b04ad27 100644
--- a/hooks/useShifts.ts
+++ b/hooks/useShifts.ts
@@ -3,18 +3,17 @@ import { ShiftWithCalendar } from "@/lib/types";
import { ShiftFormData } from "@/components/shift-sheet";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
-import { parseLocalDate } from "@/lib/date-utils";
+import { parseLocalDate, toLocalDate } from "@/lib/date-utils";
import { queryKeys } from "@/lib/query-keys";
+import { ApiError } from "@/lib/api-error";
+import { useIsCalendarAccessible } from "@/hooks/useCalendars";
+import { LIVE_REFETCH_INTERVAL } from "@/lib/query-client";
// Helper to convert API response timestamps to Date objects
export function normalizeShift(
shift: Record<string, unknown>
): ShiftWithCalendar {
- const dateValue = shift.date as string | number | Date;
- const parsedDate =
- typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
- ? parseLocalDate(dateValue)
- : new Date(dateValue);
+ const parsedDate = toLocalDate(shift.date as string | number | Date);
return {
...(shift as Omit<ShiftWithCalendar, "date" | "createdAt" | "updatedAt">),
@@ -32,7 +31,7 @@ async function fetchShiftsApi(
const response = await fetch(`/api/shifts?${params}`);
if (!response.ok) {
- throw new Error(`Failed to fetch shifts: ${response.statusText}`);
+ throw new ApiError(`Failed to fetch shifts: ${response.statusText}`, response.status);
}
const data = await response.json();
@@ -111,6 +110,8 @@ export function useShifts(calendarId: string | undefined) {
const t = useTranslations();
const queryClient = useQueryClient();
+ const accessible = useIsCalendarAccessible(calendarId);
+
// Data fetching with React Query
const {
data: shifts = [],
@@ -119,7 +120,8 @@ export function useShifts(calendarId: string | undefined) {
} = useQuery({
queryKey: queryKeys.shifts.byCalendar(calendarId!),
queryFn: () => fetchShiftsApi(calendarId!),
- enabled: !!calendarId,
+ enabled: accessible,
+ refetchInterval: LIVE_REFETCH_INTERVAL,
});
// Create mutation with optimistic update
diff --git a/hooks/useSignOut.ts b/hooks/useSignOut.ts
new file mode 100644
index 0000000..d788d47
--- /dev/null
+++ b/hooks/useSignOut.ts
@@ -0,0 +1,36 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { signOut } from "@/lib/auth/client";
+
+/** Ends the session, confirms it and returns to the sign-in page. */
+export function useSignOut() {
+ const t = useTranslations();
+ const router = useRouter();
+
+ return async () => {
+ try {
+ // Better Auth resolves with `{ error }` instead of rejecting, so a failed
+ // sign-out must be caught here — navigating anyway would bounce the still
+ // signed-in user straight back from /login.
+ const { error } = await signOut();
+
+ if (error) {
+ if (error.status === 429) {
+ toast.error(t("rateLimit.title"), { description: t("rateLimit.fallback") });
+ } else {
+ toast.error(error.message || t("common.error"));
+ }
+ return;
+ }
+
+ toast.success(t("auth.logoutSuccess"));
+ router.replace("/login");
+ } catch (error) {
+ console.error("Sign out error:", error);
+ toast.error(t("common.error"));
+ }
+ };
+}
diff --git a/hooks/useStampShortcuts.ts b/hooks/useStampShortcuts.ts
new file mode 100644
index 0000000..d43ef15
--- /dev/null
+++ b/hooks/useStampShortcuts.ts
@@ -0,0 +1,52 @@
+"use client";
+
+import { useEffect } from "react";
+
+interface UseStampShortcutsOptions {
+ presetIds: string[];
+ selectedPresetId: string | undefined;
+ onSelectPreset: (id: string | undefined) => void;
+ enabled?: boolean;
+}
+
+function isTypingTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ return (
+ target.isContentEditable ||
+ ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)
+ );
+}
+
+/** Digits 1–9 arm or disarm the matching preset, Escape disarms. */
+export function useStampShortcuts({
+ presetIds,
+ selectedPresetId,
+ onSelectPreset,
+ enabled = true,
+}: UseStampShortcutsOptions) {
+ useEffect(() => {
+ if (!enabled) return;
+
+ const handler = (event: KeyboardEvent) => {
+ if (event.metaKey || event.ctrlKey || event.altKey) return;
+ if (isTypingTarget(event.target)) return;
+ // Leave keys alone while a dialog or sheet owns the focus
+ if (document.querySelector("[role='dialog'][data-state='open']")) return;
+
+ if (event.key === "Escape" && selectedPresetId) {
+ onSelectPreset(undefined);
+ return;
+ }
+
+ const index = Number(event.key) - 1;
+ if (!Number.isInteger(index) || index < 0 || index > 8) return;
+ const id = presetIds[index];
+ if (!id) return;
+ event.preventDefault();
+ onSelectPreset(id === selectedPresetId ? undefined : id);
+ };
+
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [enabled, presetIds, selectedPresetId, onSelectPreset]);
+}
diff --git a/hooks/useViewSettings.ts b/hooks/useViewSettings.ts
index af6abc8..b51b394 100644
--- a/hooks/useViewSettings.ts
+++ b/hooks/useViewSettings.ts
@@ -1,233 +1,229 @@
-import { useState, useCallback } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { useAuth } from "@/hooks/useAuth";
+import { useAuthFeatures } from "@/hooks/useAuthFeatures";
+import { queryKeys } from "@/lib/query-keys";
+import {
+ CalendarViewSettings,
+ DEFAULT_PERSONAL_VIEW_SETTINGS,
+ PersonalViewSettings,
+ resolveViewSettings,
+ sanitizePersonalViewSettings,
+} from "@/lib/view-settings";
+
+// Per-device keys: guests and auth-less instances keep using them, accounts migrate them once
+const STORAGE_KEYS = {
+ shiftsPerDay: "shifts-per-day",
+ externalShiftsPerDay: "external-shifts-per-day",
+ showShiftNotes: "show-shift-notes",
+ sortType: "shift-sort-type",
+ sortOrder: "shift-sort-order",
+ combinedSort: "combined-sort-mode",
+ hidePresetHeader: "hide-preset-header",
+ highlightedWeekdays: "highlighted-weekdays",
+ highlightColor: "highlight-color",
+} as const;
+
+function readStorage(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
-export function useViewSettings() {
- const [shiftsPerDay, setShiftsPerDay] = useState<number | null>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("shifts-per-day");
- if (stored === "null") return null;
- if (stored) {
- const parsed = parseInt(stored);
- return isNaN(parsed) ? 3 : parsed;
- }
- }
- return 3;
- });
+function writeStorage(key: string, value: string) {
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ // Storage can be unavailable (private mode, quota); the in-memory state still applies
+ }
+}
- const [externalShiftsPerDay, setExternalShiftsPerDay] = useState<
- number | null
- >(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("external-shifts-per-day");
- if (stored === "null") return null;
- if (stored) {
- const parsed = parseInt(stored);
- return isNaN(parsed) ? 3 : parsed;
- }
- }
- return 3;
- });
+function parseLimit(raw: string | null): number | null | undefined {
+ if (raw === null) return undefined;
+ if (raw === "null") return null;
+ const parsed = parseInt(raw, 10);
+ return isNaN(parsed) ? undefined : parsed;
+}
- const [showShiftNotes, setShowShiftNotes] = useState<boolean>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("show-shift-notes");
- return stored === "true";
- }
- return false;
- });
+function parseBoolean(raw: string | null): boolean | undefined {
+ return raw === null ? undefined : raw === "true";
+}
- const [showFullTitles, setShowFullTitles] = useState<boolean>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("show-full-titles");
- return stored === "true";
- }
- return false;
- });
+function parseJson(raw: string | null): unknown {
+ if (raw === null) return undefined;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+}
- const [shiftSortType, setShiftSortType] = useState<
- "startTime" | "createdAt" | "title"
- >(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("shift-sort-type");
- if (
- stored === "startTime" ||
- stored === "createdAt" ||
- stored === "title"
- ) {
- return stored;
- }
- }
- return "createdAt";
- });
+function hasLocalViewSettings(): boolean {
+ return Object.values(STORAGE_KEYS).some((key) => readStorage(key) !== null);
+}
- const [shiftSortOrder, setShiftSortOrder] = useState<"asc" | "desc">(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("shift-sort-order");
- if (stored === "asc" || stored === "desc") {
- return stored;
- }
- }
- return "asc";
+function readLocalViewSettings(): PersonalViewSettings {
+ if (typeof window === "undefined") return DEFAULT_PERSONAL_VIEW_SETTINGS;
+ const hidePresetHeader = parseBoolean(readStorage(STORAGE_KEYS.hidePresetHeader));
+ return sanitizePersonalViewSettings({
+ shiftsPerDay: parseLimit(readStorage(STORAGE_KEYS.shiftsPerDay)),
+ externalShiftsPerDay: parseLimit(readStorage(STORAGE_KEYS.externalShiftsPerDay)),
+ showShiftNotes: parseBoolean(readStorage(STORAGE_KEYS.showShiftNotes)),
+ sortType: readStorage(STORAGE_KEYS.sortType) ?? undefined,
+ sortOrder: readStorage(STORAGE_KEYS.sortOrder) ?? undefined,
+ combinedSort: parseBoolean(readStorage(STORAGE_KEYS.combinedSort)),
+ showStampBar: hidePresetHeader === undefined ? undefined : !hidePresetHeader,
+ highlightedWeekdays: parseJson(readStorage(STORAGE_KEYS.highlightedWeekdays)),
+ highlightColor: readStorage(STORAGE_KEYS.highlightColor) ?? undefined,
});
+}
- const [combinedSortMode, setCombinedSortMode] = useState<boolean>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("combined-sort-mode");
- return stored === "true";
- }
- return false;
- });
+function writeLocalViewSettings(settings: PersonalViewSettings) {
+ const limit = (value: number | null) => (value === null ? "null" : String(value));
+ writeStorage(STORAGE_KEYS.shiftsPerDay, limit(settings.shiftsPerDay));
+ writeStorage(STORAGE_KEYS.externalShiftsPerDay, limit(settings.externalShiftsPerDay));
+ writeStorage(STORAGE_KEYS.showShiftNotes, String(settings.showShiftNotes));
+ writeStorage(STORAGE_KEYS.sortType, settings.sortType);
+ writeStorage(STORAGE_KEYS.sortOrder, settings.sortOrder);
+ writeStorage(STORAGE_KEYS.combinedSort, String(settings.combinedSort));
+ writeStorage(STORAGE_KEYS.hidePresetHeader, String(!settings.showStampBar));
+ writeStorage(STORAGE_KEYS.highlightedWeekdays, JSON.stringify(settings.highlightedWeekdays));
+ writeStorage(STORAGE_KEYS.highlightColor, settings.highlightColor);
+}
- const [hidePresetHeader, setHidePresetHeader] = useState<boolean>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("hide-preset-header");
- return stored === "true";
- }
- return false;
- });
+async function fetchPersonalViewSettingsApi(): Promise<PersonalViewSettings | null> {
+ const response = await fetch("/api/user/view-settings");
+ if (!response.ok) {
+ throw new Error(`Failed to fetch view settings: ${response.statusText}`);
+ }
+ const data = await response.json();
+ return data.viewSettings ? sanitizePersonalViewSettings(data.viewSettings) : null;
+}
- const [highlightWeekends, setHighlightWeekends] = useState<boolean>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("highlight-weekends");
- return stored === "true";
- }
- return false;
+async function updatePersonalViewSettingsApi(
+ patch: Partial<PersonalViewSettings>
+): Promise<PersonalViewSettings> {
+ const response = await fetch("/api/user/view-settings", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ viewSettings: patch }),
});
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(
+ `Failed to update view settings: ${response.status} ${response.statusText} - ${errorText}`
+ );
+ }
+ const data = await response.json();
+ return sanitizePersonalViewSettings(data.viewSettings);
+}
- const [highlightedWeekdays, setHighlightedWeekdays] = useState<number[]>(
- () => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("highlighted-weekdays");
- if (stored) {
- try {
- return JSON.parse(stored);
- } catch {
- return [];
- }
- }
- }
- return [];
- }
- );
+interface UpdateViewSettingsContext {
+ previous: PersonalViewSettings | null | undefined;
+}
- const [highlightColor, setHighlightColor] = useState<string>(() => {
- if (typeof window !== "undefined") {
- const stored = localStorage.getItem("highlight-color");
- if (stored) return stored;
- }
- return "#fbbf24"; // Default amber
+/**
+ * The personal view: stored in the account when signed in, in localStorage for
+ * guests and with auth disabled. `forCalendar` applies a calendar's own view on top.
+ */
+export function useViewSettings() {
+ const t = useTranslations();
+ const queryClient = useQueryClient();
+ const { user, isLoading: sessionLoading } = useAuth();
+ const { isAuthEnabled } = useAuthFeatures();
+ const userId = isAuthEnabled && user ? user.id : null;
+
+ // better-auth reports pending again on every guest refetch, so only the first load counts
+ const [sessionSettled, setSessionSettled] = useState(!isAuthEnabled);
+ if (!sessionSettled && !sessionLoading) setSessionSettled(true);
+ const queryKey = queryKeys.userPreferences.viewSettings(userId ?? "");
+
+ const [local, setLocal] = useState<PersonalViewSettings>(readLocalViewSettings);
+
+ const {
+ data: stored,
+ isSuccess,
+ isPending,
+ } = useQuery({
+ queryKey,
+ queryFn: fetchPersonalViewSettingsApi,
+ enabled: !!userId,
+ refetchInterval: false,
+ retry: 1,
});
- const handleShiftsPerDayChange = useCallback((count: number | null) => {
- setShiftsPerDay(count);
- if (typeof window !== "undefined") {
- localStorage.setItem(
- "shifts-per-day",
- count === null ? "null" : count.toString()
+ // Until the account has a stored view, this device's values stand in for it
+ const personal = userId ? (stored ?? local) : local;
+
+ const { mutate } = useMutation<
+ PersonalViewSettings,
+ Error,
+ Partial<PersonalViewSettings>,
+ UpdateViewSettingsContext
+ >({
+ mutationKey: queryKey,
+ mutationFn: updatePersonalViewSettingsApi,
+ onMutate: async (patch) => {
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<PersonalViewSettings | null>(queryKey);
+ queryClient.setQueryData<PersonalViewSettings | null>(queryKey, (old) =>
+ sanitizePersonalViewSettings({ ...(old ?? personal), ...patch })
);
- }
- }, []);
-
- const handleExternalShiftsPerDayChange = useCallback(
- (count: number | null) => {
- setExternalShiftsPerDay(count);
- if (typeof window !== "undefined") {
- localStorage.setItem(
- "external-shifts-per-day",
- count === null ? "null" : count.toString()
- );
+ return { previous };
+ },
+ onError: (err, patch, context) => {
+ if (context) {
+ queryClient.setQueryData(queryKey, context.previous);
}
+ console.error("Failed to update view settings:", err);
+ toast.error(t("common.updateError", { item: t("view.settingsTitle") }));
},
- []
- );
+ onSettled: () => {
+ // Refetching while a later toggle is still in flight would flash the older value
+ if (queryClient.isMutating({ mutationKey: queryKey }) === 1) {
+ queryClient.invalidateQueries({ queryKey });
+ }
+ },
+ });
- const handleShowShiftNotesChange = useCallback((show: boolean) => {
- setShowShiftNotes(show);
- if (typeof window !== "undefined") {
- localStorage.setItem("show-shift-notes", show.toString());
- }
- }, []);
-
- const handleShowFullTitlesChange = useCallback((show: boolean) => {
- setShowFullTitles(show);
- if (typeof window !== "undefined") {
- localStorage.setItem("show-full-titles", show.toString());
- }
- }, []);
-
- const handleShiftSortTypeChange = useCallback(
- (type: "startTime" | "createdAt" | "title") => {
- setShiftSortType(type);
- if (typeof window !== "undefined") {
- localStorage.setItem("shift-sort-type", type);
+ // One-time move of this device's settings into an account that has none yet
+ const migratedFor = useRef<string | null>(null);
+ useEffect(() => {
+ if (!userId || !isSuccess || stored !== null || migratedFor.current === userId) return;
+ migratedFor.current = userId;
+ if (hasLocalViewSettings()) mutate(readLocalViewSettings());
+ }, [userId, isSuccess, stored, mutate]);
+
+ const updatePersonal = useCallback(
+ (patch: Partial<PersonalViewSettings>) => {
+ if (userId) {
+ mutate(patch);
+ return;
}
+ const next = sanitizePersonalViewSettings({ ...local, ...patch });
+ setLocal(next);
+ writeLocalViewSettings(next);
},
- []
+ [userId, mutate, local]
);
- const handleShiftSortOrderChange = useCallback((order: "asc" | "desc") => {
- setShiftSortOrder(order);
- if (typeof window !== "undefined") {
- localStorage.setItem("shift-sort-order", order);
- }
- }, []);
-
- const handleCombinedSortModeChange = useCallback((combined: boolean) => {
- setCombinedSortMode(combined);
- if (typeof window !== "undefined") {
- localStorage.setItem("combined-sort-mode", combined.toString());
- }
- }, []);
-
- const handleHidePresetHeaderChange = useCallback((hide: boolean) => {
- setHidePresetHeader(hide);
- if (typeof window !== "undefined") {
- localStorage.setItem("hide-preset-header", hide.toString());
- }
- }, []);
-
- const handleHighlightWeekendsChange = useCallback((highlight: boolean) => {
- setHighlightWeekends(highlight);
- if (typeof window !== "undefined") {
- localStorage.setItem("highlight-weekends", highlight.toString());
- }
- }, []);
-
- const handleHighlightedWeekdaysChange = useCallback((days: number[]) => {
- setHighlightedWeekdays(days);
- if (typeof window !== "undefined") {
- localStorage.setItem("highlighted-weekdays", JSON.stringify(days));
- }
- }, []);
-
- const handleHighlightColorChange = useCallback((color: string) => {
- setHighlightColor(color);
- if (typeof window !== "undefined") {
- localStorage.setItem("highlight-color", color);
- }
- }, []);
+ const forCalendar = useCallback(
+ (calendar?: { viewSettings?: CalendarViewSettings | null } | null) =>
+ resolveViewSettings(personal, calendar?.viewSettings),
+ [personal]
+ );
return {
- shiftsPerDay,
- externalShiftsPerDay,
- showShiftNotes,
- showFullTitles,
- shiftSortType,
- shiftSortOrder,
- combinedSortMode,
- hidePresetHeader,
- highlightWeekends,
- highlightedWeekdays,
- highlightColor,
- handleShiftsPerDayChange,
- handleExternalShiftsPerDayChange,
- handleShowShiftNotesChange,
- handleShowFullTitlesChange,
- handleShiftSortTypeChange,
- handleShiftSortOrderChange,
- handleCombinedSortModeChange,
- handleHidePresetHeaderChange,
- handleHighlightWeekendsChange,
- handleHighlightedWeekdaysChange,
- handleHighlightColorChange,
+ personal,
+ updatePersonal,
+ forCalendar,
+ /** True while a signed-in account's view is still loading, to avoid a flash of device values */
+ loading: !sessionSettled || (!!userId && isPending),
+ /** false for guests and auth-less instances, whose view lives on this device */
+ storedInAccount: !!userId,
};
}
diff --git a/lib/admin-list.ts b/lib/admin-list.ts
new file mode 100644
index 0000000..471850f
--- /dev/null
+++ b/lib/admin-list.ts
@@ -0,0 +1,153 @@
+/**
+ * Shared contract of the paginated admin list endpoints (`/api/admin/users`,
+ * `/api/admin/calendars`) and the hooks that call them. Pure module: safe to
+ * import from route handlers and client code alike.
+ */
+
+export const ADMIN_PAGE_SIZE = 25;
+export const ADMIN_MAX_PAGE_SIZE = 100;
+
+export const SORT_ORDERS = ["asc", "desc"] as const;
+export type SortOrder = (typeof SORT_ORDERS)[number];
+
+export interface AdminListResponse<T, C> {
+ items: T[];
+ /** Rows matching the current search and filters */
+ total: number;
+ /** Instance-wide totals, independent of search and filters */
+ counts: C;
+ /** The page actually served; out-of-range requests get the last page */
+ page: number;
+ limit: number;
+}
+
+// Users
+
+export const USER_ROLE_FILTERS = ["all", "superadmin", "admin", "user"] as const;
+export const USER_STATUS_FILTERS = ["all", "active", "banned"] as const;
+export const USER_SORT_FIELDS = [
+ "name",
+ "email",
+ "role",
+ "status",
+ "createdAt",
+ "lastActivity",
+ "calendarCount",
+] as const;
+
+export type UserRoleFilter = (typeof USER_ROLE_FILTERS)[number];
+export type UserStatusFilter = (typeof USER_STATUS_FILTERS)[number];
+export type UserSortField = (typeof USER_SORT_FIELDS)[number];
+
+export interface UserListParams {
+ search: string;
+ role: UserRoleFilter;
+ status: UserStatusFilter;
+ sort: UserSortField;
+ order: SortOrder;
+ page: number;
+ limit: number;
+}
+
+export interface UserListCounts {
+ total: number;
+ superadmin: number;
+ admin: number;
+ user: number;
+ banned: number;
+ active: number;
+}
+
+// Calendars
+
+export const CALENDAR_CONTENT_FILTERS = ["all", "shared", "synced"] as const;
+export const CALENDAR_OWNER_FILTERS = ["all", "orphaned", "with-owner"] as const;
+export const CALENDAR_SORT_FIELDS = [
+ "name",
+ "createdAt",
+ "owner",
+ "shiftsCount",
+ "sharesCount",
+ "externalSyncsCount",
+ "guestPermission",
+] as const;
+
+export type CalendarContentFilter = (typeof CALENDAR_CONTENT_FILTERS)[number];
+export type CalendarOwnerFilter = (typeof CALENDAR_OWNER_FILTERS)[number];
+export type CalendarSortField = (typeof CALENDAR_SORT_FIELDS)[number];
+
+export interface CalendarListParams {
+ search: string;
+ content: CalendarContentFilter;
+ owner: CalendarOwnerFilter;
+ sort: CalendarSortField;
+ order: SortOrder;
+ page: number;
+ limit: number;
+}
+
+export interface CalendarListCounts {
+ total: number;
+ orphaned: number;
+ shared: number;
+ synced: number;
+ shifts: number;
+}
+
+// Helpers
+
+export function pickParam<T extends string>(
+ value: string | null,
+ allowed: readonly T[],
+ fallback: T
+): T {
+ return value !== null && (allowed as readonly string[]).includes(value) ? (value as T) : fallback;
+}
+
+function positiveInt(value: string | null, fallback: number): number {
+ const parsed = Number.parseInt(value ?? "", 10);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+/** Requested page (1-based) and page size, with the size capped. */
+export function parsePaging(searchParams: URLSearchParams) {
+ return {
+ page: positiveInt(searchParams.get("page"), 1),
+ limit: Math.min(positiveInt(searchParams.get("limit"), ADMIN_PAGE_SIZE), ADMIN_MAX_PAGE_SIZE),
+ };
+}
+
+/** Clamps the page to the last one that has rows, so a shrinking list never shows an empty page. */
+export function clampPage(page: number, limit: number, total: number) {
+ const lastPage = Math.max(1, Math.ceil(total / limit));
+ const served = Math.min(page, lastPage);
+ return { page: served, offset: (served - 1) * limit };
+}
+
+/** Lower-cased `LIKE` pattern with `%`, `_` and `\` escaped; pair it with `ESCAPE '\'`. */
+export function containsPattern(search: string): string {
+ return `%${search.toLowerCase().replace(/[\\%_]/g, (char) => `\\${char}`)}%`;
+}
+
+/**
+ * Filter defaults are sent explicitly rather than omitted: the endpoints accept
+ * "all" as a value, and skipping it here would also swallow a free-text search
+ * for the literal "all".
+ */
+export function toSearchParams(params: object): URLSearchParams {
+ const searchParams = new URLSearchParams();
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined && value !== "") {
+ searchParams.set(key, String(value));
+ }
+ }
+ return searchParams;
+}
+
+/** Failed admin request; hooks translate `status` into a message when they show it. */
+export class AdminRequestError extends Error {
+ constructor(public readonly status: number) {
+ super(`Admin request failed with status ${status}`);
+ this.name = "AdminRequestError";
+ }
+}
diff --git a/lib/api-error.ts b/lib/api-error.ts
new file mode 100644
index 0000000..6dbbb42
--- /dev/null
+++ b/lib/api-error.ts
@@ -0,0 +1,23 @@
+/**
+ * Carries the HTTP status alongside the message so the query client can tell a
+ * refused request from a network blip. Pure module: no React, no fetch.
+ */
+export class ApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number
+ ) {
+ super(message);
+ this.name = "ApiError";
+ }
+}
+
+/**
+ * True for a 4xx, which is a verdict rather than a hiccup: retrying a 403 only
+ * repeats it, and retrying a 429 makes the rate limit worse. Duck-typed on
+ * `status`, so `AdminRequestError` is covered too.
+ */
+export function isClientError(error: unknown): boolean {
+ const status = (error as { status?: unknown } | null)?.status;
+ return typeof status === "number" && status >= 400 && status < 500;
+}
diff --git a/lib/audit-log.ts b/lib/audit-log.ts
index b7fab86..c53b5ea 100644
--- a/lib/audit-log.ts
+++ b/lib/audit-log.ts
@@ -71,7 +71,8 @@ export interface CalendarDeletedMetadata {
export interface CalendarUpdatedMetadata {
calendarName: string;
- changes: string[]; // e.g., ["name", "color", "guestPermission"]
+ changes: string[]; // e.g., ["name", "color", "guestPermission", "viewSettings"]
+ viewSettings?: "enabled" | "updated" | "disabled";
}
export interface CalendarSharedMetadata {
diff --git a/lib/constants.ts b/lib/constants.ts
index fc9058c..ccb69a6 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -6,12 +6,14 @@
* Preset color options for shifts and calendars
*/
export const PRESET_COLORS = [
- { name: "Blue", value: "#3b82f6" },
- { name: "Red", value: "#ef4444" },
- { name: "Green", value: "#10b981" },
- { name: "Amber", value: "#f59e0b" },
- { name: "Violet", value: "#8b5cf6" },
- { name: "Pink", value: "#ec4899" },
- { name: "Cyan", value: "#06b6d4" },
- { name: "Orange", value: "#f97316" },
+ { name: "Blue", value: "#2563eb" },
+ { name: "Red", value: "#dc2626" },
+ { name: "Green", value: "#059669" },
+ { name: "Amber", value: "#d97706" },
+ { name: "Violet", value: "#7c3aed" },
+ { name: "Pink", value: "#db2777" },
+ { name: "Cyan", value: "#0891b2" },
+ { name: "Orange", value: "#ea580c" },
];
+
+export const DEFAULT_COLOR = PRESET_COLORS[0].value;
diff --git a/lib/date-utils.ts b/lib/date-utils.ts
index dcb474b..7accc53 100644
--- a/lib/date-utils.ts
+++ b/lib/date-utils.ts
@@ -9,6 +9,33 @@ export function formatDateToLocal(date: Date): string {
return `${year}-${month}-${day}`;
}
+const longDateFormatters = new Map<string, Intl.DateTimeFormat>();
+
+/**
+ * The "Montag, 15. Januar" heading used by every day view, sheet and dialog.
+ * Formatters are cached because they are built during render.
+ */
+export function formatLongDate(
+ date: Date,
+ locale: string,
+ { year = false, month = "long" }: { year?: boolean; month?: "long" | "short" } = {}
+): string {
+ const key = `${locale}|${month}|${year}`;
+ let formatter = longDateFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(locale, {
+ weekday: "long",
+ day: "numeric",
+ month,
+ ...(year ? { year: "numeric" as const } : {}),
+ });
+ longDateFormatters.set(key, formatter);
+ }
+ return formatter.format(date);
+}
+
+const LOCAL_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
+
/**
* Parses a YYYY-MM-DD date string as a local date (NOT UTC!)
* This fixes the timezone bug where "2025-01-15" was interpreted as UTC midnight
@@ -26,8 +53,7 @@ export function parseLocalDate(dateString: string): Date {
}
// 2. Match strict YYYY-MM-DD pattern
- const datePattern = /^\d{4}-\d{2}-\d{2}$/;
- if (!datePattern.test(dateString)) {
+ if (!LOCAL_DATE_PATTERN.test(dateString)) {
throw new TypeError(
`Invalid date format: expected YYYY-MM-DD, got "${dateString}"`
);
@@ -76,6 +102,17 @@ export function parseLocalDate(dateString: string): Date {
return date;
}
+/**
+ * Normalises an API date field, which is either a local YYYY-MM-DD string or a
+ * timestamp. Passing the former to `new Date()` would read it as UTC midnight
+ * and shift the day in negative offsets.
+ */
+export function toLocalDate(value: Date | string | number): Date {
+ return typeof value === "string" && LOCAL_DATE_PATTERN.test(value)
+ ? parseLocalDate(value)
+ : new Date(value);
+}
+
/**
* Checks if a year is a leap year
* @param year - The year to check
diff --git a/lib/db/db-path.mjs b/lib/db/db-path.mjs
index 5b3bb9d..e1492c5 100644
--- a/lib/db/db-path.mjs
+++ b/lib/db/db-path.mjs
@@ -1,8 +1,8 @@
import path from "node:path";
-// Shared by lib/db/index.ts and scripts/migrate.mjs. If these two ever resolve
-// differently, migrations run against one file and the server opens another,
-// silently and with no error.
+// Shared by lib/db/index.ts, scripts/migrate.mjs and drizzle.config.ts. If these
+// ever resolve differently, drizzle-kit, the migrator and the server end up
+// pointed at different files, silently and with no error.
export function resolveDatabasePath() {
return (
process.env.DATABASE_URL?.replace("file:", "") ||
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 0a5edf8..321ba7e 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -1,5 +1,9 @@
import { sqliteTable, text, integer, index } from "drizzle-orm/sqlite-core";
import { sql, relations } from "drizzle-orm";
+import type {
+ CalendarViewSettings,
+ PersonalViewSettings,
+} from "../view-settings";
// =====================================================
// Better Auth Tables (generated by @better-auth/cli)
@@ -113,6 +117,10 @@ export const calendars = sqliteTable(
})
.notNull()
.default("none"),
+ // null = no own view; every user sees their personal view
+ viewSettings: text("view_settings", {
+ mode: "json",
+ }).$type<CalendarViewSettings>(),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
@@ -184,6 +192,19 @@ export const userCalendarSubscriptions = sqliteTable(
]
);
+export const userPreferences = sqliteTable("user_preferences", {
+ userId: text("user_id")
+ .primaryKey()
+ .references(() => user.id, { onDelete: "cascade" }),
+ viewSettings: text("view_settings", {
+ mode: "json",
+ }).$type<PersonalViewSettings>(),
+ updatedAt: integer("updated_at", { mode: "timestamp" })
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`)
+ .$onUpdate(() => new Date()),
+});
+
export const externalSyncs = sqliteTable("external_syncs", {
id: text("id")
.primaryKey()
@@ -416,6 +437,8 @@ export type Session = typeof session.$inferSelect;
export type Account = typeof account.$inferSelect;
export type CalendarShare = typeof calendarShares.$inferSelect;
export type NewCalendarShare = typeof calendarShares.$inferInsert;
+export type UserPreferences = typeof userPreferences.$inferSelect;
+export type NewUserPreferences = typeof userPreferences.$inferInsert;
export type UserCalendarSubscription =
typeof userCalendarSubscriptions.$inferSelect;
export type NewUserCalendarSubscription =
@@ -425,7 +448,8 @@ export type NewUserCalendarSubscription =
// Drizzle Relations (for experimental joins)
// =====================================================
-export const userRelations = relations(user, ({ many }) => ({
+export const userRelations = relations(user, ({ one, many }) => ({
+ preferences: one(userPreferences),
sessions: many(session),
accounts: many(account),
ownedCalendars: many(calendars),
@@ -492,6 +516,16 @@ export const userCalendarSubscriptionsRelations = relations(
})
);
+export const userPreferencesRelations = relations(
+ userPreferences,
+ ({ one }) => ({
+ user: one(user, {
+ fields: [userPreferences.userId],
+ references: [user.id],
+ }),
+ })
+);
+
export const auditLogsRelations = relations(auditLogs, ({ one }) => ({
user: one(user, {
fields: [auditLogs.userId],
diff --git a/lib/event-utils.ts b/lib/event-utils.ts
index 7c70471..674cbaa 100644
--- a/lib/event-utils.ts
+++ b/lib/event-utils.ts
@@ -1,5 +1,6 @@
+import { differenceInCalendarDays } from "date-fns";
import { CalendarNote } from "./db/schema";
-import { parseLocalDate } from "./date-utils";
+import { toLocalDate } from "./date-utils";
export function matchesRecurringEvent(
eventDate: Date,
@@ -27,16 +28,8 @@ export function matchesRecurringEvent(
if (eventDayOfWeek !== targetDayOfWeek) return false;
if (targetDate < eventDate) return false;
- // Normalize dates to midnight to avoid time component issues
- const eventMidnight = new Date(eventDate);
- eventMidnight.setHours(0, 0, 0, 0);
- const targetMidnight = new Date(targetDate);
- targetMidnight.setHours(0, 0, 0, 0);
-
- const daysDiff = Math.floor(
- (targetMidnight.getTime() - eventMidnight.getTime()) /
- (1000 * 60 * 60 * 24)
- );
+ // Calendar days, not elapsed ms: a DST switch makes one day 23 or 25 hours long
+ const daysDiff = differenceInCalendarDays(targetDate, eventDate);
return daysDiff % (7 * recurringInterval) === 0;
}
@@ -70,40 +63,6 @@ export function matchesRecurringEvent(
}
}
-// Find all events for a specific date (including recurring)
-export function findEventsForDate(
- notes: CalendarNote[],
- date: Date
-): CalendarNote[] {
- return notes.filter((note) => {
- if (note.type !== "event" || !note.date) return false;
- const dateValue = note.date;
- const noteDate =
- dateValue instanceof Date
- ? dateValue
- : typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
- ? parseLocalDate(dateValue)
- : new Date(dateValue);
-
- // Exact date match
- if (
- noteDate.getFullYear() === date.getFullYear() &&
- noteDate.getMonth() === date.getMonth() &&
- noteDate.getDate() === date.getDate()
- ) {
- return true;
- }
-
- // Recurring match
- return matchesRecurringEvent(
- noteDate,
- date,
- note.recurringPattern,
- note.recurringInterval
- );
- });
-}
-
// Find all notes for a specific date (both notes and events, including recurring)
export function findNotesForDate(
notes: CalendarNote[],
@@ -111,13 +70,7 @@ export function findNotesForDate(
): CalendarNote[] {
return notes.filter((note) => {
if (!note.date) return false;
- const dateValue = note.date;
- const noteDate =
- dateValue instanceof Date
- ? dateValue
- : typeof dateValue === "string" && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)
- ? parseLocalDate(dateValue)
- : new Date(dateValue);
+ const noteDate = toLocalDate(note.date);
// Exact date match
if (
diff --git a/lib/free-days.ts b/lib/free-days.ts
new file mode 100644
index 0000000..6a99e7e
--- /dev/null
+++ b/lib/free-days.ts
@@ -0,0 +1,20 @@
+import { differenceInCalendarDays } from "date-fns";
+import { parseLocalDate } from "@/lib/date-utils";
+
+interface StatsWindow {
+ startDate: string;
+ endDate: string;
+ daysWithShifts: number;
+}
+
+/** Days in the stats API's inclusive `YYYY-MM-DD` window without a stats-counted shift. */
+export function countFreeDays({ startDate, endDate, daysWithShifts }: StatsWindow): number | null {
+ try {
+ const periodDays =
+ differenceInCalendarDays(parseLocalDate(endDate), parseLocalDate(startDate)) + 1;
+ if (periodDays < 1) return null;
+ return Math.max(0, periodDays - daysWithShifts);
+ } catch {
+ return null;
+ }
+}
diff --git a/lib/query-client.ts b/lib/query-client.ts
index 0b80e7c..8a1c42b 100644
--- a/lib/query-client.ts
+++ b/lib/query-client.ts
@@ -1,16 +1,26 @@
import { QueryClient } from "@tanstack/react-query";
+import { isClientError } from "@/lib/api-error";
-export const REFETCH_INTERVAL = 5000; // 5s polling for live updates
+/**
+ * Polling tiers. `refetchOnWindowFocus` is what actually keeps the app feeling
+ * live — returning to a tab refetches immediately — so the intervals only have
+ * to cover a window someone is already watching.
+ */
+/** Shift-level data, which changes from another device while you watch */
+export const LIVE_REFETCH_INTERVAL = 15000;
+/** Everything else: calendars, presets, subscriptions, sync state, admin lists */
+export const BACKGROUND_REFETCH_INTERVAL = 60000;
export const queryClientConfig = {
defaultOptions: {
queries: {
- staleTime: 3000, // 3s - data considered fresh
+ staleTime: 10000,
gcTime: 300000, // 5min - cache retention
- refetchInterval: REFETCH_INTERVAL,
+ refetchInterval: BACKGROUND_REFETCH_INTERVAL,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
- retry: 3,
+ retry: (failureCount: number, error: unknown) =>
+ !isClientError(error) && failureCount < 3,
retryDelay: (attemptIndex: number) =>
Math.min(1000 * 2 ** attemptIndex, 30000),
},
diff --git a/lib/query-keys.ts b/lib/query-keys.ts
index 741ba51..dc196a1 100644
--- a/lib/query-keys.ts
+++ b/lib/query-keys.ts
@@ -36,12 +36,21 @@ export const queryKeys = {
// Admin Data
admin: {
- stats: (deps?: object) => ["admin", "stats", deps] as const,
- users: (filters?: object) => ["admin", "users", filters] as const,
- userDetails: (userId: string) => ["admin", "users", userId] as const,
- calendars: (filters?: object) => ["admin", "calendars", filters] as const,
- calendarDetails: (calendarId: string) =>
- ["admin", "calendars", calendarId] as const,
+ stats: ["admin", "stats"] as const,
+ users: {
+ all: ["admin", "users"] as const,
+ lists: ["admin", "users", "list"] as const,
+ list: (params: object) => ["admin", "users", "list", params] as const,
+ detail: (userId: string) => ["admin", "users", "detail", userId] as const,
+ },
+ calendars: {
+ all: ["admin", "calendars"] as const,
+ lists: ["admin", "calendars", "list"] as const,
+ list: (params: object) => ["admin", "calendars", "list", params] as const,
+ detail: (calendarId: string) =>
+ ["admin", "calendars", "detail", calendarId] as const,
+ },
+ auditLogsAll: ["admin", "audit-logs"] as const,
auditLogs: (filters?: object) => ["admin", "audit-logs", filters] as const,
},
@@ -56,6 +65,13 @@ export const queryKeys = {
all: ["subscriptions"] as const,
},
+ // Per-account preferences
+ userPreferences: {
+ viewSettings: (userId: string) =>
+ ["user-preferences", userId, "view-settings"] as const,
+ },
+
// User Activity Logs
+ activityLogsAll: ["activity-logs"] as const,
activityLogs: (filters?: object) => ["activity-logs", filters] as const,
} as const;
diff --git a/lib/request.ts b/lib/request.ts
deleted file mode 100644
index 87b8264..0000000
--- a/lib/request.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { getRequestConfig } from "next-intl/server";
-import { locales } from "./locales";
-
-export default getRequestConfig(async ({ requestLocale }) => {
- let locale = await requestLocale;
-
- // Ensure that the incoming locale is valid
- if (!locale || !(locales as readonly string[]).includes(locale)) {
- locale = "en";
- }
-
- return {
- locale,
- messages: (await import(`../../messages/${locale}.json`)).default,
- };
-});
diff --git a/lib/safe-return-url.ts b/lib/safe-return-url.ts
new file mode 100644
index 0000000..5bdebf2
--- /dev/null
+++ b/lib/safe-return-url.ts
@@ -0,0 +1,32 @@
+const DUMMY_ORIGIN = "https://safe-return-url.invalid";
+
+// C0/C1 controls (tab, LF, CR included) and backslashes: the URL parser strips
+// the first from anywhere in the input and treats the second as a slash.
+const UNSAFE_CHARACTERS = /[\p{Cc}\\]/u;
+
+/**
+ * Only same-origin relative paths may be used as post-login targets; anything
+ * else (absolute URLs, protocol-relative "//host", javascript:) falls back to "/".
+ */
+export function safeReturnUrl(value: string | null | undefined): string {
+ if (!value || value.length > 2048) {
+ return "/";
+ }
+ if (value[0] !== "/" || value[1] === "/") {
+ return "/";
+ }
+ if (UNSAFE_CHARACTERS.test(value)) {
+ return "/";
+ }
+
+ try {
+ const resolved = new URL(value, DUMMY_ORIGIN);
+ if (resolved.origin !== DUMMY_ORIGIN || !resolved.pathname.startsWith("/") || resolved.pathname.startsWith("//")) {
+ return "/";
+ }
+ } catch {
+ return "/";
+ }
+
+ return value;
+}
diff --git a/lib/shift-display.ts b/lib/shift-display.ts
new file mode 100644
index 0000000..e3c086e
--- /dev/null
+++ b/lib/shift-display.ts
@@ -0,0 +1,188 @@
+import { CSSProperties } from "react";
+import { isSameDay } from "date-fns";
+import { ShiftWithCalendar } from "@/lib/types";
+import { ExternalSync } from "@/lib/db/schema";
+import { calculateShiftDuration } from "@/lib/date-utils";
+
+export type ShiftSortType = "startTime" | "createdAt" | "title";
+export type ShiftSortOrder = "asc" | "desc";
+
+export interface DayLayoutOptions {
+ maxShifts?: number;
+ maxExternalShifts?: number;
+ sortType?: ShiftSortType;
+ sortOrder?: ShiftSortOrder;
+ combinedSort?: boolean;
+}
+
+export interface DayShiftLayout {
+ /** Chips to render in the cell, already sorted and capped */
+ visible: ShiftWithCalendar[];
+ /** Shifts cut by the per-day limits */
+ hiddenCount: number;
+ /** The part of hiddenCount that came from external syncs */
+ hiddenExternalCount: number;
+ /** External syncs in "minimal" mode collapse into one counter each */
+ minimalGroups: { sync: ExternalSync; shifts: ShiftWithCalendar[] }[];
+}
+
+function getShiftsForDay(
+ shifts: ShiftWithCalendar[],
+ day: Date
+): ShiftWithCalendar[] {
+ return shifts.filter((shift) => shift.date && isSameDay(shift.date as Date, day));
+}
+
+/** The day's shifts in start-time order — the shape every day view needs. */
+export function getDayShifts(
+ shifts: ShiftWithCalendar[],
+ day: Date
+): ShiftWithCalendar[] {
+ return sortShifts(getShiftsForDay(shifts, day), "startTime");
+}
+
+export function sortShifts(
+ shifts: ShiftWithCalendar[],
+ type: ShiftSortType = "startTime",
+ order: ShiftSortOrder = "asc"
+): ShiftWithCalendar[] {
+ return [...shifts].sort((a, b) => {
+ let comparison = 0;
+ switch (type) {
+ case "startTime":
+ comparison = a.startTime.localeCompare(b.startTime);
+ break;
+ case "createdAt": {
+ const aTime = a.createdAt ? new Date(a.createdAt).getTime() : 0;
+ const bTime = b.createdAt ? new Date(b.createdAt).getTime() : 0;
+ comparison = aTime - bTime;
+ break;
+ }
+ case "title":
+ comparison = a.title.localeCompare(b.title);
+ break;
+ }
+ return order === "asc" ? comparison : -comparison;
+ });
+}
+
+export function buildDayShiftLayout(
+ dayShifts: ShiftWithCalendar[],
+ externalSyncs: ExternalSync[],
+ {
+ maxShifts,
+ maxExternalShifts,
+ sortType = "createdAt",
+ sortOrder = "asc",
+ combinedSort = false,
+ }: DayLayoutOptions = {}
+): DayShiftLayout {
+ const syncById = new Map(externalSyncs.map((s) => [s.id, s]));
+ const modeOf = (shift: ShiftWithCalendar) =>
+ shift.externalSyncId
+ ? syncById.get(shift.externalSyncId)?.displayMode
+ : undefined;
+
+ const regular = sortShifts(
+ dayShifts.filter((s) => !s.syncedFromExternal),
+ sortType,
+ sortOrder
+ );
+ const external = sortShifts(
+ dayShifts.filter((s) => s.syncedFromExternal && modeOf(s) === "normal"),
+ sortType,
+ sortOrder
+ );
+
+ const shownRegular =
+ maxShifts === undefined ? regular : regular.slice(0, maxShifts);
+ const shownExternal =
+ maxExternalShifts === undefined
+ ? external
+ : external.slice(0, maxExternalShifts);
+
+ let visible: ShiftWithCalendar[];
+ if (combinedSort) {
+ const shownIds = new Set([...shownRegular, ...shownExternal].map((s) => s.id));
+ visible = sortShifts([...regular, ...external], sortType, sortOrder).filter(
+ (s) => shownIds.has(s.id)
+ );
+ } else {
+ visible = [...shownRegular, ...shownExternal];
+ }
+
+ const minimal = new Map<string, ShiftWithCalendar[]>();
+ for (const shift of dayShifts) {
+ if (shift.syncedFromExternal && shift.externalSyncId && modeOf(shift) === "minimal") {
+ const list = minimal.get(shift.externalSyncId) ?? [];
+ list.push(shift);
+ minimal.set(shift.externalSyncId, list);
+ }
+ }
+
+ return {
+ visible,
+ hiddenCount:
+ regular.length - shownRegular.length + external.length - shownExternal.length,
+ hiddenExternalCount: external.length - shownExternal.length,
+ minimalGroups: [...minimal.entries()].flatMap(([id, shifts]) => {
+ const sync = syncById.get(id);
+ return sync ? [{ sync, shifts }] : [];
+ }),
+ };
+}
+
+export function getShiftMinutes(shift: ShiftWithCalendar): number {
+ return shift.isAllDay
+ ? 0
+ : calculateShiftDuration(shift.startTime, shift.endTime);
+}
+
+export function sumShiftMinutes(shifts: ShiftWithCalendar[]): number {
+ return shifts.reduce((total, shift) => total + getShiftMinutes(shift), 0);
+}
+
+/** Shift colour for the `shift-chip` / `shift-solid` / `shift-rail` utilities. */
+export function shiftVars(color?: string | null): CSSProperties {
+ return { "--shift": color || undefined } as CSSProperties;
+}
+
+/** One-letter stamp code used where only a block fits (stamp dock, preset list, compare). */
+export function getShiftCode(title: string): string {
+ const first = Array.from(title.trim())[0];
+ return first ? first.toLocaleUpperCase() : "·";
+}
+
+const hourFormatters = new Map<string, Intl.NumberFormat>();
+
+function hourFormatter(locale: string): Intl.NumberFormat {
+ let formatter = hourFormatters.get(locale);
+ if (!formatter) {
+ formatter = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 });
+ hourFormatters.set(locale, formatter);
+ }
+ return formatter;
+}
+
+export function formatHours(
+ minutes: number,
+ locale: string,
+ { unit = true }: { unit?: boolean } = {}
+): string {
+ const hours = hourFormatter(locale).format(minutes / 60);
+ return unit ? `${hours}h` : hours;
+}
+
+export function presetTime(
+ preset: { isAllDay: boolean; startTime: string; endTime: string },
+ allDayLabel: string
+): string {
+ return preset.isAllDay ? allDayLabel : formatTimeRange(preset);
+}
+
+export function formatTimeRange(times: {
+ startTime: string;
+ endTime: string;
+}): string {
+ return `${times.startTime.slice(0, 5)} – ${times.endTime.slice(0, 5)}`;
+}
diff --git a/lib/types.ts b/lib/types.ts
index 46088fe..2f559e1 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -1,3 +1,5 @@
+import type { CalendarViewSettings } from "./view-settings";
+
// Re-export types from Drizzle schema
export type { Calendar, Shift, ExternalSync } from "./db/schema";
@@ -7,6 +9,8 @@ export interface CalendarWithCount {
color: string;
ownerId?: string | null;
guestPermission?: "none" | "read" | "write";
+ /** The calendar's own view; null means everyone sees their personal view */
+ viewSettings?: CalendarViewSettings | null;
createdAt: Date | null;
updatedAt: Date | null;
_count?: number;
diff --git a/lib/utils.ts b/lib/utils.ts
index a5ef193..cd38bc9 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -4,3 +4,17 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+
+/** Up to two initials from a name, falling back to the e-mail. */
+export function getUserInitials(user: { name?: string | null; email?: string }): string {
+ const source = user.name?.trim();
+ if (source) {
+ return source
+ .split(/\s+/)
+ .map((part) => part[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+ }
+ return user.email?.slice(0, 2).toUpperCase() || "?";
+}
diff --git a/lib/view-settings.ts b/lib/view-settings.ts
new file mode 100644
index 0000000..af1e4b9
--- /dev/null
+++ b/lib/view-settings.ts
@@ -0,0 +1,125 @@
+import { PRESET_COLORS } from "@/lib/constants";
+import type { ShiftSortOrder, ShiftSortType } from "@/lib/shift-display";
+
+/** Display options a calendar can pin for everyone with access to it. */
+export interface CalendarViewSettings {
+ /** null shows as many as fit into the cell */
+ shiftsPerDay: number | null;
+ externalShiftsPerDay: number | null;
+ showShiftNotes: boolean;
+ sortType: ShiftSortType;
+ sortOrder: ShiftSortOrder;
+ combinedSort: boolean;
+ /** 0 = Sunday … 6 = Saturday, unique and sorted */
+ highlightedWeekdays: number[];
+ highlightColor: string;
+}
+
+/** A user's own view; the stamp bar is never taken over by a calendar. */
+export interface PersonalViewSettings extends CalendarViewSettings {
+ showStampBar: boolean;
+}
+
+export const SHIFTS_PER_DAY_MAX = 3;
+
+const SORT_TYPES: readonly ShiftSortType[] = ["startTime", "createdAt", "title"];
+const SORT_ORDERS: readonly ShiftSortOrder[] = ["asc", "desc"];
+const HEX_COLOR = /^#[0-9a-f]{6}$/;
+const LEGACY_DEFAULT_HIGHLIGHT_COLOR = "#fbbf24";
+
+export const DEFAULT_HIGHLIGHT_COLOR =
+ PRESET_COLORS.find((c) => c.name === "Amber")?.value ?? "#d97706";
+
+export const DEFAULT_CALENDAR_VIEW_SETTINGS: CalendarViewSettings = {
+ shiftsPerDay: 3,
+ externalShiftsPerDay: 3,
+ showShiftNotes: false,
+ sortType: "createdAt",
+ sortOrder: "asc",
+ combinedSort: false,
+ highlightedWeekdays: [],
+ highlightColor: DEFAULT_HIGHLIGHT_COLOR,
+};
+
+export const DEFAULT_PERSONAL_VIEW_SETTINGS: PersonalViewSettings = {
+ ...DEFAULT_CALENDAR_VIEW_SETTINGS,
+ showStampBar: true,
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function sanitizeLimit(value: unknown, fallback: number | null): number | null {
+ if (value === null) return null;
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ const limit = Math.max(1, Math.round(value));
+ // Month cells show at most four rows, so any higher limit behaves like filling the cell
+ return limit > SHIFTS_PER_DAY_MAX ? null : limit;
+}
+
+function sanitizeBoolean(value: unknown, fallback: boolean): boolean {
+ return typeof value === "boolean" ? value : fallback;
+}
+
+function sanitizeEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
+ return allowed.includes(value as T) ? (value as T) : fallback;
+}
+
+function sanitizeWeekdays(value: unknown, fallback: number[]): number[] {
+ if (!Array.isArray(value)) return fallback;
+ const days = value.filter(
+ (d): d is number => typeof d === "number" && Number.isInteger(d) && d >= 0 && d <= 6
+ );
+ return Array.from(new Set(days)).sort((a, b) => a - b);
+}
+
+function sanitizeColor(value: unknown, fallback: string): string {
+ if (typeof value !== "string") return fallback;
+ const color = value.trim().toLowerCase();
+ if (color === LEGACY_DEFAULT_HIGHLIGHT_COLOR) return DEFAULT_HIGHLIGHT_COLOR;
+ return HEX_COLOR.test(color) ? color : fallback;
+}
+
+/** Whitelists and normalises calendar keys; anything missing or invalid falls back to the default. */
+export function sanitizeCalendarViewSettings(input: unknown): CalendarViewSettings {
+ const src = isRecord(input) ? input : {};
+ const d = DEFAULT_CALENDAR_VIEW_SETTINGS;
+ return {
+ shiftsPerDay: sanitizeLimit(src.shiftsPerDay, d.shiftsPerDay),
+ externalShiftsPerDay: sanitizeLimit(src.externalShiftsPerDay, d.externalShiftsPerDay),
+ showShiftNotes: sanitizeBoolean(src.showShiftNotes, d.showShiftNotes),
+ sortType: sanitizeEnum(src.sortType, SORT_TYPES, d.sortType),
+ sortOrder: sanitizeEnum(src.sortOrder, SORT_ORDERS, d.sortOrder),
+ combinedSort: sanitizeBoolean(src.combinedSort, d.combinedSort),
+ highlightedWeekdays: sanitizeWeekdays(src.highlightedWeekdays, d.highlightedWeekdays),
+ highlightColor: sanitizeColor(src.highlightColor, d.highlightColor),
+ };
+}
+
+export function sanitizePersonalViewSettings(input: unknown): PersonalViewSettings {
+ const src = isRecord(input) ? input : {};
+ return {
+ ...sanitizeCalendarViewSettings(src),
+ showStampBar: sanitizeBoolean(src.showStampBar, DEFAULT_PERSONAL_VIEW_SETTINGS.showStampBar),
+ };
+}
+
+export function calendarViewSettingsEqual(a: CalendarViewSettings, b: CalendarViewSettings): boolean {
+ const x = sanitizeCalendarViewSettings(a);
+ const y = sanitizeCalendarViewSettings(b);
+ return (Object.keys(x) as (keyof CalendarViewSettings)[]).every((key) =>
+ key === "highlightedWeekdays"
+ ? x.highlightedWeekdays.join(",") === y.highlightedWeekdays.join(",")
+ : x[key] === y[key]
+ );
+}
+
+/** A calendar's own view replaces the personal one as a whole; the stamp bar stays personal. */
+export function resolveViewSettings(
+ personal: PersonalViewSettings,
+ calendarView: unknown
+): PersonalViewSettings {
+ if (!isRecord(calendarView)) return personal;
+ return { ...sanitizeCalendarViewSettings(calendarView), showStampBar: personal.showStampBar };
+}
diff --git a/messages/cs.json b/messages/cs.json
index bc822a1..047a229 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -12,15 +12,11 @@
"save": "Uložit",
"saving": "Ukládání...",
"close": "Zavřít",
- "optional": "(volitelné)",
"delete": "Smazat",
"loading": "Načítání...",
- "add": "Přidat",
- "adding": "Přidávání...",
"or": "nebo",
"next": "Další",
"previous": "Předchozí",
- "of": "z",
"unsavedChanges": "Neuložené změny",
"unsavedChangesDescription": "Máte neuložené změny. Opravdu chcete zavřít bez uložení?",
"closeWithoutSaving": "Zavřít bez uložení",
@@ -30,7 +26,6 @@
"createError": "Nepodařilo se vytvořit {item}",
"updateError": "Nepodařilo se aktualizovat {item}",
"deleteError": "Nepodařilo se smazat {item}",
- "deleteConfirm": "Opravdu smazat {item} „{name}“?",
"shifts": "Směny",
"success": "Úspěch",
"error": "Chyba",
@@ -58,15 +53,6 @@
"deleteSelected": "Smazat vybrané",
"viewAll": "Zobrazit vše",
"viewDetails": "Zobrazit podrobnosti",
- "weekday": {
- "monday": "Po",
- "tuesday": "Út",
- "wednesday": "St",
- "thursday": "Čt",
- "friday": "Pá",
- "saturday": "So",
- "sunday": "Ne"
- },
"labels": {
"name": "Jméno",
"email": "E-mail",
@@ -97,8 +83,7 @@
"users": "Uživatelé"
},
"status": {
- "active": "Aktivní",
- "inactive": "Neaktivní"
+ "active": "Aktivní"
},
"roles": {
"admin": "Správce",
@@ -106,12 +91,14 @@
"user": "Uživatel"
},
"time": {
- "never": "Nikdy",
"lastActive": "Naposledy aktivní"
},
"filters": {
"allSeverities": "Všechny závažnosti",
- "clearFilters": "Vymazat filtry"
+ "clearFilters": "Vymazat filtry",
+ "title": "Filtry",
+ "done": "Hotovo",
+ "remove": "Odebrat {filter}"
},
"severity": {
"info": "Informace",
@@ -120,7 +107,6 @@
"critical": "Kritické"
},
"stats": {
- "statistics": "Statistiky",
"created": "Vytvořeno"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Barva",
"notesLabel": "Poznámky (volitelné)",
"notesPlaceholder": "Další informace...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organizujte své směny"
+ "title": "BetterShift"
},
"calendar": {
"title": "Kalendář",
"create": "Vytvořit nový kalendář",
"createDescription": "Vytvořte nový kalendář pro organizaci svých směn",
- "selectDescription": "Vyberte kalendář pro správu svých směn",
"name": "Název kalendáře",
"myCalendars": "Moje kalendáře",
"sharedCalendars": "Sdílené kalendáře",
"tokenCalendars": "Přes přístupový odkaz",
"publicCalendars": "Veřejné kalendáře",
- "select": "Váš kalendář BetterShift",
"deleteCalendar": "Smazat kalendář",
"deleteWarning": "Smazány budou také všechny směny, předvolby a poznámky.",
- "settings": "Nastavení kalendáře „{name}“",
- "settingsDescription": "Přizpůsobte název a barvu",
"compare": "Porovnat kalendáře",
"compareMode": "Režim porovnání",
- "exitCompare": "Ukončit porovnání",
"selectToCompare": "Vyberte kalendáře k porovnání",
"selectToCompareDescription": "Vyberte 2–3 kalendáře pro zobrazení vedle sebe",
"compareSelected": "{count} vybráno",
"startComparing": "Zahájit porovnání",
- "mobileNotOptimized": "Zobrazení porovnání není optimalizováno pro mobil. Pro nejlepší zážitek použijte prosím větší obrazovku.",
"shareLink": "Sdílet odkaz",
- "shareLinkDescription": "Zkopírovat odkaz na zobrazení porovnání",
"browseCalendars": "Sdílené kalendáře",
"browseCalendarsDescription": "Objevujte a spravujte odběry kalendářů",
"subscribe": "Odebírat",
- "subscribed": "Odebíráno",
"noPublicCalendars": "Nejsou k dispozici žádné veřejné kalendáře",
"noSharedCalendars": "Zatím s vámi nebyly sdíleny žádné kalendáře",
"noHiddenCalendars": "Žádné skryté kalendáře",
@@ -201,81 +177,45 @@
"customDescription": "Vyberte vlastní barvu pomocí výběru barev"
},
"note": {
- "create": "Vytvořit {item}",
- "edit": "Upravit {item}",
"note": "Poznámka",
"placeholder": "např. Ranní směna kvůli odpolední schůzce...",
- "hintMobile": "Pro přidání nebo úpravu poznámky či události podržte prst na dni v kalendáři.",
- "hintDesktop": "Pro přidání nebo úpravu poznámky či události klikněte na den v kalendáři pravým tlačítkem.",
"type": "Typ",
- "typeNote": "Poznámky",
"typeEvent": "Události",
"eventColor": "Barva události",
- "eventTitle": "Název události",
"eventPlaceholder": "např. Vánoce, narozeniny...",
- "recurring": "Opakování",
- "recurringNone": "Neopakovat",
- "recurringCustom": "Vlastní",
- "recurringEveryWeeks": "Každé {count} týdny",
- "recurringEveryMonths": "Každé {count} měsíce",
"customInterval": "Interval",
"every": "Každé",
- "weeks": "týdny",
- "months": "měsíce",
- "multipleEntries": "{count} záznamů",
"noEntries": "Nejsou k dispozici žádné poznámky ani události",
"recurringEditWarning": "Toto je opakující se událost. Změny se projeví u všech výskytů."
},
"shift": {
"create": "Nová směna",
- "createDescription": "Přidejte do kalendáře novou směnu",
"edit": "Upravit směnu",
- "editDescription": "Aktualizujte podrobnosti směny",
"date": "Datum",
- "startTime": "Čas začátku",
- "endTime": "Čas konce",
"titlePlaceholder": "např. Ranní směna",
"titleLabel": "Název",
- "allDay": "Celý den",
"allDayShift": "Celodenní směna",
"noShiftsInMonth": "Tento měsíc žádné směny",
- "noShiftsInMonthDescription": "Přidejte směny kliknutím na dny v kalendáři výše.",
- "shift_one": "směna",
- "selectPreset": "Vybrat předvolbu",
- "none": "Žádná"
+ "shift_one": "směna"
},
"preset": {
"preset": "Předvolba",
- "createNew": "Vytvořit novou předvolbu",
- "createYourFirst": "Vytvořte svou první předvolbu",
"edit": "Upravit předvolbu",
- "manage": "Spravovat předvolby",
- "manageDescription": "Upravte nebo smažte své předvolby směn",
"saveAsPreset": "Uložit jako předvolbu",
"presetName": "Název předvolby",
"presetNamePlaceholder": "např. Ranní směna, večerní směna...",
"noPresets": "Zatím žádné předvolby směn",
- "createFirstDescription": "Vytvořte svou první předvolbu pro rychlé přidávání směn do kalendáře. Předvolby uloží vaše často používané časy a podrobnosti směn.",
"deleteConfirm": "Smazat tuto předvolbu? Tím se smažou i všechny směny vytvořené z této předvolby.",
- "primaryPresets": "Primární předvolby",
- "secondaryPresets": "Sekundární předvolby",
- "secondary": "Sekundární",
- "markAsSecondary": "Označit jako sekundární (ve výchozím stavu sbalené)",
- "hideFromStats": "Skrýt ze statistik",
- "hideFromStatsHint": "Vyloučit směny z této předvolby ze statistik",
- "showPresets": "Zobrazit předvolby",
- "hidePresets": "Skrýt předvolby",
- "hiddenFromStats": "Skryto ze statistik",
- "cannotAddPresetHint": "Tato předvolba patří jinému kalendáři a nelze ji sem přidat."
+ "secondary": "Další",
+ "hideFromStats": "Skrýt ze statistik"
},
"view": {
- "settingsTitle": "Nastavení zobrazení",
- "settingsDescription": "Přizpůsobte, jak se směny zobrazují ve všech kalendářích",
+ "settingsTitle": "Moje zobrazení",
+ "settingsDescription": "Vaše osobní zobrazení. Platí pro všechny kalendáře bez vlastního zobrazení a vidíte ho jen vy.",
"shiftsPerDay": "Běžné směny za den",
- "shiftsPerDayHint": "Maximální počet běžných směn zobrazených za den",
+ "shiftsPerDayHint": "Další se zobrazí jako „+N“. Auto zobrazí tolik, kolik se vejde do buňky dne.",
"externalShiftsPerDay": "Externí směny za den",
- "externalShiftsPerDayHint": "Maximální počet směn z externích kalendářů zobrazených za den",
- "showAll": "Vše",
+ "externalShiftsPerDayHint": "Platí pro externí kalendáře zobrazené „Jako vlastní“. Další se zobrazí jako „+N“.",
"sortOptions": "Možnosti řazení",
"sortBy": "Řadit podle",
"sortByStartTime": "Času začátku",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Sestupně",
"combinedSort": "Řadit všechny směny dohromady",
"combinedSortHint": "Řadit běžné a externí směny dohromady místo odděleně",
- "displayOptions": "Možnosti zobrazení",
"showNotes": "Zobrazit poznámky směn",
- "showNotesHint": "Zobrazit poznámky směn v mřížce kalendáře",
- "showFullTitles": "Zobrazit celé názvy směn",
- "showFullTitlesHint": "Zobrazit úplné názvy směn bez zkracování",
+ "showNotesHint": "Poznámka směny jako druhý řádek v měsíčním zobrazení",
"dayHighlighting": "Zvýraznění dnů",
"highlightWeekends": "Zvýraznit víkendy",
"highlightWeekendsHint": "Zvýraznit soboty a neděle barvou",
@@ -303,7 +240,17 @@
"friday": "Pátek",
"saturday": "Sobota",
"sunday": "Neděle",
- "highlightColor": "Barva zvýraznění"
+ "highlightColor": "Barva zvýraznění",
+ "density": "Hustota",
+ "showPresetBar": "Zobrazit lištu šablon",
+ "showPresetBarHint": "Lišta šablon pod nebo nad kalendářem",
+ "settingsDescriptionLocal": "Vaše osobní zobrazení na tomto zařízení. Platí pro všechny kalendáře bez vlastního zobrazení.",
+ "overriddenByCalendar": "„{calendar}“ má vlastní zobrazení. Vaše osobní zobrazení tam neplatí.",
+ "calendarOwn": "Vlastní zobrazení pro tento kalendář",
+ "calendarOwnHint": "Platí pro všechny, kdo mají k tomuto kalendáři přístup.",
+ "calendarOffNote": "Každý tu vidí své osobní zobrazení. To vaše nastavíte v „Moje zobrazení“.",
+ "calendarLocked": "Nastaveno pro tento kalendář. Změnit ho mohou jen ti, kdo kalendář spravují.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Statistiky směn",
@@ -329,52 +276,16 @@
"connected": "Připojeno k serveru",
"disconnected": "Spojení se serverem bylo ztraceno"
},
- "onboarding": {
- "welcome": "Vítejte v BetterShift",
- "description": "Vytvořte svůj první kalendář pro správu směn.",
- "createCalendar": "Vytvořit kalendář"
- },
- "guestEmptyState": {
- "title": "Nejsou k dispozici žádné veřejné kalendáře",
- "description": "Momentálně nejsou sdíleny žádné veřejné kalendáře. Pro vytváření a správu vlastních kalendářů se prosím přihlaste.",
- "loginButton": "Přejít na přihlášení"
- },
- "footer": {
- "version": "Verze",
- "github": "GitHub",
- "support": "Podpora"
- },
- "theme": {
- "switchToLight": "Přepnout na světlý režim",
- "switchToDark": "Přepnout na tmavý režim"
- },
"externalSync": {
- "manageTitle": "Spravovat externí kalendáře",
- "manageDescription": "Přidávejte a spravujte více externích kalendářů pro tento kalendář",
"noSyncs": "Zatím nebyly přidány žádné externí kalendáře",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Vlastní kalendář",
"importMethod": "Způsob importu",
- "importMethodUrl": "URL (lze synchronizovat)",
- "importMethodFile": "Nahrát soubor (jednorázový import)",
"importMethodUrlHint": "URL externího kalendáře (iCloud, Google nebo jiné ICS URL)",
"importMethodFileHint": "Jednorázově importovat soubor ICS",
"fileLabel": "Soubor ICS",
- "fileSelected": "Soubor vybrán",
"oneTimeImport": "Jednorázový import",
- "displayMode": "Zobrazit synchronizované směny",
- "displayModeNormal": "Normální (zobrazit všechny směny)",
- "displayModeMinimal": "Minimální (zobrazit pouze počet)",
- "displayModeHint": "Vyberte, jak se mají synchronizované směny zobrazovat v kalendáři",
- "addNewSync": "Přidat nový externí kalendář",
- "editSync": "Upravit externí kalendář",
- "colorHint": "Vyberte barvu pro všechny importované směny",
- "hideCalendar": "Skrýt kalendář",
- "hideCalendarHint": "Skrýt směny z tohoto kalendáře",
- "hideFromStats": "Skrýt ze statistik",
- "hideFromStatsHint": "Vyloučit směny z tohoto kalendáře ze statistik",
- "lastSynced": "Naposledy synchronizováno",
"delete": "Smazat externí kalendář",
"deleteConfirm": "Smazat tento externí kalendář? Všechny importované směny budou odstraněny.",
"hintsTitle": "Jak najít URL svého kalendáře",
@@ -384,8 +295,6 @@
"hintICloud": "Otevřete iCloud.com → Kalendář → Klikněte na ikonu sdílení vedle kalendáře → Zapněte „Veřejný kalendář“ → Zkopírujte URL webcal:// a vložte ji sem.",
"hintGoogle": "Otevřete Kalendář Google → Nastavení → Vyberte svůj kalendář → Přejděte na „Tajná adresa ve formátu iCal“ → Zkopírujte URL a vložte ji sem.",
"hintCustom": "Funguje jakýkoli veřejně dostupný kalendář ICS. URL musí začínat https:// nebo webcal:// a končit na .ics. Příklad: https://example.com/calendar.ics",
- "autoSyncLabel": "Automatická synchronizace",
- "autoSyncHint": "Vyberte, jak často se má tento kalendář automaticky synchronizovat",
"autoSyncManual": "Ručně",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automatická",
"syncTypeManual": "Ruční",
"noChanges": "Žádné změny",
- "errorMessage": "Chybová zpráva",
"filterAll": "Zobrazit vše",
"filterSuccess": "Pouze úspěšné",
"filterError": "Pouze chyby",
@@ -415,9 +323,6 @@
"viewOnGitHub": "Zobrazit na GitHubu"
},
"export": {
- "title": "Exportovat kalendář",
- "description": "Exportujte svůj kalendář jako soubor ICS nebo PDF",
- "exportCalendar": "Exportovat kalendář",
"formatLabel": "Formát exportu",
"icsFormat": "ICS (soubor kalendáře)",
"pdfFormat": "PDF (dokument)",
@@ -432,34 +337,19 @@
"download": "Stáhnout",
"multiCalendar": "Exportovat více kalendářů",
"multiCalendarHint": "Zkombinujte směny z více kalendářů do jednoho souboru exportu",
- "selectCalendars": "Vyberte kalendáře",
- "selectCalendarsDescription": "Vyberte, které kalendáře zahrnout do exportu",
"selectedCount": "{count, plural, =0 {Nevybrány žádné kalendáře} =1 {Vybrán 1 kalendář} few {Vybrány # kalendáře} other {Vybráno # kalendářů}}",
"selectAtLeastOne": "Vyberte prosím alespoň jeden kalendář"
},
"update": {
- "available": "Dostupná aktualizace",
- "newVersion": "Je dostupná verze {version}",
- "viewChangelog": "Zobrazit seznam změn"
+ "newVersion": "Je dostupná verze {version}"
},
"auth": {
"login": "Přihlásit se",
- "loginTitle": "Přihlaste se do BetterShift",
- "loginDescription": "Přihlaste se svým účtem nebo použijte jednoho z poskytovatelů níže",
"register": "Registrovat se",
- "registerTitle": "Vytvořit účet",
- "registerDescription": "Vytvořte si nový účet a začněte",
"logout": "Odhlásit se",
"profile": "Profil",
- "profileTitle": "Váš profil",
- "profileDescription": "Spravujte nastavení a předvolby svého účtu",
- "profileBasicInfoDescription": "Základní informace o vašem účtu",
- "changePasswordDescription": "Aktualizujte své heslo pro zabezpečení účtu",
- "connectedAccountsDescription": "Spravujte své propojené poskytovatele OAuth",
"dangerZone": "Nebezpečná zóna",
- "dangerZoneDescription": "Nevratné akce, které ovlivňují váš účet",
"logoutDescription": "Odhlásit se z aktuální relace",
- "deleteAccountDescription": "Trvale smazat váš účet a všechna data",
"noConnectedAccounts": "Zatím žádné propojené účty",
"emailPasswordAuth": "E-mail/heslo",
"emailPlaceholder": "[email protected]",
@@ -468,13 +358,9 @@
"confirmPasswordLabel": "Potvrzení hesla",
"enterPassword": "Zadejte heslo",
"namePlaceholder": "Vaše jméno",
- "continueWith": "Pokračovat přes {provider}",
- "alreadyHaveAccount": "Už máte účet?",
"noAccountYet": "Ještě nemáte účet?",
"changePassword": "Změnit heslo",
"deleteAccount": "Smazat účet",
- "editProfile": "Upravit profil",
- "editProfileDescription": "Aktualizujte své jméno, e-mail a profilový obrázek",
"profileUpdated": "Profil byl úspěšně aktualizován",
"profilePicture": "Profilový obrázek",
"avatarHint": "Max. 5 MB. Podporované formáty: JPEG, PNG, GIF, WebP",
@@ -503,47 +389,27 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Spravujte svá přihlášená zařízení a relace",
"noActiveSessions": "Žádné aktivní relace",
- "browser": "Prohlížeč",
- "operatingSystem": "OS",
- "logoutAllDevices": "Odhlásit ze všech ostatních zařízení",
"sessionsRevokedCount": "Odhlášeno z {count} zařízení"
},
"system": {
"unavailable": "Systém není dostupný",
- "unavailableDescription": "Systém je momentálně nedostupný kvůli kritické chybě. Zkuste to prosím znovu později nebo kontaktujte správce.",
- "unavailableRetry": "Obnovte prosím tuto stránku a zkuste to znovu, nebo se vraťte později."
+ "unavailableDescription": "Systém je momentálně nedostupný kvůli kritické chybě. Zkuste to prosím znovu později nebo kontaktujte správce."
},
"guest": {
"viewingAsGuest": "Prohlížíte si jako host",
"bannerMessage": "Tento kalendář si prohlížíte jako host. Pro plný přístup se přihlaste.",
- "loginForFullAccess": "Přihlaste se pro plný přístup",
"cannotEdit": "V režimu pouze pro čtení nelze upravovat"
},
"share": {
- "manageSharing": "Spravovat sdílení",
- "manageSharingDescription": "Určete, kdo má přístup k „{name}“",
- "userShares": "Sdílení s uživateli",
"publicAccess": "Veřejný přístup",
- "accessLinks": "Přístupové odkazy",
"public": "Veřejné",
"links": "Odkazy",
"share": "sdílení",
- "sharedBy": "Sdílel(a)",
- "sharedOn": "Sdíleno dne",
- "addUser": "Přidat uživatele",
- "addUserDescription": "Vyhledejte uživatele, se kterým chcete tento kalendář sdílet",
"searchUser": "Hledat uživatele",
"searchUserPlaceholder": "Zadejte jméno nebo e-mail...",
- "selectedUser": "Vybraný uživatel",
- "noShares": "Zatím nemá přístup žádný uživatel",
"noSharesDescription": "Sdílejte tento kalendář s ostatními uživateli pro spolupráci",
- "userSharesDescription": "Spravujte, kdo má přístup k tomuto kalendáři",
- "publicAccessDescription": "Určete veřejný přístup pro přihlášené uživatele a hosty",
- "publicPermissionNoneDesc": "Bez výslovného sdílení nemá ke kalendáři přístup nikdo",
- "publicPermissionReadDesc": "Kalendář může zobrazit jakýkoli přihlášený uživatel",
- "publicPermissionWriteDesc": "Kalendář může zobrazit a upravovat jakýkoli přihlášený uživatel",
+ "publicPermissionNoneDesc": "Přístup máte jen vy, pozvaní lidé a držitelé přístupového odkazu.",
"shareAdded": "Kalendář byl úspěšně sdílen",
"shareUpdated": "Oprávnění bylo úspěšně aktualizováno",
"shareRemoved": "Přístup byl úspěšně odebrán",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "Odebrat přístup ke kalendáři?",
"removeShareConfirmDesc": "Opravdu chcete odebrat přístup uživateli {user}? Už nebude moci tento kalendář zobrazit ani upravovat.",
"you": "Vy",
- "sharedWithYou": "Sdíleno s vámi"
+ "sharedWithYou": "Sdíleno s vámi",
+ "publicPermissionReadDescGuestsOn": "Kalendář může zobrazit kdokoli, i bez účtu. Přihlášení uživatelé si ho přidají přes „Sdílené kalendáře“.",
+ "publicPermissionWriteDescGuestsOn": "Kalendář může zobrazit a upravovat kdokoli, i bez účtu. Přihlášení uživatelé si ho přidají přes „Sdílené kalendáře“.",
+ "publicPermissionReadDescGuestsOff": "Přihlášení uživatelé této instance si kalendář mohou přidat a zobrazit přes „Sdílené kalendáře“. Bez účtu přístup není možný, protože přístup pro hosty je na této instanci vypnutý.",
+ "publicPermissionWriteDescGuestsOff": "Přihlášení uživatelé této instance si kalendář mohou přidat, zobrazit a upravovat přes „Sdílené kalendáře“. Bez účtu přístup není možný, protože přístup pro hosty je na této instanci vypnutý.",
+ "publicAccessDescriptionGuestsOn": "Určete veřejný přístup pro přihlášené uživatele a návštěvníky bez účtu.",
+ "publicAccessDescriptionGuestsOff": "Určete veřejný přístup pro přihlášené uživatele této instance."
},
"token": {
"accessLinks": "Přístupové odkazy",
- "accessLinksDescription": "Sdílejte tento kalendář pomocí zabezpečených odkazů",
- "createLink": "Vytvořit odkaz",
- "createFirstLink": "Vytvořit první odkaz",
- "noTokensYet": "Zatím žádné přístupové odkazy",
- "noTokensDescription": "Vytvořte odkaz pro sdílení, abyste poskytli přístup ostatním uživatelům",
"unnamed": "Bez názvu",
- "namePlaceholder": "např. Rodinný odkaz, pracovní tým",
"token": "Token",
- "tokenValue": "Hodnota tokenu",
- "readOnlyDescription": "Zobrazit směny a poznámky",
- "editDescription": "Vytvářet a upravovat směny",
- "expiration": "Platnost",
- "expires": "Vyprší",
- "expired": "Vypršelo",
"expiration1Day": "1 den",
"expiration7Days": "7 dní",
"expiration30Days": "30 dní",
- "expirationNever": "Nikdy",
- "expiresOn": "Vyprší dne",
- "usage": "Použití",
"usedCount": "{count, plural, =0 {Nikdy nepoužito} =1 {Použito jednou} other {Použito #×}}",
- "neverUsed": "Nikdy nepoužito",
"enable": "Povolit",
"disable": "Zakázat",
"revoke": "Zrušit",
"revokeConfirm": "Zrušit přístupový odkaz?",
- "revokeConfirmDescription": "Opravdu chcete zrušit „{name}“? Kdokoli používající tento odkaz okamžitě ztratí přístup.",
- "generate": "Vygenerovat odkaz",
- "shareLink": "Sdílet odkaz",
- "linkCreated": "Odkaz vytvořen!",
- "linkCreatedDescription": "Váš odkaz pro sdílení byl úspěšně vytvořen",
- "saveWarning": "Uložte si tento odkaz nyní – znovu se nezobrazí!",
- "shareInfo": "Kdokoli s tímto odkazem může přistupovat k vašemu kalendáři s uvedenou úrovní oprávnění",
- "accessedViaLink": "Přístup přes odkaz pro sdílení",
- "linkName": "Název odkazu",
- "createLinkDescription": "Vytvořte sdílitelný odkaz pro poskytnutí přístupu k tomuto kalendáři ostatním"
+ "revokeConfirmDescription": "Opravdu chcete zrušit „{name}“? Kdokoli používající tento odkaz okamžitě ztratí přístup."
},
"rateLimit": {
"title": "Příliš mnoho požadavků",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Protokol aktivity",
- "description": "Zobrazte aktivitu svého účtu a bezpečnostní události",
+ "description": "Přihlášení, změny a bezpečnostní události vašeho účtu",
"noLogs": "Zatím nebyla zaznamenána žádná aktivita",
"eventType": "Typ události",
"resource": "Zdroj",
"details": "Podrobnosti",
"clearAll": "Vymazat vše",
- "refresh": "Obnovit",
- "refreshed": "Protokol aktivity byl obnoven",
"confirmClear": "Opravdu chcete vymazat všechny protokoly aktivity? Tuto akci nelze vrátit zpět.",
- "totalLogs": "{count} protokolů celkem",
+ "totalLogs": "{count, plural, one {# záznam} few {# záznamy} other {# záznamů}}",
"showingResults": "Zobrazeno {start}–{end} z {total}",
"searchPlaceholder": "Hledat podle akce, zdroje nebo ID...",
"noMetadata": "Nejsou k dispozici žádné další podrobnosti",
@@ -622,7 +467,8 @@
"auth": "Ověřování",
"sync": "Synchronizace",
"security": "Zabezpečení",
- "calendar": "Kalendář"
+ "calendar": "Kalendář",
+ "heading": "Události"
},
"admin": {
"title": "Panel správce",
@@ -630,7 +476,6 @@
"dashboard": "Přehled",
"usersMenu": "Uživatelé",
"calendarsMenu": "Kalendáře",
- "orphanedCalendars": "Osiřelé kalendáře",
"auditLogs": "Protokoly auditu",
"backToApp": "Zpět do aplikace",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Sbalit postranní panel",
"accessDenied": "Vyžadován přístup správce",
"stats": {
- "totalUsers": "Uživatelé celkem",
- "totalCalendars": "Kalendáře celkem",
- "orphanedCalendars": "Osiřelé kalendáře",
- "totalShifts": "Směny celkem",
- "activeShares": "Aktivní sdílení",
- "recentActivity": "Nedávná aktivita",
"usersByRole": "{superadmin} superadmin, {admin} správců, {user} uživatelů",
- "calendarsDescription": "Kalendáře s vlastníky celkem",
- "orphanedDescription": "Kalendáře bez vlastníka",
"sharesDescription": "{user} sdílení s uživateli, {token} sdílení tokenem",
- "shiftsDescription": "Směny napříč všemi kalendáři celkem",
- "last7Days": "Posledních 7 dní",
- "needsAttention": "Vyžaduje pozornost"
+ "last7Days": "Posledních 7 dní"
},
"systemInfo": {
"title": "Informace o systému",
- "description": "Aktuální verze systému a podrobnosti o sestavení",
"version": "Verze",
"buildDate": "Datum sestavení",
"commitHash": "Hash commitu",
@@ -666,29 +500,20 @@
"development": "Vývoj",
"unknown": "Neznámé"
},
- "dashboardDescription": "Vítejte v panelu správce BetterShift",
"orphanedCalendarsWarning": "Zjištěny osiřelé kalendáře",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {Existuje 1 kalendář bez vlastníka} few {Existují # kalendáře bez vlastníka} other {Existuje # kalendářů bez vlastníka}}. Přiřaďte je prosím uživatelům.",
- "manageOrphanedCalendars": "Spravovat osiřelé kalendáře",
"recentActivityDescription": "Nejnovější protokoly aktivity související se správou a zabezpečením",
"statsFetchError": "Nepodařilo se načíst statistiky",
- "userManagement": "Správa uživatelů",
- "userManagementDescription": "Spravujte uživatelské účty a oprávnění",
"searchUsers": "Hledat podle jména nebo e-mailu...",
"allRoles": "Všechny role",
"allStatuses": "Všechny stavy",
"banned": "Zablokováno",
"role": "Role",
"calendarsCount": "Kalendáře",
- "page": "stránka",
- "usersCount": "{count, plural, =0 {Žádní uživatelé} =1 {1 uživatel} few {# uživatelé} other {# uživatelů}}",
"neverActive": "Nikdy",
"editUser": "Upravit uživatele",
- "editUserDescription": "Aktualizujte informace a oprávnění uživatele",
"userDetails": "Podrobnosti o uživateli",
- "userDetailsDescription": "Zobrazit podrobné informace o uživateli",
"ownedCalendars": "Vlastněné kalendáře",
- "joined": "Připojil(a) se",
"banUser": "Zablokovat uživatele",
"banUserConfirm": "Zablokovat uživatele {name}?",
"banWarning": "Uživatel bude okamžitě odhlášen a nebude se moci přihlásit, dokud nebude odblokován.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "Změna role uživatele okamžitě ovlivní jeho oprávnění",
"calendars": {
- "title": "Správa kalendářů",
- "description": "Spravujte všechny kalendáře v systému",
"owner": "Vlastník",
"updated": "Aktualizováno",
"guestPermission": "Oprávnění hosta",
@@ -736,8 +559,6 @@
"orphanedOnly": "Pouze osiřelé",
"withOwner": "S vlastníkem",
"searchPlaceholder": "Hledat podle názvu...",
- "calendarsCount": "{count, plural, =0 {Žádné kalendáře} =1 {1 kalendář} few {# kalendáře} other {# kalendářů}}",
- "selectedCount": "{count, plural, =1 {1 kalendář vybrán} few {# kalendáře vybrány} other {# kalendářů vybráno}}",
"transferSelected": "Převést vybrané",
"clearSelection": "Zrušit výběr",
"noCalendarsFound": "Nebyly nalezeny žádné kalendáře",
@@ -748,19 +569,13 @@
"transferOwnership": "Převést vlastnictví",
"deleteCalendar": "Smazat kalendář",
"calendarDetails": "Podrobnosti o kalendáři",
- "calendarDetailsDescription": "Zobrazit podrobné informace o kalendáři",
- "userShares": "uživatel",
- "tokenShares": "token",
"userSharesList": "Sdílení s uživateli",
"tokenSharesList": "Sdílení tokenem",
"externalSyncs": "Externí synchronizace",
"externalSyncsShort": "Synchr.",
"lastSynced": "Naposledy synchronizováno",
- "quickActions": "Rychlé akce",
- "editCalendarDescription": "Aktualizovat informace o kalendáři",
"namePlaceholder": "Zadejte název kalendáře",
"guestPermissionHint": "Určuje veřejný přístup k tomuto kalendáři",
- "transferSingleDescription": "Převést vlastnictví „{name}“",
"transferMultipleDescription": "{count, plural, =1 {1 kalendář bude převeden} few {# kalendáře budou převedeny} other {# kalendářů bude převedeno}}",
"calendarsToTransfer": "Kalendáře k převedení",
"calendarToTransfer": "Kalendář k převedení",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 kalendář smazán} few {# kalendáře smazány} other {# kalendářů smazáno}}",
"calendarsTransferred": "{count, plural, =1 {1 kalendář převeden} few {# kalendáře převedeny} other {# kalendářů převedeno}}"
},
- "auditLogsDescription": "Spravovat všechny protokoly",
"allActions": "Všechny akce",
"adminActions": "Akce správce",
"calendarActions": "Akce kalendáře",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Vyberte prosím datum",
"pleaseConfirmDeletion": "Potvrďte prosím smazání",
"willDeleteLogsOlderThan": "Všechny protokoly starší než {date} budou smazány",
- "preview": "Náhled",
"auditLogDetails": "Podrobnosti protokolu auditu",
"resourceType": "Typ zdroje",
"resourceId": "ID zdroje",
@@ -815,5 +628,421 @@
"clearSelection": "Zrušit výběr",
"deleteSelectedLogsDescription": "Smazat {count, plural, one {# vybraný protokol} few {# vybrané protokoly} other {# vybraných protokolů}}. Tuto akci nelze vrátit zpět.",
"willDeleteSelectedLogs": "{count, plural, one {# protokol} few {# protokoly} other {# protokolů}} bude trvale smazáno"
+ },
+ "appearance": {
+ "title": "Vzhled",
+ "hint": "Volba platí pro toto zařízení a ukládá se lokálně. Změna se projeví okamžitě, bez obnovení stránky.",
+ "system": {
+ "title": "Systém",
+ "description": "Řídí se nastavením zařízení"
+ },
+ "light": {
+ "title": "Světlý",
+ "description": "Vždy světlý"
+ },
+ "dark": {
+ "title": "Tmavý",
+ "description": "Vždy tmavý"
+ }
+ },
+ "appMenu": {
+ "account": "Účet",
+ "language": "Jazyk",
+ "preferences": "Předvolby",
+ "viewSettings": "Moje zobrazení",
+ "settingsAndAccount": "Nastavení a účet"
+ },
+ "calendarView": {
+ "previousMonth": "Předchozí měsíc",
+ "nextMonth": "Další měsíc",
+ "today": "Dnes",
+ "tomorrow": "Zítra",
+ "yesterday": "Včera",
+ "calendarWeek": "Týden {week}",
+ "weekdayShort": {
+ "monday": "Po",
+ "tuesday": "Út",
+ "wednesday": "St",
+ "thursday": "Čt",
+ "friday": "Pá",
+ "saturday": "So",
+ "sunday": "Ne"
+ },
+ "allDayShort": "celý den",
+ "externalCount": "{count} externí",
+ "hasNotes": "{count, plural, one {# poznámka} few {# poznámky} other {# poznámek}}",
+ "shift": "Směna",
+ "kpiShifts": "Směny",
+ "kpiHours": "Hodiny",
+ "kpiNotes": "Poznámky",
+ "kpiAvgPerShift": "⌀ na směnu",
+ "kpiFreeDays": "Volné dny",
+ "dayEmpty": "Na tento den není nic zapsáno.",
+ "dayFree": "volno",
+ "notesCount": "{count, plural, one {# poznámka} few {# poznámky} other {# poznámek}}",
+ "addNoteOrEvent": "Poznámka nebo událost",
+ "monthTotal": "{month} celkem",
+ "allShiftsIn": "Všechny směny: {month}",
+ "openStats": "Grafy a statistiky",
+ "shiftCount": "{count, plural, one {# směna} few {# směny} other {# směn}}",
+ "shiftActions": "Akce pro směnu",
+ "external": "externí",
+ "syncedReadOnly": "Z externího kalendáře, jen pro čtení",
+ "changedOn": "změněno {date}",
+ "stamp": "Šablony",
+ "managePresets": "Spravovat šablony",
+ "createPreset": "Vytvořit šablonu",
+ "manage": "Spravovat",
+ "stampHint": "Klepnutím na den přidáte {title}, dalším klepnutím ji odeberete.",
+ "addShiftManually": "Přidat směnu ručně",
+ "sheetDescription": "Směny a poznámky vybraného dne",
+ "sheetExpand": "Rozbalit",
+ "sheetShrink": "Zmenšit",
+ "periodLabel": "Období",
+ "wholeWeek": "Celý týden",
+ "wholeMonth": "Celý měsíc",
+ "wholeYear": "Celý rok",
+ "readOnlyTitle": "Jen pro čtení",
+ "readOnlyMessage": "Tento kalendář s vámi byl sdílen jen pro čtení, proto jsou šablony a přidávání skryté.",
+ "offlineTitle": "Žádné spojení se serverem",
+ "offlineMessage": "Vidíte naposledy načtený stav. Změny budou znovu možné po obnovení spojení; mezitím se neukládají.",
+ "retry": "Zkusit znovu",
+ "note": "Poznámka",
+ "event": "Událost",
+ "eventCount": "{count, plural, one {# událost} few {# události} other {# událostí}}",
+ "statsSheetDescription": "Směny, hodiny a volné dny za týden, měsíc nebo rok"
+ },
+ "calendarCompare": {
+ "title": "Porovnání",
+ "exit": "Ukončit",
+ "addCalendar": "Třetí kalendář",
+ "stampActive": "Šablona aktivní",
+ "tapToMoveStamp": "Klikněte na šablonu a vložte ji do tohoto sloupce",
+ "subtitle": "{count, plural, one {# kalendář} few {# kalendáře} other {# kalendářů}}",
+ "laneHintTwo": "Horní řada {top}, dolní {bottom} — poznáte podle pruhu vlevo. Prázdný rámeček znamená volno.",
+ "laneHintMany": "Řady shora: {order} — poznáte podle pruhu vlevo. Prázdný rámeček znamená volno.",
+ "maxHint": "nejvýše {max}"
+ },
+ "formKit": {
+ "optional": " (volitelné)",
+ "customColor": "Vlastní"
+ },
+ "settings": {
+ "title": "Nastavení",
+ "description": "Platí pro všechny, kdo mají k tomuto kalendáři přístup",
+ "general": "Název a barva",
+ "generalHint": "Zobrazovaný název, barva kalendáře, smazání",
+ "presets": "Šablony",
+ "presetsHint": "{count, plural, =0 {Zatím žádné šablony} one {# šablona} few {# šablony} other {# šablon}}",
+ "external": "Externí kalendáře",
+ "externalHint": "{count, plural, =0 {Odběr, zobrazení, interval} one {# odběr, zobrazení, interval} few {# odběry, zobrazení, interval} other {# odběrů, zobrazení, interval}}",
+ "sharing": "Sdílení",
+ "sharingHint": "{count, plural, =0 {Lidé, veřejný přístup, odkazy} one {Lidé, veřejný přístup, # aktivní odkaz} few {Lidé, veřejný přístup, # aktivní odkazy} other {Lidé, veřejný přístup, # aktivních odkazů}}",
+ "export": "Export",
+ "exportHint": "Soubor ICS nebo PDF",
+ "view": "Zobrazení kalendáře",
+ "viewHint": "Vlastní zobrazení, hustota, řazení",
+ "notifications": "Oznámení",
+ "notificationsHint": "Synchronizace",
+ "notificationsError": "Chyba synchronizace",
+ "deleteImpact": "{count, plural, =0 {Kalendář bude trvale smazán} one {Smaže se i # směna} few {Smažou se i # směny} other {Smaže se i # směn}}",
+ "appliesToAll": "Změny platí okamžitě pro všechny, se kterými je kalendář sdílen.",
+ "groupAccount": "Účet",
+ "groupApp": "Aplikace",
+ "viewOn": "zapnuto",
+ "viewOff": "vypnuto",
+ "groupPersonal": "Jen pro vás",
+ "personalCaption": "Platí ve všech kalendářích, ostatní to nevidí"
+ },
+ "presetSheet": {
+ "title": "Předvolby",
+ "description": "Pořadí určuje lištu šablon",
+ "primary": "V liště",
+ "newPreset": "Nová předvolba",
+ "titlePlaceholder": "např. Pohotovost",
+ "start": "Začátek",
+ "end": "Konec",
+ "allDay": "Celý den",
+ "allDayShort": "celý den",
+ "markAsSecondary": "Sbalit pod „Další“",
+ "hideFromStatsHint": "Nezapočítává se do hodin ani statistik",
+ "notInStats": "Mimo statistiky",
+ "save": "Uložit předvolbu",
+ "delete": "Smazat předvolbu",
+ "dragHandle": "Přetažením změníte pořadí",
+ "secondarySection": "Pod „Další“",
+ "markAsSecondaryHint": "V liště šablon se zobrazí až po kliknutí na „Další“"
+ },
+ "syncSheet": {
+ "intervalPill": "Každých {interval}",
+ "intervalValue": "každých {interval}",
+ "lastSynced": "naposledy {time}",
+ "syncNow": "Synchronizovat nyní",
+ "sourceUrl": "Odebírat adresu",
+ "sourceFile": "Importovat soubor",
+ "chooseFile": "Vybrat soubor ICS",
+ "urlLabel": "Adresa souboru ICS",
+ "colorLabel": "Barva všech importovaných směn",
+ "displayLabel": "Zobrazení v kalendáři",
+ "displayMinimal": "Jen počet",
+ "displayNormal": "Jako vlastní",
+ "autoSyncLabel": "Načítat automaticky",
+ "hideShifts": "Skrýt směny tohoto odběru",
+ "excludeFromStats": "Vyloučit ze statistik",
+ "addSubscription": "Přidat odběr"
+ },
+ "syncLog": {
+ "description": "Poslední načtení externích kalendářů",
+ "statusSuccess": "Úspěšné"
+ },
+ "sharingSheet": {
+ "tabPeople": "Lidé",
+ "invite": "Pozvat",
+ "haveAccess": "Mají přístup",
+ "owner": "Vlastník",
+ "permRead": "Jen čtení",
+ "permWrite": "Úpravy",
+ "permReadDesc": "Prohlížet kalendář, nic neměnit",
+ "permWriteDesc": "Vytvářet a mazat směny",
+ "permAdminDesc": "Navíc spravovat sdílení a nastavení",
+ "changePermission": "Změnit oprávnění pro {name}",
+ "publicOffTitle": "Veřejný přístup je vypnutý",
+ "publicOnTitle": "Veřejný přístup je zapnutý",
+ "accessNone": "Bez přístupu",
+ "guestNoneShort": "Jen pozvaní a odkazy",
+ "activeLinks": "Aktivní odkazy",
+ "inactiveLinks": "Deaktivované nebo prošlé",
+ "noActiveLinks": "Žádný aktivní odkaz",
+ "expiresOn": "platí do {date}",
+ "expiredOn": "vypršel {date}",
+ "noExpiry": "bez omezení",
+ "lastUsed": "naposledy {time}",
+ "newLink": "Vytvořit nový odkaz",
+ "linkName": "Označení",
+ "linkNameHint": "volitelné, pomůže při rušení",
+ "linkNamePlaceholder": "např. Nástěnka v odpočívárně",
+ "validity": "Platnost",
+ "validityUnlimited": "Bez omezení",
+ "validUntilRevoked": "platí, dokud ho nezrušíte",
+ "createLink": "Vytvořit odkaz",
+ "creating": "Vytváří se …",
+ "linkReady": "Odkaz je připravený",
+ "copyNowTitle": "Zkopírujte ho hned",
+ "copyNowBody": "Po zavření už token nepůjde znovu zobrazit. Pokud se ztratí, vytvořte nový a tento zrušte.",
+ "shareLinkLabel": "Odkaz ke sdílení",
+ "copied": "Zkopírováno",
+ "guestReadShortGuestsOn": "Všichni mohou prohlížet",
+ "guestWriteShortGuestsOn": "Všichni mohou upravovat",
+ "guestReadShortGuestsOff": "Přihlášení mohou prohlížet",
+ "guestWriteShortGuestsOff": "Přihlášení mohou upravovat",
+ "publicOffBodyGuestsOn": "Přístup mají jen pozvaní lidé a držitelé přístupového odkazu; odkazy fungují i bez účtu. Na kartě „Veřejné“ můžete kalendář zpřístupnit všem, i návštěvníkům bez účtu.",
+ "publicOffBodyGuestsOff": "Přístup mají jen pozvaní lidé a držitelé přístupového odkazu; příjemci odkazu se musí přihlásit, protože přístup pro hosty je na této instanci vypnutý. Na kartě „Veřejné“ můžete kalendář zpřístupnit přihlášeným uživatelům této instance.",
+ "linkInfoGuestsOn": "Odkaz otevře kalendář přímo, bez přihlášení. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit.",
+ "linkInfoGuestsOff": "Odkaz otevře kalendář přímo. Přístup pro hosty je na této instanci vypnutý, takže se příjemci musí přihlásit. V seznamu ho můžete kdykoli zrušit — pak okamžitě přestane platit."
+ },
+ "shiftSheet": {
+ "start": "Začátek",
+ "end": "Konec",
+ "duration": "Délka",
+ "allDay": "Celý den",
+ "noPreset": "Vlastní",
+ "createAction": "Vytvořit směnu"
+ },
+ "noteSheet": {
+ "createTitle": "Nový záznam",
+ "editTitle": "Upravit záznam",
+ "createAction": "Vytvořit záznam",
+ "typeEvent": "Událost",
+ "typeNote": "Poznámka",
+ "typeHint": "Událost se zobrazí s názvem a barvou v buňce dne. Poznámka zůstává nenápadná a zobrazí se jen jako ikona.",
+ "text": "Text",
+ "repeat": "Opakování",
+ "repeatNone": "Jednorázově",
+ "repeatWeekly": "Týdně",
+ "repeatMonthly": "Měsíčně",
+ "repeatYearly": "Ročně",
+ "unitWeeks": "{count, plural, one {týden} few {týdny} other {týdnů}}",
+ "unitMonths": "{count, plural, one {měsíc} few {měsíce} other {měsíců}}",
+ "unitYears": "{count, plural, one {rok} few {roky} other {let}}",
+ "intervalInactive": "jen při opakování",
+ "recurrenceWeeks": "{count, plural, one {týdně} few {každé # týdny} other {každých # týdnů}}",
+ "recurrenceMonths": "{count, plural, one {měsíčně} few {každé # měsíce} other {každých # měsíců}}",
+ "recurrenceYears": "{count, plural, one {ročně} few {každé # roky} other {každých # let}}",
+ "listTitle": "Poznámky a události",
+ "entryCount": "{count, plural, one {# záznam} few {# záznamy} other {# záznamů}}",
+ "addAnother": "Přidat další záznam",
+ "shortcutHint": "Zkratka: pravým tlačítkem na den na počítači, dlouhým stiskem na telefonu."
+ },
+ "authPage": {
+ "loginSubtitle": "Pokračovat ke kalendářům",
+ "signInWith": "Přihlásit se přes {provider}",
+ "registerTitle": "Vytvořit účet",
+ "registerSubtitle": "Poté budete rovnou přihlášeni",
+ "passwordHint": "Alespoň 8 znaků",
+ "repeatPassword": "Zopakovat heslo",
+ "passwordsMatch": "Hesla se shodují",
+ "haveAccount": "Už máte účet?",
+ "showPassword": "Zobrazit heslo",
+ "hidePassword": "Skrýt heslo",
+ "sampleMonth": "Ukázkový měsíc",
+ "instance": "Instance"
+ },
+ "emptyState": {
+ "guestBadge": "Host",
+ "noCalendarTitle": "Zatím žádný kalendář",
+ "noCalendarDescription": "Kalendář sdružuje směny, šablony a sdílení jedné skupiny. Později si jich můžete vytvořit libovolně mnoho a přepínat mezi nimi.",
+ "createCalendar": "Vytvořit kalendář",
+ "browseShared": "Procházet sdílené",
+ "guestTitle": "Žádný kalendář není veřejně sdílen",
+ "guestDescription": "Bez účtu vidíte jen kalendáře, které byly výslovně otevřeny pro hosty. Pokud jste dostali přístupový odkaz, otevřete ho přímo – odkaz obsahuje přístup.",
+ "pasteAccessLink": "Vložit přístupový odkaz",
+ "accessLinkDescription": "Vložte odkaz, který jste dostali – nebo jen token z něj.",
+ "accessLinkLabel": "Přístupový odkaz",
+ "accessLinkInvalid": "Toto není platný přístupový odkaz.",
+ "openAccessLink": "Otevřít"
+ },
+ "discovery": {
+ "unsubscribe": "Zrušit odběr"
+ },
+ "profile": {
+ "title": "Můj účet",
+ "navProfileHint": "Jméno, e-mail, profilový obrázek",
+ "navPasswordHint": "Potvrzení aktuálního hesla",
+ "navSessionsHint": "{count, plural, one {# přihlášené zařízení} few {# přihlášená zařízení} other {# přihlášených zařízení}}",
+ "navActivityHint": "Co se naposledy změnilo",
+ "navDangerHint": "Odhlášení, smazání účtu",
+ "groupAccount": "Účet",
+ "groupSecurity": "Zabezpečení",
+ "chooseImage": "Vybrat obrázek",
+ "removeImage": "Odebrat",
+ "appliesEverywhere": "Změny platí okamžitě pro všechna zařízení.",
+ "discard": "Zahodit",
+ "managedByProvider": "Jméno a e-mail pocházejí od vašeho poskytovatele přihlášení a zde je nelze změnit.",
+ "accountsTitle": "Způsoby přihlášení",
+ "accountsHint": "Pomocí těchto účtů se můžete přihlásit.",
+ "connectedSince": "Propojeno od {date}",
+ "passwordNote": "Ostatní zařízení zůstanou přihlášená.",
+ "sessionsTitle": "Přihlášená zařízení",
+ "sessionsHint": "Odhlášení relaci okamžitě ukončí.",
+ "signOutOthers": "Odhlásit ostatní",
+ "thisDevice": "toto zařízení",
+ "activeNow": "právě aktivní",
+ "sessionRevoked": "Zařízení odhlášeno",
+ "unknownBrowser": "Neznámý prohlížeč",
+ "unknownOs": "Neznámý systém",
+ "deleteImpact": "Smažou se i kalendáře, směny a sdílení.",
+ "deleteNeedsPassword": "Vyžaduje vaše heslo."
+ },
+ "adminKit": {
+ "banned": "Zablokován",
+ "active": "Aktivní",
+ "severityInfo": "info",
+ "severityWarning": "Varování",
+ "severityError": "Chyba",
+ "severityCritical": "kritické"
+ },
+ "adminShell": {
+ "logsShort": "Logy",
+ "breadcrumb": "Drobečková navigace"
+ },
+ "adminDashboard": {
+ "title": "Přehled",
+ "attention": "{count, plural, one {Jedna věc vyžaduje pozornost} few {# věci vyžadují pozornost} other {# věcí vyžaduje pozornost}}",
+ "allClear": "Nic teď nevyžaduje pozornost",
+ "openCalendars": "Otevřít kalendáře",
+ "recentTitle": "Co se naposledy stalo",
+ "recentShort": "Naposledy",
+ "activityFooter": "{shown} z {count, plural, one {# události} few {# událostí} other {# událostí}}",
+ "scope": "Rozsah",
+ "events": "Události",
+ "acrossCalendars": "ve všech kalendářích",
+ "calendarsAllOwned": "všechny mají vlastníka",
+ "calendarsOrphaned": "{count, plural, one {# bez vlastníka} few {# bez vlastníka} other {# bez vlastníka}}",
+ "usersSub": "{count, plural, one {# účet} few {# účty} other {# účtů}}",
+ "calendarsSub": "{count, plural, one {# kalendář} few {# kalendáře} other {# kalendářů}}, {orphaned} bez vlastníka",
+ "logsSub": "{count, plural, one {# událost} few {# události} other {# událostí}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# záznam} few {# záznamy} other {# záznamů}}",
+ "dateRange": "Období",
+ "clearRange": "Zrušit období",
+ "filterTitle": "Filtry",
+ "done": "Hotovo",
+ "selectAll": "Vybrat vše na této stránce",
+ "selectEntry": "Vybrat záznam",
+ "severityShort": "Závažnost",
+ "whatHappened": "Co se stalo",
+ "details": "Podrobnosti",
+ "describe": {
+ "userBanned": "{user} zablokován",
+ "userBannedPermanently": "{user} trvale zablokován",
+ "userUnbanned": "Blokace {user} zrušena",
+ "passwordReset": "Heslo pro {user} obnoveno",
+ "userDeleted": "Účet {user} smazán",
+ "userUpdated": "Účet {user} upraven",
+ "calendarTransferred": "Kalendář „{calendar}“ převeden na {user}",
+ "calendarsTransferred": "{count, plural, one {# kalendář převeden} few {# kalendáře převedeny} other {# kalendářů převedeno}} na {user}",
+ "calendarsDeleted": "{count, plural, one {# kalendář smazán} few {# kalendáře smazány} other {# kalendářů smazáno}}",
+ "logsDeleted": "{count, plural, one {# záznam protokolu smazán} few {# záznamy protokolu smazány} other {# záznamů protokolu smazáno}}",
+ "calendarUpdated": "Kalendář „{calendar}“ upraven",
+ "calendarDeleted": "Kalendář „{calendar}“ smazán",
+ "calendarCreated": "Kalendář „{calendar}“ vytvořen",
+ "calendarShared": "Kalendář „{calendar}“ sdílen s {user}",
+ "shareRemoved": "Sdílení „{calendar}“ s {user} odebráno",
+ "permissionChanged": "Oprávnění {user} pro „{calendar}“ změněno",
+ "guestPermissionChanged": "Přístup hostů ke kalendáři „{calendar}“ změněn",
+ "syncCreated": "Synchronizace „{sync}“ vytvořena",
+ "syncDeleted": "Synchronizace „{sync}“ odebrána",
+ "syncDisabled": "Synchronizace „{sync}“ vypnuta, kalendář nemá vlastníka",
+ "syncFailed": "Synchronizace „{sync}“ selhala",
+ "syncExecuted": "„{sync}“ synchronizováno: {added} nových, {updated} změněných, {deleted} odebraných",
+ "rateLimit": "Dosažen limit požadavků ({endpoint})",
+ "loginProvider": "Přihlášení přes {provider}",
+ "loginEmail": "Přihlášení e-mailem a heslem",
+ "loginFailed": "Neúspěšné přihlášení pro {email}",
+ "registered": "Registrován nový účet {email}",
+ "profileUpdated": "Profil upraven",
+ "passwordChanged": "Heslo změněno",
+ "accountDeleted": "Vlastní účet smazán",
+ "sessionsRevoked": "{count, plural, one {# relace ukončena} few {# relace ukončeny} other {# relací ukončeno}}"
+ }
+ },
+ "adminUsers": {
+ "actions": "Akce",
+ "all": "Vše",
+ "ban": "Zablokovat",
+ "banReasonQuoted": "Důvod: „{reason}“",
+ "calendarCount": "{count, plural, one {# kalendář} few {# kalendáře} other {# kalendářů}}",
+ "edit": "Upravit",
+ "filterLabel": "Filtrovat uživatele",
+ "hidePassword": "Skrýt heslo",
+ "joinedOn": "Registrace {date}",
+ "moreActions": "Další akce",
+ "moreFilters": "Další filtry",
+ "numbers": "Čísla",
+ "showPassword": "Zobrazit heslo",
+ "subtitle": "{count, plural, one {# účet} few {# účty} other {# účtů}}{banned, plural, =0 {} one {, z toho # zablokovaný} few {, z toho # zablokované} other {, z toho # zablokovaných}}"
+ },
+ "adminCalendars": {
+ "content": "Obsah",
+ "filterLabel": "Filtrovat kalendáře",
+ "filterShared": "Sdílené",
+ "filterSynced": "Se synchronizací",
+ "guestColumn": "Přístup hosta",
+ "guestNoneHint": "Kalendář vidí jen lidé, se kterými je sdílený",
+ "guestPermissionValue": "Oprávnění hosta: {permission}",
+ "guestReadHint": "Kdokoli s odkazem kalendář uvidí",
+ "guestWriteHint": "Kdokoli s odkazem může kalendář upravovat",
+ "publicAccess": "Veřejný přístup",
+ "selectAll": "Vybrat vše",
+ "selectedCount": "Vybráno: {count}",
+ "selectedNone": "Vybráno: nic",
+ "sharesAndLinks": "Sdílení, {links, plural, one {# přístupový odkaz} few {# přístupové odkazy} other {# přístupových odkazů}}",
+ "showOrphaned": "Zobrazit",
+ "subtitle": "{count, plural, one {# kalendář} few {# kalendáře} other {# kalendářů}}, celkem {shifts, plural, one {# směna} few {# směny} other {# směn}}"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} z {total}",
+ "label": "Stránky"
}
}
diff --git a/messages/de.json b/messages/de.json
index 87d4363..052f78a 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -12,16 +12,12 @@
"save": "Speichern",
"saving": "Speichere...",
"close": "Schließen",
- "optional": "(optional)",
"delete": "Löschen",
"deleteSelected": "Ausgewählte löschen",
"loading": "Lädt...",
- "add": "Hinzufügen",
- "adding": "Wird hinzugefügt...",
"or": "oder",
"next": "Weiter",
"previous": "Zurück",
- "of": "von",
"unsavedChanges": "Ungespeicherte Änderungen",
"unsavedChangesDescription": "Du hast ungespeicherte Änderungen. Möchtest du wirklich schließen, ohne zu speichern?",
"closeWithoutSaving": "Schließen ohne Speichern",
@@ -31,7 +27,6 @@
"createError": "{item} konnte nicht erstellt werden",
"updateError": "{item} konnte nicht aktualisiert werden",
"deleteError": "{item} konnte nicht gelöscht werden",
- "deleteConfirm": "{item} \"{name}\" wirklich löschen?",
"shifts": "Schichten",
"success": "Erfolgreich",
"error": "Fehler",
@@ -58,15 +53,6 @@
"no": "Nein",
"viewAll": "Alle anzeigen",
"viewDetails": "Details anzeigen",
- "weekday": {
- "monday": "Mo",
- "tuesday": "Di",
- "wednesday": "Mi",
- "thursday": "Do",
- "friday": "Fr",
- "saturday": "Sa",
- "sunday": "So"
- },
"labels": {
"name": "Name",
"email": "E-Mail",
@@ -97,8 +83,7 @@
"users": "Benutzer"
},
"status": {
- "active": "Aktiv",
- "inactive": "Inaktiv"
+ "active": "Aktiv"
},
"roles": {
"admin": "Admin",
@@ -106,12 +91,14 @@
"user": "Benutzer"
},
"time": {
- "never": "Niemals",
"lastActive": "Zuletzt aktiv"
},
"filters": {
"allSeverities": "Alle Schweregrade",
- "clearFilters": "Filter löschen"
+ "clearFilters": "Filter löschen",
+ "title": "Filter",
+ "done": "Fertig",
+ "remove": "{filter} entfernen"
},
"severity": {
"info": "Info",
@@ -120,7 +107,6 @@
"critical": "Kritisch"
},
"stats": {
- "statistics": "Statistiken",
"created": "Erstellt"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Farbe",
"notesLabel": "Notizen (optional)",
"notesPlaceholder": "Zusätzliche Informationen...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organisiere deine Schichten"
+ "title": "BetterShift"
},
"calendar": {
"title": "Kalender",
"create": "Neuen Kalender erstellen",
"createDescription": "Erstelle einen neuen Kalender, um deine Schichten zu organisieren",
- "selectDescription": "Wähle einen Kalender aus, um deine Schichten zu verwalten",
"name": "Kalendername",
"myCalendars": "Meine Kalender",
"sharedCalendars": "Geteilte Kalender",
"tokenCalendars": "Via Zugangslink",
"publicCalendars": "Öffentliche Kalender",
- "select": "Dein BetterShift Kalender",
"deleteCalendar": "Kalender löschen",
"deleteWarning": "Alle Schichten, Presets und Notizen werden ebenfalls gelöscht.",
- "settings": "Kalendereinstellungen für \"{name}\"",
- "settingsDescription": "Passe Name und Farbe an",
"compare": "Vergleichen",
"compareMode": "Vergleichsmodus",
- "exitCompare": "Vergleich beenden",
"selectToCompare": "Wähle Kalender zum Vergleichen",
"selectToCompareDescription": "Wähle 2-3 Kalender aus, um sie nebeneinander zu vergleichen",
"compareSelected": "{count} ausgewählt",
"startComparing": "Vergleich starten",
- "mobileNotOptimized": "Die Vergleichsansicht ist nicht für Mobile optimiert. Für die beste Erfahrung nutze bitte einen größeren Bildschirm.",
"shareLink": "Link teilen",
- "shareLinkDescription": "Kopiere den Link zur Vergleichsansicht",
"browseCalendars": "Geteilte Kalender",
"browseCalendarsDescription": "Kalender-Abonnements entdecken und verwalten",
"subscribe": "Abonnieren",
- "subscribed": "Abonniert",
"noPublicCalendars": "Keine öffentlichen Kalender verfügbar",
"subscriptionSuccess": "Abonniert: {name}",
"unsubscribeSuccess": "Deabonniert: {name}",
@@ -201,81 +177,45 @@
"customDescription": "Wähle eine eigene Farbe mit dem Farbwähler"
},
"note": {
- "create": "{item} erstellen",
- "edit": "{item} bearbeiten",
"note": "Notiz",
"placeholder": "z.B. Frühdienst weil nachmittags Termin...",
- "hintMobile": "Um eine Notiz oder ein Event hinzuzufügen oder zu bearbeiten, drücke lange auf einen Tag im Kalender.",
- "hintDesktop": "Um eine Notiz oder ein Event hinzuzufügen oder zu bearbeiten, mache einen Rechtsklick auf einen Tag im Kalender.",
"type": "Typ",
- "typeNote": "Notizen",
"typeEvent": "Events",
"eventColor": "Event-Farbe",
- "eventTitle": "Event-Name",
"eventPlaceholder": "z.B. Weihnachten, Geburtstag...",
- "recurring": "Wiederholen",
- "recurringNone": "Nicht wiederholen",
- "recurringCustom": "Benutzerdefiniert",
- "recurringEveryWeeks": "Alle {count} Wochen",
- "recurringEveryMonths": "Alle {count} Monate",
"customInterval": "Intervall",
"every": "Alle",
- "weeks": "Wochen",
- "months": "Monate",
- "multipleEntries": "{count} Einträge",
"noEntries": "Keine Notizen oder Events vorhanden",
"recurringEditWarning": "Dies ist ein wiederkehrendes Event. Änderungen wirken sich auf alle Wiederholungen aus."
},
"shift": {
"create": "Neue Schicht",
- "createDescription": "Füge eine neue Schicht zu deinem Kalender hinzu",
"edit": "Schicht bearbeiten",
- "editDescription": "Aktualisiere die Schichtdetails",
"date": "Datum",
- "startTime": "Startzeit",
- "endTime": "Endzeit",
"titlePlaceholder": "z.B. Frühschicht",
"titleLabel": "Titel",
- "allDay": "GT",
"allDayShift": "Ganztägige Schicht",
"noShiftsInMonth": "Keine Schichten in diesem Monat",
- "noShiftsInMonthDescription": "Füge Schichten hinzu, indem du auf Tage im Kalender oben klickst.",
- "shift_one": "Schicht",
- "selectPreset": "Vorlage auswählen",
- "none": "Keine"
+ "shift_one": "Schicht"
},
"preset": {
"preset": "Vorlage",
- "createNew": "Neue Vorlage erstellen",
- "createYourFirst": "Erstelle deine erste Vorlage",
"edit": "Vorlage bearbeiten",
- "manage": "Vorlagen verwalten",
- "manageDescription": "Bearbeite oder lösche deine Schichtvorlagen",
"saveAsPreset": "Als Vorlage speichern",
"presetName": "Vorlagenname",
"presetNamePlaceholder": "z.B. Frühschicht, Spätschicht...",
"noPresets": "Noch keine Schichtvorlagen",
- "createFirstDescription": "Erstelle deine erste Vorlage, um Schichten schnell zu deinem Kalender hinzuzufügen. Vorlagen speichern deine häufig genutzten Schichtzeiten und Details.",
"deleteConfirm": "Diese Vorlage löschen? Alle aus dieser Vorlage erstellten Schichten werden ebenfalls gelöscht.",
- "primaryPresets": "Primäre Vorlagen",
- "secondaryPresets": "Sekundäre Vorlagen",
- "secondary": "Sekundär",
- "markAsSecondary": "Als sekundär markieren (standardmäßig eingeklappt)",
- "hideFromStats": "Aus Statistik ausblenden",
- "hideFromStatsHint": "Schichten dieser Vorlage aus der Statistik ausschließen",
- "showPresets": "Vorlagen anzeigen",
- "hidePresets": "Vorlagen ausblenden",
- "hiddenFromStats": "Aus Statistik ausgeblendet",
- "cannotAddPresetHint": "Diese Vorlage gehört zu einem anderen Kalender und kann hier nicht hinzugefügt werden."
+ "secondary": "Weitere",
+ "hideFromStats": "Aus Statistik ausblenden"
},
"view": {
- "settingsTitle": "Ansichtseinstellungen",
- "settingsDescription": "Passe an, wie Schichten in allen Kalendern angezeigt werden",
+ "settingsTitle": "Meine Ansicht",
+ "settingsDescription": "Deine persönliche Ansicht. Gilt für alle Kalender ohne eigene Ansicht und ist nur für dich sichtbar.",
"shiftsPerDay": "Normale Schichten pro Tag",
- "shiftsPerDayHint": "Maximale Anzahl der normalen Schichten pro Tag",
+ "shiftsPerDayHint": "Weitere erscheinen als „+N“. Auto zeigt so viele, wie in die Tageszelle passen.",
"externalShiftsPerDay": "Externe Schichten pro Tag",
- "externalShiftsPerDayHint": "Maximale Anzahl der Schichten aus externen Kalendern pro Tag",
- "showAll": "Alle",
+ "externalShiftsPerDayHint": "Gilt für externe Kalender mit der Anzeige „Wie eigene“. Weitere erscheinen als „+N“.",
"sortOptions": "Sortieroptionen",
"sortBy": "Sortieren nach",
"sortByStartTime": "Startzeit",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Absteigend",
"combinedSort": "Alle Schichten zusammen sortieren",
"combinedSortHint": "Normale und externe Schichten gemeinsam sortieren statt separat",
- "displayOptions": "Anzeigeoptionen",
"showNotes": "Schichtnotizen anzeigen",
- "showNotesHint": "Notizen der Schichten im Kalender anzeigen",
- "showFullTitles": "Vollständige Schichttitel anzeigen",
- "showFullTitlesHint": "Schichttitel vollständig ohne Kürzung anzeigen",
+ "showNotesHint": "Die Notiz einer Schicht als zweite Zeile in der Monatsansicht",
"dayHighlighting": "Tage hervorheben",
"highlightWeekends": "Wochenenden hervorheben",
"highlightWeekendsHint": "Samstage und Sonntage farbig hervorheben",
@@ -303,7 +240,17 @@
"friday": "Freitag",
"saturday": "Samstag",
"sunday": "Sonntag",
- "highlightColor": "Hervorhebungsfarbe"
+ "highlightColor": "Hervorhebungsfarbe",
+ "density": "Dichte",
+ "showPresetBar": "Vorlagenleiste anzeigen",
+ "showPresetBarHint": "Vorlagenleiste unter bzw. über dem Kalender",
+ "settingsDescriptionLocal": "Deine persönliche Ansicht auf diesem Gerät. Gilt für alle Kalender ohne eigene Ansicht.",
+ "overriddenByCalendar": "„{calendar}“ hat eine eigene Ansicht. Dort gilt deine persönliche Ansicht nicht.",
+ "calendarOwn": "Eigene Ansicht für diesen Kalender",
+ "calendarOwnHint": "Gilt für alle mit Zugriff auf diesen Kalender.",
+ "calendarOffNote": "Alle sehen hier ihre persönliche Ansicht. Deine stellst du unter „Meine Ansicht“ ein.",
+ "calendarLocked": "Für diesen Kalender festgelegt. Ändern können das nur Personen, die den Kalender verwalten.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Schichtenstatistik",
@@ -329,52 +276,16 @@
"connected": "Server Verbindung hergestellt",
"disconnected": "Server Verbindung verloren"
},
- "onboarding": {
- "welcome": "Willkommen bei BetterShift",
- "description": "Erstelle deinen ersten Kalender, um deine Schichten zu verwalten.",
- "createCalendar": "Kalender erstellen"
- },
- "guestEmptyState": {
- "title": "Keine öffentlichen Kalender verfügbar",
- "description": "Es sind derzeit keine öffentlichen Kalender freigegeben. Bitte melde dich an, um eigene Kalender zu erstellen und zu verwalten.",
- "loginButton": "Zur Anmeldung"
- },
- "footer": {
- "version": "Version",
- "github": "GitHub",
- "support": "Unterstützen"
- },
- "theme": {
- "switchToLight": "Zum hellen Modus wechseln",
- "switchToDark": "Zum dunklen Modus wechseln"
- },
"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",
"importMethod": "Import-Methode",
- "importMethodUrl": "URL (kann synchronisiert werden)",
- "importMethodFile": "Datei hochladen (einmaliger Import)",
"importMethodUrlHint": "Externe Kalender-URL (iCloud, Google oder andere ICS-URLs)",
"importMethodFileHint": "ICS-Datei einmalig importieren",
"fileLabel": "ICS-Datei",
- "fileSelected": "Datei ausgewählt",
"oneTimeImport": "Einmaliger Import",
- "displayMode": "Synchronisierte Schichten anzeigen",
- "displayModeNormal": "Normal (alle Schichten anzeigen)",
- "displayModeMinimal": "Minimalistisch (nur Anzahl anzeigen)",
- "displayModeHint": "Wähle, wie synchronisierte Schichten im Kalender angezeigt werden sollen",
- "addNewSync": "Neuen externen Kalender hinzufügen",
- "editSync": "Externen Kalender bearbeiten",
- "colorHint": "Wähle die Farbe für alle importierten Schichten",
- "hideCalendar": "Kalender ausblenden",
- "hideCalendarHint": "Schichten dieses Kalenders ausblenden",
- "hideFromStats": "Aus Statistik ausblenden",
- "hideFromStatsHint": "Schichten dieses Kalenders aus der Statistik ausschließen",
- "lastSynced": "Zuletzt synchronisiert",
"delete": "Externen Kalender löschen",
"deleteConfirm": "Diesen externen Kalender löschen? Alle importierten Schichten werden entfernt.",
"hintsTitle": "Kalender-URL finden",
@@ -384,8 +295,6 @@
"hintICloud": "Öffne iCloud.com → Kalender → Klicke auf das Teilen-Symbol neben deinem Kalender → Aktiviere 'Öffentlicher Kalender' → Kopiere die webcal:// URL und füge sie hier ein.",
"hintGoogle": "Öffne Google Kalender → Einstellungen → Wähle deinen Kalender → Scrolle zu 'Geheime Adresse im iCal-Format' → Kopiere die URL und füge sie hier ein.",
"hintCustom": "Jeder öffentlich zugängliche ICS-Kalender funktioniert. Die URL muss mit https:// oder webcal:// beginnen und auf .ics enden. Beispiel: https://example.com/calendar.ics",
- "autoSyncLabel": "Automatische Synchronisierung",
- "autoSyncHint": "Wähle wie oft dieser Kalender automatisch synchronisiert werden soll",
"autoSyncManual": "Manuell",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automatisch",
"syncTypeManual": "Manuell",
"noChanges": "Keine Änderungen",
- "errorMessage": "Fehlermeldung",
"filterAll": "Alle anzeigen",
"filterSuccess": "Nur Erfolgreiche",
"filterError": "Nur Fehler",
@@ -415,9 +323,6 @@
"viewOnGitHub": "Auf GitHub ansehen"
},
"export": {
- "title": "Kalender exportieren",
- "description": "Exportiere deinen Kalender als ICS- oder PDF-Datei",
- "exportCalendar": "Kalender exportieren",
"formatLabel": "Export-Format",
"icsFormat": "ICS (Kalenderdatei)",
"pdfFormat": "PDF (Dokument)",
@@ -432,34 +337,19 @@
"download": "Herunterladen",
"multiCalendar": "Mehrere Kalender exportieren",
"multiCalendarHint": "Schichten aus mehreren Kalendern in einer Export-Datei kombinieren",
- "selectCalendars": "Kalender auswählen",
- "selectCalendarsDescription": "Wähle aus, welche Kalender in den Export einbezogen werden sollen",
"selectedCount": "{count, plural, =0 {Keine Kalender ausgewählt} =1 {1 Kalender ausgewählt} other {# Kalender ausgewählt}}",
"selectAtLeastOne": "Bitte wähle mindestens einen Kalender aus"
},
"update": {
- "available": "Update verfügbar",
- "newVersion": "Version {version} ist verfügbar",
- "viewChangelog": "Changelog anzeigen"
+ "newVersion": "Version {version} ist verfügbar"
},
"auth": {
"login": "Anmelden",
- "loginTitle": "Bei BetterShift anmelden",
- "loginDescription": "Melde dich mit deinem Konto an oder verwende einen der Provider unten",
"register": "Registrieren",
- "registerTitle": "Konto erstellen",
- "registerDescription": "Erstelle ein neues Konto, um loszulegen",
"logout": "Abmelden",
"profile": "Profil",
- "profileTitle": "Dein Profil",
- "profileDescription": "Verwalte deine Kontoeinstellungen und Präferenzen",
- "profileBasicInfoDescription": "Deine grundlegenden Kontoinformationen",
- "changePasswordDescription": "Aktualisiere dein Passwort, um dein Konto sicher zu halten",
- "connectedAccountsDescription": "Verwalte deine verbundenen OAuth-Anbieter",
"dangerZone": "Gefahrenzone",
- "dangerZoneDescription": "Unwiderrufliche Aktionen, die dein Konto betreffen",
"logoutDescription": "Von deiner aktuellen Sitzung abmelden",
- "deleteAccountDescription": "Lösche dein Konto und alle Daten dauerhaft",
"noConnectedAccounts": "Noch keine verbundenen Konten",
"emailPasswordAuth": "E-Mail/Passwort",
"emailPlaceholder": "[email protected]",
@@ -468,14 +358,10 @@
"confirmPasswordLabel": "Passwortbestätigung",
"enterPassword": "Passwort eingeben",
"namePlaceholder": "Dein Name",
- "continueWith": "Weiter mit {provider}",
"continueAsGuest": "Als Gast fortfahren",
- "alreadyHaveAccount": "Hast du bereits ein Konto?",
"noAccountYet": "Noch kein Konto?",
"changePassword": "Passwort ändern",
"deleteAccount": "Konto löschen",
- "editProfile": "Profil bearbeiten",
- "editProfileDescription": "Aktualisiere deinen Namen, E-Mail und Profilbild",
"profileUpdated": "Profil erfolgreich aktualisiert",
"profilePicture": "Profilbild",
"avatarHint": "Max. 5MB. Unterstützte Formate: JPEG, PNG, GIF, WebP",
@@ -502,48 +388,28 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Verwalte deine angemeldeten Geräte und Sitzungen",
"noActiveSessions": "Keine aktiven Sitzungen",
- "browser": "Browser",
- "operatingSystem": "Betriebssystem",
- "logoutAllDevices": "Von allen anderen Geräten abmelden",
"sessionsRevokedCount": "Von {count} Gerät(en) abgemeldet",
"accountBanned": "Konto gesperrt"
},
"system": {
"unavailable": "System nicht verfügbar",
- "unavailableDescription": "Das System ist derzeit durch einen kritischen Fehler nicht verfügbar. Bitte versuche es später erneut oder kontaktiere einen Administrator.",
- "unavailableRetry": "Bitte aktualisiere diese Seite, um es erneut zu versuchen, oder schaue später wieder vorbei."
+ "unavailableDescription": "Das System ist derzeit durch einen kritischen Fehler nicht verfügbar. Bitte versuche es später erneut oder kontaktiere einen Administrator."
},
"guest": {
"viewingAsGuest": "Du betrachtest als Gast",
"bannerMessage": "Du betrachtest diesen Kalender als Gast. Melde dich an für vollen Zugriff.",
- "loginForFullAccess": "Anmelden für vollen Zugriff",
"cannotEdit": "Du kannst im Nur-Lesen-Modus nicht bearbeiten"
},
"share": {
- "manageSharing": "Freigaben verwalten",
- "manageSharingDescription": "Bestimme, wer auf \"{name}\" zugreifen kann",
- "userShares": "Benutzerfreigaben",
"publicAccess": "Öffentlicher Zugriff",
- "accessLinks": "Zugangslinks",
"public": "Öffentlich",
"links": "Links",
"share": "Freigabe",
- "sharedBy": "Geteilt von",
- "sharedOn": "Geteilt am",
- "addUser": "Benutzer hinzufügen",
- "addUserDescription": "Suche nach einem Benutzer, um diesen Kalender zu teilen",
"searchUser": "Benutzer suchen",
"searchUserPlaceholder": "Name oder E-Mail eingeben...",
- "selectedUser": "Ausgewählter Benutzer",
- "noShares": "Noch keine Benutzer haben Zugriff",
"noSharesDescription": "Teile diesen Kalender mit anderen Benutzern zur Zusammenarbeit",
- "userSharesDescription": "Verwalte, wer auf diesen Kalender zugreifen kann",
- "publicAccessDescription": "Bestimme den öffentlichen Zugriff für authentifizierte und Gastbenutzer",
- "publicPermissionNoneDesc": "Niemand kann ohne Freigabe auf diesen Kalender zugreifen",
- "publicPermissionReadDesc": "Jeder authentifizierte Benutzer kann den Kalender ansehen",
- "publicPermissionWriteDesc": "Jeder authentifizierte Benutzer kann den Kalender ansehen und bearbeiten",
+ "publicPermissionNoneDesc": "Nur du, eingeladene Personen und Inhaber eines Zugangslinks haben Zugriff.",
"shareAdded": "Kalender erfolgreich geteilt",
"shareUpdated": "Berechtigung erfolgreich aktualisiert",
"shareRemoved": "Zugriff erfolgreich entfernt",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "Kalenderzugriff entfernen?",
"removeShareConfirmDesc": "Bist du sicher, dass du den Zugriff für {user} entfernen möchtest? Diese Person kann den Kalender dann nicht mehr sehen oder bearbeiten.",
"you": "Du",
- "sharedWithYou": "Mit dir geteilt"
+ "sharedWithYou": "Mit dir geteilt",
+ "publicPermissionReadDescGuestsOn": "Jeder kann den Kalender ansehen, auch ohne Konto. Angemeldete Nutzer fügen ihn über „Geteilte Kalender“ hinzu.",
+ "publicPermissionWriteDescGuestsOn": "Jeder kann den Kalender ansehen und bearbeiten, auch ohne Konto. Angemeldete Nutzer fügen ihn über „Geteilte Kalender“ hinzu.",
+ "publicPermissionReadDescGuestsOff": "Angemeldete Nutzer dieser Instanz können den Kalender über „Geteilte Kalender“ hinzufügen und ansehen. Ohne Konto ist kein Zugriff möglich, weil der Gastzugang auf dieser Instanz aus ist.",
+ "publicPermissionWriteDescGuestsOff": "Angemeldete Nutzer dieser Instanz können den Kalender über „Geteilte Kalender“ hinzufügen, ansehen und bearbeiten. Ohne Konto ist kein Zugriff möglich, weil der Gastzugang auf dieser Instanz aus ist.",
+ "publicAccessDescriptionGuestsOn": "Bestimme den öffentlichen Zugriff für angemeldete Nutzer und Besucher ohne Konto.",
+ "publicAccessDescriptionGuestsOff": "Bestimme den öffentlichen Zugriff für angemeldete Nutzer dieser Instanz."
},
"token": {
"accessLinks": "Zugangslinks",
- "accessLinksDescription": "Teile diesen Kalender über sichere Links",
- "createLink": "Link erstellen",
- "createFirstLink": "Ersten Link erstellen",
- "noTokensYet": "Noch keine Zugangslinks",
- "noTokensDescription": "Erstelle einen Freigabelink, um anderen Zugriff zu gewähren",
"unnamed": "Unbenannt",
- "namePlaceholder": "z.B. Familien-Link, Arbeitsteam",
"token": "Token",
- "tokenValue": "Token-Wert",
- "readOnlyDescription": "Schichten und Notizen ansehen",
- "editDescription": "Schichten erstellen und bearbeiten",
- "expiration": "Ablauf",
- "expires": "Läuft ab",
- "expired": "Abgelaufen",
"expiration1Day": "1 Tag",
"expiration7Days": "7 Tage",
"expiration30Days": "30 Tage",
- "expirationNever": "Niemals",
- "expiresOn": "Läuft ab am",
- "usage": "Nutzung",
"usedCount": "{count, plural, =0 {Nie verwendet} =1 {1x verwendet} other {#x verwendet}}",
- "neverUsed": "Nie verwendet",
"enable": "Aktivieren",
"disable": "Deaktivieren",
"revoke": "Widerrufen",
"revokeConfirm": "Zugangslink widerrufen?",
- "revokeConfirmDescription": "Bist du sicher, dass du \"{name}\" widerrufen möchtest? Jeder, der diesen Link verwendet, verliert sofort den Zugriff.",
- "generate": "Link generieren",
- "shareLink": "Freigabelink",
- "linkCreated": "Link erstellt!",
- "linkCreatedDescription": "Dein Freigabelink wurde erfolgreich erstellt",
- "saveWarning": "Speichere diesen Link jetzt - er wird nicht erneut angezeigt!",
- "shareInfo": "Jeder mit diesem Link kann auf deinen Kalender mit der angegebenen Berechtigungsstufe zugreifen",
- "accessedViaLink": "Zugriff über Freigabelink",
- "linkName": "Link-Name",
- "createLinkDescription": "Erstelle einen Zugangslink, um diesen Kalender zu teilen"
+ "revokeConfirmDescription": "Bist du sicher, dass du \"{name}\" widerrufen möchtest? Jeder, der diesen Link verwendet, verliert sofort den Zugriff."
},
"rateLimit": {
"title": "Zu viele Anfragen",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Aktivitätsprotokoll",
- "description": "Zeigt deine Kontoaktivität und Sicherheitsereignisse an",
+ "description": "Anmeldungen, Änderungen und Sicherheitsereignisse deines Kontos",
"noLogs": "Noch keine Aktivität aufgezeichnet",
"eventType": "Ereignistyp",
"resource": "Ressource",
"details": "Details",
"clearAll": "Alle löschen",
- "refresh": "Aktualisieren",
- "refreshed": "Aktivitätsprotokoll aktualisiert",
"confirmClear": "Bist du sicher, dass du alle Aktivitätsprotokolle löschen möchtest? Dies kann nicht rückgängig gemacht werden.",
- "totalLogs": "{count} Protokolle insgesamt",
+ "totalLogs": "{count, plural, one {# Eintrag} other {# Einträge}}",
"showingResults": "Zeige {start}-{end} von {total}",
"searchPlaceholder": "Suche nach Aktion, Ressource oder ID...",
"noMetadata": "Keine zusätzlichen Details verfügbar",
@@ -622,7 +467,8 @@
"auth": "Authentifizierung",
"sync": "Synchronisation",
"security": "Sicherheit",
- "calendar": "Kalender"
+ "calendar": "Kalender",
+ "heading": "Ereignisse"
},
"admin": {
"title": "Admin-Panel",
@@ -630,7 +476,6 @@
"dashboard": "Dashboard",
"usersMenu": "Benutzer",
"calendarsMenu": "Kalender",
- "orphanedCalendars": "Verwaiste Kalender",
"auditLogs": "Audit-Logs",
"backToApp": "Zurück zur App",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Seitenleiste einklappen",
"accessDenied": "Admin-Zugriff erforderlich",
"stats": {
- "totalUsers": "Benutzer gesamt",
- "totalCalendars": "Kalender gesamt",
- "orphanedCalendars": "Verwaiste Kalender",
- "totalShifts": "Schichten gesamt",
- "activeShares": "Aktive Freigaben",
- "recentActivity": "Letzte Aktivitäten",
"usersByRole": "{superadmin} Superadmin, {admin} Admin, {user} Benutzer",
- "calendarsDescription": "Kalender mit Besitzern",
- "orphanedDescription": "Kalender ohne Besitzer",
"sharesDescription": "{user} Benutzerfreigaben, {token} Token-Freigaben",
- "shiftsDescription": "Schichten über alle Kalender",
- "last7Days": "Letzte 7 Tage",
- "needsAttention": "Benötigt Aufmerksamkeit"
+ "last7Days": "Letzte 7 Tage"
},
"systemInfo": {
"title": "Systeminformationen",
- "description": "Aktuelle Systemversion und Build-Details",
"version": "Version",
"buildDate": "Build-Datum",
"commitHash": "Commit-Hash",
@@ -666,29 +500,20 @@
"development": "Entwicklung",
"unknown": "Unbekannt"
},
- "dashboardDescription": "Willkommen im BetterShift Admin-Panel",
"orphanedCalendarsWarning": "Verwaiste Kalender erkannt",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {Es gibt 1 Kalender ohne Besitzer} other {Es gibt # Kalender ohne Besitzer}}. Bitte weise diese(n) Benutzern zu.",
- "manageOrphanedCalendars": "Verwaiste Kalender verwalten",
"recentActivityDescription": "Admin- und sicherheitsrelevante Aktivitätsprotokolle",
"statsFetchError": "Fehler beim Laden der Statistiken",
- "userManagement": "Benutzerverwaltung",
- "userManagementDescription": "Benutzerkonten und Berechtigungen verwalten",
"searchUsers": "Nach Name oder E-Mail suchen...",
"allRoles": "Alle Rollen",
"allStatuses": "Alle Status",
"banned": "Gesperrt",
"role": "Rolle",
"calendarsCount": "Kalender",
- "page": "Seite",
- "usersCount": "{count, plural, =0 {Keine Benutzer} =1 {1 Benutzer} other {# Benutzer}}",
"neverActive": "Nie",
"editUser": "Benutzer bearbeiten",
- "editUserDescription": "Benutzerinformationen und Berechtigungen aktualisieren",
"userDetails": "Benutzerdetails",
- "userDetailsDescription": "Detaillierte Benutzerinformationen anzeigen",
"ownedCalendars": "Eigene Kalender",
- "joined": "Beigetreten",
"banUser": "Benutzer sperren",
"banUserConfirm": "Benutzer {name} sperren?",
"banWarning": "Der Benutzer wird sofort abgemeldet und kann sich erst wieder anmelden, wenn die Sperre aufgehoben wird.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "Eine Änderung der Benutzerrolle wirkt sich sofort auf die Berechtigungen aus",
"calendars": {
- "title": "Kalenderverwaltung",
- "description": "Verwalte alle Kalender im System",
"owner": "Besitzer",
"updated": "Aktualisiert",
"guestPermission": "Gastberechtigung",
@@ -736,8 +559,6 @@
"orphanedOnly": "Nur verwaiste",
"withOwner": "Mit Besitzer",
"searchPlaceholder": "Nach Name suchen...",
- "calendarsCount": "{count, plural, =0 {Keine Kalender} =1 {1 Kalender} other {# Kalender}}",
- "selectedCount": "{count, plural, =1 {1 Kalender ausgewählt} other {# Kalender ausgewählt}}",
"transferSelected": "Ausgewählte übertragen",
"clearSelection": "Auswahl löschen",
"noCalendarsFound": "Keine Kalender gefunden",
@@ -748,19 +569,13 @@
"transferOwnership": "Besitz übertragen",
"deleteCalendar": "Kalender löschen",
"calendarDetails": "Kalenderdetails",
- "calendarDetailsDescription": "Detaillierte Kalenderinformationen anzeigen",
- "userShares": "Benutzer",
- "tokenShares": "Token",
"userSharesList": "Benutzer-Freigaben",
"tokenSharesList": "Token-Freigaben",
"externalSyncs": "Externe Synchronisationen",
"externalSyncsShort": "Syncs",
"lastSynced": "Zuletzt synchronisiert",
- "quickActions": "Schnellaktionen",
- "editCalendarDescription": "Kalenderinformationen aktualisieren",
"namePlaceholder": "Kalendername eingeben",
"guestPermissionHint": "Kontrolliert den öffentlichen Zugriff auf diesen Kalender",
- "transferSingleDescription": "Besitz von \"{name}\" übertragen",
"transferMultipleDescription": "{count, plural, =1 {1 Kalender} other {# Kalender}} werden übertragen",
"calendarsToTransfer": "Zu übertragende Kalender",
"calendarToTransfer": "Zu übertragender Kalender",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 Kalender gelöscht} other {# Kalender gelöscht}}",
"calendarsTransferred": "{count, plural, =1 {1 Kalender übertragen} other {# Kalender übertragen}}"
},
- "auditLogsDescription": "Alle Protokolle verwalten",
"allActions": "Alle Aktionen",
"adminActions": "Admin-Aktionen",
"calendarActions": "Kalender-Aktionen",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Bitte wähle ein Datum",
"pleaseConfirmDeletion": "Bitte bestätige das Löschen",
"willDeleteLogsOlderThan": "Alle Protokolle älter als {date} werden gelöscht",
- "preview": "Vorschau",
"auditLogDetails": "Audit-Log-Details",
"resourceType": "Ressourcentyp",
"resourceId": "Ressourcen-ID",
@@ -815,5 +628,421 @@
"clearSelection": "Auswahl aufheben",
"deleteSelectedLogsDescription": "{count, plural, one {# ausgewähltes Protokoll} other {# ausgewählte Protokolle}} löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
"willDeleteSelectedLogs": "{count, plural, one {# Protokoll} other {# Protokolle}} werden dauerhaft gelöscht"
+ },
+ "appearance": {
+ "title": "Erscheinungsbild",
+ "hint": "Die Wahl gilt pro Gerät und wird lokal gespeichert. Der Wechsel greift sofort, ohne Neuladen.",
+ "system": {
+ "title": "System",
+ "description": "Folgt der Einstellung des Geräts"
+ },
+ "light": {
+ "title": "Hell",
+ "description": "Immer hell"
+ },
+ "dark": {
+ "title": "Dunkel",
+ "description": "Immer dunkel"
+ }
+ },
+ "appMenu": {
+ "account": "Konto",
+ "language": "Sprache",
+ "preferences": "Einstellungen",
+ "viewSettings": "Meine Ansicht",
+ "settingsAndAccount": "Einstellungen und Konto"
+ },
+ "calendarView": {
+ "previousMonth": "Vorheriger Monat",
+ "nextMonth": "Nächster Monat",
+ "today": "Heute",
+ "tomorrow": "Morgen",
+ "yesterday": "Gestern",
+ "calendarWeek": "KW {week}",
+ "weekdayShort": {
+ "monday": "Mo",
+ "tuesday": "Di",
+ "wednesday": "Mi",
+ "thursday": "Do",
+ "friday": "Fr",
+ "saturday": "Sa",
+ "sunday": "So"
+ },
+ "allDayShort": "ganztg.",
+ "externalCount": "{count} extern",
+ "hasNotes": "{count, plural, one {# Notiz} other {# Notizen}}",
+ "shift": "Schicht",
+ "kpiShifts": "Schichten",
+ "kpiHours": "Stunden",
+ "kpiNotes": "Notizen",
+ "kpiAvgPerShift": "⌀ pro Schicht",
+ "kpiFreeDays": "Freie Tage",
+ "dayEmpty": "An diesem Tag ist nichts eingetragen.",
+ "dayFree": "frei",
+ "notesCount": "{count, plural, one {# Notiz} other {# Notizen}}",
+ "addNoteOrEvent": "Notiz oder Event",
+ "monthTotal": "{month} gesamt",
+ "allShiftsIn": "Alle Schichten im {month}",
+ "openStats": "Diagramme und Auswertung",
+ "shiftCount": "{count, plural, one {# Schicht} other {# Schichten}}",
+ "shiftActions": "Aktionen für die Schicht",
+ "external": "extern",
+ "syncedReadOnly": "Aus einem externen Kalender, nur lesbar",
+ "changedOn": "geändert {date}",
+ "stamp": "Vorlagen",
+ "managePresets": "Vorlagen verwalten",
+ "createPreset": "Vorlage anlegen",
+ "manage": "Verwalten",
+ "stampHint": "Tag antippen setzt {title}, nochmal antippen entfernt ihn.",
+ "addShiftManually": "Schicht manuell anlegen",
+ "sheetDescription": "Schichten und Notizen des gewählten Tages",
+ "sheetExpand": "Aufziehen",
+ "sheetShrink": "Verkleinern",
+ "periodLabel": "Zeitraum",
+ "wholeWeek": "Ganze Woche",
+ "wholeMonth": "Ganzer Monat",
+ "wholeYear": "Ganzes Jahr",
+ "readOnlyTitle": "Nur lesen",
+ "readOnlyMessage": "Dieser Kalender wurde dir schreibgeschützt freigegeben. Vorlagen und Anlegen sind deshalb ausgeblendet.",
+ "offlineTitle": "Keine Verbindung zum Server",
+ "offlineMessage": "Du siehst den zuletzt geladenen Stand. Änderungen sind erst wieder möglich, wenn die Verbindung steht — sie werden nicht zwischengespeichert.",
+ "retry": "Erneut versuchen",
+ "note": "Notiz",
+ "event": "Event",
+ "eventCount": "{count, plural, one {# Event} other {# Events}}",
+ "statsSheetDescription": "Schichten, Stunden und freie Tage für Woche, Monat oder Jahr"
+ },
+ "calendarCompare": {
+ "title": "Vergleich",
+ "exit": "Beenden",
+ "addCalendar": "Dritter Kalender",
+ "stampActive": "Vorlage aktiv",
+ "tapToMoveStamp": "Vorlage anklicken, um sie in dieser Spalte zu setzen",
+ "subtitle": "{count} Kalender",
+ "laneHintTwo": "Obere Reihe {top}, untere {bottom} — erkennbar am Balken links. Leerer Rahmen heißt frei.",
+ "laneHintMany": "Reihen von oben: {order} — erkennbar am Balken links. Leerer Rahmen heißt frei.",
+ "maxHint": "höchstens {max}"
+ },
+ "formKit": {
+ "optional": " (optional)",
+ "customColor": "Eigene"
+ },
+ "settings": {
+ "title": "Einstellungen",
+ "description": "Gilt für alle mit Zugriff auf diesen Kalender",
+ "general": "Name und Farbe",
+ "generalHint": "Anzeigename, Kalenderfarbe, Löschen",
+ "presets": "Vorlagen",
+ "presetsHint": "{count, plural, =0 {Noch keine Vorlagen} one {# Vorlage} other {# Vorlagen}}",
+ "external": "Externe Kalender",
+ "externalHint": "{count, plural, =0 {Abo, Anzeigemodus, Intervall} one {# Abo, Anzeigemodus, Intervall} other {# Abos, Anzeigemodus, Intervall}}",
+ "sharing": "Freigaben",
+ "sharingHint": "{count, plural, =0 {Personen, öffentlicher Zugriff, Links} one {Personen, öffentlicher Zugriff, # aktiver Link} other {Personen, öffentlicher Zugriff, # aktive Links}}",
+ "export": "Exportieren",
+ "exportHint": "ICS-Datei oder PDF",
+ "view": "Kalenderansicht",
+ "viewHint": "Eigene Ansicht, Dichte, Sortierung",
+ "notifications": "Benachrichtigungen",
+ "notificationsHint": "Synchronisierung",
+ "notificationsError": "Fehler bei der Synchronisierung",
+ "deleteImpact": "{count, plural, =0 {Der Kalender wird endgültig gelöscht} one {# Schicht wird mitgelöscht} other {# Schichten werden mitgelöscht}}",
+ "appliesToAll": "Änderungen werden sofort für alle Freigaben wirksam.",
+ "groupAccount": "Konto",
+ "groupApp": "App",
+ "viewOn": "an",
+ "viewOff": "aus",
+ "groupPersonal": "Nur für dich",
+ "personalCaption": "Gilt in allen Kalendern, andere sehen es nicht"
+ },
+ "presetSheet": {
+ "title": "Vorlagen",
+ "description": "Reihenfolge bestimmt die Vorlagenleiste",
+ "primary": "In der Leiste",
+ "newPreset": "Neue Vorlage",
+ "titlePlaceholder": "z. B. Bereitschaft",
+ "start": "Beginn",
+ "end": "Ende",
+ "allDay": "Ganztägig",
+ "allDayShort": "ganztägig",
+ "markAsSecondary": "Unter „Weitere“ einklappen",
+ "hideFromStatsHint": "Zählt nicht in Stunden und Auswertung",
+ "notInStats": "Nicht in Statistik",
+ "save": "Vorlage speichern",
+ "delete": "Vorlage löschen",
+ "dragHandle": "Zum Sortieren ziehen",
+ "secondarySection": "Unter „Weitere“",
+ "markAsSecondaryHint": "Erscheint in der Vorlagenleiste erst nach Klick auf „Weitere“"
+ },
+ "syncSheet": {
+ "intervalPill": "Alle {interval}",
+ "intervalValue": "alle {interval}",
+ "lastSynced": "zuletzt {time}",
+ "syncNow": "Jetzt abrufen",
+ "sourceUrl": "Adresse abonnieren",
+ "sourceFile": "Datei importieren",
+ "chooseFile": "ICS-Datei auswählen",
+ "urlLabel": "Adresse der ICS-Datei",
+ "colorLabel": "Farbe aller importierten Schichten",
+ "displayLabel": "Darstellung im Kalender",
+ "displayMinimal": "Nur Anzahl",
+ "displayNormal": "Wie eigene",
+ "autoSyncLabel": "Automatisch abrufen",
+ "hideShifts": "Schichten dieses Abos ausblenden",
+ "excludeFromStats": "Aus der Statistik ausschließen",
+ "addSubscription": "Abo hinzufügen"
+ },
+ "syncLog": {
+ "description": "Letzte Abrufe externer Kalender",
+ "statusSuccess": "Erfolgreich"
+ },
+ "sharingSheet": {
+ "tabPeople": "Personen",
+ "invite": "Einladen",
+ "haveAccess": "Zugriff haben",
+ "owner": "Eigentümer",
+ "permRead": "Nur lesen",
+ "permWrite": "Bearbeiten",
+ "permReadDesc": "Kalender ansehen, nichts ändern",
+ "permWriteDesc": "Schichten anlegen und löschen",
+ "permAdminDesc": "Zusätzlich Freigaben und Einstellungen verwalten",
+ "changePermission": "Berechtigung für {name} ändern",
+ "publicOffTitle": "Öffentlicher Zugang ist aus",
+ "publicOnTitle": "Öffentlicher Zugang ist an",
+ "accessNone": "Kein Zugriff",
+ "guestNoneShort": "Nur Eingeladene und Links",
+ "activeLinks": "Aktive Links",
+ "inactiveLinks": "Deaktiviert oder abgelaufen",
+ "noActiveLinks": "Kein aktiver Link",
+ "expiresOn": "läuft ab am {date}",
+ "expiredOn": "abgelaufen am {date}",
+ "noExpiry": "unbefristet",
+ "lastUsed": "zuletzt {time}",
+ "newLink": "Neuen Link erzeugen",
+ "linkName": "Bezeichnung",
+ "linkNameHint": "optional, hilft beim Widerrufen",
+ "linkNamePlaceholder": "z. B. Aushang Pausenraum",
+ "validity": "Gültigkeit",
+ "validityUnlimited": "Unbefristet",
+ "validUntilRevoked": "gilt, bis du ihn widerrufst",
+ "createLink": "Link erzeugen",
+ "creating": "Wird erzeugt …",
+ "linkReady": "Link steht bereit",
+ "copyNowTitle": "Jetzt kopieren",
+ "copyNowBody": "Nach dem Schließen ist der Token nicht mehr abrufbar. Wer ihn verliert, erzeugt einen neuen und widerruft diesen.",
+ "shareLinkLabel": "Link zum Weitergeben",
+ "copied": "Kopiert",
+ "guestReadShortGuestsOn": "Alle können ansehen",
+ "guestWriteShortGuestsOn": "Alle können ändern",
+ "guestReadShortGuestsOff": "Angemeldete können ansehen",
+ "guestWriteShortGuestsOff": "Angemeldete können ändern",
+ "publicOffBodyGuestsOn": "Zugriff haben nur eingeladene Personen und Inhaber eines Zugangslinks – Links funktionieren auch ohne Konto. Über den Reiter „Öffentlich“ kannst du den Kalender für alle freigeben, auch für Besucher ohne Konto.",
+ "publicOffBodyGuestsOff": "Zugriff haben nur eingeladene Personen und Inhaber eines Zugangslinks; Link-Empfänger müssen sich anmelden, weil der Gastzugang auf dieser Instanz aus ist. Über den Reiter „Öffentlich“ kannst du den Kalender für angemeldete Nutzer dieser Instanz freigeben.",
+ "linkInfoGuestsOn": "Der Link öffnet den Kalender direkt, ohne Anmeldung. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig.",
+ "linkInfoGuestsOff": "Der Link öffnet den Kalender direkt. Weil der Gastzugang auf dieser Instanz aus ist, müssen sich Empfänger anmelden. Er lässt sich jederzeit in der Liste widerrufen — dann ist er sofort ungültig."
+ },
+ "shiftSheet": {
+ "start": "Beginn",
+ "end": "Ende",
+ "duration": "Dauer",
+ "allDay": "Ganztägig",
+ "noPreset": "Frei",
+ "createAction": "Schicht anlegen"
+ },
+ "noteSheet": {
+ "createTitle": "Neuer Eintrag",
+ "editTitle": "Eintrag bearbeiten",
+ "createAction": "Eintrag anlegen",
+ "typeEvent": "Event",
+ "typeNote": "Notiz",
+ "typeHint": "Ein Event erscheint mit Titel und Farbe in der Tageszelle. Eine Notiz bleibt unauffällig und erscheint nur als Symbol.",
+ "text": "Text",
+ "repeat": "Wiederholung",
+ "repeatNone": "Einmalig",
+ "repeatWeekly": "Wöchentlich",
+ "repeatMonthly": "Monatlich",
+ "repeatYearly": "Jährlich",
+ "unitWeeks": "{count, plural, one {Woche} other {Wochen}}",
+ "unitMonths": "{count, plural, one {Monat} other {Monate}}",
+ "unitYears": "{count, plural, one {Jahr} other {Jahre}}",
+ "intervalInactive": "nur bei Wiederholung",
+ "recurrenceWeeks": "{count, plural, one {wöchentlich} other {alle # Wochen}}",
+ "recurrenceMonths": "{count, plural, one {monatlich} other {alle # Monate}}",
+ "recurrenceYears": "{count, plural, one {jährlich} other {alle # Jahre}}",
+ "listTitle": "Notizen und Events",
+ "entryCount": "{count, plural, one {# Eintrag} other {# Einträge}}",
+ "addAnother": "Weiteren Eintrag anlegen",
+ "shortcutHint": "Abkürzung: Rechtsklick auf einen Tag am Desktop, langes Drücken am Handy."
+ },
+ "authPage": {
+ "loginSubtitle": "Weiter zu deinen Kalendern",
+ "signInWith": "Mit {provider} anmelden",
+ "registerTitle": "Konto anlegen",
+ "registerSubtitle": "Danach bist du direkt angemeldet",
+ "passwordHint": "Mindestens 8 Zeichen",
+ "repeatPassword": "Passwort wiederholen",
+ "passwordsMatch": "Passwörter stimmen überein",
+ "haveAccount": "Schon ein Konto?",
+ "showPassword": "Passwort anzeigen",
+ "hidePassword": "Passwort verbergen",
+ "sampleMonth": "Beispielmonat",
+ "instance": "Instanz"
+ },
+ "emptyState": {
+ "guestBadge": "Gast",
+ "noCalendarTitle": "Noch kein Kalender",
+ "noCalendarDescription": "Ein Kalender fasst Schichten, Vorlagen und Freigaben einer Gruppe zusammen. Du kannst später beliebig viele anlegen und zwischen ihnen wechseln.",
+ "createCalendar": "Kalender anlegen",
+ "browseShared": "Freigegebene durchsuchen",
+ "guestTitle": "Kein Kalender öffentlich freigegeben",
+ "guestDescription": "Ohne Konto siehst du nur Kalender, die ausdrücklich für Gäste geöffnet wurden. Wenn du einen Zugangslink bekommen hast, öffne ihn direkt – der Link enthält den Zugriff.",
+ "pasteAccessLink": "Zugangslink einfügen",
+ "accessLinkDescription": "Füge den Link ein, den du bekommen hast – oder nur den Token daraus.",
+ "accessLinkLabel": "Zugangslink",
+ "accessLinkInvalid": "Das ist kein gültiger Zugangslink.",
+ "openAccessLink": "Öffnen"
+ },
+ "discovery": {
+ "unsubscribe": "Deabonnieren"
+ },
+ "profile": {
+ "title": "Mein Konto",
+ "navProfileHint": "Name, E-Mail, Profilbild",
+ "navPasswordHint": "Aktuelles Passwort bestätigen",
+ "navSessionsHint": "{count, plural, one {# Gerät angemeldet} other {# Geräte angemeldet}}",
+ "navActivityHint": "Was zuletzt geändert wurde",
+ "navDangerHint": "Abmelden, Konto löschen",
+ "groupAccount": "Konto",
+ "groupSecurity": "Sicherheit",
+ "chooseImage": "Bild wählen",
+ "removeImage": "Entfernen",
+ "appliesEverywhere": "Änderungen gelten sofort für alle Geräte.",
+ "discard": "Verwerfen",
+ "managedByProvider": "Name und E-Mail kommen von deinem Anmeldeanbieter und lassen sich hier nicht ändern.",
+ "accountsTitle": "Anmeldemethoden",
+ "accountsHint": "Mit diesen Konten kannst du dich anmelden.",
+ "connectedSince": "Verbunden seit {date}",
+ "passwordNote": "Andere Geräte bleiben angemeldet.",
+ "sessionsTitle": "Angemeldete Geräte",
+ "sessionsHint": "Abmelden beendet die Sitzung sofort.",
+ "signOutOthers": "Alle anderen abmelden",
+ "thisDevice": "dieses Gerät",
+ "activeNow": "gerade aktiv",
+ "sessionRevoked": "Gerät abgemeldet",
+ "unknownBrowser": "Unbekannter Browser",
+ "unknownOs": "Unbekanntes System",
+ "deleteImpact": "Kalender, Schichten und Freigaben werden mitgelöscht.",
+ "deleteNeedsPassword": "Verlangt dein Passwort."
+ },
+ "adminKit": {
+ "banned": "Gesperrt",
+ "active": "Aktiv",
+ "severityInfo": "info",
+ "severityWarning": "Warnung",
+ "severityError": "Fehler",
+ "severityCritical": "kritisch"
+ },
+ "adminShell": {
+ "logsShort": "Logs",
+ "breadcrumb": "Navigationspfad"
+ },
+ "adminDashboard": {
+ "title": "Übersicht",
+ "attention": "{count, plural, one {Eine Sache braucht Aufmerksamkeit} other {# Dinge brauchen Aufmerksamkeit}}",
+ "allClear": "Nichts braucht gerade Aufmerksamkeit",
+ "openCalendars": "Kalender öffnen",
+ "recentTitle": "Was zuletzt passiert ist",
+ "recentShort": "Zuletzt passiert",
+ "activityFooter": "{shown} von {count, plural, one {# Ereignis} other {# Ereignissen}}",
+ "scope": "Umfang",
+ "events": "Ereignisse",
+ "acrossCalendars": "über alle Kalender",
+ "calendarsAllOwned": "alle mit Besitzer",
+ "calendarsOrphaned": "{count, plural, one {# verwaist} other {# verwaist}}",
+ "usersSub": "{count, plural, one {# Konto} other {# Konten}}",
+ "calendarsSub": "{count, plural, one {# Kalender} other {# Kalender}}, {orphaned} verwaist",
+ "logsSub": "{count, plural, one {# Ereignis} other {# Ereignisse}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# Eintrag} other {# Einträge}}",
+ "dateRange": "Zeitraum",
+ "clearRange": "Zeitraum zurücksetzen",
+ "filterTitle": "Filter",
+ "done": "Fertig",
+ "selectAll": "Alle auf dieser Seite auswählen",
+ "selectEntry": "Eintrag auswählen",
+ "severityShort": "Schwere",
+ "whatHappened": "Was passiert ist",
+ "details": "Details",
+ "describe": {
+ "userBanned": "{user} gesperrt",
+ "userBannedPermanently": "{user} dauerhaft gesperrt",
+ "userUnbanned": "Sperre für {user} aufgehoben",
+ "passwordReset": "Passwort für {user} zurückgesetzt",
+ "userDeleted": "Konto {user} gelöscht",
+ "userUpdated": "Konto {user} bearbeitet",
+ "calendarTransferred": "Kalender „{calendar}“ an {user} übertragen",
+ "calendarsTransferred": "{count, plural, one {# Kalender} other {# Kalender}} an {user} übertragen",
+ "calendarsDeleted": "{count, plural, one {# Kalender} other {# Kalender}} gelöscht",
+ "logsDeleted": "{count, plural, one {# Protokolleintrag} other {# Protokolleinträge}} gelöscht",
+ "calendarUpdated": "Kalender „{calendar}“ bearbeitet",
+ "calendarDeleted": "Kalender „{calendar}“ gelöscht",
+ "calendarCreated": "Kalender „{calendar}“ angelegt",
+ "calendarShared": "Kalender „{calendar}“ für {user} freigegeben",
+ "shareRemoved": "Freigabe von „{calendar}“ für {user} entfernt",
+ "permissionChanged": "Berechtigung von {user} für „{calendar}“ geändert",
+ "guestPermissionChanged": "Gastzugriff für „{calendar}“ geändert",
+ "syncCreated": "Synchronisierung „{sync}“ angelegt",
+ "syncDeleted": "Synchronisierung „{sync}“ entfernt",
+ "syncDisabled": "Synchronisierung „{sync}“ deaktiviert, Kalender ohne Besitzer",
+ "syncFailed": "Synchronisierung „{sync}“ fehlgeschlagen",
+ "syncExecuted": "„{sync}“ synchronisiert: {added} neu, {updated} geändert, {deleted} entfernt",
+ "rateLimit": "Anfragelimit erreicht ({endpoint})",
+ "loginProvider": "Anmeldung über {provider}",
+ "loginEmail": "Anmeldung mit E-Mail und Passwort",
+ "loginFailed": "Fehlgeschlagene Anmeldung für {email}",
+ "registered": "Neues Konto {email} registriert",
+ "profileUpdated": "Profil bearbeitet",
+ "passwordChanged": "Passwort geändert",
+ "accountDeleted": "Eigenes Konto gelöscht",
+ "sessionsRevoked": "{count, plural, one {# Sitzung} other {# Sitzungen}} beendet"
+ }
+ },
+ "adminUsers": {
+ "actions": "Aktionen",
+ "all": "Alle",
+ "ban": "Sperren",
+ "banReasonQuoted": "Grund: „{reason}“",
+ "calendarCount": "{count, plural, one {# Kalender} other {# Kalender}}",
+ "edit": "Bearbeiten",
+ "filterLabel": "Benutzer filtern",
+ "hidePassword": "Passwort verbergen",
+ "joinedOn": "Beigetreten {date}",
+ "moreActions": "Weitere Aktionen",
+ "moreFilters": "Weitere Filter",
+ "numbers": "Zahlen",
+ "showPassword": "Passwort anzeigen",
+ "subtitle": "{count, plural, one {# Konto} other {# Konten}}{banned, plural, =0 {} other {, davon # gesperrt}}"
+ },
+ "adminCalendars": {
+ "content": "Inhalt",
+ "filterLabel": "Kalender filtern",
+ "filterShared": "Geteilt",
+ "filterSynced": "Mit Sync",
+ "guestColumn": "Gastrecht",
+ "guestNoneHint": "Nur Personen mit Freigabe sehen den Kalender",
+ "guestPermissionValue": "Gastberechtigung: {permission}",
+ "guestReadHint": "Wer den Link kennt, sieht den Kalender",
+ "guestWriteHint": "Wer den Link kennt, kann den Kalender bearbeiten",
+ "publicAccess": "Öffentlicher Zugriff",
+ "selectAll": "Alle auswählen",
+ "selectedCount": "Ausgewählt: {count}",
+ "selectedNone": "Ausgewählt: keine",
+ "sharesAndLinks": "Freigaben, {links, plural, one {# Zugangslink} other {# Zugangslinks}}",
+ "showOrphaned": "Anzeigen",
+ "subtitle": "{count, plural, one {# Kalender} other {# Kalender}}, {shifts, plural, one {# Schicht} other {# Schichten}} insgesamt"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} von {total}",
+ "label": "Seiten"
}
}
diff --git a/messages/en.json b/messages/en.json
index de8ff76..4e85c24 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -12,15 +12,11 @@
"save": "Save",
"saving": "Saving...",
"close": "Close",
- "optional": "(optional)",
"delete": "Delete",
"loading": "Loading...",
- "add": "Add",
- "adding": "Adding...",
"or": "or",
"next": "Next",
"previous": "Previous",
- "of": "of",
"unsavedChanges": "Unsaved Changes",
"unsavedChangesDescription": "You have unsaved changes. Do you really want to close without saving?",
"closeWithoutSaving": "Close Without Saving",
@@ -30,7 +26,6 @@
"createError": "Failed to create {item}",
"updateError": "Failed to update {item}",
"deleteError": "Failed to delete {item}",
- "deleteConfirm": "Really delete {item} \"{name}\"?",
"shifts": "Shifts",
"success": "Success",
"error": "Error",
@@ -58,15 +53,6 @@
"deleteSelected": "Delete Selected",
"viewAll": "View All",
"viewDetails": "View Details",
- "weekday": {
- "monday": "Mon",
- "tuesday": "Tue",
- "wednesday": "Wed",
- "thursday": "Thu",
- "friday": "Fri",
- "saturday": "Sat",
- "sunday": "Sun"
- },
"labels": {
"name": "Name",
"email": "Email",
@@ -97,8 +83,7 @@
"users": "Users"
},
"status": {
- "active": "Active",
- "inactive": "Inactive"
+ "active": "Active"
},
"roles": {
"admin": "Admin",
@@ -106,12 +91,14 @@
"user": "User"
},
"time": {
- "never": "Never",
"lastActive": "Last Active"
},
"filters": {
"allSeverities": "All Severities",
- "clearFilters": "Clear Filters"
+ "clearFilters": "Clear Filters",
+ "title": "Filters",
+ "done": "Done",
+ "remove": "Remove {filter}"
},
"severity": {
"info": "Info",
@@ -120,7 +107,6 @@
"critical": "Critical"
},
"stats": {
- "statistics": "Statistics",
"created": "Created"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Color",
"notesLabel": "Notes (optional)",
"notesPlaceholder": "Additional information...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organize your shifts"
+ "title": "BetterShift"
},
"calendar": {
"title": "Calendar",
"create": "Create New Calendar",
"createDescription": "Create a new calendar to organize your shifts",
- "selectDescription": "Choose a calendar to manage your shifts",
"name": "Calendar Name",
"myCalendars": "My Calendars",
"sharedCalendars": "Shared Calendars",
"tokenCalendars": "Via Access Link",
"publicCalendars": "Public Calendars",
- "select": "Your BetterShift Calendar",
"deleteCalendar": "Delete Calendar",
"deleteWarning": "All shifts, presets and notes will also be deleted.",
- "settings": "Calendar Settings for \"{name}\"",
- "settingsDescription": "Customize name and color",
"compare": "Compare Calendars",
"compareMode": "Comparison Mode",
- "exitCompare": "Exit Comparison",
"selectToCompare": "Select calendars to compare",
"selectToCompareDescription": "Choose 2-3 calendars to view them side by side",
"compareSelected": "{count} selected",
"startComparing": "Start Comparing",
- "mobileNotOptimized": "The comparison view is not optimized for mobile. Please use a larger screen for the best experience.",
"shareLink": "Share Link",
- "shareLinkDescription": "Copy link to comparison view",
"browseCalendars": "Shared Calendars",
"browseCalendarsDescription": "Discover and manage calendar subscriptions",
"subscribe": "Subscribe",
- "subscribed": "Subscribed",
"noPublicCalendars": "No public calendars available",
"noSharedCalendars": "No calendars shared with you yet",
"noHiddenCalendars": "No hidden calendars",
@@ -201,81 +177,45 @@
"customDescription": "Choose a custom color using the color picker"
},
"note": {
- "create": "Create {item}",
- "edit": "Edit {item}",
"note": "Note",
"placeholder": "e.g., Early shift because appointment in the afternoon...",
- "hintMobile": "To add or edit a note or event, long press on a day in the calendar.",
- "hintDesktop": "To add or edit a note or event, right-click on a day in the calendar.",
"type": "Type",
- "typeNote": "Notes",
"typeEvent": "Events",
"eventColor": "Event Color",
- "eventTitle": "Event Name",
"eventPlaceholder": "e.g., Christmas, Birthday...",
- "recurring": "Repeat",
- "recurringNone": "Don't repeat",
- "recurringCustom": "Custom",
- "recurringEveryWeeks": "Every {count} weeks",
- "recurringEveryMonths": "Every {count} months",
"customInterval": "Interval",
"every": "Every",
- "weeks": "weeks",
- "months": "months",
- "multipleEntries": "{count} entries",
"noEntries": "No notes or events available",
"recurringEditWarning": "This is a recurring event. Changes will affect all occurrences."
},
"shift": {
"create": "New Shift",
- "createDescription": "Add a new shift to your calendar",
"edit": "Edit Shift",
- "editDescription": "Update the shift details",
"date": "Date",
- "startTime": "Start Time",
- "endTime": "End Time",
"titlePlaceholder": "e.g., Morning Shift",
"titleLabel": "Title",
- "allDay": "All Day",
"allDayShift": "All-day shift",
"noShiftsInMonth": "No shifts this month",
- "noShiftsInMonthDescription": "Add shifts by clicking on days in the calendar above.",
- "shift_one": "shift",
- "selectPreset": "Select Preset",
- "none": "None"
+ "shift_one": "shift"
},
"preset": {
"preset": "Preset",
- "createNew": "Create New Preset",
- "createYourFirst": "Create Your First Preset",
"edit": "Edit Preset",
- "manage": "Manage Presets",
- "manageDescription": "Edit or delete your shift presets",
"saveAsPreset": "Save as preset",
"presetName": "Preset name",
"presetNamePlaceholder": "e.g., Morning Shift, Evening Shift...",
"noPresets": "No shift presets yet",
- "createFirstDescription": "Create your first preset to quickly add shifts to your calendar. Presets save your frequently used shift times and details.",
"deleteConfirm": "Delete this preset? This will also delete all shifts created from this preset.",
- "primaryPresets": "Primary Presets",
- "secondaryPresets": "Secondary Presets",
- "secondary": "Secondary",
- "markAsSecondary": "Mark as secondary (collapsed by default)",
- "hideFromStats": "Hide from statistics",
- "hideFromStatsHint": "Exclude shifts from this preset from statistics",
- "showPresets": "Show presets",
- "hidePresets": "Hide presets",
- "hiddenFromStats": "Hidden from statistics",
- "cannotAddPresetHint": "This preset belongs to a different calendar and cannot be added here."
+ "secondary": "More",
+ "hideFromStats": "Hide from statistics"
},
"view": {
- "settingsTitle": "View Settings",
- "settingsDescription": "Customize how shifts are displayed in all calendars",
+ "settingsTitle": "My view",
+ "settingsDescription": "Your personal view. Applies to all calendars without their own view and is only visible to you.",
"shiftsPerDay": "Regular shifts per day",
- "shiftsPerDayHint": "Maximum number of regular shifts to display per day",
+ "shiftsPerDayHint": "More appear as “+N”. Auto shows as many as fit into the day cell.",
"externalShiftsPerDay": "External shifts per day",
- "externalShiftsPerDayHint": "Maximum number of external calendar shifts to display per day",
- "showAll": "All",
+ "externalShiftsPerDayHint": "Applies to external calendars shown “Like your own”. More appear as “+N”.",
"sortOptions": "Sort Options",
"sortBy": "Sort by",
"sortByStartTime": "Start time",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Descending",
"combinedSort": "Sort all shifts together",
"combinedSortHint": "Sort regular and external shifts together instead of separately",
- "displayOptions": "Display Options",
"showNotes": "Show shift notes",
- "showNotesHint": "Display shift notes in calendar grid",
- "showFullTitles": "Show full shift titles",
- "showFullTitlesHint": "Display complete shift titles without truncation",
+ "showNotesHint": "A shift's note as a second line in the month view",
"dayHighlighting": "Day Highlighting",
"highlightWeekends": "Highlight Weekends",
"highlightWeekendsHint": "Highlight Saturdays and Sundays with color",
@@ -303,7 +240,17 @@
"friday": "Friday",
"saturday": "Saturday",
"sunday": "Sunday",
- "highlightColor": "Highlight Color"
+ "highlightColor": "Highlight Color",
+ "density": "Density",
+ "showPresetBar": "Show preset bar",
+ "showPresetBarHint": "Preset bar below or above the calendar",
+ "settingsDescriptionLocal": "Your personal view on this device. Applies to all calendars without their own view.",
+ "overriddenByCalendar": "“{calendar}” has its own view. Your personal view does not apply there.",
+ "calendarOwn": "Own view for this calendar",
+ "calendarOwnHint": "Applies to everyone with access to this calendar.",
+ "calendarOffNote": "Everyone sees their personal view here. You set yours under “My view”.",
+ "calendarLocked": "Set for this calendar. Only people who manage the calendar can change it.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Shift Statistics",
@@ -329,52 +276,16 @@
"connected": "Connected to server",
"disconnected": "Connection to server lost"
},
- "onboarding": {
- "welcome": "Welcome to BetterShift",
- "description": "Create your first calendar to manage your shifts.",
- "createCalendar": "Create Calendar"
- },
- "guestEmptyState": {
- "title": "No Public Calendars Available",
- "description": "There are currently no public calendars shared. Please log in to create and manage your own calendars.",
- "loginButton": "Go to Login"
- },
- "footer": {
- "version": "Version",
- "github": "GitHub",
- "support": "Support"
- },
- "theme": {
- "switchToLight": "Switch to light mode",
- "switchToDark": "Switch to dark mode"
- },
"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",
"importMethod": "Import Method",
- "importMethodUrl": "URL (can be synced)",
- "importMethodFile": "Upload File (one-time import)",
"importMethodUrlHint": "External calendar URL (iCloud, Google, or other ICS URLs)",
"importMethodFileHint": "Import ICS file once",
"fileLabel": "ICS File",
- "fileSelected": "File selected",
"oneTimeImport": "One-time import",
- "displayMode": "Display synced shifts",
- "displayModeNormal": "Normal (show all shifts)",
- "displayModeMinimal": "Minimal (show count only)",
- "displayModeHint": "Choose how synced shifts should be displayed in the calendar",
- "addNewSync": "Add New External Calendar",
- "editSync": "Edit External Calendar",
- "colorHint": "Choose the color for all imported shifts",
- "hideCalendar": "Hide calendar",
- "hideCalendarHint": "Hide shifts from this calendar",
- "hideFromStats": "Hide from statistics",
- "hideFromStatsHint": "Exclude shifts from this calendar from statistics",
- "lastSynced": "Last synced",
"delete": "Delete External Calendar",
"deleteConfirm": "Delete this external calendar? All imported shifts will be removed.",
"hintsTitle": "Finding Your Calendar URL",
@@ -384,8 +295,6 @@
"hintICloud": "Open iCloud.com → Calendar → Click the share icon next to your calendar → Enable 'Public Calendar' → Copy the webcal:// URL and paste it here.",
"hintGoogle": "Open Google Calendar → Settings → Select your calendar → Scroll to 'Secret address in iCal format' → Copy the URL and paste it here.",
"hintCustom": "Any publicly accessible ICS calendar will work. The URL must start with https:// or webcal:// and end with .ics. Example: https://example.com/calendar.ics",
- "autoSyncLabel": "Auto Sync",
- "autoSyncHint": "Choose how often this calendar should automatically sync",
"autoSyncManual": "Manual",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automatic",
"syncTypeManual": "Manual",
"noChanges": "No changes",
- "errorMessage": "Error message",
"filterAll": "Show all",
"filterSuccess": "Success only",
"filterError": "Errors only",
@@ -415,9 +323,6 @@
"viewOnGitHub": "View on GitHub"
},
"export": {
- "title": "Export Calendar",
- "description": "Export your calendar as an ICS or PDF file",
- "exportCalendar": "Export Calendar",
"formatLabel": "Export Format",
"icsFormat": "ICS (Calendar File)",
"pdfFormat": "PDF (Document)",
@@ -432,34 +337,19 @@
"download": "Download",
"multiCalendar": "Export multiple calendars",
"multiCalendarHint": "Combine shifts from multiple calendars into one export file",
- "selectCalendars": "Select Calendars",
- "selectCalendarsDescription": "Choose which calendars to include in the export",
"selectedCount": "{count, plural, =0 {No calendars selected} =1 {1 calendar selected} other {# calendars selected}}",
"selectAtLeastOne": "Please select at least one calendar"
},
"update": {
- "available": "Update Available",
- "newVersion": "Version {version} is available",
- "viewChangelog": "View Changelog"
+ "newVersion": "Version {version} is available"
},
"auth": {
"login": "Sign In",
- "loginTitle": "Sign in to BetterShift",
- "loginDescription": "Sign in with your account or use one of the providers below",
"register": "Sign Up",
- "registerTitle": "Create Account",
- "registerDescription": "Create a new account to get started",
"logout": "Sign Out",
"profile": "Profile",
- "profileTitle": "Your Profile",
- "profileDescription": "Manage your account settings and preferences",
- "profileBasicInfoDescription": "Your basic account information",
- "changePasswordDescription": "Update your password to keep your account secure",
- "connectedAccountsDescription": "Manage your connected OAuth providers",
"dangerZone": "Danger Zone",
- "dangerZoneDescription": "Irreversible actions that affect your account",
"logoutDescription": "Sign out from your current session",
- "deleteAccountDescription": "Permanently delete your account and all data",
"noConnectedAccounts": "No connected accounts yet",
"emailPasswordAuth": "Email/Password",
"emailPlaceholder": "[email protected]",
@@ -468,13 +358,9 @@
"confirmPasswordLabel": "Password Confirmation",
"enterPassword": "Enter password",
"namePlaceholder": "Your name",
- "continueWith": "Continue with {provider}",
- "alreadyHaveAccount": "Already have an account?",
"noAccountYet": "Don't have an account yet?",
"changePassword": "Change Password",
"deleteAccount": "Delete Account",
- "editProfile": "Edit Profile",
- "editProfileDescription": "Update your name, email, and profile picture",
"profileUpdated": "Profile updated successfully",
"profilePicture": "Profile Picture",
"avatarHint": "Max 5MB. Supported formats: JPEG, PNG, GIF, WebP",
@@ -503,47 +389,27 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Manage your logged-in devices and sessions",
"noActiveSessions": "No active sessions",
- "browser": "Browser",
- "operatingSystem": "OS",
- "logoutAllDevices": "Logout from all other devices",
"sessionsRevokedCount": "Logged out from {count} device(s)"
},
"system": {
"unavailable": "System Unavailable",
- "unavailableDescription": "The system is currently unavailable due to a critical error. Please try again later or contact an administrator.",
- "unavailableRetry": "Please refresh this page to try again or check back later."
+ "unavailableDescription": "The system is currently unavailable due to a critical error. Please try again later or contact an administrator."
},
"guest": {
"viewingAsGuest": "You are viewing as guest",
"bannerMessage": "You are viewing this calendar as a guest. Sign in for full access.",
- "loginForFullAccess": "Sign in for full access",
"cannotEdit": "You cannot edit in read-only mode"
},
"share": {
- "manageSharing": "Manage Sharing",
- "manageSharingDescription": "Control who can access \"{name}\"",
- "userShares": "User Shares",
"publicAccess": "Public Access",
- "accessLinks": "Access Links",
"public": "Public",
"links": "Links",
"share": "share",
- "sharedBy": "Shared By",
- "sharedOn": "Shared On",
- "addUser": "Add User",
- "addUserDescription": "Search for a user to share this calendar with",
"searchUser": "Search user",
"searchUserPlaceholder": "Enter name or email...",
- "selectedUser": "Selected user",
- "noShares": "No users have access yet",
"noSharesDescription": "Share this calendar with other users to collaborate",
- "userSharesDescription": "Manage who can access this calendar",
- "publicAccessDescription": "Control public access for authenticated and guest users",
- "publicPermissionNoneDesc": "No one can access this calendar without being explicitly shared",
- "publicPermissionReadDesc": "Any authenticated user can view the calendar",
- "publicPermissionWriteDesc": "Any authenticated user can view and edit the calendar",
+ "publicPermissionNoneDesc": "Only you, invited people and holders of an access link have access.",
"shareAdded": "Calendar shared successfully",
"shareUpdated": "Permission updated successfully",
"shareRemoved": "Access removed successfully",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "Remove calendar access?",
"removeShareConfirmDesc": "Are you sure you want to remove access for {user}? They will no longer be able to view or edit this calendar.",
"you": "You",
- "sharedWithYou": "Shared with you"
+ "sharedWithYou": "Shared with you",
+ "publicPermissionReadDescGuestsOn": "Anyone can view the calendar, even without an account. Signed-in users add it via “Shared Calendars”.",
+ "publicPermissionWriteDescGuestsOn": "Anyone can view and edit the calendar, even without an account. Signed-in users add it via “Shared Calendars”.",
+ "publicPermissionReadDescGuestsOff": "Signed-in users of this instance can add and view the calendar via “Shared Calendars”. There is no access without an account, because guest access is off on this instance.",
+ "publicPermissionWriteDescGuestsOff": "Signed-in users of this instance can add, view and edit the calendar via “Shared Calendars”. There is no access without an account, because guest access is off on this instance.",
+ "publicAccessDescriptionGuestsOn": "Control public access for signed-in users and visitors without an account.",
+ "publicAccessDescriptionGuestsOff": "Control public access for signed-in users of this instance."
},
"token": {
"accessLinks": "Access Links",
- "accessLinksDescription": "Share this calendar via secure links",
- "createLink": "Create Link",
- "createFirstLink": "Create First Link",
- "noTokensYet": "No access links yet",
- "noTokensDescription": "Create a share link to give other users access",
"unnamed": "Unnamed",
- "namePlaceholder": "e.g., Family Link, Work Team",
"token": "Token",
- "tokenValue": "Token Value",
- "readOnlyDescription": "View shifts and notes",
- "editDescription": "Create and edit shifts",
- "expiration": "Expiration",
- "expires": "Expires",
- "expired": "Expired",
"expiration1Day": "1 Day",
"expiration7Days": "7 Days",
"expiration30Days": "30 Days",
- "expirationNever": "Never",
- "expiresOn": "Expires on",
- "usage": "Usage",
"usedCount": "{count, plural, =0 {Never used} =1 {Used once} other {Used # times}}",
- "neverUsed": "Never used",
"enable": "Enable",
"disable": "Disable",
"revoke": "Revoke",
"revokeConfirm": "Revoke Access Link?",
- "revokeConfirmDescription": "Are you sure you want to revoke \"{name}\"? Anyone using this link will immediately lose access.",
- "generate": "Generate Link",
- "shareLink": "Share Link",
- "linkCreated": "Link Created!",
- "linkCreatedDescription": "Your share link has been created successfully",
- "saveWarning": "Save this link now - it won't be shown again!",
- "shareInfo": "Anyone with this link can access your calendar with the specified permission level",
- "accessedViaLink": "Accessed via Share Link",
- "linkName": "Link Name",
- "createLinkDescription": "Create a shareable link to give others access to this calendar"
+ "revokeConfirmDescription": "Are you sure you want to revoke \"{name}\"? Anyone using this link will immediately lose access."
},
"rateLimit": {
"title": "Too Many Requests",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Activity Log",
- "description": "View your account activity and security events",
+ "description": "Sign-ins, changes and security events of your account",
"noLogs": "No activity recorded yet",
"eventType": "Event Type",
"resource": "Resource",
"details": "Details",
"clearAll": "Clear All",
- "refresh": "Refresh",
- "refreshed": "Activity log refreshed",
"confirmClear": "Are you sure you want to clear all activity logs? This cannot be undone.",
- "totalLogs": "{count} total logs",
+ "totalLogs": "{count, plural, one {# entry} other {# entries}}",
"showingResults": "Showing {start}-{end} of {total}",
"searchPlaceholder": "Search by action, resource, or ID...",
"noMetadata": "No additional details available",
@@ -622,7 +467,8 @@
"auth": "Authentication",
"sync": "Sync",
"security": "Security",
- "calendar": "Calendar"
+ "calendar": "Calendar",
+ "heading": "Events"
},
"admin": {
"title": "Admin Panel",
@@ -630,7 +476,6 @@
"dashboard": "Dashboard",
"usersMenu": "Users",
"calendarsMenu": "Calendars",
- "orphanedCalendars": "Orphaned Calendars",
"auditLogs": "Audit Logs",
"backToApp": "Back to App",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Collapse Sidebar",
"accessDenied": "Admin access required",
"stats": {
- "totalUsers": "Total Users",
- "totalCalendars": "Total Calendars",
- "orphanedCalendars": "Orphaned Calendars",
- "totalShifts": "Total Shifts",
- "activeShares": "Active Shares",
- "recentActivity": "Recent Activity",
"usersByRole": "{superadmin} superadmin, {admin} admin, {user} users",
- "calendarsDescription": "Total calendars with owners",
- "orphanedDescription": "Calendars without an owner",
"sharesDescription": "{user} user shares, {token} token shares",
- "shiftsDescription": "Total shifts across all calendars",
- "last7Days": "Last 7 days",
- "needsAttention": "Needs Attention"
+ "last7Days": "Last 7 days"
},
"systemInfo": {
"title": "System Information",
- "description": "Current system version and build details",
"version": "Version",
"buildDate": "Build Date",
"commitHash": "Commit Hash",
@@ -666,29 +500,20 @@
"development": "Development",
"unknown": "Unknown"
},
- "dashboardDescription": "Welcome to the BetterShift Admin Panel",
"orphanedCalendarsWarning": "Orphaned Calendars Detected",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {There is 1 calendar without an owner} other {There are # calendars without an owner}}. Please assign them to users.",
- "manageOrphanedCalendars": "Manage Orphaned Calendars",
"recentActivityDescription": "Latest admin- and security-related activity logs",
"statsFetchError": "Failed to load statistics",
- "userManagement": "User Management",
- "userManagementDescription": "Manage user accounts and permissions",
"searchUsers": "Search by name or email...",
"allRoles": "All Roles",
"allStatuses": "All Statuses",
"banned": "Banned",
"role": "Role",
"calendarsCount": "Calendars",
- "page": "page",
- "usersCount": "{count, plural, =0 {No users} =1 {1 user} other {# users}}",
"neverActive": "Never",
"editUser": "Edit User",
- "editUserDescription": "Update user information and permissions",
"userDetails": "User Details",
- "userDetailsDescription": "View detailed user information",
"ownedCalendars": "Owned Calendars",
- "joined": "Joined",
"banUser": "Ban User",
"banUserConfirm": "Ban user {name}?",
"banWarning": "User will be logged out immediately and cannot sign in until unbanned.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "Changing a user's role will affect their permissions immediately",
"calendars": {
- "title": "Calendar Management",
- "description": "Manage all calendars in the system",
"owner": "Owner",
"updated": "Updated",
"guestPermission": "Guest Permission",
@@ -736,8 +559,6 @@
"orphanedOnly": "Orphaned Only",
"withOwner": "With Owner",
"searchPlaceholder": "Search by name...",
- "calendarsCount": "{count, plural, =0 {No calendars} =1 {1 calendar} other {# calendars}}",
- "selectedCount": "{count, plural, =1 {1 calendar selected} other {# calendars selected}}",
"transferSelected": "Transfer Selected",
"clearSelection": "Clear Selection",
"noCalendarsFound": "No calendars found",
@@ -748,19 +569,13 @@
"transferOwnership": "Transfer Ownership",
"deleteCalendar": "Delete Calendar",
"calendarDetails": "Calendar Details",
- "calendarDetailsDescription": "View detailed calendar information",
- "userShares": "user",
- "tokenShares": "token",
"userSharesList": "User Shares",
"tokenSharesList": "Token Shares",
"externalSyncs": "External Syncs",
"externalSyncsShort": "Syncs",
"lastSynced": "Last synced",
- "quickActions": "Quick Actions",
- "editCalendarDescription": "Update calendar information",
"namePlaceholder": "Enter calendar name",
"guestPermissionHint": "Controls public access to this calendar",
- "transferSingleDescription": "Transfer ownership of \"{name}\"",
"transferMultipleDescription": "{count, plural, =1 {1 calendar} other {# calendars}} will be transferred",
"calendarsToTransfer": "Calendars to Transfer",
"calendarToTransfer": "Calendar to Transfer",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 calendar deleted} other {# calendars deleted}}",
"calendarsTransferred": "{count, plural, =1 {1 calendar transferred} other {# calendars transferred}}"
},
- "auditLogsDescription": "Manage all logs",
"allActions": "All Actions",
"adminActions": "Admin Actions",
"calendarActions": "Calendar Actions",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Please select a date",
"pleaseConfirmDeletion": "Please confirm the deletion",
"willDeleteLogsOlderThan": "All logs older than {date} will be deleted",
- "preview": "Preview",
"auditLogDetails": "Audit Log Details",
"resourceType": "Resource Type",
"resourceId": "Resource ID",
@@ -815,5 +628,421 @@
"clearSelection": "Clear Selection",
"deleteSelectedLogsDescription": "Delete {count, plural, one {# selected log} other {# selected logs}}. This action cannot be undone.",
"willDeleteSelectedLogs": "{count, plural, one {# log} other {# logs}} will be permanently deleted"
+ },
+ "appearance": {
+ "title": "Appearance",
+ "hint": "Your choice applies to this device and is stored locally. It takes effect immediately, without reloading.",
+ "system": {
+ "title": "System",
+ "description": "Follows your device setting"
+ },
+ "light": {
+ "title": "Light",
+ "description": "Always light"
+ },
+ "dark": {
+ "title": "Dark",
+ "description": "Always dark"
+ }
+ },
+ "appMenu": {
+ "account": "Account",
+ "language": "Language",
+ "preferences": "Preferences",
+ "viewSettings": "My view",
+ "settingsAndAccount": "Settings and account"
+ },
+ "calendarView": {
+ "previousMonth": "Previous month",
+ "nextMonth": "Next month",
+ "today": "Today",
+ "tomorrow": "Tomorrow",
+ "yesterday": "Yesterday",
+ "calendarWeek": "Week {week}",
+ "weekdayShort": {
+ "monday": "Mo",
+ "tuesday": "Tu",
+ "wednesday": "We",
+ "thursday": "Th",
+ "friday": "Fr",
+ "saturday": "Sa",
+ "sunday": "Su"
+ },
+ "allDayShort": "all day",
+ "externalCount": "{count} external",
+ "hasNotes": "{count, plural, one {# note} other {# notes}}",
+ "shift": "Shift",
+ "kpiShifts": "Shifts",
+ "kpiHours": "Hours",
+ "kpiNotes": "Notes",
+ "kpiAvgPerShift": "⌀ per shift",
+ "kpiFreeDays": "Days off",
+ "dayEmpty": "Nothing is scheduled on this day.",
+ "dayFree": "off",
+ "notesCount": "{count, plural, one {# note} other {# notes}}",
+ "addNoteOrEvent": "Note or event",
+ "monthTotal": "{month} total",
+ "allShiftsIn": "All shifts in {month}",
+ "openStats": "Charts and statistics",
+ "shiftCount": "{count, plural, one {# shift} other {# shifts}}",
+ "shiftActions": "Shift actions",
+ "external": "external",
+ "syncedReadOnly": "From an external calendar, read-only",
+ "changedOn": "changed {date}",
+ "stamp": "Presets",
+ "managePresets": "Manage presets",
+ "createPreset": "Create preset",
+ "manage": "Manage",
+ "stampHint": "Tap a day to add {title}, tap again to remove it.",
+ "addShiftManually": "Add shift manually",
+ "sheetDescription": "Shifts and notes for the selected day",
+ "sheetExpand": "Expand",
+ "sheetShrink": "Shrink",
+ "periodLabel": "Period",
+ "wholeWeek": "Whole week",
+ "wholeMonth": "Whole month",
+ "wholeYear": "Whole year",
+ "readOnlyTitle": "Read-only",
+ "readOnlyMessage": "This calendar was shared with you as read-only, so presets and adding entries are hidden.",
+ "offlineTitle": "No connection to the server",
+ "offlineMessage": "You are looking at the last loaded state. Changes are possible again once the connection is back — they are not stored in between.",
+ "retry": "Try again",
+ "note": "Note",
+ "event": "Event",
+ "eventCount": "{count, plural, one {# event} other {# events}}",
+ "statsSheetDescription": "Shifts, hours and free days for the week, month or year"
+ },
+ "calendarCompare": {
+ "title": "Compare",
+ "exit": "Exit",
+ "addCalendar": "Third calendar",
+ "stampActive": "Preset active",
+ "tapToMoveStamp": "Click a preset to place it in this column",
+ "subtitle": "{count} calendars",
+ "laneHintTwo": "Top row {top}, bottom row {bottom} — see the bar on the left. An empty frame means off.",
+ "laneHintMany": "Rows from the top: {order} — see the bar on the left. An empty frame means off.",
+ "maxHint": "at most {max}"
+ },
+ "formKit": {
+ "optional": " (optional)",
+ "customColor": "Custom"
+ },
+ "settings": {
+ "title": "Settings",
+ "description": "Applies to everyone with access to this calendar",
+ "general": "Name and color",
+ "generalHint": "Display name, calendar color, delete",
+ "presets": "Presets",
+ "presetsHint": "{count, plural, =0 {No presets yet} one {# preset} other {# presets}}",
+ "external": "External calendars",
+ "externalHint": "{count, plural, =0 {Subscription, display mode, interval} one {# subscription, display mode, interval} other {# subscriptions, display mode, interval}}",
+ "sharing": "Sharing",
+ "sharingHint": "{count, plural, =0 {People, public access, links} one {People, public access, # active link} other {People, public access, # active links}}",
+ "export": "Export",
+ "exportHint": "ICS file or PDF",
+ "view": "Calendar view",
+ "viewHint": "Own view, density, sorting",
+ "notifications": "Notifications",
+ "notificationsHint": "Synchronization",
+ "notificationsError": "Sync error",
+ "deleteImpact": "{count, plural, =0 {The calendar is deleted permanently} one {# shift will be deleted too} other {# shifts will be deleted too}}",
+ "appliesToAll": "Changes apply immediately for everyone it is shared with.",
+ "groupAccount": "Account",
+ "groupApp": "App",
+ "viewOn": "on",
+ "viewOff": "off",
+ "groupPersonal": "Just for you",
+ "personalCaption": "Applies in every calendar, others don't see it"
+ },
+ "presetSheet": {
+ "title": "Presets",
+ "description": "The order sets the preset bar",
+ "primary": "In the bar",
+ "newPreset": "New preset",
+ "titlePlaceholder": "e.g. On call",
+ "start": "Start",
+ "end": "End",
+ "allDay": "All day",
+ "allDayShort": "all day",
+ "markAsSecondary": "Tuck under “More”",
+ "hideFromStatsHint": "Not counted in hours and statistics",
+ "notInStats": "Not in statistics",
+ "save": "Save preset",
+ "delete": "Delete preset",
+ "dragHandle": "Drag to reorder",
+ "secondarySection": "Under “More”",
+ "markAsSecondaryHint": "Shows in the preset bar only after clicking “More”"
+ },
+ "syncSheet": {
+ "intervalPill": "Every {interval}",
+ "intervalValue": "every {interval}",
+ "lastSynced": "last {time}",
+ "syncNow": "Sync now",
+ "sourceUrl": "Subscribe to address",
+ "sourceFile": "Import file",
+ "chooseFile": "Choose ICS file",
+ "urlLabel": "ICS file address",
+ "colorLabel": "Color of all imported shifts",
+ "displayLabel": "Display in calendar",
+ "displayMinimal": "Count only",
+ "displayNormal": "Like your own",
+ "autoSyncLabel": "Fetch automatically",
+ "hideShifts": "Hide shifts from this subscription",
+ "excludeFromStats": "Exclude from statistics",
+ "addSubscription": "Add subscription"
+ },
+ "syncLog": {
+ "description": "Recent fetches of external calendars",
+ "statusSuccess": "Successful"
+ },
+ "sharingSheet": {
+ "tabPeople": "People",
+ "invite": "Invite",
+ "haveAccess": "Have access",
+ "owner": "Owner",
+ "permRead": "Read only",
+ "permWrite": "Edit",
+ "permReadDesc": "View the calendar, change nothing",
+ "permWriteDesc": "Create and delete shifts",
+ "permAdminDesc": "Also manage sharing and settings",
+ "changePermission": "Change permission for {name}",
+ "publicOffTitle": "Public access is off",
+ "publicOnTitle": "Public access is on",
+ "accessNone": "No access",
+ "guestNoneShort": "Invited people and links only",
+ "activeLinks": "Active links",
+ "inactiveLinks": "Disabled or expired",
+ "noActiveLinks": "No active link",
+ "expiresOn": "expires on {date}",
+ "expiredOn": "expired on {date}",
+ "noExpiry": "no expiry",
+ "lastUsed": "last used {time}",
+ "newLink": "Create a new link",
+ "linkName": "Label",
+ "linkNameHint": "optional, helps when revoking",
+ "linkNamePlaceholder": "e.g. Break room notice",
+ "validity": "Valid for",
+ "validityUnlimited": "No expiry",
+ "validUntilRevoked": "valid until you revoke it",
+ "createLink": "Create link",
+ "creating": "Creating …",
+ "linkReady": "Link is ready",
+ "copyNowTitle": "Copy it now",
+ "copyNowBody": "Once closed, the token cannot be retrieved again. If it gets lost, create a new one and revoke this one.",
+ "shareLinkLabel": "Link to share",
+ "copied": "Copied",
+ "guestReadShortGuestsOn": "Everyone can view",
+ "guestWriteShortGuestsOn": "Everyone can edit",
+ "guestReadShortGuestsOff": "Signed-in users can view",
+ "guestWriteShortGuestsOff": "Signed-in users can edit",
+ "publicOffBodyGuestsOn": "Only invited people and holders of an access link have access; links work without an account too. Use the “Public” tab to open the calendar to everyone, including visitors without an account.",
+ "publicOffBodyGuestsOff": "Only invited people and holders of an access link have access; link recipients need to sign in, because guest access is off on this instance. Use the “Public” tab to open the calendar to signed-in users of this instance.",
+ "linkInfoGuestsOn": "The link opens the calendar directly, without signing in. You can revoke it from the list at any time — it stops working immediately.",
+ "linkInfoGuestsOff": "The link opens the calendar directly. Guest access is off on this instance, so recipients need to sign in. You can revoke it from the list at any time — it stops working immediately."
+ },
+ "shiftSheet": {
+ "start": "Start",
+ "end": "End",
+ "duration": "Duration",
+ "allDay": "All day",
+ "noPreset": "Custom",
+ "createAction": "Create shift"
+ },
+ "noteSheet": {
+ "createTitle": "New entry",
+ "editTitle": "Edit entry",
+ "createAction": "Create entry",
+ "typeEvent": "Event",
+ "typeNote": "Note",
+ "typeHint": "An event shows its title and color in the day cell. A note stays unobtrusive and only appears as an icon.",
+ "text": "Text",
+ "repeat": "Repeat",
+ "repeatNone": "Once",
+ "repeatWeekly": "Weekly",
+ "repeatMonthly": "Monthly",
+ "repeatYearly": "Yearly",
+ "unitWeeks": "{count, plural, one {week} other {weeks}}",
+ "unitMonths": "{count, plural, one {month} other {months}}",
+ "unitYears": "{count, plural, one {year} other {years}}",
+ "intervalInactive": "only when repeating",
+ "recurrenceWeeks": "{count, plural, one {weekly} other {every # weeks}}",
+ "recurrenceMonths": "{count, plural, one {monthly} other {every # months}}",
+ "recurrenceYears": "{count, plural, one {yearly} other {every # years}}",
+ "listTitle": "Notes and events",
+ "entryCount": "{count, plural, one {# entry} other {# entries}}",
+ "addAnother": "Add another entry",
+ "shortcutHint": "Shortcut: right-click a day on desktop, long-press it on your phone."
+ },
+ "authPage": {
+ "loginSubtitle": "Continue to your calendars",
+ "signInWith": "Sign in with {provider}",
+ "registerTitle": "Create account",
+ "registerSubtitle": "You'll be signed in right away",
+ "passwordHint": "At least 8 characters",
+ "repeatPassword": "Repeat password",
+ "passwordsMatch": "Passwords match",
+ "haveAccount": "Already have an account?",
+ "showPassword": "Show password",
+ "hidePassword": "Hide password",
+ "sampleMonth": "Sample month",
+ "instance": "Instance"
+ },
+ "emptyState": {
+ "guestBadge": "Guest",
+ "noCalendarTitle": "No calendar yet",
+ "noCalendarDescription": "A calendar brings together a group's shifts, templates and shares. You can create as many as you like later and switch between them.",
+ "createCalendar": "Create calendar",
+ "browseShared": "Browse shared calendars",
+ "guestTitle": "No calendar is shared publicly",
+ "guestDescription": "Without an account you only see calendars that were explicitly opened to guests. If you received an access link, open it directly – the link carries the access.",
+ "pasteAccessLink": "Paste access link",
+ "accessLinkDescription": "Paste the link you received – or just the token from it.",
+ "accessLinkLabel": "Access link",
+ "accessLinkInvalid": "This is not a valid access link.",
+ "openAccessLink": "Open"
+ },
+ "discovery": {
+ "unsubscribe": "Unsubscribe"
+ },
+ "profile": {
+ "title": "My account",
+ "navProfileHint": "Name, email, profile picture",
+ "navPasswordHint": "Confirm your current password",
+ "navSessionsHint": "{count, plural, one {# device signed in} other {# devices signed in}}",
+ "navActivityHint": "What changed recently",
+ "navDangerHint": "Sign out, delete account",
+ "groupAccount": "Account",
+ "groupSecurity": "Security",
+ "chooseImage": "Choose image",
+ "removeImage": "Remove",
+ "appliesEverywhere": "Changes apply to all devices immediately.",
+ "discard": "Discard",
+ "managedByProvider": "Your name and email come from your sign-in provider and can't be changed here.",
+ "accountsTitle": "Sign-in methods",
+ "accountsHint": "You can sign in with these accounts.",
+ "connectedSince": "Connected since {date}",
+ "passwordNote": "Other devices stay signed in.",
+ "sessionsTitle": "Signed-in devices",
+ "sessionsHint": "Signing out ends the session immediately.",
+ "signOutOthers": "Sign out all others",
+ "thisDevice": "this device",
+ "activeNow": "active now",
+ "sessionRevoked": "Device signed out",
+ "unknownBrowser": "Unknown browser",
+ "unknownOs": "Unknown system",
+ "deleteImpact": "Calendars, shifts and shares are deleted as well.",
+ "deleteNeedsPassword": "Requires your password."
+ },
+ "adminKit": {
+ "banned": "Banned",
+ "active": "Active",
+ "severityInfo": "info",
+ "severityWarning": "Warning",
+ "severityError": "Error",
+ "severityCritical": "critical"
+ },
+ "adminShell": {
+ "logsShort": "Logs",
+ "breadcrumb": "Breadcrumb"
+ },
+ "adminDashboard": {
+ "title": "Overview",
+ "attention": "{count, plural, one {One thing needs attention} other {# things need attention}}",
+ "allClear": "Nothing needs attention right now",
+ "openCalendars": "Open calendars",
+ "recentTitle": "What happened recently",
+ "recentShort": "Recently",
+ "activityFooter": "{shown} of {count, plural, one {# event} other {# events}}",
+ "scope": "Scope",
+ "events": "Events",
+ "acrossCalendars": "across all calendars",
+ "calendarsAllOwned": "all have an owner",
+ "calendarsOrphaned": "{count, plural, one {# without owner} other {# without owner}}",
+ "usersSub": "{count, plural, one {# account} other {# accounts}}",
+ "calendarsSub": "{count, plural, one {# calendar} other {# calendars}}, {orphaned} orphaned",
+ "logsSub": "{count, plural, one {# event} other {# events}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# entry} other {# entries}}",
+ "dateRange": "Date range",
+ "clearRange": "Clear date range",
+ "filterTitle": "Filters",
+ "done": "Done",
+ "selectAll": "Select all on this page",
+ "selectEntry": "Select entry",
+ "severityShort": "Severity",
+ "whatHappened": "What happened",
+ "details": "Details",
+ "describe": {
+ "userBanned": "{user} banned",
+ "userBannedPermanently": "{user} banned permanently",
+ "userUnbanned": "Ban lifted for {user}",
+ "passwordReset": "Password reset for {user}",
+ "userDeleted": "Account {user} deleted",
+ "userUpdated": "Account {user} edited",
+ "calendarTransferred": "Calendar “{calendar}” transferred to {user}",
+ "calendarsTransferred": "{count, plural, one {# calendar} other {# calendars}} transferred to {user}",
+ "calendarsDeleted": "{count, plural, one {# calendar} other {# calendars}} deleted",
+ "logsDeleted": "{count, plural, one {# log entry} other {# log entries}} deleted",
+ "calendarUpdated": "Calendar “{calendar}” edited",
+ "calendarDeleted": "Calendar “{calendar}” deleted",
+ "calendarCreated": "Calendar “{calendar}” created",
+ "calendarShared": "Calendar “{calendar}” shared with {user}",
+ "shareRemoved": "Share of “{calendar}” with {user} removed",
+ "permissionChanged": "Permission of {user} on “{calendar}” changed",
+ "guestPermissionChanged": "Guest access to “{calendar}” changed",
+ "syncCreated": "Sync “{sync}” created",
+ "syncDeleted": "Sync “{sync}” removed",
+ "syncDisabled": "Sync “{sync}” disabled, calendar has no owner",
+ "syncFailed": "Sync “{sync}” failed",
+ "syncExecuted": "“{sync}” synced: {added} new, {updated} changed, {deleted} removed",
+ "rateLimit": "Rate limit reached ({endpoint})",
+ "loginProvider": "Signed in via {provider}",
+ "loginEmail": "Signed in with email and password",
+ "loginFailed": "Failed sign-in for {email}",
+ "registered": "New account {email} registered",
+ "profileUpdated": "Profile edited",
+ "passwordChanged": "Password changed",
+ "accountDeleted": "Own account deleted",
+ "sessionsRevoked": "{count, plural, one {# session} other {# sessions}} ended"
+ }
+ },
+ "adminUsers": {
+ "actions": "Actions",
+ "all": "All",
+ "ban": "Ban",
+ "banReasonQuoted": "Reason: “{reason}”",
+ "calendarCount": "{count, plural, one {# calendar} other {# calendars}}",
+ "edit": "Edit",
+ "filterLabel": "Filter users",
+ "hidePassword": "Hide password",
+ "joinedOn": "Joined {date}",
+ "moreActions": "More actions",
+ "moreFilters": "More filters",
+ "numbers": "Numbers",
+ "showPassword": "Show password",
+ "subtitle": "{count, plural, one {# account} other {# accounts}}{banned, plural, =0 {} other {, # banned}}"
+ },
+ "adminCalendars": {
+ "content": "Content",
+ "filterLabel": "Filter calendars",
+ "filterShared": "Shared",
+ "filterSynced": "With sync",
+ "guestColumn": "Guest access",
+ "guestNoneHint": "Only people it is shared with can see the calendar",
+ "guestPermissionValue": "Guest permission: {permission}",
+ "guestReadHint": "Anyone with the link can see the calendar",
+ "guestWriteHint": "Anyone with the link can edit the calendar",
+ "publicAccess": "Public access",
+ "selectAll": "Select all",
+ "selectedCount": "Selected: {count}",
+ "selectedNone": "Selected: none",
+ "sharesAndLinks": "Shares, {links, plural, one {# access link} other {# access links}}",
+ "showOrphaned": "Show",
+ "subtitle": "{count, plural, one {# calendar} other {# calendars}}, {shifts, plural, one {# shift} other {# shifts}} in total"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} of {total}",
+ "label": "Pages"
}
}
diff --git a/messages/es.json b/messages/es.json
index 3883f69..dbfc194 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -12,15 +12,11 @@
"save": "Guardar",
"saving": "Guardando...",
"close": "Cerrar",
- "optional": "(opcional)",
"delete": "Eliminar",
"loading": "Cargando...",
- "add": "Añadir",
- "adding": "Añadiendo...",
"or": "o",
"next": "Siguiente",
"previous": "Anterior",
- "of": "de",
"unsavedChanges": "Cambios sin guardar",
"unsavedChangesDescription": "Tienes cambios sin guardar. ¿Realmente quieres cerrar sin guardar?",
"closeWithoutSaving": "Cerrar sin guardar",
@@ -30,7 +26,6 @@
"createError": "Error al crear {item}",
"updateError": "Error al actualizar {item}",
"deleteError": "Error al eliminar {item}",
- "deleteConfirm": "¿Realmente quieres eliminar {item} \"{name}\"?",
"shifts": "Turnos",
"success": "Éxito",
"error": "Error",
@@ -58,15 +53,6 @@
"deleteSelected": "Eliminar seleccionados",
"viewAll": "Ver todo",
"viewDetails": "Ver detalles",
- "weekday": {
- "monday": "Lun",
- "tuesday": "Mar",
- "wednesday": "Mié",
- "thursday": "Jue",
- "friday": "Vie",
- "saturday": "Sáb",
- "sunday": "Dom"
- },
"labels": {
"name": "Nombre",
"email": "Correo electrónico",
@@ -97,8 +83,7 @@
"users": "Usuarios"
},
"status": {
- "active": "Activo",
- "inactive": "Inactivo"
+ "active": "Activo"
},
"roles": {
"admin": "Admin",
@@ -106,12 +91,14 @@
"user": "Usuario"
},
"time": {
- "never": "Nunca",
"lastActive": "Última actividad"
},
"filters": {
"allSeverities": "Todas las severidades",
- "clearFilters": "Limpiar filtros"
+ "clearFilters": "Limpiar filtros",
+ "title": "Filtros",
+ "done": "Listo",
+ "remove": "Quitar {filter}"
},
"severity": {
"info": "Información",
@@ -120,7 +107,6 @@
"critical": "Crítico"
},
"stats": {
- "statistics": "Estadísticas",
"created": "Creado"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Color",
"notesLabel": "Notas (opcional)",
"notesPlaceholder": "Información adicional...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organiza tus turnos"
+ "title": "BetterShift"
},
"calendar": {
"title": "Calendario",
"create": "Crear nuevo calendario",
"createDescription": "Crea un nuevo calendario para organizar tus turnos",
- "selectDescription": "Elige un calendario para gestionar tus turnos",
"name": "Nombre del calendario",
"myCalendars": "Mis calendarios",
"sharedCalendars": "Calendarios compartidos",
"tokenCalendars": "Vía enlace de acceso",
"publicCalendars": "Calendarios públicos",
- "select": "Tu calendario BetterShift",
"deleteCalendar": "Eliminar calendario",
"deleteWarning": "Todos los turnos, preajustes y notas también se eliminarán.",
- "settings": "Ajustes del calendario para \"{name}\"",
- "settingsDescription": "Personalizar nombre y color",
"compare": "Comparar calendarios",
"compareMode": "Modo comparación",
- "exitCompare": "Salir de comparación",
"selectToCompare": "Seleccionar calendarios para comparar",
"selectToCompareDescription": "Elige 2-3 calendarios para verlos lado a lado",
"compareSelected": "{count} seleccionados",
"startComparing": "Empezar a comparar",
- "mobileNotOptimized": "La vista de comparación no está optimizada para móviles. Por favor, usa una pantalla más grande para una mejor experiencia.",
"shareLink": "Compartir enlace",
- "shareLinkDescription": "Copiar enlace a la vista de comparación",
"browseCalendars": "Calendarios compartidos",
"browseCalendarsDescription": "Descubre y gestiona suscripciones a calendarios",
"subscribe": "Suscribirse",
- "subscribed": "Suscrito",
"noPublicCalendars": "No hay calendarios públicos disponibles",
"noSharedCalendars": "Aún no hay calendarios compartidos contigo",
"noHiddenCalendars": "No hay calendarios ocultos",
@@ -201,81 +177,45 @@
"customDescription": "Elige un color personalizado usando el selector"
},
"note": {
- "create": "Crear {item}",
- "edit": "Editar {item}",
"note": "Nota",
"placeholder": "ej., Turno de mañana porque tengo cita por la tarde...",
- "hintMobile": "Para añadir o editar una nota o evento, mantén pulsado un día en el calendario.",
- "hintDesktop": "Para añadir o editar una nota o evento, haz clic derecho en un día en el calendario.",
"type": "Tipo",
- "typeNote": "Notas",
"typeEvent": "Eventos",
"eventColor": "Color del evento",
- "eventTitle": "Nombre del evento",
"eventPlaceholder": "ej., Navidad, Cumpleaños...",
- "recurring": "Repetir",
- "recurringNone": "No repetir",
- "recurringCustom": "Personalizado",
- "recurringEveryWeeks": "Cada {count} semanas",
- "recurringEveryMonths": "Cada {count} meses",
"customInterval": "Intervalo",
"every": "Cada",
- "weeks": "semanas",
- "months": "meses",
- "multipleEntries": "{count} entradas",
"noEntries": "No hay notas ni eventos disponibles",
"recurringEditWarning": "Este es un evento recurrente. Los cambios afectarán a todas las ocurrencias."
},
"shift": {
"create": "Nuevo turno",
- "createDescription": "Añadir un nuevo turno a tu calendario",
"edit": "Editar turno",
- "editDescription": "Actualizar los detalles del turno",
"date": "Fecha",
- "startTime": "Hora de inicio",
- "endTime": "Hora de fin",
"titlePlaceholder": "ej., Turno de mañana",
"titleLabel": "Título",
- "allDay": "Todo el día",
"allDayShift": "Turno de todo el día",
"noShiftsInMonth": "No hay turnos este mes",
- "noShiftsInMonthDescription": "Añade turnos haciendo clic en los días del calendario superior.",
- "shift_one": "turno",
- "selectPreset": "Seleccionar preajuste",
- "none": "Ninguno"
+ "shift_one": "turno"
},
"preset": {
"preset": "Preajuste",
- "createNew": "Crear nuevo preajuste",
- "createYourFirst": "Crea tu primer preajuste",
"edit": "Editar preajuste",
- "manage": "Gestionar preajustes",
- "manageDescription": "Edita o elimina tus preajustes de turno",
"saveAsPreset": "Guardar como preajuste",
"presetName": "Nombre del preajuste",
"presetNamePlaceholder": "ej., Turno de mañana, Turno de tarde...",
"noPresets": "Aún no hay preajustes de turno",
- "createFirstDescription": "Crea tu primer preajuste para añadir turnos rápidamente a tu calendario. Los preajustes guardan tus horarios y detalles de turno más frecuentes.",
"deleteConfirm": "¿Eliminar este preajuste? Esto también eliminará todos los turnos creados a partir de él.",
- "primaryPresets": "Preajustes primarios",
- "secondaryPresets": "Preajustes secundarios",
- "secondary": "Secundario",
- "markAsSecondary": "Marcar como secundario (colapsado por defecto)",
- "hideFromStats": "Ocultar de las estadísticas",
- "hideFromStatsHint": "Excluir turnos de este preajuste de las estadísticas",
- "showPresets": "Mostrar preajustes",
- "hidePresets": "Ocultar preajustes",
- "hiddenFromStats": "Oculto de las estadísticas",
- "cannotAddPresetHint": "Este preajuste pertenece a un calendario diferente y no se puede añadir aquí."
+ "secondary": "Más",
+ "hideFromStats": "Ocultar de las estadísticas"
},
"view": {
- "settingsTitle": "Ajustes de vista",
- "settingsDescription": "Personaliza cómo se muestran los turnos en todos los calendarios",
+ "settingsTitle": "Mi vista",
+ "settingsDescription": "Tu vista personal. Se aplica a todos los calendarios sin vista propia y solo tú la ves.",
"shiftsPerDay": "Turnos regulares por día",
- "shiftsPerDayHint": "Número máximo de turnos regulares a mostrar por día",
+ "shiftsPerDayHint": "Los demás aparecen como «+N». Auto muestra tantos como quepan en la celda del día.",
"externalShiftsPerDay": "Turnos externos por día",
- "externalShiftsPerDayHint": "Número máximo de turnos de calendarios externos a mostrar por día",
- "showAll": "Todo",
+ "externalShiftsPerDayHint": "Se aplica a calendarios externos mostrados «Como los propios». Los demás aparecen como «+N».",
"sortOptions": "Opciones de orden",
"sortBy": "Ordenar por",
"sortByStartTime": "Hora de inicio",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Descendente",
"combinedSort": "Ordenar todos los turnos juntos",
"combinedSortHint": "Ordena los turnos regulares y externos juntos en lugar de por separado",
- "displayOptions": "Opciones de visualización",
"showNotes": "Mostrar notas del turno",
- "showNotesHint": "Muestra las notas del turno en la cuadrícula del calendario",
- "showFullTitles": "Mostrar títulos completos",
- "showFullTitlesHint": "Muestra los títulos de los turnos completos sin recortar",
+ "showNotesHint": "La nota de un turno como segunda línea en la vista mensual",
"dayHighlighting": "Resaltado de días",
"highlightWeekends": "Resaltar fines de semana",
"highlightWeekendsHint": "Resalta sábados y domingos con color",
@@ -303,7 +240,17 @@
"friday": "Viernes",
"saturday": "Sábado",
"sunday": "Domingo",
- "highlightColor": "Color de resaltado"
+ "highlightColor": "Color de resaltado",
+ "density": "Densidad",
+ "showPresetBar": "Mostrar barra de plantillas",
+ "showPresetBarHint": "Barra de plantillas debajo o encima del calendario",
+ "settingsDescriptionLocal": "Tu vista personal en este dispositivo. Se aplica a todos los calendarios sin vista propia.",
+ "overriddenByCalendar": "«{calendar}» tiene su propia vista. Allí no se aplica tu vista personal.",
+ "calendarOwn": "Vista propia para este calendario",
+ "calendarOwnHint": "Se aplica a todas las personas con acceso a este calendario.",
+ "calendarOffNote": "Aquí cada persona ve su vista personal. La tuya se ajusta en «Mi vista».",
+ "calendarLocked": "Definida para este calendario. Solo quienes gestionan el calendario pueden cambiarla.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Estadísticas de turnos",
@@ -329,52 +276,16 @@
"connected": "Conectado al servidor",
"disconnected": "Conexión al servidor perdida"
},
- "onboarding": {
- "welcome": "Bienvenido a BetterShift",
- "description": "Crea tu primer calendario para gestionar tus turnos.",
- "createCalendar": "Crear calendario"
- },
- "guestEmptyState": {
- "title": "No hay calendarios públicos disponibles",
- "description": "Actualmente no hay calendarios públicos compartidos. Por favor, inicia sesión para crear y gestionar tus propios calendarios.",
- "loginButton": "Ir al inicio de sesión"
- },
- "footer": {
- "version": "Versión",
- "github": "GitHub",
- "support": "Soporte"
- },
- "theme": {
- "switchToLight": "Cambiar a modo claro",
- "switchToDark": "Cambiar a modo oscuro"
- },
"externalSync": {
- "manageTitle": "Gestionar calendarios externos",
- "manageDescription": "Añade y gestiona múltiples calendarios externos para este calendario",
"noSyncs": "Aún no se han añadido calendarios externos",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Calendario personalizado",
"importMethod": "Método de importación",
- "importMethodUrl": "URL (sincronizable)",
- "importMethodFile": "Subir archivo (importación única)",
"importMethodUrlHint": "URL del calendario externo (iCloud, Google u otras URLs ICS)",
"importMethodFileHint": "Importar archivo ICS una vez",
"fileLabel": "Archivo ICS",
- "fileSelected": "Archivo seleccionado",
"oneTimeImport": "Importación única",
- "displayMode": "Mostrar turnos sincronizados",
- "displayModeNormal": "Normal (mostrar todos)",
- "displayModeMinimal": "Mínimo (mostrar solo recuento)",
- "displayModeHint": "Elige cómo deben mostrarse los turnos sincronizados en el calendario",
- "addNewSync": "Añadir nuevo calendario externo",
- "editSync": "Editar calendario externo",
- "colorHint": "Elige el color para todos los turnos importados",
- "hideCalendar": "Ocultar calendario",
- "hideCalendarHint": "Ocultar turnos de este calendario",
- "hideFromStats": "Ocultar de las estadísticas",
- "hideFromStatsHint": "Excluir turnos de este calendario de las estadísticas",
- "lastSynced": "Última sincronización",
"delete": "Eliminar calendario externo",
"deleteConfirm": "¿Eliminar este calendario externo? Todos los turnos importados se borrarán.",
"hintsTitle": "Cómo encontrar la URL de tu calendario",
@@ -384,8 +295,6 @@
"hintICloud": "Abre iCloud.com → Calendario → Haz clic en el icono de compartir junto a tu calendario → Activa 'Calendario público' → Copia la URL webcal:// y pégala aquí.",
"hintGoogle": "Abre Google Calendar → Configuración → Selecciona tu calendario → Baja hasta 'Dirección secreta en formato iCal' → Copia la URL y pégala aquí.",
"hintCustom": "Cualquier calendario ICS de acceso público funcionará. La URL debe empezar por https:// o webcal:// y terminar en .ics. Ejemplo: https://ejemplo.com/calendario.ics",
- "autoSyncLabel": "Sincronización automática",
- "autoSyncHint": "Elige con qué frecuencia debe sincronizarse este calendario",
"autoSyncManual": "Manual",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automática",
"syncTypeManual": "Manual",
"noChanges": "Sin cambios",
- "errorMessage": "Mensaje de error",
"filterAll": "Mostrar todo",
"filterSuccess": "Solo éxitos",
"filterError": "Solo errores",
@@ -415,9 +323,6 @@
"viewOnGitHub": "Ver en GitHub"
},
"export": {
- "title": "Exportar calendario",
- "description": "Exporta tu calendario como archivo ICS o PDF",
- "exportCalendar": "Exportar calendario",
"formatLabel": "Formato de exportación",
"icsFormat": "ICS (Archivo de calendario)",
"pdfFormat": "PDF (Documento)",
@@ -432,34 +337,19 @@
"download": "Descargar",
"multiCalendar": "Exportar múltiples calendarios",
"multiCalendarHint": "Combina turnos de varios calendarios en un solo archivo",
- "selectCalendars": "Seleccionar calendarios",
- "selectCalendarsDescription": "Elige qué calendarios incluir en la exportación",
"selectedCount": "{count, plural, =0 {Sin calendarios seleccionados} =1 {1 calendario seleccionado} other {# calendarios seleccionados}}",
"selectAtLeastOne": "Por favor, selecciona al menos un calendario"
},
"update": {
- "available": "Actualización disponible",
- "newVersion": "La versión {version} está disponible",
- "viewChangelog": "Ver registro de cambios"
+ "newVersion": "La versión {version} está disponible"
},
"auth": {
"login": "Iniciar sesión",
- "loginTitle": "Iniciar sesión en BetterShift",
- "loginDescription": "Inicia sesión con tu cuenta o usa uno de los proveedores de abajo",
"register": "Registrarse",
- "registerTitle": "Crear cuenta",
- "registerDescription": "Crea una cuenta nueva para empezar",
"logout": "Cerrar sesión",
"profile": "Perfil",
- "profileTitle": "Tu perfil",
- "profileDescription": "Gestiona los ajustes y preferencias de tu cuenta",
- "profileBasicInfoDescription": "Información básica de tu cuenta",
- "changePasswordDescription": "Actualiza tu contraseña para mantener tu cuenta segura",
- "connectedAccountsDescription": "Gestiona tus proveedores OAuth conectados",
"dangerZone": "Zona de peligro",
- "dangerZoneDescription": "Acciones irreversibles que afectan a tu cuenta",
"logoutDescription": "Cierra la sesión actual",
- "deleteAccountDescription": "Eliminar permanentemente tu cuenta y todos tus datos",
"noConnectedAccounts": "Aún no hay cuentas conectadas",
"emailPasswordAuth": "Email/Contraseña",
"emailPlaceholder": "[email protected]",
@@ -468,13 +358,9 @@
"confirmPasswordLabel": "Confirmación de contraseña",
"enterPassword": "Introduce la contraseña",
"namePlaceholder": "Tu nombre",
- "continueWith": "Continuar con {provider}",
- "alreadyHaveAccount": "¿Ya tienes una cuenta?",
"noAccountYet": "¿Aún no tienes cuenta?",
"changePassword": "Cambiar contraseña",
"deleteAccount": "Eliminar cuenta",
- "editProfile": "Editar perfil",
- "editProfileDescription": "Actualiza tu nombre, email y foto de perfil",
"profileUpdated": "Perfil actualizado con éxito",
"profilePicture": "Foto de perfil",
"avatarHint": "Máx 5MB. Formatos soportados: JPEG, PNG, GIF, WebP",
@@ -503,47 +389,27 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Gestiona tus dispositivos y sesiones activas",
"noActiveSessions": "Sin sesiones activas",
- "browser": "Navegador",
- "operatingSystem": "SO",
- "logoutAllDevices": "Cerrar sesión en todos los demás dispositivos",
"sessionsRevokedCount": "Sesión cerrada en {count} dispositivo(s)"
},
"system": {
"unavailable": "Sistema no disponible",
- "unavailableDescription": "El sistema no está disponible actualmente debido a un error crítico. Por favor, inténtalo más tarde o contacta con un administrador.",
- "unavailableRetry": "Refresca esta página para intentarlo de nuevo o vuelve más tarde."
+ "unavailableDescription": "El sistema no está disponible actualmente debido a un error crítico. Por favor, inténtalo más tarde o contacta con un administrador."
},
"guest": {
"viewingAsGuest": "Estás viendo como invitado",
"bannerMessage": "Estás viendo este calendario como invitado. Inicia sesión para tener acceso completo.",
- "loginForFullAccess": "Iniciar sesión para acceso completo",
"cannotEdit": "No puedes editar en modo de solo lectura"
},
"share": {
- "manageSharing": "Gestionar compartición",
- "manageSharingDescription": "Controla quién puede acceder a \"{name}\"",
- "userShares": "Compartido con usuarios",
"publicAccess": "Acceso público",
- "accessLinks": "Enlaces de acceso",
"public": "Público",
"links": "Enlaces",
"share": "compartir",
- "sharedBy": "Compartido por",
- "sharedOn": "Compartido el",
- "addUser": "Añadir usuario",
- "addUserDescription": "Busca un usuario para compartir este calendario",
"searchUser": "Buscar usuario",
"searchUserPlaceholder": "Introduce nombre o email...",
- "selectedUser": "Usuario seleccionado",
- "noShares": "Aún no hay usuarios con acceso",
"noSharesDescription": "Comparte este calendario con otros usuarios para colaborar",
- "userSharesDescription": "Gestiona quién puede acceder a este calendario",
- "publicAccessDescription": "Controla el acceso público para usuarios autenticados e invitados",
- "publicPermissionNoneDesc": "Nadie puede acceder a este calendario sin que se haya compartido explícitamente",
- "publicPermissionReadDesc": "Cualquier usuario autenticado puede ver el calendario",
- "publicPermissionWriteDesc": "Cualquier usuario autenticado puede ver y editar el calendario",
+ "publicPermissionNoneDesc": "Solo tú, las personas invitadas y quienes tengan un enlace de acceso pueden acceder.",
"shareAdded": "Calendario compartido con éxito",
"shareUpdated": "Permiso actualizado con éxito",
"shareRemoved": "Acceso eliminado con éxito",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "¿Eliminar acceso al calendario?",
"removeShareConfirmDesc": "¿Estás seguro de que quieres eliminar el acceso para {user}? Ya no podrá ver ni editar este calendario.",
"you": "Tú",
- "sharedWithYou": "Compartido contigo"
+ "sharedWithYou": "Compartido contigo",
+ "publicPermissionReadDescGuestsOn": "Cualquiera puede ver el calendario, incluso sin cuenta. Los usuarios autenticados lo añaden desde «Calendarios compartidos».",
+ "publicPermissionWriteDescGuestsOn": "Cualquiera puede ver y editar el calendario, incluso sin cuenta. Los usuarios autenticados lo añaden desde «Calendarios compartidos».",
+ "publicPermissionReadDescGuestsOff": "Los usuarios autenticados de esta instancia pueden añadir y ver el calendario desde «Calendarios compartidos». Sin cuenta no hay acceso, porque el acceso de invitados está desactivado en esta instancia.",
+ "publicPermissionWriteDescGuestsOff": "Los usuarios autenticados de esta instancia pueden añadir, ver y editar el calendario desde «Calendarios compartidos». Sin cuenta no hay acceso, porque el acceso de invitados está desactivado en esta instancia.",
+ "publicAccessDescriptionGuestsOn": "Controla el acceso público para usuarios autenticados y visitantes sin cuenta.",
+ "publicAccessDescriptionGuestsOff": "Controla el acceso público para los usuarios autenticados de esta instancia."
},
"token": {
"accessLinks": "Enlaces de acceso",
- "accessLinksDescription": "Comparte este calendario mediante enlaces seguros",
- "createLink": "Crear enlace",
- "createFirstLink": "Crear primer enlace",
- "noTokensYet": "Aún no hay enlaces de acceso",
- "noTokensDescription": "Crea un enlace para dar acceso a otros usuarios",
"unnamed": "Sin nombre",
- "namePlaceholder": "ej., Enlace familia, Equipo de trabajo",
"token": "Token",
- "tokenValue": "Valor del token",
- "readOnlyDescription": "Ver turnos y notas",
- "editDescription": "Crear y editar turnos",
- "expiration": "Expiración",
- "expires": "Expira",
- "expired": "Expirado",
"expiration1Day": "1 Día",
"expiration7Days": "7 Días",
"expiration30Days": "30 Días",
- "expirationNever": "Nunca",
- "expiresOn": "Expira el",
- "usage": "Uso",
"usedCount": "{count, plural, =0 {Nunca usado} =1 {Usado una vez} other {Usado # veces}}",
- "neverUsed": "Nunca usado",
"enable": "Activar",
"disable": "Desactivar",
"revoke": "Revocar",
"revokeConfirm": "¿Revocar enlace de acceso?",
- "revokeConfirmDescription": "¿Estás seguro de que quieres revocar \"{name}\"? Cualquier persona que use este enlace perderá el acceso inmediatamente.",
- "generate": "Generar enlace",
- "shareLink": "Compartir enlace",
- "linkCreated": "¡Enlace creado!",
- "linkCreatedDescription": "Tu enlace compartido se ha creado con éxito",
- "saveWarning": "Guarda este enlace ahora - ¡no se volverá a mostrar!",
- "shareInfo": "Cualquiera con este enlace podrá acceder a tu calendario con el nivel de permiso especificado",
- "accessedViaLink": "Accedido vía enlace compartido",
- "linkName": "Nombre del enlace",
- "createLinkDescription": "Crea un enlace para dar acceso a otros a este calendario"
+ "revokeConfirmDescription": "¿Estás seguro de que quieres revocar \"{name}\"? Cualquier persona que use este enlace perderá el acceso inmediatamente."
},
"rateLimit": {
"title": "Demasiadas peticiones",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Registro de actividad",
- "description": "Ver la actividad de tu cuenta y eventos de seguridad",
+ "description": "Inicios de sesión, cambios y eventos de seguridad de tu cuenta",
"noLogs": "Aún no hay actividad registrada",
"eventType": "Tipo de evento",
"resource": "Recurso",
"details": "Detalles",
"clearAll": "Limpiar todo",
- "refresh": "Refrescar",
- "refreshed": "Registro de actividad refrescado",
"confirmClear": "¿Estás seguro de que quieres limpiar todos los registros? Esta acción no se puede deshacer.",
- "totalLogs": "{count} registros en total",
+ "totalLogs": "{count, plural, one {# entrada} other {# entradas}}",
"showingResults": "Mostrando {start}-{end} de {total}",
"searchPlaceholder": "Buscar por acción, recurso o ID...",
"noMetadata": "No hay detalles adicionales disponibles",
@@ -622,7 +467,8 @@
"auth": "Autenticación",
"sync": "Sincronización",
"security": "Seguridad",
- "calendar": "Calendario"
+ "calendar": "Calendario",
+ "heading": "Eventos"
},
"admin": {
"title": "Panel de administración",
@@ -630,7 +476,6 @@
"dashboard": "Tablero",
"usersMenu": "Usuarios",
"calendarsMenu": "Calendarios",
- "orphanedCalendars": "Calendarios huérfanos",
"auditLogs": "Registros de auditoría",
"backToApp": "Volver a la App",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Contraer barra lateral",
"accessDenied": "Se requiere acceso de administrador",
"stats": {
- "totalUsers": "Total de usuarios",
- "totalCalendars": "Total de calendarios",
- "orphanedCalendars": "Calendarios huérfanos",
- "totalShifts": "Total de turnos",
- "activeShares": "Compartidos activos",
- "recentActivity": "Actividad reciente",
"usersByRole": "{superadmin} superadmin, {admin} admin, {user} usuarios",
- "calendarsDescription": "Total de calendarios con propietario",
- "orphanedDescription": "Calendarios sin propietario",
"sharesDescription": "{user} compartidos con usuarios, {token} compartidos por token",
- "shiftsDescription": "Total de turnos en todos los calendarios",
- "last7Days": "Últimos 7 días",
- "needsAttention": "Requiere atención"
+ "last7Days": "Últimos 7 días"
},
"systemInfo": {
"title": "Información del sistema",
- "description": "Versión actual del sistema y detalles de construcción",
"version": "Versión",
"buildDate": "Fecha de construcción",
"commitHash": "Hash de commit",
@@ -666,29 +500,20 @@
"development": "Desarrollo",
"unknown": "Desconocido"
},
- "dashboardDescription": "Bienvenido al Panel de Administración de BetterShift",
"orphanedCalendarsWarning": "Se han detectado calendarios huérfanos",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {Hay 1 calendario sin propietario} other {Hay # calendarios sin propietario}}. Por favor, asígnalos a usuarios.",
- "manageOrphanedCalendars": "Gestionar calendarios huérfanos",
"recentActivityDescription": "Últimos registros de actividad relacionados con administración y seguridad",
"statsFetchError": "Error al cargar estadísticas",
- "userManagement": "Gestión de usuarios",
- "userManagementDescription": "Gestiona cuentas de usuario y permisos",
"searchUsers": "Buscar por nombre o email...",
"allRoles": "Todos los roles",
"allStatuses": "Todos los estados",
"banned": "Baneado",
"role": "Rol",
"calendarsCount": "Calendarios",
- "page": "página",
- "usersCount": "{count, plural, =0 {Sin usuarios} =1 {1 usuario} other {# usuarios}}",
"neverActive": "Nunca",
"editUser": "Editar usuario",
- "editUserDescription": "Actualizar información de usuario y permisos",
"userDetails": "Detalles del usuario",
- "userDetailsDescription": "Ver información detallada del usuario",
"ownedCalendars": "Calendarios en propiedad",
- "joined": "Se unió",
"banUser": "Banear usuario",
"banUserConfirm": "¿Banear al usuario {name}?",
"banWarning": "El usuario cerrará la sesión inmediatamente y no podrá entrar hasta que sea desbaneado.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "Cambiar el rol de un usuario afectará a sus permisos inmediatamente",
"calendars": {
- "title": "Gestión de calendarios",
- "description": "Gestionar todos los calendarios del sistema",
"owner": "Propietario",
"updated": "Actualizado",
"guestPermission": "Permiso de invitado",
@@ -736,8 +559,6 @@
"orphanedOnly": "Solo huérfanos",
"withOwner": "Con propietario",
"searchPlaceholder": "Buscar por nombre...",
- "calendarsCount": "{count, plural, =0 {Sin calendarios} =1 {1 calendario} other {# calendarios}}",
- "selectedCount": "{count, plural, =1 {1 calendario seleccionado} other {# calendarios seleccionados}}",
"transferSelected": "Transferir seleccionados",
"clearSelection": "Limpiar selección",
"noCalendarsFound": "No se encontraron calendarios",
@@ -748,19 +569,13 @@
"transferOwnership": "Transferir propiedad",
"deleteCalendar": "Eliminar calendario",
"calendarDetails": "Detalles del calendario",
- "calendarDetailsDescription": "Ver información detallada del calendario",
- "userShares": "usuario",
- "tokenShares": "token",
"userSharesList": "Compartidos con usuarios",
"tokenSharesList": "Enlaces de acceso",
"externalSyncs": "Sincronizaciones externas",
"externalSyncsShort": "Sincros",
"lastSynced": "Última sincronización",
- "quickActions": "Acciones rápidas",
- "editCalendarDescription": "Actualizar información del calendario",
"namePlaceholder": "Nombre del calendario",
"guestPermissionHint": "Controla el acceso público a este calendario",
- "transferSingleDescription": "Transferir propiedad de \"{name}\"",
"transferMultipleDescription": "se transferirán {count, plural, =1 {1 calendario} other {# calendarios}}",
"calendarsToTransfer": "Calendarios a transferir",
"calendarToTransfer": "Calendario a transferir",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 calendario eliminado} other {# calendarios eliminados}}",
"calendarsTransferred": "{count, plural, =1 {1 calendario transferido} other {# calendarios transferidos}}"
},
- "auditLogsDescription": "Gestionar todos los registros",
"allActions": "Todas las acciones",
"adminActions": "Acciones de admin",
"calendarActions": "Acciones de calendario",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Por favor, selecciona una fecha",
"pleaseConfirmDeletion": "Por favor, confirma la eliminación",
"willDeleteLogsOlderThan": "Se eliminarán todos los registros anteriores al {date}",
- "preview": "Vista previa",
"auditLogDetails": "Detalles del registro de auditoría",
"resourceType": "Tipo de recurso",
"resourceId": "ID del recurso",
@@ -815,5 +628,421 @@
"clearSelection": "Limpiar selección",
"deleteSelectedLogsDescription": "Eliminar {count, plural, one {# registro seleccionado} other {# registros seleccionados}}. Esta acción no se puede deshacer.",
"willDeleteSelectedLogs": "{count, plural, one {# registro} other {# registros}} se borrarán permanentemente"
+ },
+ "appearance": {
+ "title": "Apariencia",
+ "hint": "La elección se aplica a este dispositivo y se guarda localmente. El cambio es inmediato, sin recargar.",
+ "system": {
+ "title": "Sistema",
+ "description": "Sigue la configuración del dispositivo"
+ },
+ "light": {
+ "title": "Claro",
+ "description": "Siempre claro"
+ },
+ "dark": {
+ "title": "Oscuro",
+ "description": "Siempre oscuro"
+ }
+ },
+ "appMenu": {
+ "account": "Cuenta",
+ "language": "Idioma",
+ "preferences": "Preferencias",
+ "viewSettings": "Mi vista",
+ "settingsAndAccount": "Ajustes y cuenta"
+ },
+ "calendarView": {
+ "previousMonth": "Mes anterior",
+ "nextMonth": "Mes siguiente",
+ "today": "Hoy",
+ "tomorrow": "Mañana",
+ "yesterday": "Ayer",
+ "calendarWeek": "Semana {week}",
+ "weekdayShort": {
+ "monday": "Lu",
+ "tuesday": "Ma",
+ "wednesday": "Mi",
+ "thursday": "Ju",
+ "friday": "Vi",
+ "saturday": "Sá",
+ "sunday": "Do"
+ },
+ "allDayShort": "todo el día",
+ "externalCount": "{count} externos",
+ "hasNotes": "{count, plural, one {# nota} other {# notas}}",
+ "shift": "Turno",
+ "kpiShifts": "Turnos",
+ "kpiHours": "Horas",
+ "kpiNotes": "Notas",
+ "kpiAvgPerShift": "⌀ por turno",
+ "kpiFreeDays": "Días libres",
+ "dayEmpty": "No hay nada registrado este día.",
+ "dayFree": "libre",
+ "notesCount": "{count, plural, one {# nota} other {# notas}}",
+ "addNoteOrEvent": "Nota o evento",
+ "monthTotal": "Total de {month}",
+ "allShiftsIn": "Todos los turnos de {month}",
+ "openStats": "Gráficos y estadísticas",
+ "shiftCount": "{count, plural, one {# turno} other {# turnos}}",
+ "shiftActions": "Acciones del turno",
+ "external": "externo",
+ "syncedReadOnly": "De un calendario externo, solo lectura",
+ "changedOn": "modificado {date}",
+ "stamp": "Plantillas",
+ "managePresets": "Gestionar plantillas",
+ "createPreset": "Crear plantilla",
+ "manage": "Gestionar",
+ "stampHint": "Toca un día para añadir {title}; vuelve a tocar para quitarlo.",
+ "addShiftManually": "Añadir turno manualmente",
+ "sheetDescription": "Turnos y notas del día seleccionado",
+ "sheetExpand": "Ampliar",
+ "sheetShrink": "Reducir",
+ "periodLabel": "Periodo",
+ "wholeWeek": "Semana completa",
+ "wholeMonth": "Mes completo",
+ "wholeYear": "Año completo",
+ "readOnlyTitle": "Solo lectura",
+ "readOnlyMessage": "Este calendario se compartió contigo en modo de solo lectura; por eso las plantillas y la creación están ocultas.",
+ "offlineTitle": "Sin conexión con el servidor",
+ "offlineMessage": "Ves el último estado cargado. Podrás hacer cambios cuando vuelva la conexión; no se guardan entretanto.",
+ "retry": "Reintentar",
+ "note": "Nota",
+ "event": "Evento",
+ "eventCount": "{count, plural, one {# evento} other {# eventos}}",
+ "statsSheetDescription": "Turnos, horas y días libres de la semana, el mes o el año"
+ },
+ "calendarCompare": {
+ "title": "Comparar",
+ "exit": "Salir",
+ "addCalendar": "Tercer calendario",
+ "stampActive": "Plantilla activa",
+ "tapToMoveStamp": "Haz clic en una plantilla para ponerla en esta columna",
+ "subtitle": "{count} calendarios",
+ "laneHintTwo": "Fila superior {top}, inferior {bottom}; se distinguen por la barra izquierda. Un marco vacío significa libre.",
+ "laneHintMany": "Filas desde arriba: {order}; se distinguen por la barra izquierda. Un marco vacío significa libre.",
+ "maxHint": "como máximo {max}"
+ },
+ "formKit": {
+ "optional": " (opcional)",
+ "customColor": "Personalizado"
+ },
+ "settings": {
+ "title": "Ajustes",
+ "description": "Se aplica a todas las personas con acceso a este calendario",
+ "general": "Nombre y color",
+ "generalHint": "Nombre visible, color del calendario, eliminar",
+ "presets": "Plantillas",
+ "presetsHint": "{count, plural, =0 {Aún no hay plantillas} one {# plantilla} other {# plantillas}}",
+ "external": "Calendarios externos",
+ "externalHint": "{count, plural, =0 {Suscripción, modo de vista, intervalo} one {# suscripción, modo de vista, intervalo} other {# suscripciones, modo de vista, intervalo}}",
+ "sharing": "Compartir",
+ "sharingHint": "{count, plural, =0 {Personas, acceso público, enlaces} one {Personas, acceso público, # enlace activo} other {Personas, acceso público, # enlaces activos}}",
+ "export": "Exportar",
+ "exportHint": "Archivo ICS o PDF",
+ "view": "Vista del calendario",
+ "viewHint": "Vista propia, densidad, orden",
+ "notifications": "Notificaciones",
+ "notificationsHint": "Sincronización",
+ "notificationsError": "Error de sincronización",
+ "deleteImpact": "{count, plural, =0 {El calendario se elimina definitivamente} one {También se eliminará # turno} other {También se eliminarán # turnos}}",
+ "appliesToAll": "Los cambios se aplican de inmediato para todas las personas con acceso.",
+ "groupAccount": "Cuenta",
+ "groupApp": "App",
+ "viewOn": "activada",
+ "viewOff": "desactivada",
+ "groupPersonal": "Solo para ti",
+ "personalCaption": "Se aplica en todos los calendarios, nadie más lo ve"
+ },
+ "presetSheet": {
+ "title": "Preajustes",
+ "description": "El orden define la barra de plantillas",
+ "primary": "En la barra",
+ "newPreset": "Nuevo preajuste",
+ "titlePlaceholder": "p. ej. Guardia",
+ "start": "Inicio",
+ "end": "Fin",
+ "allDay": "Todo el día",
+ "allDayShort": "todo el día",
+ "markAsSecondary": "Agrupar en «Más»",
+ "hideFromStatsHint": "No cuenta en horas ni estadísticas",
+ "notInStats": "Fuera de estadísticas",
+ "save": "Guardar preajuste",
+ "delete": "Eliminar preajuste",
+ "dragHandle": "Arrastrar para ordenar",
+ "secondarySection": "En «Más»",
+ "markAsSecondaryHint": "Aparece en la barra de plantillas solo al pulsar «Más»"
+ },
+ "syncSheet": {
+ "intervalPill": "Cada {interval}",
+ "intervalValue": "cada {interval}",
+ "lastSynced": "último {time}",
+ "syncNow": "Sincronizar ahora",
+ "sourceUrl": "Suscribirse a dirección",
+ "sourceFile": "Importar archivo",
+ "chooseFile": "Elegir archivo ICS",
+ "urlLabel": "Dirección del archivo ICS",
+ "colorLabel": "Color de todos los turnos importados",
+ "displayLabel": "Vista en el calendario",
+ "displayMinimal": "Solo cantidad",
+ "displayNormal": "Como los propios",
+ "autoSyncLabel": "Obtener automáticamente",
+ "hideShifts": "Ocultar los turnos de esta suscripción",
+ "excludeFromStats": "Excluir de las estadísticas",
+ "addSubscription": "Añadir suscripción"
+ },
+ "syncLog": {
+ "description": "Últimas obtenciones de calendarios externos",
+ "statusSuccess": "Correcto"
+ },
+ "sharingSheet": {
+ "tabPeople": "Personas",
+ "invite": "Invitar",
+ "haveAccess": "Tienen acceso",
+ "owner": "Propietario",
+ "permRead": "Solo lectura",
+ "permWrite": "Editar",
+ "permReadDesc": "Ver el calendario sin cambiar nada",
+ "permWriteDesc": "Crear y eliminar turnos",
+ "permAdminDesc": "Además gestionar compartidos y ajustes",
+ "changePermission": "Cambiar el permiso de {name}",
+ "publicOffTitle": "El acceso público está desactivado",
+ "publicOnTitle": "El acceso público está activado",
+ "accessNone": "Sin acceso",
+ "guestNoneShort": "Solo invitados y enlaces",
+ "activeLinks": "Enlaces activos",
+ "inactiveLinks": "Desactivados o caducados",
+ "noActiveLinks": "Ningún enlace activo",
+ "expiresOn": "caduca el {date}",
+ "expiredOn": "caducó el {date}",
+ "noExpiry": "sin caducidad",
+ "lastUsed": "último uso {time}",
+ "newLink": "Crear un enlace nuevo",
+ "linkName": "Nombre",
+ "linkNameHint": "opcional, ayuda al revocar",
+ "linkNamePlaceholder": "p. ej. Tablón de la sala de descanso",
+ "validity": "Validez",
+ "validityUnlimited": "Sin caducidad",
+ "validUntilRevoked": "válido hasta que lo revoques",
+ "createLink": "Crear enlace",
+ "creating": "Creando …",
+ "linkReady": "El enlace está listo",
+ "copyNowTitle": "Cópialo ahora",
+ "copyNowBody": "Después de cerrar, el token ya no se puede recuperar. Si se pierde, crea uno nuevo y revoca este.",
+ "shareLinkLabel": "Enlace para compartir",
+ "copied": "Copiado",
+ "guestReadShortGuestsOn": "Todos pueden ver",
+ "guestWriteShortGuestsOn": "Todos pueden editar",
+ "guestReadShortGuestsOff": "Usuarios con cuenta pueden ver",
+ "guestWriteShortGuestsOff": "Usuarios con cuenta pueden editar",
+ "publicOffBodyGuestsOn": "Solo tienen acceso las personas invitadas y quienes tengan un enlace de acceso; los enlaces también funcionan sin cuenta. En la pestaña «Público» puedes abrir el calendario a todos, incluso a visitantes sin cuenta.",
+ "publicOffBodyGuestsOff": "Solo tienen acceso las personas invitadas y quienes tengan un enlace de acceso; quienes reciban un enlace deben iniciar sesión, porque el acceso de invitados está desactivado en esta instancia. En la pestaña «Público» puedes abrir el calendario a los usuarios autenticados de esta instancia.",
+ "linkInfoGuestsOn": "El enlace abre el calendario directamente, sin iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante.",
+ "linkInfoGuestsOff": "El enlace abre el calendario directamente. El acceso de invitados está desactivado en esta instancia, así que los destinatarios deben iniciar sesión. Puedes revocarlo en la lista en cualquier momento; deja de funcionar al instante."
+ },
+ "shiftSheet": {
+ "start": "Inicio",
+ "end": "Fin",
+ "duration": "Duración",
+ "allDay": "Todo el día",
+ "noPreset": "Libre",
+ "createAction": "Crear turno"
+ },
+ "noteSheet": {
+ "createTitle": "Nueva entrada",
+ "editTitle": "Editar entrada",
+ "createAction": "Crear entrada",
+ "typeEvent": "Evento",
+ "typeNote": "Nota",
+ "typeHint": "Un evento muestra su título y color en la celda del día. Una nota pasa desapercibida y solo aparece como icono.",
+ "text": "Texto",
+ "repeat": "Repetición",
+ "repeatNone": "Una vez",
+ "repeatWeekly": "Semanal",
+ "repeatMonthly": "Mensual",
+ "repeatYearly": "Anual",
+ "unitWeeks": "{count, plural, one {semana} other {semanas}}",
+ "unitMonths": "{count, plural, one {mes} other {meses}}",
+ "unitYears": "{count, plural, one {año} other {años}}",
+ "intervalInactive": "solo al repetir",
+ "recurrenceWeeks": "{count, plural, one {semanal} other {cada # semanas}}",
+ "recurrenceMonths": "{count, plural, one {mensual} other {cada # meses}}",
+ "recurrenceYears": "{count, plural, one {anual} other {cada # años}}",
+ "listTitle": "Notas y eventos",
+ "entryCount": "{count, plural, one {# entrada} other {# entradas}}",
+ "addAnother": "Añadir otra entrada",
+ "shortcutHint": "Atajo: clic derecho en un día en el escritorio, pulsación larga en el móvil."
+ },
+ "authPage": {
+ "loginSubtitle": "Continúa a tus calendarios",
+ "signInWith": "Iniciar sesión con {provider}",
+ "registerTitle": "Crear cuenta",
+ "registerSubtitle": "Después iniciarás sesión directamente",
+ "passwordHint": "Al menos 8 caracteres",
+ "repeatPassword": "Repetir contraseña",
+ "passwordsMatch": "Las contraseñas coinciden",
+ "haveAccount": "¿Ya tienes una cuenta?",
+ "showPassword": "Mostrar contraseña",
+ "hidePassword": "Ocultar contraseña",
+ "sampleMonth": "Mes de ejemplo",
+ "instance": "Instancia"
+ },
+ "emptyState": {
+ "guestBadge": "Invitado",
+ "noCalendarTitle": "Aún no hay calendario",
+ "noCalendarDescription": "Un calendario reúne los turnos, plantillas y permisos compartidos de un grupo. Más adelante puedes crear tantos como quieras y cambiar entre ellos.",
+ "createCalendar": "Crear calendario",
+ "browseShared": "Explorar compartidos",
+ "guestTitle": "Ningún calendario compartido públicamente",
+ "guestDescription": "Sin cuenta solo ves los calendarios abiertos expresamente a invitados. Si has recibido un enlace de acceso, ábrelo directamente: el enlace contiene el acceso.",
+ "pasteAccessLink": "Pegar enlace de acceso",
+ "accessLinkDescription": "Pega el enlace que has recibido, o solo el token que contiene.",
+ "accessLinkLabel": "Enlace de acceso",
+ "accessLinkInvalid": "No es un enlace de acceso válido.",
+ "openAccessLink": "Abrir"
+ },
+ "discovery": {
+ "unsubscribe": "Cancelar suscripción"
+ },
+ "profile": {
+ "title": "Mi cuenta",
+ "navProfileHint": "Nombre, correo, foto de perfil",
+ "navPasswordHint": "Confirmar la contraseña actual",
+ "navSessionsHint": "{count, plural, one {# dispositivo conectado} other {# dispositivos conectados}}",
+ "navActivityHint": "Qué ha cambiado últimamente",
+ "navDangerHint": "Cerrar sesión, eliminar cuenta",
+ "groupAccount": "Cuenta",
+ "groupSecurity": "Seguridad",
+ "chooseImage": "Elegir imagen",
+ "removeImage": "Quitar",
+ "appliesEverywhere": "Los cambios se aplican de inmediato en todos los dispositivos.",
+ "discard": "Descartar",
+ "managedByProvider": "Tu nombre y tu correo provienen de tu proveedor de inicio de sesión y no se pueden cambiar aquí.",
+ "accountsTitle": "Métodos de inicio de sesión",
+ "accountsHint": "Puedes iniciar sesión con estas cuentas.",
+ "connectedSince": "Conectado desde {date}",
+ "passwordNote": "Los demás dispositivos siguen conectados.",
+ "sessionsTitle": "Dispositivos conectados",
+ "sessionsHint": "Cerrar sesión la finaliza de inmediato.",
+ "signOutOthers": "Cerrar las demás sesiones",
+ "thisDevice": "este dispositivo",
+ "activeNow": "activo ahora",
+ "sessionRevoked": "Sesión del dispositivo cerrada",
+ "unknownBrowser": "Navegador desconocido",
+ "unknownOs": "Sistema desconocido",
+ "deleteImpact": "También se eliminan los calendarios, turnos y compartidos.",
+ "deleteNeedsPassword": "Requiere tu contraseña."
+ },
+ "adminKit": {
+ "banned": "Bloqueado",
+ "active": "Activo",
+ "severityInfo": "info",
+ "severityWarning": "Aviso",
+ "severityError": "Error",
+ "severityCritical": "crítico"
+ },
+ "adminShell": {
+ "logsShort": "Registros",
+ "breadcrumb": "Ruta de navegación"
+ },
+ "adminDashboard": {
+ "title": "Resumen",
+ "attention": "{count, plural, one {Una cosa requiere atención} other {# cosas requieren atención}}",
+ "allClear": "Nada requiere atención ahora",
+ "openCalendars": "Abrir calendarios",
+ "recentTitle": "Lo que ha pasado últimamente",
+ "recentShort": "Recientes",
+ "activityFooter": "{shown} de {count, plural, one {# evento} other {# eventos}}",
+ "scope": "Alcance",
+ "events": "Eventos",
+ "acrossCalendars": "en todos los calendarios",
+ "calendarsAllOwned": "todos con propietario",
+ "calendarsOrphaned": "{count, plural, one {# sin propietario} other {# sin propietario}}",
+ "usersSub": "{count, plural, one {# cuenta} other {# cuentas}}",
+ "calendarsSub": "{count, plural, one {# calendario} other {# calendarios}}, {orphaned} sin propietario",
+ "logsSub": "{count, plural, one {# evento} other {# eventos}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# entrada} other {# entradas}}",
+ "dateRange": "Periodo",
+ "clearRange": "Borrar periodo",
+ "filterTitle": "Filtros",
+ "done": "Listo",
+ "selectAll": "Seleccionar todo en esta página",
+ "selectEntry": "Seleccionar entrada",
+ "severityShort": "Gravedad",
+ "whatHappened": "Qué ha pasado",
+ "details": "Detalles",
+ "describe": {
+ "userBanned": "{user} bloqueado",
+ "userBannedPermanently": "{user} bloqueado permanentemente",
+ "userUnbanned": "Bloqueo de {user} levantado",
+ "passwordReset": "Contraseña de {user} restablecida",
+ "userDeleted": "Cuenta {user} eliminada",
+ "userUpdated": "Cuenta {user} editada",
+ "calendarTransferred": "Calendario «{calendar}» transferido a {user}",
+ "calendarsTransferred": "{count, plural, one {# calendario transferido} other {# calendarios transferidos}} a {user}",
+ "calendarsDeleted": "{count, plural, one {# calendario eliminado} other {# calendarios eliminados}}",
+ "logsDeleted": "{count, plural, one {# entrada de registro eliminada} other {# entradas de registro eliminadas}}",
+ "calendarUpdated": "Calendario «{calendar}» editado",
+ "calendarDeleted": "Calendario «{calendar}» eliminado",
+ "calendarCreated": "Calendario «{calendar}» creado",
+ "calendarShared": "Calendario «{calendar}» compartido con {user}",
+ "shareRemoved": "Se quitó el acceso de {user} a «{calendar}»",
+ "permissionChanged": "Permiso de {user} en «{calendar}» cambiado",
+ "guestPermissionChanged": "Acceso de invitados a «{calendar}» cambiado",
+ "syncCreated": "Sincronización «{sync}» creada",
+ "syncDeleted": "Sincronización «{sync}» eliminada",
+ "syncDisabled": "Sincronización «{sync}» desactivada, el calendario no tiene propietario",
+ "syncFailed": "La sincronización «{sync}» falló",
+ "syncExecuted": "«{sync}» sincronizado: {added} nuevos, {updated} cambiados, {deleted} eliminados",
+ "rateLimit": "Límite de solicitudes alcanzado ({endpoint})",
+ "loginProvider": "Inicio de sesión con {provider}",
+ "loginEmail": "Inicio de sesión con correo y contraseña",
+ "loginFailed": "Inicio de sesión fallido para {email}",
+ "registered": "Nueva cuenta {email} registrada",
+ "profileUpdated": "Perfil editado",
+ "passwordChanged": "Contraseña cambiada",
+ "accountDeleted": "Cuenta propia eliminada",
+ "sessionsRevoked": "{count, plural, one {# sesión cerrada} other {# sesiones cerradas}}"
+ }
+ },
+ "adminUsers": {
+ "actions": "Acciones",
+ "all": "Todos",
+ "ban": "Bloquear",
+ "banReasonQuoted": "Motivo: «{reason}»",
+ "calendarCount": "{count, plural, one {# calendario} other {# calendarios}}",
+ "edit": "Editar",
+ "filterLabel": "Filtrar usuarios",
+ "hidePassword": "Ocultar contraseña",
+ "joinedOn": "Se unió el {date}",
+ "moreActions": "Más acciones",
+ "moreFilters": "Más filtros",
+ "numbers": "Cifras",
+ "showPassword": "Mostrar contraseña",
+ "subtitle": "{count, plural, one {# cuenta} other {# cuentas}}{banned, plural, =0 {} one {, # bloqueada} other {, # bloqueadas}}"
+ },
+ "adminCalendars": {
+ "content": "Contenido",
+ "filterLabel": "Filtrar calendarios",
+ "filterShared": "Compartidos",
+ "filterSynced": "Con sincronización",
+ "guestColumn": "Acceso invitado",
+ "guestNoneHint": "Solo las personas con las que se comparte pueden ver el calendario",
+ "guestPermissionValue": "Permiso de invitado: {permission}",
+ "guestReadHint": "Cualquiera con el enlace puede ver el calendario",
+ "guestWriteHint": "Cualquiera con el enlace puede editar el calendario",
+ "publicAccess": "Acceso público",
+ "selectAll": "Seleccionar todo",
+ "selectedCount": "Seleccionados: {count}",
+ "selectedNone": "Seleccionados: ninguno",
+ "sharesAndLinks": "Compartidos, {links, plural, one {# enlace de acceso} other {# enlaces de acceso}}",
+ "showOrphaned": "Mostrar",
+ "subtitle": "{count, plural, one {# calendario} other {# calendarios}}, {shifts, plural, one {# turno} other {# turnos}} en total"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} de {total}",
+ "label": "Páginas"
}
}
diff --git a/messages/fr.json b/messages/fr.json
index 2c66668..55f2b6c 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -12,15 +12,11 @@
"save": "Enregistrer",
"saving": "Enregistrement...",
"close": "Fermer",
- "optional": "(facultatif)",
"delete": "Supprimer",
"loading": "Chargement...",
- "add": "Ajouter",
- "adding": "Ajout...",
"or": "ou",
"next": "Suivant",
"previous": "Précédent",
- "of": "sur",
"unsavedChanges": "Modifications non enregistrées",
"unsavedChangesDescription": "Vous avez des modifications non enregistrées. Voulez-vous vraiment fermer sans enregistrer ?",
"closeWithoutSaving": "Fermer sans enregistrer",
@@ -30,7 +26,6 @@
"createError": "Échec de la création de {item}",
"updateError": "Échec de la mise à jour de {item}",
"deleteError": "Échec de la suppression de {item}",
- "deleteConfirm": "Supprimer {item} \"{name}\" ?",
"shifts": "Créneaux",
"success": "Succès",
"error": "Erreur",
@@ -58,15 +53,6 @@
"deleteSelected": "Supprimer la sélection",
"viewAll": "Tout afficher",
"viewDetails": "Voir les détails",
- "weekday": {
- "monday": "Lun",
- "tuesday": "Mar",
- "wednesday": "Mer",
- "thursday": "Jeu",
- "friday": "Ven",
- "saturday": "Sam",
- "sunday": "Dim"
- },
"labels": {
"name": "Nom",
"email": "E-mail",
@@ -97,8 +83,7 @@
"users": "Utilisateurs"
},
"status": {
- "active": "Actif",
- "inactive": "Inactif"
+ "active": "Actif"
},
"roles": {
"admin": "Admin",
@@ -106,12 +91,14 @@
"user": "Utilisateur"
},
"time": {
- "never": "Jamais",
"lastActive": "Dernière activité"
},
"filters": {
"allSeverities": "Toutes les gravités",
- "clearFilters": "Réinitialiser les filtres"
+ "clearFilters": "Réinitialiser les filtres",
+ "title": "Filtres",
+ "done": "Terminé",
+ "remove": "Retirer {filter}"
},
"severity": {
"info": "Info",
@@ -120,7 +107,6 @@
"critical": "Critique"
},
"stats": {
- "statistics": "Statistiques",
"created": "Créé"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Couleur",
"notesLabel": "Notes (facultatif)",
"notesPlaceholder": "Informations complémentaires...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organisez vos créneaux"
+ "title": "BetterShift"
},
"calendar": {
"title": "Calendrier",
"create": "Créer un nouveau calendrier",
"createDescription": "Créez un nouveau calendrier pour organiser vos créneaux",
- "selectDescription": "Choisissez un calendrier pour gérer vos créneaux",
"name": "Nom du calendrier",
"myCalendars": "Mes calendriers",
"sharedCalendars": "Calendriers partagés",
"tokenCalendars": "Via lien d'accès",
"publicCalendars": "Calendriers publics",
- "select": "Votre calendrier BetterShift",
"deleteCalendar": "Supprimer le calendrier",
"deleteWarning": "Tous les créneaux, modèles et notes seront également supprimés.",
- "settings": "Paramètres du calendrier \"{name}\"",
- "settingsDescription": "Personnalisez le nom et la couleur",
"compare": "Comparer les calendriers",
"compareMode": "Mode comparaison",
- "exitCompare": "Quitter la comparaison",
"selectToCompare": "Sélectionner les calendriers à comparer",
"selectToCompareDescription": "Choisissez 2 à 3 calendriers pour les afficher côte à côte",
"compareSelected": "{count} sélectionné(s)",
"startComparing": "Lancer la comparaison",
- "mobileNotOptimized": "La vue comparaison n'est pas optimisée pour mobile. Veuillez utiliser un écran plus grand pour une meilleure expérience.",
"shareLink": "Lien de partage",
- "shareLinkDescription": "Copier le lien vers la vue comparaison",
"browseCalendars": "Calendriers partagés",
"browseCalendarsDescription": "Découvrez et gérez vos abonnements aux calendriers",
"subscribe": "S'abonner",
- "subscribed": "Abonné",
"noPublicCalendars": "Aucun calendrier public disponible",
"noSharedCalendars": "Aucun calendrier partagé avec vous pour le moment",
"noHiddenCalendars": "Aucun calendrier masqué",
@@ -201,81 +177,45 @@
"customDescription": "Choisissez une couleur personnalisée avec le sélecteur de couleur"
},
"note": {
- "create": "Créer {item}",
- "edit": "Modifier {item}",
"note": "Note",
"placeholder": "ex. : Créneau matinal car rendez-vous l'après-midi...",
- "hintMobile": "Pour ajouter ou modifier une note ou un événement, appuyez longuement sur un jour dans le calendrier.",
- "hintDesktop": "Pour ajouter ou modifier une note ou un événement, faites un clic droit sur un jour dans le calendrier.",
"type": "Type",
- "typeNote": "Notes",
"typeEvent": "Événements",
"eventColor": "Couleur de l'événement",
- "eventTitle": "Nom de l'événement",
"eventPlaceholder": "ex. : Noël, Anniversaire...",
- "recurring": "Répétition",
- "recurringNone": "Ne pas répéter",
- "recurringCustom": "Personnalisée",
- "recurringEveryWeeks": "Toutes les {count} semaines",
- "recurringEveryMonths": "Tous les {count} mois",
"customInterval": "Intervalle",
"every": "Tous les",
- "weeks": "semaines",
- "months": "mois",
- "multipleEntries": "{count} entrées",
"noEntries": "Aucune note ou événement disponible",
"recurringEditWarning": "Cet événement est récurrent. Les modifications s'appliqueront à toutes les occurrences."
},
"shift": {
"create": "Nouveau créneau",
- "createDescription": "Ajouter un nouveau créneau à votre calendrier",
"edit": "Modifier le créneau",
- "editDescription": "Mettre à jour les détails du créneau",
"date": "Date",
- "startTime": "Heure de début",
- "endTime": "Heure de fin",
"titlePlaceholder": "ex. : Créneau du matin",
"titleLabel": "Titre",
- "allDay": "Toute la journée",
"allDayShift": "Créneau sur toute la journée",
"noShiftsInMonth": "Aucun créneau ce mois-ci",
- "noShiftsInMonthDescription": "Ajoutez des créneaux en cliquant sur les jours dans le calendrier ci-dessus.",
- "shift_one": "créneau",
- "selectPreset": "Sélectionner un modèle",
- "none": "Aucun"
+ "shift_one": "créneau"
},
"preset": {
"preset": "Modèle",
- "createNew": "Créer un nouveau modèle",
- "createYourFirst": "Créez votre premier modèle",
"edit": "Modifier le modèle",
- "manage": "Gérer les modèles",
- "manageDescription": "Modifier ou supprimer vos modèles de créneaux",
"saveAsPreset": "Enregistrer comme modèle",
"presetName": "Nom du modèle",
"presetNamePlaceholder": "ex. : Créneau matin, Créneau soir...",
"noPresets": "Aucun modèle de créneau pour l'instant",
- "createFirstDescription": "Créez votre premier modèle pour ajouter rapidement des créneaux à votre calendrier. Les modèles mémorisent vos horaires et détails de créneaux fréquemment utilisés.",
"deleteConfirm": "Supprimer ce modèle ? Tous les créneaux créés à partir de ce modèle seront également supprimés.",
- "primaryPresets": "Modèles principaux",
- "secondaryPresets": "Modèles secondaires",
- "secondary": "Secondaire",
- "markAsSecondary": "Marquer comme secondaire (réduit par défaut)",
- "hideFromStats": "Exclure des statistiques",
- "hideFromStatsHint": "Exclure les créneaux de ce modèle des statistiques",
- "showPresets": "Afficher les modèles",
- "hidePresets": "Masquer les modèles",
- "hiddenFromStats": "Exclu des statistiques",
- "cannotAddPresetHint": "Ce modèle appartient à un autre calendrier et ne peut pas être ajouté ici."
+ "secondary": "Plus",
+ "hideFromStats": "Exclure des statistiques"
},
"view": {
- "settingsTitle": "Paramètres d'affichage",
- "settingsDescription": "Personnalisez l'affichage des créneaux dans tous les calendriers",
+ "settingsTitle": "Mon affichage",
+ "settingsDescription": "Votre affichage personnel. Il s’applique à tous les calendriers sans affichage propre et n’est visible que par vous.",
"shiftsPerDay": "Créneaux réguliers par jour",
- "shiftsPerDayHint": "Nombre maximum de créneaux réguliers affichés par jour",
+ "shiftsPerDayHint": "Les autres apparaissent sous la forme « +N ». Auto en affiche autant que la case du jour peut contenir.",
"externalShiftsPerDay": "Créneaux externes par jour",
- "externalShiftsPerDayHint": "Nombre maximum de créneaux de calendriers externes affichés par jour",
- "showAll": "Tous",
+ "externalShiftsPerDayHint": "S'applique aux calendriers externes affichés « Comme les vôtres ». Les autres apparaissent sous la forme « +N ».",
"sortOptions": "Options de tri",
"sortBy": "Trier par",
"sortByStartTime": "Heure de début",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Décroissant",
"combinedSort": "Trier tous les créneaux ensemble",
"combinedSortHint": "Trier les créneaux réguliers et externes ensemble plutôt que séparément",
- "displayOptions": "Options d'affichage",
"showNotes": "Afficher les notes des créneaux",
- "showNotesHint": "Afficher les notes des créneaux dans la grille du calendrier",
- "showFullTitles": "Afficher les titres complets",
- "showFullTitlesHint": "Afficher les titres des créneaux en entier sans les tronquer",
+ "showNotesHint": "La note d'un créneau sur une deuxième ligne dans la vue mensuelle",
"dayHighlighting": "Mise en évidence des jours",
"highlightWeekends": "Mettre en évidence les week-ends",
"highlightWeekendsHint": "Mettre en évidence les samedis et dimanches avec une couleur",
@@ -303,7 +240,17 @@
"friday": "Vendredi",
"saturday": "Samedi",
"sunday": "Dimanche",
- "highlightColor": "Couleur de mise en évidence"
+ "highlightColor": "Couleur de mise en évidence",
+ "density": "Densité",
+ "showPresetBar": "Afficher la barre de modèles",
+ "showPresetBarHint": "Barre de modèles sous ou au-dessus du calendrier",
+ "settingsDescriptionLocal": "Votre affichage personnel sur cet appareil. Il s’applique à tous les calendriers sans affichage propre.",
+ "overriddenByCalendar": "« {calendar} » a son propre affichage. Votre affichage personnel ne s’y applique pas.",
+ "calendarOwn": "Affichage propre à ce calendrier",
+ "calendarOwnHint": "S’applique à toutes les personnes ayant accès à ce calendrier.",
+ "calendarOffNote": "Chacun voit ici son affichage personnel. Le vôtre se règle dans « Mon affichage ».",
+ "calendarLocked": "Défini pour ce calendrier. Seules les personnes qui gèrent le calendrier peuvent le modifier.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Statistiques des créneaux",
@@ -329,52 +276,16 @@
"connected": "Connecté au serveur",
"disconnected": "Connexion au serveur perdue"
},
- "onboarding": {
- "welcome": "Bienvenue sur BetterShift",
- "description": "Créez votre premier calendrier pour gérer vos créneaux.",
- "createCalendar": "Créer un calendrier"
- },
- "guestEmptyState": {
- "title": "Aucun calendrier public disponible",
- "description": "Aucun calendrier public n'est partagé pour l'instant. Connectez-vous pour créer et gérer vos propres calendriers.",
- "loginButton": "Aller à la connexion"
- },
- "footer": {
- "version": "Version",
- "github": "GitHub",
- "support": "Support"
- },
- "theme": {
- "switchToLight": "Passer en mode clair",
- "switchToDark": "Passer en mode sombre"
- },
"externalSync": {
- "manageTitle": "Gérer les calendriers externes",
- "manageDescription": "Ajouter et gérer plusieurs calendriers externes pour ce calendrier",
"noSyncs": "Aucun calendrier externe ajouté pour l'instant",
"syncTypeICloud": "iCloud",
"syncTypeGoogle": "Google",
"syncTypeCustom": "Calendrier personnalisé",
"importMethod": "Méthode d'import",
- "importMethodUrl": "URL (peut être synchronisé)",
- "importMethodFile": "Importer un fichier (import unique)",
"importMethodUrlHint": "URL du calendrier externe (iCloud, Google ou autre URL ICS)",
"importMethodFileHint": "Importer un fichier ICS une seule fois",
"fileLabel": "Fichier ICS",
- "fileSelected": "Fichier sélectionné",
"oneTimeImport": "Import unique",
- "displayMode": "Affichage des créneaux synchronisés",
- "displayModeNormal": "Normal (afficher tous les créneaux)",
- "displayModeMinimal": "Minimal (afficher le nombre uniquement)",
- "displayModeHint": "Choisissez comment les créneaux synchronisés doivent être affichés dans le calendrier",
- "addNewSync": "Ajouter un nouveau calendrier externe",
- "editSync": "Modifier le calendrier externe",
- "colorHint": "Choisissez la couleur pour tous les créneaux importés",
- "hideCalendar": "Masquer le calendrier",
- "hideCalendarHint": "Masquer les créneaux de ce calendrier",
- "hideFromStats": "Exclure des statistiques",
- "hideFromStatsHint": "Exclure les créneaux de ce calendrier des statistiques",
- "lastSynced": "Dernière synchronisation",
"delete": "Supprimer le calendrier externe",
"deleteConfirm": "Supprimer ce calendrier externe ? Tous les créneaux importés seront supprimés.",
"hintsTitle": "Trouver l'URL de votre calendrier",
@@ -384,8 +295,6 @@
"hintICloud": "Ouvrez iCloud.com → Calendrier → Cliquez sur l'icône de partage à côté de votre calendrier → Activez 'Calendrier public' → Copiez l'URL webcal:// et collez-la ici.",
"hintGoogle": "Ouvrez Google Agenda → Paramètres → Sélectionnez votre calendrier → Faites défiler jusqu'à 'Adresse secrète au format iCal' → Copiez l'URL et collez-la ici.",
"hintCustom": "Tout calendrier ICS accessible publiquement fonctionnera. L'URL doit commencer par https:// ou webcal:// et se terminer par .ics. Exemple : https://example.com/calendar.ics",
- "autoSyncLabel": "Synchronisation automatique",
- "autoSyncHint": "Choisissez la fréquence de synchronisation automatique de ce calendrier",
"autoSyncManual": "Manuel",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automatique",
"syncTypeManual": "Manuel",
"noChanges": "Aucun changement",
- "errorMessage": "Message d'erreur",
"filterAll": "Tout afficher",
"filterSuccess": "Succès uniquement",
"filterError": "Erreurs uniquement",
@@ -415,9 +323,6 @@
"viewOnGitHub": "Voir sur GitHub"
},
"export": {
- "title": "Exporter le calendrier",
- "description": "Exportez votre calendrier en fichier ICS ou PDF",
- "exportCalendar": "Exporter le calendrier",
"formatLabel": "Format d'export",
"icsFormat": "ICS (fichier calendrier)",
"pdfFormat": "PDF (document)",
@@ -432,34 +337,19 @@
"download": "Télécharger",
"multiCalendar": "Exporter plusieurs calendriers",
"multiCalendarHint": "Combiner les créneaux de plusieurs calendriers dans un seul fichier d'export",
- "selectCalendars": "Sélectionner les calendriers",
- "selectCalendarsDescription": "Choisissez les calendriers à inclure dans l'export",
"selectedCount": "{count, plural, =0 {Aucun calendrier sélectionné} =1 {1 calendrier sélectionné} other {# calendriers sélectionnés}}",
"selectAtLeastOne": "Veuillez sélectionner au moins un calendrier"
},
"update": {
- "available": "Mise à jour disponible",
- "newVersion": "La version {version} est disponible",
- "viewChangelog": "Voir le journal des modifications"
+ "newVersion": "La version {version} est disponible"
},
"auth": {
"login": "Se connecter",
- "loginTitle": "Connexion à BetterShift",
- "loginDescription": "Connectez-vous avec votre compte ou utilisez l'un des fournisseurs ci-dessous",
"register": "S'inscrire",
- "registerTitle": "Créer un compte",
- "registerDescription": "Créez un nouveau compte pour commencer",
"logout": "Se déconnecter",
"profile": "Profil",
- "profileTitle": "Votre profil",
- "profileDescription": "Gérez les paramètres et préférences de votre compte",
- "profileBasicInfoDescription": "Les informations de base de votre compte",
- "changePasswordDescription": "Mettez à jour votre mot de passe pour sécuriser votre compte",
- "connectedAccountsDescription": "Gérez vos fournisseurs OAuth liés",
"dangerZone": "Zone de danger",
- "dangerZoneDescription": "Actions irréversibles affectant votre compte",
"logoutDescription": "Se déconnecter de la session actuelle",
- "deleteAccountDescription": "Supprimer définitivement votre compte et toutes vos données",
"noConnectedAccounts": "Aucun compte lié pour l'instant",
"emailPasswordAuth": "E-mail / Mot de passe",
"emailPlaceholder": "[email protected]",
@@ -468,13 +358,9 @@
"confirmPasswordLabel": "Confirmation du mot de passe",
"enterPassword": "Saisir le mot de passe",
"namePlaceholder": "Votre nom",
- "continueWith": "Continuer avec {provider}",
- "alreadyHaveAccount": "Vous avez déjà un compte ?",
"noAccountYet": "Pas encore de compte ?",
"changePassword": "Modifier le mot de passe",
"deleteAccount": "Supprimer le compte",
- "editProfile": "Modifier le profil",
- "editProfileDescription": "Mettez à jour votre nom, e-mail et photo de profil",
"profileUpdated": "Profil mis à jour avec succès",
"profilePicture": "Photo de profil",
"avatarHint": "5 Mo maximum. Formats acceptés : JPEG, PNG, GIF, WebP",
@@ -503,47 +389,27 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Gérez vos appareils et sessions connectés",
"noActiveSessions": "Aucune session active",
- "browser": "Navigateur",
- "operatingSystem": "Système d'exploitation",
- "logoutAllDevices": "Se déconnecter de tous les autres appareils",
"sessionsRevokedCount": "Déconnecté de {count} appareil(s)"
},
"system": {
"unavailable": "Système indisponible",
- "unavailableDescription": "Le système est actuellement indisponible en raison d'une erreur critique. Veuillez réessayer ultérieurement ou contacter un administrateur.",
- "unavailableRetry": "Veuillez actualiser cette page pour réessayer ou revenez plus tard."
+ "unavailableDescription": "Le système est actuellement indisponible en raison d'une erreur critique. Veuillez réessayer ultérieurement ou contacter un administrateur."
},
"guest": {
"viewingAsGuest": "Vous consultez en tant qu'invité",
"bannerMessage": "Vous consultez ce calendrier en tant qu'invité. Connectez-vous pour un accès complet.",
- "loginForFullAccess": "Se connecter pour un accès complet",
"cannotEdit": "Vous ne pouvez pas modifier en mode lecture seule"
},
"share": {
- "manageSharing": "Gérer le partage",
- "manageSharingDescription": "Contrôlez qui peut accéder à \"{name}\"",
- "userShares": "Partages utilisateurs",
"publicAccess": "Accès public",
- "accessLinks": "Liens d'accès",
"public": "Public",
"links": "Liens",
"share": "partage",
- "sharedBy": "Partagé par",
- "sharedOn": "Partagé le",
- "addUser": "Ajouter un utilisateur",
- "addUserDescription": "Recherchez un utilisateur avec qui partager ce calendrier",
"searchUser": "Rechercher un utilisateur",
"searchUserPlaceholder": "Saisir un nom ou un e-mail...",
- "selectedUser": "Utilisateur sélectionné",
- "noShares": "Aucun utilisateur n'a accès pour l'instant",
"noSharesDescription": "Partagez ce calendrier avec d'autres utilisateurs pour collaborer",
- "userSharesDescription": "Gérez qui peut accéder à ce calendrier",
- "publicAccessDescription": "Contrôlez l'accès public pour les utilisateurs connectés et les invités",
- "publicPermissionNoneDesc": "Personne ne peut accéder à ce calendrier sans partage explicite",
- "publicPermissionReadDesc": "Tout utilisateur connecté peut consulter le calendrier",
- "publicPermissionWriteDesc": "Tout utilisateur connecté peut consulter et modifier le calendrier",
+ "publicPermissionNoneDesc": "Seuls vous, les personnes invitées et les détenteurs d’un lien d’accès y ont accès.",
"shareAdded": "Calendrier partagé avec succès",
"shareUpdated": "Permission mise à jour avec succès",
"shareRemoved": "Accès retiré avec succès",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "Retirer l'accès au calendrier ?",
"removeShareConfirmDesc": "Voulez-vous vraiment retirer l'accès à {user} ? Cette personne ne pourra plus consulter ni modifier ce calendrier.",
"you": "Vous",
- "sharedWithYou": "Partagé avec vous"
+ "sharedWithYou": "Partagé avec vous",
+ "publicPermissionReadDescGuestsOn": "Tout le monde peut consulter le calendrier, même sans compte. Les utilisateurs connectés l’ajoutent via « Calendriers partagés ».",
+ "publicPermissionWriteDescGuestsOn": "Tout le monde peut consulter et modifier le calendrier, même sans compte. Les utilisateurs connectés l’ajoutent via « Calendriers partagés ».",
+ "publicPermissionReadDescGuestsOff": "Les utilisateurs connectés de cette instance peuvent ajouter et consulter le calendrier via « Calendriers partagés ». Sans compte, aucun accès n’est possible, car l’accès invité est désactivé sur cette instance.",
+ "publicPermissionWriteDescGuestsOff": "Les utilisateurs connectés de cette instance peuvent ajouter, consulter et modifier le calendrier via « Calendriers partagés ». Sans compte, aucun accès n’est possible, car l’accès invité est désactivé sur cette instance.",
+ "publicAccessDescriptionGuestsOn": "Contrôlez l’accès public pour les utilisateurs connectés et les visiteurs sans compte.",
+ "publicAccessDescriptionGuestsOff": "Contrôlez l’accès public pour les utilisateurs connectés de cette instance."
},
"token": {
"accessLinks": "Liens d'accès",
- "accessLinksDescription": "Partagez ce calendrier via des liens sécurisés",
- "createLink": "Créer un lien",
- "createFirstLink": "Créer le premier lien",
- "noTokensYet": "Aucun lien d'accès pour l'instant",
- "noTokensDescription": "Créez un lien de partage pour donner accès à d'autres utilisateurs",
"unnamed": "Sans nom",
- "namePlaceholder": "ex. : Lien famille, Équipe travail",
"token": "Jeton",
- "tokenValue": "Valeur du jeton",
- "readOnlyDescription": "Consulter les créneaux et les notes",
- "editDescription": "Créer et modifier des créneaux",
- "expiration": "Expiration",
- "expires": "Expire",
- "expired": "Expiré",
"expiration1Day": "1 jour",
"expiration7Days": "7 jours",
"expiration30Days": "30 jours",
- "expirationNever": "Jamais",
- "expiresOn": "Expire le",
- "usage": "Utilisation",
"usedCount": "{count, plural, =0 {Jamais utilisé} =1 {Utilisé une fois} other {Utilisé # fois}}",
- "neverUsed": "Jamais utilisé",
"enable": "Activer",
"disable": "Désactiver",
"revoke": "Révoquer",
"revokeConfirm": "Révoquer le lien d'accès ?",
- "revokeConfirmDescription": "Voulez-vous vraiment révoquer \"{name}\" ? Toute personne utilisant ce lien perdra immédiatement son accès.",
- "generate": "Générer un lien",
- "shareLink": "Lien de partage",
- "linkCreated": "Lien créé !",
- "linkCreatedDescription": "Votre lien de partage a été créé avec succès",
- "saveWarning": "Sauvegardez ce lien maintenant — il ne sera plus affiché !",
- "shareInfo": "Toute personne disposant de ce lien pourra accéder à votre calendrier avec le niveau de permission spécifié",
- "accessedViaLink": "Accès via un lien de partage",
- "linkName": "Nom du lien",
- "createLinkDescription": "Créez un lien partageable pour donner accès à ce calendrier"
+ "revokeConfirmDescription": "Voulez-vous vraiment révoquer \"{name}\" ? Toute personne utilisant ce lien perdra immédiatement son accès."
},
"rateLimit": {
"title": "Trop de requêtes",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Journal d'activité",
- "description": "Consultez l'activité de votre compte et les événements de sécurité",
+ "description": "Connexions, modifications et événements de sécurité de votre compte",
"noLogs": "Aucune activité enregistrée pour l'instant",
"eventType": "Type d'événement",
"resource": "Ressource",
"details": "Détails",
"clearAll": "Tout effacer",
- "refresh": "Actualiser",
- "refreshed": "Journal d'activité actualisé",
"confirmClear": "Voulez-vous vraiment effacer tous les journaux d'activité ? Cette action est irréversible.",
- "totalLogs": "{count} entrées au total",
+ "totalLogs": "{count, plural, one {# entrée} other {# entrées}}",
"showingResults": "Affichage de {start} à {end} sur {total}",
"searchPlaceholder": "Rechercher par action, ressource ou ID...",
"noMetadata": "Aucun détail supplémentaire disponible",
@@ -622,7 +467,8 @@
"auth": "Authentification",
"sync": "Synchronisation",
"security": "Sécurité",
- "calendar": "Calendrier"
+ "calendar": "Calendrier",
+ "heading": "Événements"
},
"admin": {
"title": "Panneau d'administration",
@@ -630,7 +476,6 @@
"dashboard": "Tableau de bord",
"usersMenu": "Utilisateurs",
"calendarsMenu": "Calendriers",
- "orphanedCalendars": "Calendriers orphelins",
"auditLogs": "Journaux d'audit",
"backToApp": "Retour à l'application",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Réduire la barre latérale",
"accessDenied": "Accès administrateur requis",
"stats": {
- "totalUsers": "Utilisateurs au total",
- "totalCalendars": "Calendriers au total",
- "orphanedCalendars": "Calendriers orphelins",
- "totalShifts": "Créneaux au total",
- "activeShares": "Partages actifs",
- "recentActivity": "Activité récente",
"usersByRole": "{superadmin} superadmin, {admin} admin, {user} utilisateurs",
- "calendarsDescription": "Total des calendriers avec propriétaires",
- "orphanedDescription": "Calendriers sans propriétaire",
"sharesDescription": "{user} partages utilisateurs, {token} partages par lien",
- "shiftsDescription": "Total des créneaux sur tous les calendriers",
- "last7Days": "7 derniers jours",
- "needsAttention": "Nécessite une attention"
+ "last7Days": "7 derniers jours"
},
"systemInfo": {
"title": "Informations système",
- "description": "Version actuelle du système et détails de compilation",
"version": "Version",
"buildDate": "Date de compilation",
"commitHash": "Hash du commit",
@@ -666,29 +500,20 @@
"development": "Développement",
"unknown": "Inconnu"
},
- "dashboardDescription": "Bienvenue dans le panneau d'administration de BetterShift",
"orphanedCalendarsWarning": "Calendriers orphelins détectés",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {1 calendrier n'a pas de propriétaire} other {# calendriers n'ont pas de propriétaire}}. Veuillez les attribuer à des utilisateurs.",
- "manageOrphanedCalendars": "Gérer les calendriers orphelins",
"recentActivityDescription": "Derniers journaux d'activité liés à l'administration et à la sécurité",
"statsFetchError": "Échec du chargement des statistiques",
- "userManagement": "Gestion des utilisateurs",
- "userManagementDescription": "Gérez les comptes utilisateurs et les permissions",
"searchUsers": "Rechercher par nom ou e-mail...",
"allRoles": "Tous les rôles",
"allStatuses": "Tous les statuts",
"banned": "Banni",
"role": "Rôle",
"calendarsCount": "Calendriers",
- "page": "page",
- "usersCount": "{count, plural, =0 {Aucun utilisateur} =1 {1 utilisateur} other {# utilisateurs}}",
"neverActive": "Jamais",
"editUser": "Modifier l'utilisateur",
- "editUserDescription": "Mettre à jour les informations et permissions de l'utilisateur",
"userDetails": "Détails de l'utilisateur",
- "userDetailsDescription": "Consulter les informations détaillées de l'utilisateur",
"ownedCalendars": "Calendriers possédés",
- "joined": "Inscrit le",
"banUser": "Bannir l'utilisateur",
"banUserConfirm": "Bannir l'utilisateur {name} ?",
"banWarning": "L'utilisateur sera déconnecté immédiatement et ne pourra plus se connecter jusqu'à la levée du bannissement.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "La modification du rôle d'un utilisateur affecte ses permissions immédiatement",
"calendars": {
- "title": "Gestion des calendriers",
- "description": "Gérez tous les calendriers du système",
"owner": "Propriétaire",
"updated": "Mis à jour",
"guestPermission": "Permission invité",
@@ -736,8 +559,6 @@
"orphanedOnly": "Orphelins uniquement",
"withOwner": "Avec propriétaire",
"searchPlaceholder": "Rechercher par nom...",
- "calendarsCount": "{count, plural, =0 {Aucun calendrier} =1 {1 calendrier} other {# calendriers}}",
- "selectedCount": "{count, plural, =1 {1 calendrier sélectionné} other {# calendriers sélectionnés}}",
"transferSelected": "Transférer la sélection",
"clearSelection": "Effacer la sélection",
"noCalendarsFound": "Aucun calendrier trouvé",
@@ -748,19 +569,13 @@
"transferOwnership": "Transférer la propriété",
"deleteCalendar": "Supprimer le calendrier",
"calendarDetails": "Détails du calendrier",
- "calendarDetailsDescription": "Consulter les informations détaillées du calendrier",
- "userShares": "utilisateur",
- "tokenShares": "lien",
"userSharesList": "Partages utilisateurs",
"tokenSharesList": "Partages par lien",
"externalSyncs": "Synchronisations externes",
"externalSyncsShort": "Syncs",
"lastSynced": "Dernière synchronisation",
- "quickActions": "Actions rapides",
- "editCalendarDescription": "Mettre à jour les informations du calendrier",
"namePlaceholder": "Saisir le nom du calendrier",
"guestPermissionHint": "Contrôle l'accès public à ce calendrier",
- "transferSingleDescription": "Transférer la propriété de \"{name}\"",
"transferMultipleDescription": "{count, plural, =1 {1 calendrier} other {# calendriers}} sera/seront transféré(s)",
"calendarsToTransfer": "Calendriers à transférer",
"calendarToTransfer": "Calendrier à transférer",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 calendrier supprimé} other {# calendriers supprimés}}",
"calendarsTransferred": "{count, plural, =1 {1 calendrier transféré} other {# calendriers transférés}}"
},
- "auditLogsDescription": "Gérer tous les journaux",
"allActions": "Toutes les actions",
"adminActions": "Actions d'administration",
"calendarActions": "Actions sur les calendriers",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Veuillez sélectionner une date",
"pleaseConfirmDeletion": "Veuillez confirmer la suppression",
"willDeleteLogsOlderThan": "Tous les journaux antérieurs au {date} seront supprimés",
- "preview": "Aperçu",
"auditLogDetails": "Détails du journal d'audit",
"resourceType": "Type de ressource",
"resourceId": "ID de la ressource",
@@ -815,5 +628,421 @@
"clearSelection": "Effacer la sélection",
"deleteSelectedLogsDescription": "Supprimer {count, plural, one {# journal sélectionné} other {# journaux sélectionnés}}. Cette action est irréversible.",
"willDeleteSelectedLogs": "{count, plural, one {# journal} other {# journaux}} sera/seront supprimé(s) définitivement"
+ },
+ "appearance": {
+ "title": "Apparence",
+ "hint": "Le choix s’applique à cet appareil et est enregistré localement. Il prend effet immédiatement, sans rechargement.",
+ "system": {
+ "title": "Système",
+ "description": "Suit le réglage de l’appareil"
+ },
+ "light": {
+ "title": "Clair",
+ "description": "Toujours clair"
+ },
+ "dark": {
+ "title": "Sombre",
+ "description": "Toujours sombre"
+ }
+ },
+ "appMenu": {
+ "account": "Compte",
+ "language": "Langue",
+ "preferences": "Préférences",
+ "viewSettings": "Mon affichage",
+ "settingsAndAccount": "Paramètres et compte"
+ },
+ "calendarView": {
+ "previousMonth": "Mois précédent",
+ "nextMonth": "Mois suivant",
+ "today": "Aujourd’hui",
+ "tomorrow": "Demain",
+ "yesterday": "Hier",
+ "calendarWeek": "Semaine {week}",
+ "weekdayShort": {
+ "monday": "Lu",
+ "tuesday": "Ma",
+ "wednesday": "Me",
+ "thursday": "Je",
+ "friday": "Ve",
+ "saturday": "Sa",
+ "sunday": "Di"
+ },
+ "allDayShort": "journée",
+ "externalCount": "{count} externes",
+ "hasNotes": "{count, plural, one {# note} other {# notes}}",
+ "shift": "Service",
+ "kpiShifts": "Services",
+ "kpiHours": "Heures",
+ "kpiNotes": "Notes",
+ "kpiAvgPerShift": "⌀ par service",
+ "kpiFreeDays": "Jours libres",
+ "dayEmpty": "Rien n’est prévu ce jour-là.",
+ "dayFree": "libre",
+ "notesCount": "{count, plural, one {# note} other {# notes}}",
+ "addNoteOrEvent": "Note ou événement",
+ "monthTotal": "Total de {month}",
+ "allShiftsIn": "Tous les services de {month}",
+ "openStats": "Graphiques et statistiques",
+ "shiftCount": "{count, plural, one {# service} other {# services}}",
+ "shiftActions": "Actions du service",
+ "external": "externe",
+ "syncedReadOnly": "Depuis un calendrier externe, lecture seule",
+ "changedOn": "modifié le {date}",
+ "stamp": "Modèles",
+ "managePresets": "Gérer les modèles",
+ "createPreset": "Créer un modèle",
+ "manage": "Gérer",
+ "stampHint": "Touchez un jour pour ajouter {title}, touchez à nouveau pour le retirer.",
+ "addShiftManually": "Ajouter un service manuellement",
+ "sheetDescription": "Services et notes du jour sélectionné",
+ "sheetExpand": "Agrandir",
+ "sheetShrink": "Réduire",
+ "periodLabel": "Période",
+ "wholeWeek": "Semaine entière",
+ "wholeMonth": "Mois entier",
+ "wholeYear": "Année entière",
+ "readOnlyTitle": "Lecture seule",
+ "readOnlyMessage": "Ce calendrier vous a été partagé en lecture seule ; les modèles et l’ajout sont donc masqués.",
+ "offlineTitle": "Pas de connexion au serveur",
+ "offlineMessage": "Vous voyez le dernier état chargé. Les modifications seront de nouveau possibles une fois la connexion rétablie ; elles ne sont pas mises en attente.",
+ "retry": "Réessayer",
+ "note": "Note",
+ "event": "Événement",
+ "eventCount": "{count, plural, one {# événement} other {# événements}}",
+ "statsSheetDescription": "Services, heures et jours libres pour la semaine, le mois ou l'année"
+ },
+ "calendarCompare": {
+ "title": "Comparer",
+ "exit": "Quitter",
+ "addCalendar": "Troisième calendrier",
+ "stampActive": "Modèle actif",
+ "tapToMoveStamp": "Cliquez sur un modèle pour le placer dans cette colonne",
+ "subtitle": "{count} calendriers",
+ "laneHintTwo": "Ligne du haut {top}, du bas {bottom} — repérable à la barre de gauche. Un cadre vide signifie libre.",
+ "laneHintMany": "Lignes depuis le haut : {order} — repérables à la barre de gauche. Un cadre vide signifie libre.",
+ "maxHint": "au maximum {max}"
+ },
+ "formKit": {
+ "optional": " (facultatif)",
+ "customColor": "Personnalisée"
+ },
+ "settings": {
+ "title": "Réglages",
+ "description": "S’applique à toutes les personnes ayant accès à ce calendrier",
+ "general": "Nom et couleur",
+ "generalHint": "Nom affiché, couleur du calendrier, suppression",
+ "presets": "Modèles",
+ "presetsHint": "{count, plural, =0 {Aucun modèle} one {# modèle} other {# modèles}}",
+ "external": "Calendriers externes",
+ "externalHint": "{count, plural, =0 {Abonnement, affichage, intervalle} one {# abonnement, affichage, intervalle} other {# abonnements, affichage, intervalle}}",
+ "sharing": "Partage",
+ "sharingHint": "{count, plural, =0 {Personnes, accès public, liens} one {Personnes, accès public, # lien actif} other {Personnes, accès public, # liens actifs}}",
+ "export": "Exporter",
+ "exportHint": "Fichier ICS ou PDF",
+ "view": "Affichage du calendrier",
+ "viewHint": "Affichage propre, densité, tri",
+ "notifications": "Notifications",
+ "notificationsHint": "Synchronisation",
+ "notificationsError": "Erreur de synchronisation",
+ "deleteImpact": "{count, plural, =0 {Le calendrier est supprimé définitivement} one {# service sera aussi supprimé} other {# services seront aussi supprimés}}",
+ "appliesToAll": "Les modifications s’appliquent immédiatement à toutes les personnes ayant accès.",
+ "groupAccount": "Compte",
+ "groupApp": "App",
+ "viewOn": "activé",
+ "viewOff": "désactivé",
+ "groupPersonal": "Rien que pour vous",
+ "personalCaption": "S’applique à tous les calendriers, invisible pour les autres"
+ },
+ "presetSheet": {
+ "title": "Modèles",
+ "description": "L’ordre définit la barre de modèles",
+ "primary": "Dans la barre",
+ "newPreset": "Nouveau modèle",
+ "titlePlaceholder": "p. ex. Astreinte",
+ "start": "Début",
+ "end": "Fin",
+ "allDay": "Toute la journée",
+ "allDayShort": "toute la journée",
+ "markAsSecondary": "Ranger sous « Plus »",
+ "hideFromStatsHint": "Non compté dans les heures ni les statistiques",
+ "notInStats": "Hors statistiques",
+ "save": "Enregistrer le modèle",
+ "delete": "Supprimer le modèle",
+ "dragHandle": "Glisser pour réordonner",
+ "secondarySection": "Sous « Plus »",
+ "markAsSecondaryHint": "N’apparaît dans la barre de modèles qu’après un clic sur « Plus »"
+ },
+ "syncSheet": {
+ "intervalPill": "Toutes les {interval}",
+ "intervalValue": "toutes les {interval}",
+ "lastSynced": "dernier {time}",
+ "syncNow": "Synchroniser maintenant",
+ "sourceUrl": "S'abonner à une adresse",
+ "sourceFile": "Importer un fichier",
+ "chooseFile": "Choisir un fichier ICS",
+ "urlLabel": "Adresse du fichier ICS",
+ "colorLabel": "Couleur de tous les services importés",
+ "displayLabel": "Affichage dans le calendrier",
+ "displayMinimal": "Nombre uniquement",
+ "displayNormal": "Comme les vôtres",
+ "autoSyncLabel": "Récupérer automatiquement",
+ "hideShifts": "Masquer les services de cet abonnement",
+ "excludeFromStats": "Exclure des statistiques",
+ "addSubscription": "Ajouter un abonnement"
+ },
+ "syncLog": {
+ "description": "Dernières récupérations des calendriers externes",
+ "statusSuccess": "Réussi"
+ },
+ "sharingSheet": {
+ "tabPeople": "Personnes",
+ "invite": "Inviter",
+ "haveAccess": "Ont accès",
+ "owner": "Propriétaire",
+ "permRead": "Lecture seule",
+ "permWrite": "Modifier",
+ "permReadDesc": "Voir le calendrier sans rien modifier",
+ "permWriteDesc": "Créer et supprimer des postes",
+ "permAdminDesc": "Gérer aussi les partages et les paramètres",
+ "changePermission": "Modifier l’autorisation de {name}",
+ "publicOffTitle": "L’accès public est désactivé",
+ "publicOnTitle": "L’accès public est activé",
+ "accessNone": "Aucun accès",
+ "guestNoneShort": "Invités et liens uniquement",
+ "activeLinks": "Liens actifs",
+ "inactiveLinks": "Désactivés ou expirés",
+ "noActiveLinks": "Aucun lien actif",
+ "expiresOn": "expire le {date}",
+ "expiredOn": "expiré le {date}",
+ "noExpiry": "sans expiration",
+ "lastUsed": "dernière utilisation {time}",
+ "newLink": "Créer un nouveau lien",
+ "linkName": "Libellé",
+ "linkNameHint": "facultatif, utile pour la révocation",
+ "linkNamePlaceholder": "p. ex. Affichage salle de pause",
+ "validity": "Validité",
+ "validityUnlimited": "Sans expiration",
+ "validUntilRevoked": "valable jusqu’à sa révocation",
+ "createLink": "Créer le lien",
+ "creating": "Création …",
+ "linkReady": "Le lien est prêt",
+ "copyNowTitle": "Copiez-le maintenant",
+ "copyNowBody": "Une fois fermé, le jeton n’est plus récupérable. En cas de perte, créez-en un nouveau et révoquez celui-ci.",
+ "shareLinkLabel": "Lien à partager",
+ "copied": "Copié",
+ "guestReadShortGuestsOn": "Tout le monde peut voir",
+ "guestWriteShortGuestsOn": "Tout le monde peut modifier",
+ "guestReadShortGuestsOff": "Les utilisateurs connectés peuvent voir",
+ "guestWriteShortGuestsOff": "Les utilisateurs connectés peuvent modifier",
+ "publicOffBodyGuestsOn": "Seules les personnes invitées et les détenteurs d’un lien d’accès y ont accès ; les liens fonctionnent aussi sans compte. L’onglet « Public » permet d’ouvrir le calendrier à tous, y compris aux visiteurs sans compte.",
+ "publicOffBodyGuestsOff": "Seules les personnes invitées et les détenteurs d’un lien d’accès y ont accès ; les destinataires d’un lien doivent se connecter, car l’accès invité est désactivé sur cette instance. L’onglet « Public » permet d’ouvrir le calendrier aux utilisateurs connectés de cette instance.",
+ "linkInfoGuestsOn": "Le lien ouvre directement le calendrier, sans connexion. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner.",
+ "linkInfoGuestsOff": "Le lien ouvre directement le calendrier. L’accès invité est désactivé sur cette instance : les destinataires doivent se connecter. Vous pouvez le révoquer à tout moment dans la liste ; il cesse alors immédiatement de fonctionner."
+ },
+ "shiftSheet": {
+ "start": "Début",
+ "end": "Fin",
+ "duration": "Durée",
+ "allDay": "Toute la journée",
+ "noPreset": "Libre",
+ "createAction": "Créer le créneau"
+ },
+ "noteSheet": {
+ "createTitle": "Nouvelle entrée",
+ "editTitle": "Modifier l'entrée",
+ "createAction": "Créer l'entrée",
+ "typeEvent": "Événement",
+ "typeNote": "Note",
+ "typeHint": "Un événement affiche son titre et sa couleur dans la case du jour. Une note reste discrète et n'apparaît que sous forme d'icône.",
+ "text": "Texte",
+ "repeat": "Répétition",
+ "repeatNone": "Une fois",
+ "repeatWeekly": "Hebdomadaire",
+ "repeatMonthly": "Mensuel",
+ "repeatYearly": "Annuel",
+ "unitWeeks": "{count, plural, one {semaine} other {semaines}}",
+ "unitMonths": "{count, plural, one {mois} other {mois}}",
+ "unitYears": "{count, plural, one {an} other {ans}}",
+ "intervalInactive": "uniquement en cas de répétition",
+ "recurrenceWeeks": "{count, plural, one {hebdomadaire} other {toutes les # semaines}}",
+ "recurrenceMonths": "{count, plural, one {mensuel} other {tous les # mois}}",
+ "recurrenceYears": "{count, plural, one {annuel} other {tous les # ans}}",
+ "listTitle": "Notes et événements",
+ "entryCount": "{count, plural, one {# entrée} other {# entrées}}",
+ "addAnother": "Ajouter une autre entrée",
+ "shortcutHint": "Raccourci : clic droit sur un jour sur ordinateur, appui long sur mobile."
+ },
+ "authPage": {
+ "loginSubtitle": "Accéder à vos calendriers",
+ "signInWith": "Se connecter avec {provider}",
+ "registerTitle": "Créer un compte",
+ "registerSubtitle": "Vous serez connecté directement ensuite",
+ "passwordHint": "Au moins 8 caractères",
+ "repeatPassword": "Répéter le mot de passe",
+ "passwordsMatch": "Les mots de passe correspondent",
+ "haveAccount": "Vous avez déjà un compte ?",
+ "showPassword": "Afficher le mot de passe",
+ "hidePassword": "Masquer le mot de passe",
+ "sampleMonth": "Mois d'exemple",
+ "instance": "Instance"
+ },
+ "emptyState": {
+ "guestBadge": "Invité",
+ "noCalendarTitle": "Pas encore de calendrier",
+ "noCalendarDescription": "Un calendrier regroupe les services, modèles et partages d'un groupe. Vous pourrez ensuite en créer autant que vous voulez et passer de l'un à l'autre.",
+ "createCalendar": "Créer un calendrier",
+ "browseShared": "Parcourir les partagés",
+ "guestTitle": "Aucun calendrier partagé publiquement",
+ "guestDescription": "Sans compte, vous ne voyez que les calendriers explicitement ouverts aux invités. Si vous avez reçu un lien d'accès, ouvrez-le directement – le lien contient l'accès.",
+ "pasteAccessLink": "Coller un lien d'accès",
+ "accessLinkDescription": "Collez le lien que vous avez reçu – ou seulement le jeton qu'il contient.",
+ "accessLinkLabel": "Lien d'accès",
+ "accessLinkInvalid": "Ce n'est pas un lien d'accès valide.",
+ "openAccessLink": "Ouvrir"
+ },
+ "discovery": {
+ "unsubscribe": "Se désabonner"
+ },
+ "profile": {
+ "title": "Mon compte",
+ "navProfileHint": "Nom, e-mail, photo de profil",
+ "navPasswordHint": "Confirmer le mot de passe actuel",
+ "navSessionsHint": "{count, plural, one {# appareil connecté} other {# appareils connectés}}",
+ "navActivityHint": "Ce qui a changé récemment",
+ "navDangerHint": "Déconnexion, suppression du compte",
+ "groupAccount": "Compte",
+ "groupSecurity": "Sécurité",
+ "chooseImage": "Choisir une image",
+ "removeImage": "Supprimer",
+ "appliesEverywhere": "Les modifications s'appliquent immédiatement à tous les appareils.",
+ "discard": "Ignorer",
+ "managedByProvider": "Votre nom et votre e-mail proviennent de votre fournisseur de connexion et ne peuvent pas être modifiés ici.",
+ "accountsTitle": "Méthodes de connexion",
+ "accountsHint": "Vous pouvez vous connecter avec ces comptes.",
+ "connectedSince": "Connecté depuis le {date}",
+ "passwordNote": "Les autres appareils restent connectés.",
+ "sessionsTitle": "Appareils connectés",
+ "sessionsHint": "La déconnexion met fin à la session immédiatement.",
+ "signOutOthers": "Déconnecter les autres",
+ "thisDevice": "cet appareil",
+ "activeNow": "actif maintenant",
+ "sessionRevoked": "Appareil déconnecté",
+ "unknownBrowser": "Navigateur inconnu",
+ "unknownOs": "Système inconnu",
+ "deleteImpact": "Les calendriers, créneaux et partages sont également supprimés.",
+ "deleteNeedsPassword": "Nécessite votre mot de passe."
+ },
+ "adminKit": {
+ "banned": "Bloqué",
+ "active": "Actif",
+ "severityInfo": "info",
+ "severityWarning": "Avertissement",
+ "severityError": "Erreur",
+ "severityCritical": "critique"
+ },
+ "adminShell": {
+ "logsShort": "Journaux",
+ "breadcrumb": "Fil d’Ariane"
+ },
+ "adminDashboard": {
+ "title": "Aperçu",
+ "attention": "{count, plural, one {Un point à traiter} other {# points à traiter}}",
+ "allClear": "Rien à traiter pour le moment",
+ "openCalendars": "Ouvrir les calendriers",
+ "recentTitle": "Ce qui s’est passé récemment",
+ "recentShort": "Récemment",
+ "activityFooter": "{shown} sur {count, plural, one {# événement} other {# événements}}",
+ "scope": "Volume",
+ "events": "Événements",
+ "acrossCalendars": "sur tous les calendriers",
+ "calendarsAllOwned": "tous ont un propriétaire",
+ "calendarsOrphaned": "{count, plural, one {# sans propriétaire} other {# sans propriétaire}}",
+ "usersSub": "{count, plural, one {# compte} other {# comptes}}",
+ "calendarsSub": "{count, plural, one {# calendrier} other {# calendriers}}, {orphaned} sans propriétaire",
+ "logsSub": "{count, plural, one {# événement} other {# événements}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# entrée} other {# entrées}}",
+ "dateRange": "Période",
+ "clearRange": "Effacer la période",
+ "filterTitle": "Filtres",
+ "done": "Terminé",
+ "selectAll": "Tout sélectionner sur cette page",
+ "selectEntry": "Sélectionner l’entrée",
+ "severityShort": "Gravité",
+ "whatHappened": "Ce qui s’est passé",
+ "details": "Détails",
+ "describe": {
+ "userBanned": "{user} bloqué",
+ "userBannedPermanently": "{user} bloqué définitivement",
+ "userUnbanned": "Blocage de {user} levé",
+ "passwordReset": "Mot de passe de {user} réinitialisé",
+ "userDeleted": "Compte {user} supprimé",
+ "userUpdated": "Compte {user} modifié",
+ "calendarTransferred": "Calendrier « {calendar} » transféré à {user}",
+ "calendarsTransferred": "{count, plural, one {# calendrier transféré} other {# calendriers transférés}} à {user}",
+ "calendarsDeleted": "{count, plural, one {# calendrier supprimé} other {# calendriers supprimés}}",
+ "logsDeleted": "{count, plural, one {# entrée de journal supprimée} other {# entrées de journal supprimées}}",
+ "calendarUpdated": "Calendrier « {calendar} » modifié",
+ "calendarDeleted": "Calendrier « {calendar} » supprimé",
+ "calendarCreated": "Calendrier « {calendar} » créé",
+ "calendarShared": "Calendrier « {calendar} » partagé avec {user}",
+ "shareRemoved": "Partage de « {calendar} » avec {user} supprimé",
+ "permissionChanged": "Autorisation de {user} sur « {calendar} » modifiée",
+ "guestPermissionChanged": "Accès invité à « {calendar} » modifié",
+ "syncCreated": "Synchronisation « {sync} » créée",
+ "syncDeleted": "Synchronisation « {sync} » supprimée",
+ "syncDisabled": "Synchronisation « {sync} » désactivée, calendrier sans propriétaire",
+ "syncFailed": "Échec de la synchronisation « {sync} »",
+ "syncExecuted": "« {sync} » synchronisé : {added} nouveaux, {updated} modifiés, {deleted} supprimés",
+ "rateLimit": "Limite de requêtes atteinte ({endpoint})",
+ "loginProvider": "Connexion via {provider}",
+ "loginEmail": "Connexion par e-mail et mot de passe",
+ "loginFailed": "Échec de connexion pour {email}",
+ "registered": "Nouveau compte {email} enregistré",
+ "profileUpdated": "Profil modifié",
+ "passwordChanged": "Mot de passe modifié",
+ "accountDeleted": "Compte personnel supprimé",
+ "sessionsRevoked": "{count, plural, one {# session fermée} other {# sessions fermées}}"
+ }
+ },
+ "adminUsers": {
+ "actions": "Actions",
+ "all": "Tous",
+ "ban": "Bloquer",
+ "banReasonQuoted": "Motif : « {reason} »",
+ "calendarCount": "{count, plural, one {# calendrier} other {# calendriers}}",
+ "edit": "Modifier",
+ "filterLabel": "Filtrer les utilisateurs",
+ "hidePassword": "Masquer le mot de passe",
+ "joinedOn": "Inscrit le {date}",
+ "moreActions": "Plus d'actions",
+ "moreFilters": "Plus de filtres",
+ "numbers": "Chiffres",
+ "showPassword": "Afficher le mot de passe",
+ "subtitle": "{count, plural, one {# compte} other {# comptes}}{banned, plural, =0 {} one {, dont # bloqué} other {, dont # bloqués}}"
+ },
+ "adminCalendars": {
+ "content": "Contenu",
+ "filterLabel": "Filtrer les calendriers",
+ "filterShared": "Partagés",
+ "filterSynced": "Avec synchro",
+ "guestColumn": "Accès invité",
+ "guestNoneHint": "Seules les personnes avec qui il est partagé voient le calendrier",
+ "guestPermissionValue": "Autorisation invité : {permission}",
+ "guestReadHint": "Toute personne disposant du lien voit le calendrier",
+ "guestWriteHint": "Toute personne disposant du lien peut modifier le calendrier",
+ "publicAccess": "Accès public",
+ "selectAll": "Tout sélectionner",
+ "selectedCount": "Sélectionnés : {count}",
+ "selectedNone": "Sélectionnés : aucun",
+ "sharesAndLinks": "Partages, {links, plural, one {# lien d'accès} other {# liens d'accès}}",
+ "showOrphaned": "Afficher",
+ "subtitle": "{count, plural, one {# calendrier} other {# calendriers}}, {shifts, plural, one {# créneau} other {# créneaux}} au total"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} sur {total}",
+ "label": "Pages"
}
}
diff --git a/messages/it.json b/messages/it.json
index e270853..518f634 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -12,15 +12,11 @@
"save": "Salva",
"saving": "Salvataggio...",
"close": "Chiudi",
- "optional": "(opzionale)",
"delete": "Elimina",
"loading": "Caricamento...",
- "add": "Aggiungi",
- "adding": "Aggiunta...",
"or": "o",
"next": "Avanti",
"previous": "Precedente",
- "of": "di",
"unsavedChanges": "Modifiche Non Salvate",
"unsavedChangesDescription": "Hai modifiche non salvate. Vuoi davvero chiudere senza salvare?",
"closeWithoutSaving": "Chiudi Senza Salvare",
@@ -30,7 +26,6 @@
"createError": "Impossibile creare {item}",
"updateError": "Impossibile aggiornare {item}",
"deleteError": "Impossibile eliminare {item}",
- "deleteConfirm": "Eliminare davvero {item} \"{name}\"?",
"shifts": "Turni",
"success": "Successo",
"error": "Errore",
@@ -58,15 +53,6 @@
"deleteSelected": "Elimina Selezionati",
"viewAll": "Mostra Tutto",
"viewDetails": "Visualizza Dettagli",
- "weekday": {
- "monday": "Lun",
- "tuesday": "Mar",
- "wednesday": "Mer",
- "thursday": "Gio",
- "friday": "Ven",
- "saturday": "Sab",
- "sunday": "Dom"
- },
"labels": {
"name": "Nome",
"email": "Email",
@@ -97,8 +83,7 @@
"users": "Utenti"
},
"status": {
- "active": "Attivo",
- "inactive": "Inattivo"
+ "active": "Attivo"
},
"roles": {
"admin": "Admin",
@@ -106,12 +91,14 @@
"user": "Utente"
},
"time": {
- "never": "Mai",
"lastActive": "Ultima Attività"
},
"filters": {
"allSeverities": "Tutte le Gravità",
- "clearFilters": "Cancella Filtri"
+ "clearFilters": "Cancella Filtri",
+ "title": "Filtri",
+ "done": "Fatto",
+ "remove": "Rimuovi {filter}"
},
"severity": {
"info": "Info",
@@ -120,7 +107,6 @@
"critical": "Critico"
},
"stats": {
- "statistics": "Statistiche",
"created": "Creato"
},
"auth": {
@@ -146,42 +132,32 @@
"colorLabel": "Colore",
"notesLabel": "Note (opzionale)",
"notesPlaceholder": "Informazioni aggiuntive...",
- "urlLabel": "URL",
"urlPlaceholder": "https://..."
},
"app": {
- "title": "BetterShift",
- "subtitle": "Organizza i tuoi turni"
+ "title": "BetterShift"
},
"calendar": {
"title": "Calendario",
"create": "Crea Nuovo Calendario",
"createDescription": "Crea un nuovo calendario per organizzare i tuoi turni",
- "selectDescription": "Scegli un calendario per gestire i tuoi turni",
"name": "Nome Calendario",
"myCalendars": "I Miei Calendari",
"sharedCalendars": "Calendari Condivisi",
"tokenCalendars": "Tramite Link di Accesso",
"publicCalendars": "Calendari Pubblici",
- "select": "Il tuo Calendario BetterShift",
"deleteCalendar": "Elimina Calendario",
"deleteWarning": "Anche tutti i turni, i preset e le note verranno eliminati.",
- "settings": "Impostazioni Calendario per \"{name}\"",
- "settingsDescription": "Personalizza nome e colore",
"compare": "Confronta Calendari",
"compareMode": "Modalità Confronto",
- "exitCompare": "Esci dal Confronto",
"selectToCompare": "Seleziona calendari da confrontare",
"selectToCompareDescription": "Scegli 2-3 calendari per visualizzarli affiancati",
"compareSelected": "{count} selezionati",
"startComparing": "Inizia Confronto",
- "mobileNotOptimized": "La vista confronto non è ottimizzata per dispositivi mobili. Utilizza uno schermo più grande per un'esperienza migliore.",
"shareLink": "Condividi Link",
- "shareLinkDescription": "Copia link alla vista confronto",
"browseCalendars": "Calendari Condivisi",
"browseCalendarsDescription": "Scopri e gestisci gli abbonamenti ai calendari",
"subscribe": "Iscriviti",
- "subscribed": "Iscritto",
"noPublicCalendars": "Nessun calendario pubblico disponibile",
"subscriptionSuccess": "Iscritto a {name}",
"unsubscribeSuccess": "Disiscritto da {name}",
@@ -201,81 +177,45 @@
"customDescription": "Scegli un colore personalizzato usando il selettore di colori"
},
"note": {
- "create": "Crea {item}",
- "edit": "Modifica {item}",
"note": "Nota",
"placeholder": "es., Turno mattutino perché ho un appuntamento nel pomeriggio...",
- "hintMobile": "Per aggiungere o modificare una nota o un evento, premi a lungo su un giorno nel calendario.",
- "hintDesktop": "Per aggiungere o modificare una nota o un evento, fai clic destro su un giorno nel calendario.",
"type": "Tipo",
- "typeNote": "Note",
"typeEvent": "Eventi",
"eventColor": "Colore Evento",
- "eventTitle": "Nome Evento",
"eventPlaceholder": "es., Natale, Compleanno...",
- "recurring": "Ripeti",
- "recurringNone": "Non ripetere",
- "recurringCustom": "Personalizzato",
- "recurringEveryWeeks": "Ogni {count} settimane",
- "recurringEveryMonths": "Ogni {count} mesi",
"customInterval": "Intervallo",
"every": "Ogni",
- "weeks": "settimane",
- "months": "mesi",
- "multipleEntries": "{count} voci",
"noEntries": "Nessuna nota o evento disponibile",
"recurringEditWarning": "Questo è un evento ricorrente. Le modifiche interesseranno tutte le occorrenze."
},
"shift": {
"create": "Nuovo Turno",
- "createDescription": "Aggiungi un nuovo turno al tuo calendario",
"edit": "Modifica Turno",
- "editDescription": "Aggiorna i dettagli del turno",
"date": "Data",
- "startTime": "Ora di Inizio",
- "endTime": "Ora di Fine",
"titlePlaceholder": "es., Turno Mattutino",
"titleLabel": "Titolo",
- "allDay": "Tutto il Giorno",
"allDayShift": "Turno di un'intera giornata",
"noShiftsInMonth": "Nessun turno questo mese",
- "noShiftsInMonthDescription": "Aggiungi turni cliccando sui giorni nel calendario in alto.",
- "shift_one": "turno",
- "selectPreset": "Seleziona Preset",
- "none": "Nessuno"
+ "shift_one": "turno"
},
"preset": {
"preset": "Preset",
- "createNew": "Crea Nuovo Preset",
- "createYourFirst": "Crea il Tuo Primo Preset",
"edit": "Modifica Preset",
- "manage": "Gestisci Preset",
- "manageDescription": "Modifica o elimina i tuoi preset turno",
"saveAsPreset": "Salva come preset",
"presetName": "Nome preset",
"presetNamePlaceholder": "es., Turno Mattutino, Turno Serale...",
"noPresets": "Ancora nessun preset turno",
- "createFirstDescription": "Crea il tuo primo preset per aggiungere rapidamente turni al tuo calendario. I preset salvano gli orari e i dettagli dei turni utilizzati di frequente.",
"deleteConfirm": "Eliminare questo preset? Verranno eliminati anche tutti i turni creati da questo preset.",
- "primaryPresets": "Preset Primari",
- "secondaryPresets": "Preset Secondari",
- "secondary": "Secondario",
- "markAsSecondary": "Segna come secondario (compresso di default)",
- "hideFromStats": "Nascondi dalle statistiche",
- "hideFromStatsHint": "Escludi i turni da questo preset dalle statistiche",
- "showPresets": "Mostra preset",
- "hidePresets": "Nascondi preset",
- "hiddenFromStats": "Nascosto dalle statistiche",
- "cannotAddPresetHint": "Questo preset appartiene a un altro calendario e non può essere aggiunto qui."
+ "secondary": "Altri",
+ "hideFromStats": "Nascondi dalle statistiche"
},
"view": {
- "settingsTitle": "Impostazioni Vista",
- "settingsDescription": "Personalizza come vengono visualizzati i turni in tutti i calendari",
+ "settingsTitle": "La mia vista",
+ "settingsDescription": "La tua vista personale. Vale per tutti i calendari senza una vista propria ed è visibile solo a te.",
"shiftsPerDay": "Turni regolari al giorno",
- "shiftsPerDayHint": "Numero massimo di turni regolari da visualizzare per giorno",
+ "shiftsPerDayHint": "Gli altri appaiono come «+N». Auto ne mostra quanti ne entrano nella cella del giorno.",
"externalShiftsPerDay": "Turni esterni al giorno",
- "externalShiftsPerDayHint": "Numero massimo di turni da calendari esterni da visualizzare per giorno",
- "showAll": "Tutti",
+ "externalShiftsPerDayHint": "Vale per i calendari esterni mostrati «Come i propri». Gli altri appaiono come «+N».",
"sortOptions": "Opzioni di Ordinamento",
"sortBy": "Ordina per",
"sortByStartTime": "Ora di inizio",
@@ -286,11 +226,8 @@
"sortOrderDesc": "Decrescente",
"combinedSort": "Ordina tutti i turni insieme",
"combinedSortHint": "Ordina i turni regolari ed esterni insieme invece che separatamente",
- "displayOptions": "Opzioni di Visualizzazione",
"showNotes": "Mostra note turni",
- "showNotesHint": "Visualizza note dei turni nella griglia calendario",
- "showFullTitles": "Mostra titoli completi",
- "showFullTitlesHint": "Visualizza titoli completi dei turni senza troncamento",
+ "showNotesHint": "La nota di un turno come seconda riga nella vista mensile",
"dayHighlighting": "Evidenziazione Giorni",
"highlightWeekends": "Evidenzia Fine Settimana",
"highlightWeekendsHint": "Evidenzia sabato e domenica con colore",
@@ -303,7 +240,17 @@
"friday": "Venerdì",
"saturday": "Sabato",
"sunday": "Domenica",
- "highlightColor": "Colore Evidenziazione"
+ "highlightColor": "Colore Evidenziazione",
+ "density": "Densità",
+ "showPresetBar": "Mostra barra dei modelli",
+ "showPresetBarHint": "Barra dei modelli sotto o sopra il calendario",
+ "settingsDescriptionLocal": "La tua vista personale su questo dispositivo. Vale per tutti i calendari senza una vista propria.",
+ "overriddenByCalendar": "«{calendar}» ha una vista propria. Lì la tua vista personale non vale.",
+ "calendarOwn": "Vista propria per questo calendario",
+ "calendarOwnHint": "Vale per tutte le persone con accesso a questo calendario.",
+ "calendarOffNote": "Qui ognuno vede la propria vista personale. La tua si imposta in «La mia vista».",
+ "calendarLocked": "Impostata per questo calendario. Solo chi gestisce il calendario può modificarla.",
+ "limitAuto": "Auto"
},
"stats": {
"title": "Statistiche Turni",
@@ -329,52 +276,16 @@
"connected": "Connesso al server",
"disconnected": "Connessione al server persa"
},
- "onboarding": {
- "welcome": "Benvenuto in BetterShift",
- "description": "Crea il tuo primo calendario per gestire i tuoi turni.",
- "createCalendar": "Crea Calendario"
- },
- "guestEmptyState": {
- "title": "Nessun Calendario Pubblico Disponibile",
- "description": "Al momento non ci sono calendari pubblici condivisi. Effettua il login per creare e gestire i tuoi calendari.",
- "loginButton": "Vai al Login"
- },
- "footer": {
- "version": "Versione",
- "github": "GitHub",
- "support": "Supporto"
- },
- "theme": {
- "switchToLight": "Passa alla modalità chiara",
- "switchToDark": "Passa alla modalità scura"
- },
"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",
"importMethod": "Metodo di Importazione",
- "importMethodUrl": "URL (sincronizzabile)",
- "importMethodFile": "Carica File (importazione unica)",
"importMethodUrlHint": "URL del calendario esterno (iCloud, Google o altri URL ICS)",
"importMethodFileHint": "Importa file ICS una sola volta",
"fileLabel": "File ICS",
- "fileSelected": "File selezionato",
"oneTimeImport": "Importazione unica",
- "displayMode": "Visualizza turni sincronizzati",
- "displayModeNormal": "Normale (mostra tutti i turni)",
- "displayModeMinimal": "Minimale (mostra solo il conteggio)",
- "displayModeHint": "Scegli come visualizzare i turni sincronizzati nel calendario",
- "addNewSync": "Aggiungi Nuovo Calendario Esterno",
- "editSync": "Modifica Calendario Esterno",
- "colorHint": "Scegli il colore per tutti i turni importati",
- "hideCalendar": "Nascondi calendario",
- "hideCalendarHint": "Nascondi i turni da questo calendario",
- "hideFromStats": "Nascondi dalle statistiche",
- "hideFromStatsHint": "Escludi i turni da questo calendario dalle statistiche",
- "lastSynced": "Ultima sincronizzazione",
"delete": "Elimina Calendario Esterno",
"deleteConfirm": "Eliminare questo calendario esterno? Tutti i turni importati verranno rimossi.",
"hintsTitle": "Trovare l'URL del Calendario",
@@ -384,8 +295,6 @@
"hintICloud": "Apri iCloud.com → Calendario → Clicca sull'icona di condivisione accanto al tuo calendario → Abilita 'Calendario Pubblico' → Copia l'URL webcal:// e incollalo qui.",
"hintGoogle": "Apri Google Calendar → Impostazioni → Seleziona il tuo calendario → Scorri fino a 'Indirizzo segreto in formato iCal' → Copia l'URL e incollalo qui.",
"hintCustom": "Funzionerà qualsiasi calendario ICS accessibile pubblicamente. L'URL deve iniziare con https:// o webcal:// e terminare con .ics. Esempio: https://example.com/calendar.ics",
- "autoSyncLabel": "Sincronizzazione Automatica",
- "autoSyncHint": "Scegli la frequenza con cui questo calendario deve essere sincronizzato automaticamente",
"autoSyncManual": "Manuale",
"autoSync24hShort": "24 h"
},
@@ -397,7 +306,6 @@
"syncTypeAuto": "Automatica",
"syncTypeManual": "Manuale",
"noChanges": "Nessuna modifica",
- "errorMessage": "Messaggio di errore",
"filterAll": "Mostra tutto",
"filterSuccess": "Solo riuscita",
"filterError": "Solo errori",
@@ -415,9 +323,6 @@
"viewOnGitHub": "Visualizza su GitHub"
},
"export": {
- "title": "Esporta Calendario",
- "description": "Esporta il tuo calendario come file ICS o PDF",
- "exportCalendar": "Esporta Calendario",
"formatLabel": "Formato di esportazione",
"icsFormat": "ICS (File Calendario)",
"pdfFormat": "PDF (Documento)",
@@ -432,34 +337,19 @@
"download": "Scarica",
"multiCalendar": "Esporta più calendari",
"multiCalendarHint": "Combina i turni da più calendari in un unico file di esportazione",
- "selectCalendars": "Seleziona Calendari",
- "selectCalendarsDescription": "Scegli quali calendari includere nell'esportazione",
"selectedCount": "{count, plural, =0 {Nessun calendario selezionato} =1 {1 calendario selezionato} other {# calendari selezionati}}",
"selectAtLeastOne": "Seleziona almeno un calendario"
},
"update": {
- "available": "Aggiornamento disponibile",
- "newVersion": "Versione {version} è disponibile",
- "viewChangelog": "Visualizza changelog"
+ "newVersion": "Versione {version} è disponibile"
},
"auth": {
"login": "Accedi",
- "loginTitle": "Accedi a BetterShift",
- "loginDescription": "Accedi con il tuo account o usa uno dei provider sotto",
"register": "Registrati",
- "registerTitle": "Crea Account",
- "registerDescription": "Crea un nuovo account per iniziare",
"logout": "Disconnetti",
"profile": "Profilo",
- "profileTitle": "Il Tuo Profilo",
- "profileDescription": "Gestisci le impostazioni e le preferenze del tuo account",
- "profileBasicInfoDescription": "Le tue informazioni di base dell'account",
- "changePasswordDescription": "Aggiorna la tua password per mantenere il tuo account sicuro",
- "connectedAccountsDescription": "Gestisci i tuoi provider OAuth connessi",
"dangerZone": "Zona Pericolosa",
- "dangerZoneDescription": "Azioni irreversibili che influenzano il tuo account",
"logoutDescription": "Disconnettiti dalla tua sessione corrente",
- "deleteAccountDescription": "Elimina permanentemente il tuo account e tutti i dati",
"noConnectedAccounts": "Nessun account connesso ancora",
"emailPasswordAuth": "Email/Password",
"emailPlaceholder": "[email protected]",
@@ -468,14 +358,10 @@
"confirmPasswordLabel": "Conferma Password",
"enterPassword": "Inserisci password",
"namePlaceholder": "Il tuo nome",
- "continueWith": "Continua con {provider}",
"continueAsGuest": "Continua come Ospite",
- "alreadyHaveAccount": "Hai già un account?",
"noAccountYet": "Non hai ancora un account?",
"changePassword": "Cambia Password",
"deleteAccount": "Elimina Account",
- "editProfile": "Modifica Profilo",
- "editProfileDescription": "Aggiorna il tuo nome, email e immagine del profilo",
"profileUpdated": "Profilo aggiornato con successo",
"profilePicture": "Immagine del Profilo",
"avatarHint": "Max 5MB. Formati supportati: JPEG, PNG, GIF, WebP",
@@ -503,47 +389,27 @@
"discord": "Discord",
"customOidc": "SSO"
},
- "activeSessionsDescription": "Gestisci i tuoi dispositivi e sessioni attive",
"noActiveSessions": "Nessuna sessione attiva",
- "browser": "Browser",
- "operatingSystem": "Sistema Operativo",
- "logoutAllDevices": "Disconnetti da tutti gli altri dispositivi",
"sessionsRevokedCount": "Disconnesso da {count} dispositivo/i"
},
"system": {
"unavailable": "Sistema non disponibile",
- "unavailableDescription": "Il sistema è attualmente non disponibile a causa di un errore critico. Riprova più tardi o contatta un amministratore.",
- "unavailableRetry": "Aggiorna questa pagina per riprovare o torna più tardi."
+ "unavailableDescription": "Il sistema è attualmente non disponibile a causa di un errore critico. Riprova più tardi o contatta un amministratore."
},
"guest": {
"viewingAsGuest": "Stai visualizzando come ospite",
"bannerMessage": "Stai visualizzando questo calendario come ospite. Accedi per l'accesso completo.",
- "loginForFullAccess": "Accedi per l'accesso completo",
"cannotEdit": "Non puoi modificare in modalità sola lettura"
},
"share": {
- "manageSharing": "Gestisci Condivisione",
- "manageSharingDescription": "Controlla chi può accedere a \"{name}\"",
- "userShares": "Condivisioni Utente",
"publicAccess": "Accesso Pubblico",
- "accessLinks": "Link di Accesso",
"public": "Pubblico",
"links": "Link",
"share": "condivisione",
- "sharedBy": "Condiviso da",
- "sharedOn": "Condiviso Il",
- "addUser": "Aggiungi Utente",
- "addUserDescription": "Cerca un utente per condividere questo calendario",
"searchUser": "Cerca utente",
"searchUserPlaceholder": "Inserisci nome o email...",
- "selectedUser": "Utente selezionato",
- "noShares": "Nessun utente ha ancora accesso",
"noSharesDescription": "Condividi questo calendario con altri utenti per collaborare",
- "userSharesDescription": "Gestisci chi può accedere a questo calendario",
- "publicAccessDescription": "Controlla l'accesso pubblico per utenti autenticati e ospiti",
- "publicPermissionNoneDesc": "Nessuno può accedere a questo calendario senza condivisione esplicita",
- "publicPermissionReadDesc": "Qualsiasi utente autenticato può visualizzare il calendario",
- "publicPermissionWriteDesc": "Qualsiasi utente autenticato può visualizzare e modificare il calendario",
+ "publicPermissionNoneDesc": "Solo tu, le persone invitate e chi possiede un link di accesso hanno accesso.",
"shareAdded": "Calendario condiviso con successo",
"shareUpdated": "Permesso aggiornato con successo",
"shareRemoved": "Accesso rimosso con successo",
@@ -551,46 +417,27 @@
"removeShareConfirmTitle": "Rimuovere l'accesso al calendario?",
"removeShareConfirmDesc": "Sei sicuro di voler rimuovere l'accesso per {user}? Non potrà più visualizzare o modificare questo calendario.",
"you": "Tu",
- "sharedWithYou": "Condiviso con te"
+ "sharedWithYou": "Condiviso con te",
+ "publicPermissionReadDescGuestsOn": "Chiunque può visualizzare il calendario, anche senza account. Gli utenti autenticati lo aggiungono da «Calendari Condivisi».",
+ "publicPermissionWriteDescGuestsOn": "Chiunque può visualizzare e modificare il calendario, anche senza account. Gli utenti autenticati lo aggiungono da «Calendari Condivisi».",
+ "publicPermissionReadDescGuestsOff": "Gli utenti autenticati di questa istanza possono aggiungere e visualizzare il calendario da «Calendari Condivisi». Senza account non è possibile accedere, perché l’accesso ospite è disattivato su questa istanza.",
+ "publicPermissionWriteDescGuestsOff": "Gli utenti autenticati di questa istanza possono aggiungere, visualizzare e modificare il calendario da «Calendari Condivisi». Senza account non è possibile accedere, perché l’accesso ospite è disattivato su questa istanza.",
+ "publicAccessDescriptionGuestsOn": "Controlla l’accesso pubblico per utenti autenticati e visitatori senza account.",
+ "publicAccessDescriptionGuestsOff": "Controlla l’accesso pubblico per gli utenti autenticati di questa istanza."
},
"token": {
"accessLinks": "Link di Accesso",
- "accessLinksDescription": "Condividi questo calendario tramite link sicuri",
- "createLink": "Crea Link",
- "createFirstLink": "Crea Primo Link",
- "noTokensYet": "Nessun link di accesso ancora",
- "noTokensDescription": "Crea link di accesso per condividere questo calendario senza richiedere un account",
"unnamed": "Senza Nome",
- "namePlaceholder": "es. Link Famiglia, Team Lavoro",
"token": "Token",
- "tokenValue": "Valore Token",
- "readOnlyDescription": "Visualizza turni e note",
- "editDescription": "Crea e modifica turni",
- "expiration": "Scadenza",
- "expires": "Scade",
- "expired": "Scaduto",
"expiration1Day": "1 Giorno",
"expiration7Days": "7 Giorni",
"expiration30Days": "30 Giorni",
- "expirationNever": "Mai",
- "expiresOn": "Scade il",
- "usage": "Utilizzo",
"usedCount": "{count, plural, =0 {Mai usato} =1 {Usato una volta} other {Usato # volte}}",
- "neverUsed": "Mai usato",
"enable": "Attiva",
"disable": "Disattiva",
"revoke": "Revoca",
"revokeConfirm": "Revocare Link di Accesso?",
- "revokeConfirmDescription": "Sei sicuro di voler revocare \"{name}\"? Chiunque usi questo link perderà immediatamente l'accesso.",
- "generate": "Genera Link",
- "shareLink": "Link di Condivisione",
- "linkCreated": "Link Creato!",
- "linkCreatedDescription": "Il tuo link di condivisione è stato creato con successo",
- "saveWarning": "Salva questo link ora - non verrà mostrato di nuovo!",
- "shareInfo": "Chiunque abbia questo link può accedere al tuo calendario con il livello di permesso specificato",
- "accessedViaLink": "Accesso tramite Link di Condivisione",
- "linkName": "Nome Link",
- "createLinkDescription": "Crea un link di accesso per condividere questo calendario senza richiedere un account"
+ "revokeConfirmDescription": "Sei sicuro di voler revocare \"{name}\"? Chiunque usi questo link perderà immediatamente l'accesso."
},
"rateLimit": {
"title": "Troppe richieste",
@@ -605,16 +452,14 @@
},
"activityLog": {
"title": "Registro Attività",
- "description": "Visualizza l'attività del tuo account e gli eventi di sicurezza",
+ "description": "Accessi, modifiche ed eventi di sicurezza del tuo account",
"noLogs": "Nessuna attività registrata ancora",
"eventType": "Tipo Evento",
"resource": "Risorsa",
"details": "Dettagli",
"clearAll": "Cancella tutto",
- "refresh": "Aggiorna",
- "refreshed": "Registro attività aggiornato",
"confirmClear": "Sei sicuro di voler cancellare tutti i registri di attività? Questa azione non può essere annullata.",
- "totalLogs": "{count} registri totali",
+ "totalLogs": "{count, plural, one {# voce} other {# voci}}",
"showingResults": "Mostrando {start}-{end} di {total}",
"searchPlaceholder": "Cerca per azione, risorsa o ID...",
"noMetadata": "Nessun dettaglio aggiuntivo disponibile",
@@ -622,7 +467,8 @@
"auth": "Autenticazione",
"sync": "Sincronizzazione",
"security": "Sicurezza",
- "calendar": "Calendario"
+ "calendar": "Calendario",
+ "heading": "Eventi"
},
"admin": {
"title": "Pannello Admin",
@@ -630,7 +476,6 @@
"dashboard": "Dashboard",
"usersMenu": "Utenti",
"calendarsMenu": "Calendari",
- "orphanedCalendars": "Calendari Orfani",
"auditLogs": "Log di Audit",
"backToApp": "Torna all'App",
"superadminBadge": "Superadmin",
@@ -638,23 +483,12 @@
"collapseSidebar": "Comprimi Barra Laterale",
"accessDenied": "Accesso admin richiesto",
"stats": {
- "totalUsers": "Utenti Totali",
- "totalCalendars": "Calendari Totali",
- "orphanedCalendars": "Calendari Orfani",
- "totalShifts": "Turni Totali",
- "activeShares": "Condivisioni Attive",
- "recentActivity": "Attività Recente",
"usersByRole": "{superadmin} superadmin, {admin} admin, {user} utenti",
- "calendarsDescription": "Calendari con proprietari",
- "orphanedDescription": "Calendari senza proprietario",
"sharesDescription": "{user} condivisioni utente, {token} condivisioni token",
- "shiftsDescription": "Turni totali in tutti i calendari",
- "last7Days": "Ultimi 7 giorni",
- "needsAttention": "Richiede Attenzione"
+ "last7Days": "Ultimi 7 giorni"
},
"systemInfo": {
"title": "Informazioni di sistema",
- "description": "Versione corrente del sistema e dettagli di build",
"version": "Versione",
"buildDate": "Data di build",
"commitHash": "Hash commit",
@@ -666,29 +500,20 @@
"development": "Sviluppo",
"unknown": "Sconosciuto"
},
- "dashboardDescription": "Benvenuto nel Pannello Admin di BetterShift",
"orphanedCalendarsWarning": "Calendari Orfani Rilevati",
"orphanedCalendarsWarningDescription": "{count, plural, =1 {C'è 1 calendario senza proprietario} other {Ci sono # calendari senza proprietario}}. Si prega di assegnarli agli utenti.",
- "manageOrphanedCalendars": "Gestisci Calendari Orfani",
"recentActivityDescription": "Log delle ultime attività admin e di sicurezza",
"statsFetchError": "Impossibile caricare le statistiche",
- "userManagement": "Gestione Utenti",
- "userManagementDescription": "Gestisci account utente e permessi",
"searchUsers": "Cerca per nome o email...",
"allRoles": "Tutti i Ruoli",
"allStatuses": "Tutti gli Stati",
"banned": "Bannato",
"role": "Ruolo",
"calendarsCount": "Calendari",
- "page": "pagina",
- "usersCount": "{count, plural, =0 {Nessun utente} =1 {1 utente} other {# utenti}}",
"neverActive": "Mai",
"editUser": "Modifica Utente",
- "editUserDescription": "Aggiorna informazioni utente e permessi",
"userDetails": "Dettagli Utente",
- "userDetailsDescription": "Visualizza informazioni dettagliate utente",
"ownedCalendars": "Calendari Proprietari",
- "joined": "Iscritto",
"banUser": "Banna Utente",
"banUserConfirm": "Bannare utente {name}?",
"banWarning": "L'utente verrà disconnesso immediatamente e non potrà accedere fino alla rimozione del ban.",
@@ -724,8 +549,6 @@
"emailPlaceholder": "[email protected]",
"roleChangeWarning": "La modifica del ruolo utente influenzerà immediatamente i permessi",
"calendars": {
- "title": "Gestione Calendari",
- "description": "Gestisci tutti i calendari nel sistema",
"owner": "Proprietario",
"updated": "Aggiornato",
"guestPermission": "Permesso Ospite",
@@ -736,8 +559,6 @@
"orphanedOnly": "Solo Orfani",
"withOwner": "Con Proprietario",
"searchPlaceholder": "Cerca per nome...",
- "calendarsCount": "{count, plural, =0 {Nessun calendario} =1 {1 calendario} other {# calendari}}",
- "selectedCount": "{count, plural, =1 {1 calendario selezionato} other {# calendari selezionati}}",
"transferSelected": "Trasferisci Selezionati",
"clearSelection": "Cancella Selezione",
"noCalendarsFound": "Nessun calendario trovato",
@@ -748,19 +569,13 @@
"transferOwnership": "Trasferisci Proprietà",
"deleteCalendar": "Elimina Calendario",
"calendarDetails": "Dettagli Calendario",
- "calendarDetailsDescription": "Visualizza informazioni dettagliate del calendario",
- "userShares": "utente",
- "tokenShares": "token",
"userSharesList": "Condivisioni Utente",
"tokenSharesList": "Condivisioni Token",
"externalSyncs": "Sincronizzazioni Esterne",
"externalSyncsShort": "Sincronizzazioni",
"lastSynced": "Ultima sincronizzazione",
- "quickActions": "Azioni Rapide",
- "editCalendarDescription": "Aggiorna informazioni calendario",
"namePlaceholder": "Inserisci nome calendario",
"guestPermissionHint": "Controlla l'accesso pubblico a questo calendario",
- "transferSingleDescription": "Trasferisci proprietà di \"{name}\"",
"transferMultipleDescription": "{count, plural, =1 {1 calendario} other {# calendari}} saranno trasferiti",
"calendarsToTransfer": "Calendari da Trasferire",
"calendarToTransfer": "Calendario da Trasferire",
@@ -782,7 +597,6 @@
"calendarsDeleted": "{count, plural, =1 {1 calendario eliminato} other {# calendari eliminati}}",
"calendarsTransferred": "{count, plural, =1 {1 calendario trasferito} other {# calendari trasferiti}}"
},
- "auditLogsDescription": "Gestisci tutti i log",
"allActions": "Tutte le Azioni",
"adminActions": "Azioni Admin",
"calendarActions": "Azioni Calendario",
@@ -803,7 +617,6 @@
"pleaseSelectDate": "Seleziona una data",
"pleaseConfirmDeletion": "Conferma l'eliminazione",
"willDeleteLogsOlderThan": "Tutti i log più vecchi di {date} verranno eliminati",
- "preview": "Anteprima",
"auditLogDetails": "Dettagli Log di Audit",
"resourceType": "Tipo Risorsa",
"resourceId": "ID Risorsa",
@@ -815,5 +628,421 @@
"clearSelection": "Cancella Selezione",
"deleteSelectedLogsDescription": "Elimina {count, plural, one {# log selezionato} other {# log selezionati}}. Questa azione non può essere annullata.",
"willDeleteSelectedLogs": "{count, plural, one {# log} other {# log}} verranno eliminati permanentemente"
+ },
+ "appearance": {
+ "title": "Aspetto",
+ "hint": "La scelta vale per questo dispositivo ed è salvata localmente. Il cambio è immediato, senza ricaricare.",
+ "system": {
+ "title": "Sistema",
+ "description": "Segue l’impostazione del dispositivo"
+ },
+ "light": {
+ "title": "Chiaro",
+ "description": "Sempre chiaro"
+ },
+ "dark": {
+ "title": "Scuro",
+ "description": "Sempre scuro"
+ }
+ },
+ "appMenu": {
+ "account": "Account",
+ "language": "Lingua",
+ "preferences": "Preferenze",
+ "viewSettings": "La mia vista",
+ "settingsAndAccount": "Impostazioni e account"
+ },
+ "calendarView": {
+ "previousMonth": "Mese precedente",
+ "nextMonth": "Mese successivo",
+ "today": "Oggi",
+ "tomorrow": "Domani",
+ "yesterday": "Ieri",
+ "calendarWeek": "Settimana {week}",
+ "weekdayShort": {
+ "monday": "Lu",
+ "tuesday": "Ma",
+ "wednesday": "Me",
+ "thursday": "Gi",
+ "friday": "Ve",
+ "saturday": "Sa",
+ "sunday": "Do"
+ },
+ "allDayShort": "giornata",
+ "externalCount": "{count} esterni",
+ "hasNotes": "{count, plural, one {# nota} other {# note}}",
+ "shift": "Turno",
+ "kpiShifts": "Turni",
+ "kpiHours": "Ore",
+ "kpiNotes": "Note",
+ "kpiAvgPerShift": "⌀ per turno",
+ "kpiFreeDays": "Giorni liberi",
+ "dayEmpty": "Nessuna voce in questo giorno.",
+ "dayFree": "libero",
+ "notesCount": "{count, plural, one {# nota} other {# note}}",
+ "addNoteOrEvent": "Nota o evento",
+ "monthTotal": "Totale di {month}",
+ "allShiftsIn": "Tutti i turni di {month}",
+ "openStats": "Grafici e statistiche",
+ "shiftCount": "{count, plural, one {# turno} other {# turni}}",
+ "shiftActions": "Azioni del turno",
+ "external": "esterno",
+ "syncedReadOnly": "Da un calendario esterno, sola lettura",
+ "changedOn": "modificato il {date}",
+ "stamp": "Modelli",
+ "managePresets": "Gestisci modelli",
+ "createPreset": "Crea modello",
+ "manage": "Gestisci",
+ "stampHint": "Tocca un giorno per aggiungere {title}, tocca di nuovo per rimuoverlo.",
+ "addShiftManually": "Aggiungi turno manualmente",
+ "sheetDescription": "Turni e note del giorno selezionato",
+ "sheetExpand": "Espandi",
+ "sheetShrink": "Riduci",
+ "periodLabel": "Periodo",
+ "wholeWeek": "Settimana intera",
+ "wholeMonth": "Mese intero",
+ "wholeYear": "Anno intero",
+ "readOnlyTitle": "Sola lettura",
+ "readOnlyMessage": "Questo calendario è stato condiviso con te in sola lettura, quindi modelli e creazione sono nascosti.",
+ "offlineTitle": "Nessuna connessione al server",
+ "offlineMessage": "Stai vedendo l’ultimo stato caricato. Le modifiche torneranno possibili quando la connessione sarà ripristinata; non vengono salvate nel frattempo.",
+ "retry": "Riprova",
+ "note": "Nota",
+ "event": "Evento",
+ "eventCount": "{count, plural, one {# evento} other {# eventi}}",
+ "statsSheetDescription": "Turni, ore e giorni liberi per settimana, mese o anno"
+ },
+ "calendarCompare": {
+ "title": "Confronto",
+ "exit": "Esci",
+ "addCalendar": "Terzo calendario",
+ "stampActive": "Modello attivo",
+ "tapToMoveStamp": "Clicca un modello per inserirlo in questa colonna",
+ "subtitle": "{count} calendari",
+ "laneHintTwo": "Riga in alto {top}, in basso {bottom}: si riconoscono dalla barra a sinistra. Un riquadro vuoto significa libero.",
+ "laneHintMany": "Righe dall’alto: {order}: si riconoscono dalla barra a sinistra. Un riquadro vuoto significa libero.",
+ "maxHint": "al massimo {max}"
+ },
+ "formKit": {
+ "optional": " (facoltativo)",
+ "customColor": "Personalizzato"
+ },
+ "settings": {
+ "title": "Impostazioni",
+ "description": "Vale per tutte le persone con accesso a questo calendario",
+ "general": "Nome e colore",
+ "generalHint": "Nome visualizzato, colore del calendario, eliminazione",
+ "presets": "Modelli",
+ "presetsHint": "{count, plural, =0 {Nessun modello} one {# modello} other {# modelli}}",
+ "external": "Calendari esterni",
+ "externalHint": "{count, plural, =0 {Abbonamento, visualizzazione, intervallo} one {# abbonamento, visualizzazione, intervallo} other {# abbonamenti, visualizzazione, intervallo}}",
+ "sharing": "Condivisione",
+ "sharingHint": "{count, plural, =0 {Persone, accesso pubblico, link} one {Persone, accesso pubblico, # link attivo} other {Persone, accesso pubblico, # link attivi}}",
+ "export": "Esporta",
+ "exportHint": "File ICS o PDF",
+ "view": "Vista del calendario",
+ "viewHint": "Vista propria, densità, ordinamento",
+ "notifications": "Notifiche",
+ "notificationsHint": "Sincronizzazione",
+ "notificationsError": "Errore di sincronizzazione",
+ "deleteImpact": "{count, plural, =0 {Il calendario viene eliminato definitivamente} one {Verrà eliminato anche # turno} other {Verranno eliminati anche # turni}}",
+ "appliesToAll": "Le modifiche valgono subito per tutte le persone con accesso.",
+ "groupAccount": "Account",
+ "groupApp": "App",
+ "viewOn": "attiva",
+ "viewOff": "disattiva",
+ "groupPersonal": "Solo per te",
+ "personalCaption": "Vale in tutti i calendari, gli altri non lo vedono"
+ },
+ "presetSheet": {
+ "title": "Preset",
+ "description": "L’ordine determina la barra dei modelli",
+ "primary": "Nella barra",
+ "newPreset": "Nuovo preset",
+ "titlePlaceholder": "es. Reperibilità",
+ "start": "Inizio",
+ "end": "Fine",
+ "allDay": "Tutto il giorno",
+ "allDayShort": "tutto il giorno",
+ "markAsSecondary": "Raggruppa sotto «Altri»",
+ "hideFromStatsHint": "Non conta nelle ore né nelle statistiche",
+ "notInStats": "Escluso dalle statistiche",
+ "save": "Salva preset",
+ "delete": "Elimina preset",
+ "dragHandle": "Trascina per riordinare",
+ "secondarySection": "Sotto «Altri»",
+ "markAsSecondaryHint": "Compare nella barra dei modelli solo dopo aver cliccato «Altri»"
+ },
+ "syncSheet": {
+ "intervalPill": "Ogni {interval}",
+ "intervalValue": "ogni {interval}",
+ "lastSynced": "ultimo {time}",
+ "syncNow": "Sincronizza ora",
+ "sourceUrl": "Abbonati a un indirizzo",
+ "sourceFile": "Importa file",
+ "chooseFile": "Scegli file ICS",
+ "urlLabel": "Indirizzo del file ICS",
+ "colorLabel": "Colore di tutti i turni importati",
+ "displayLabel": "Visualizzazione nel calendario",
+ "displayMinimal": "Solo numero",
+ "displayNormal": "Come i propri",
+ "autoSyncLabel": "Recupera automaticamente",
+ "hideShifts": "Nascondi i turni di questo abbonamento",
+ "excludeFromStats": "Escludi dalle statistiche",
+ "addSubscription": "Aggiungi abbonamento"
+ },
+ "syncLog": {
+ "description": "Ultimi recuperi dei calendari esterni",
+ "statusSuccess": "Riuscito"
+ },
+ "sharingSheet": {
+ "tabPeople": "Persone",
+ "invite": "Invita",
+ "haveAccess": "Hanno accesso",
+ "owner": "Proprietario",
+ "permRead": "Sola lettura",
+ "permWrite": "Modifica",
+ "permReadDesc": "Vedere il calendario senza modificare nulla",
+ "permWriteDesc": "Creare ed eliminare turni",
+ "permAdminDesc": "Gestire anche condivisioni e impostazioni",
+ "changePermission": "Modifica il permesso di {name}",
+ "publicOffTitle": "L’accesso pubblico è disattivato",
+ "publicOnTitle": "L’accesso pubblico è attivo",
+ "accessNone": "Nessun accesso",
+ "guestNoneShort": "Solo invitati e link",
+ "activeLinks": "Link attivi",
+ "inactiveLinks": "Disattivati o scaduti",
+ "noActiveLinks": "Nessun link attivo",
+ "expiresOn": "scade il {date}",
+ "expiredOn": "scaduto il {date}",
+ "noExpiry": "senza scadenza",
+ "lastUsed": "ultimo uso {time}",
+ "newLink": "Crea un nuovo link",
+ "linkName": "Etichetta",
+ "linkNameHint": "facoltativa, aiuta nella revoca",
+ "linkNamePlaceholder": "es. Bacheca sala pausa",
+ "validity": "Validità",
+ "validityUnlimited": "Senza scadenza",
+ "validUntilRevoked": "valido finché non lo revochi",
+ "createLink": "Crea link",
+ "creating": "Creazione …",
+ "linkReady": "Il link è pronto",
+ "copyNowTitle": "Copialo ora",
+ "copyNowBody": "Dopo la chiusura il token non è più recuperabile. Se va perso, creane uno nuovo e revoca questo.",
+ "shareLinkLabel": "Link da condividere",
+ "copied": "Copiato",
+ "guestReadShortGuestsOn": "Tutti possono vedere",
+ "guestWriteShortGuestsOn": "Tutti possono modificare",
+ "guestReadShortGuestsOff": "Gli utenti autenticati possono vedere",
+ "guestWriteShortGuestsOff": "Gli utenti autenticati possono modificare",
+ "publicOffBodyGuestsOn": "Hanno accesso solo le persone invitate e chi possiede un link di accesso; i link funzionano anche senza account. Dalla scheda «Pubblico» puoi aprire il calendario a tutti, anche ai visitatori senza account.",
+ "publicOffBodyGuestsOff": "Hanno accesso solo le persone invitate e chi possiede un link di accesso; chi riceve un link deve accedere, perché l’accesso ospite è disattivato su questa istanza. Dalla scheda «Pubblico» puoi aprire il calendario agli utenti autenticati di questa istanza.",
+ "linkInfoGuestsOn": "Il link apre direttamente il calendario, senza accesso. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare.",
+ "linkInfoGuestsOff": "Il link apre direttamente il calendario. L’accesso ospite è disattivato su questa istanza, quindi i destinatari devono accedere. Puoi revocarlo dalla lista in qualsiasi momento: smette subito di funzionare."
+ },
+ "shiftSheet": {
+ "start": "Inizio",
+ "end": "Fine",
+ "duration": "Durata",
+ "allDay": "Tutto il giorno",
+ "noPreset": "Libero",
+ "createAction": "Crea turno"
+ },
+ "noteSheet": {
+ "createTitle": "Nuova voce",
+ "editTitle": "Modifica voce",
+ "createAction": "Crea voce",
+ "typeEvent": "Evento",
+ "typeNote": "Nota",
+ "typeHint": "Un evento mostra titolo e colore nella cella del giorno. Una nota resta discreta e compare solo come icona.",
+ "text": "Testo",
+ "repeat": "Ripetizione",
+ "repeatNone": "Una volta",
+ "repeatWeekly": "Settimanale",
+ "repeatMonthly": "Mensile",
+ "repeatYearly": "Annuale",
+ "unitWeeks": "{count, plural, one {settimana} other {settimane}}",
+ "unitMonths": "{count, plural, one {mese} other {mesi}}",
+ "unitYears": "{count, plural, one {anno} other {anni}}",
+ "intervalInactive": "solo con ripetizione",
+ "recurrenceWeeks": "{count, plural, one {settimanale} other {ogni # settimane}}",
+ "recurrenceMonths": "{count, plural, one {mensile} other {ogni # mesi}}",
+ "recurrenceYears": "{count, plural, one {annuale} other {ogni # anni}}",
+ "listTitle": "Note ed eventi",
+ "entryCount": "{count, plural, one {# voce} other {# voci}}",
+ "addAnother": "Aggiungi un'altra voce",
+ "shortcutHint": "Scorciatoia: clic destro su un giorno dal computer, pressione prolungata sul telefono."
+ },
+ "authPage": {
+ "loginSubtitle": "Continua ai tuoi calendari",
+ "signInWith": "Accedi con {provider}",
+ "registerTitle": "Crea account",
+ "registerSubtitle": "Dopo sarai subito connesso",
+ "passwordHint": "Almeno 8 caratteri",
+ "repeatPassword": "Ripeti password",
+ "passwordsMatch": "Le password coincidono",
+ "haveAccount": "Hai già un account?",
+ "showPassword": "Mostra password",
+ "hidePassword": "Nascondi password",
+ "sampleMonth": "Mese di esempio",
+ "instance": "Istanza"
+ },
+ "emptyState": {
+ "guestBadge": "Ospite",
+ "noCalendarTitle": "Ancora nessun calendario",
+ "noCalendarDescription": "Un calendario raccoglie turni, modelli e condivisioni di un gruppo. In seguito puoi crearne quanti vuoi e passare dall'uno all'altro.",
+ "createCalendar": "Crea calendario",
+ "browseShared": "Sfoglia condivisi",
+ "guestTitle": "Nessun calendario condiviso pubblicamente",
+ "guestDescription": "Senza account vedi solo i calendari aperti esplicitamente agli ospiti. Se hai ricevuto un link di accesso, aprilo direttamente: il link contiene l'accesso.",
+ "pasteAccessLink": "Incolla link di accesso",
+ "accessLinkDescription": "Incolla il link che hai ricevuto, oppure solo il token che contiene.",
+ "accessLinkLabel": "Link di accesso",
+ "accessLinkInvalid": "Questo non è un link di accesso valido.",
+ "openAccessLink": "Apri"
+ },
+ "discovery": {
+ "unsubscribe": "Disiscriviti"
+ },
+ "profile": {
+ "title": "Il mio account",
+ "navProfileHint": "Nome, e-mail, immagine del profilo",
+ "navPasswordHint": "Conferma la password attuale",
+ "navSessionsHint": "{count, plural, one {# dispositivo connesso} other {# dispositivi connessi}}",
+ "navActivityHint": "Cosa è cambiato di recente",
+ "navDangerHint": "Esci, elimina account",
+ "groupAccount": "Account",
+ "groupSecurity": "Sicurezza",
+ "chooseImage": "Scegli immagine",
+ "removeImage": "Rimuovi",
+ "appliesEverywhere": "Le modifiche si applicano subito a tutti i dispositivi.",
+ "discard": "Scarta",
+ "managedByProvider": "Nome ed e-mail provengono dal tuo provider di accesso e non possono essere modificati qui.",
+ "accountsTitle": "Metodi di accesso",
+ "accountsHint": "Puoi accedere con questi account.",
+ "connectedSince": "Collegato dal {date}",
+ "passwordNote": "Gli altri dispositivi restano connessi.",
+ "sessionsTitle": "Dispositivi connessi",
+ "sessionsHint": "La disconnessione termina subito la sessione.",
+ "signOutOthers": "Disconnetti gli altri",
+ "thisDevice": "questo dispositivo",
+ "activeNow": "attivo ora",
+ "sessionRevoked": "Dispositivo disconnesso",
+ "unknownBrowser": "Browser sconosciuto",
+ "unknownOs": "Sistema sconosciuto",
+ "deleteImpact": "Vengono eliminati anche calendari, turni e condivisioni.",
+ "deleteNeedsPassword": "Richiede la tua password."
+ },
+ "adminKit": {
+ "banned": "Bloccato",
+ "active": "Attivo",
+ "severityInfo": "info",
+ "severityWarning": "Avviso",
+ "severityError": "Errore",
+ "severityCritical": "critico"
+ },
+ "adminShell": {
+ "logsShort": "Log",
+ "breadcrumb": "Percorso di navigazione"
+ },
+ "adminDashboard": {
+ "title": "Panoramica",
+ "attention": "{count, plural, one {Una cosa richiede attenzione} other {# cose richiedono attenzione}}",
+ "allClear": "Al momento nulla richiede attenzione",
+ "openCalendars": "Apri calendari",
+ "recentTitle": "Cosa è successo di recente",
+ "recentShort": "Di recente",
+ "activityFooter": "{shown} di {count, plural, one {# evento} other {# eventi}}",
+ "scope": "Dimensioni",
+ "events": "Eventi",
+ "acrossCalendars": "su tutti i calendari",
+ "calendarsAllOwned": "tutti con proprietario",
+ "calendarsOrphaned": "{count, plural, one {# senza proprietario} other {# senza proprietario}}",
+ "usersSub": "{count, plural, one {# account} other {# account}}",
+ "calendarsSub": "{count, plural, one {# calendario} other {# calendari}}, {orphaned} senza proprietario",
+ "logsSub": "{count, plural, one {# evento} other {# eventi}}"
+ },
+ "adminAudit": {
+ "subtitle": "{count, plural, one {# voce} other {# voci}}",
+ "dateRange": "Periodo",
+ "clearRange": "Cancella periodo",
+ "filterTitle": "Filtri",
+ "done": "Fatto",
+ "selectAll": "Seleziona tutto in questa pagina",
+ "selectEntry": "Seleziona voce",
+ "severityShort": "Gravità",
+ "whatHappened": "Cosa è successo",
+ "details": "Dettagli",
+ "describe": {
+ "userBanned": "{user} bloccato",
+ "userBannedPermanently": "{user} bloccato in modo permanente",
+ "userUnbanned": "Blocco di {user} rimosso",
+ "passwordReset": "Password di {user} reimpostata",
+ "userDeleted": "Account {user} eliminato",
+ "userUpdated": "Account {user} modificato",
+ "calendarTransferred": "Calendario «{calendar}» trasferito a {user}",
+ "calendarsTransferred": "{count, plural, one {# calendario trasferito} other {# calendari trasferiti}} a {user}",
+ "calendarsDeleted": "{count, plural, one {# calendario eliminato} other {# calendari eliminati}}",
+ "logsDeleted": "{count, plural, one {# voce di log eliminata} other {# voci di log eliminate}}",
+ "calendarUpdated": "Calendario «{calendar}» modificato",
+ "calendarDeleted": "Calendario «{calendar}» eliminato",
+ "calendarCreated": "Calendario «{calendar}» creato",
+ "calendarShared": "Calendario «{calendar}» condiviso con {user}",
+ "shareRemoved": "Condivisione di «{calendar}» con {user} rimossa",
+ "permissionChanged": "Permesso di {user} su «{calendar}» modificato",
+ "guestPermissionChanged": "Accesso ospite a «{calendar}» modificato",
+ "syncCreated": "Sincronizzazione «{sync}» creata",
+ "syncDeleted": "Sincronizzazione «{sync}» rimossa",
+ "syncDisabled": "Sincronizzazione «{sync}» disattivata, calendario senza proprietario",
+ "syncFailed": "Sincronizzazione «{sync}» non riuscita",
+ "syncExecuted": "«{sync}» sincronizzato: {added} nuovi, {updated} modificati, {deleted} rimossi",
+ "rateLimit": "Limite di richieste raggiunto ({endpoint})",
+ "loginProvider": "Accesso tramite {provider}",
+ "loginEmail": "Accesso con e-mail e password",
+ "loginFailed": "Accesso non riuscito per {email}",
+ "registered": "Nuovo account {email} registrato",
+ "profileUpdated": "Profilo modificato",
+ "passwordChanged": "Password cambiata",
+ "accountDeleted": "Account personale eliminato",
+ "sessionsRevoked": "{count, plural, one {# sessione terminata} other {# sessioni terminate}}"
+ }
+ },
+ "adminUsers": {
+ "actions": "Azioni",
+ "all": "Tutti",
+ "ban": "Blocca",
+ "banReasonQuoted": "Motivo: «{reason}»",
+ "calendarCount": "{count, plural, one {# calendario} other {# calendari}}",
+ "edit": "Modifica",
+ "filterLabel": "Filtra utenti",
+ "hidePassword": "Nascondi password",
+ "joinedOn": "Iscritto il {date}",
+ "moreActions": "Altre azioni",
+ "moreFilters": "Altri filtri",
+ "numbers": "Numeri",
+ "showPassword": "Mostra password",
+ "subtitle": "{count, plural, one {# account} other {# account}}{banned, plural, =0 {} one {, di cui # bloccato} other {, di cui # bloccati}}"
+ },
+ "adminCalendars": {
+ "content": "Contenuto",
+ "filterLabel": "Filtra calendari",
+ "filterShared": "Condivisi",
+ "filterSynced": "Con sync",
+ "guestColumn": "Accesso ospite",
+ "guestNoneHint": "Solo le persone con cui è condiviso vedono il calendario",
+ "guestPermissionValue": "Permesso ospite: {permission}",
+ "guestReadHint": "Chiunque abbia il link vede il calendario",
+ "guestWriteHint": "Chiunque abbia il link può modificare il calendario",
+ "publicAccess": "Accesso pubblico",
+ "selectAll": "Seleziona tutto",
+ "selectedCount": "Selezionati: {count}",
+ "selectedNone": "Selezionati: nessuno",
+ "sharesAndLinks": "Condivisioni, {links, plural, one {# link di accesso} other {# link di accesso}}",
+ "showOrphaned": "Mostra",
+ "subtitle": "{count, plural, one {# calendario} other {# calendari}}, {shifts, plural, one {# turno} other {# turni}} in totale"
+ },
+ "adminPagination": {
+ "range": "{from}–{to} di {total}",
+ "label": "Pagine"
}
}
diff --git a/next.config.ts b/next.config.ts
index 385c979..df62c79 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -22,29 +22,8 @@ const nextConfig: NextConfig = {
},
async headers() {
- const isDev = process.env.NODE_ENV === "development";
-
- // Content Security Policy. 'unsafe-inline' stays in script-src because the
- // App Router streams its RSC payload through inline bootstrap scripts;
- // removing it requires a per-request nonce, which in turn forces every
- // page into dynamic rendering (see the Next.js "Content Security Policy"
- // guide). 'unsafe-eval' is only needed by React's development build for
- // readable server stack traces, so production does without it.
- const csp = [
- "default-src 'self'",
- `script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ""}`,
- "style-src 'self' 'unsafe-inline'", // Required for Tailwind
- "img-src 'self' data: https:",
- "font-src 'self' data:",
- "connect-src 'self'",
- "frame-ancestors 'none'",
- // Cheap hardening that costs nothing here: no plugin content, no
- // rewritten <base>, and forms may only post back to this origin.
- "object-src 'none'",
- "base-uri 'self'",
- "form-action 'self'",
- ].join("; ");
-
+ // Content-Security-Policy is set per-request in proxy.ts instead, since it
+ // carries a fresh nonce for every response.
return [
{
source: "/(.*)",
@@ -65,10 +44,6 @@ const nextConfig: NextConfig = {
key: "X-XSS-Protection",
value: "1; mode=block",
},
- {
- key: "Content-Security-Policy",
- value: csp,
- },
],
},
];
diff --git a/package-lock.json b/package-lock.json
index 708ef83..8c5119e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -50,9 +50,11 @@
"recharts": "^3.6.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
- "ua-parser-js": "^2.0.7"
+ "ua-parser-js": "^2.0.7",
+ "vaul": "^1.1.2"
},
"devDependencies": {
+ "@formatjs/icu-messageformat-parser": "^3.5.17",
"@tailwindcss/postcss": "^4",
"@tanstack/eslint-plugin-query": "^5.91.2",
"@types/better-sqlite3": "^7.6.13",
@@ -12075,6 +12077,19 @@
"base64-arraybuffer": "^1.0.2"
}
},
+ "node_modules/vaul": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
+ "integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-dialog": "^1.1.1"
+ },
+ "peerDependencies": {
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
+ }
+ },
"node_modules/victory-vendor": {
"version": "37.3.6",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
diff --git a/package.json b/package.json
index cfde4c1..ec39a8f 100644
--- a/package.json
+++ b/package.json
@@ -64,9 +64,11 @@
"recharts": "^3.6.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
- "ua-parser-js": "^2.0.7"
+ "ua-parser-js": "^2.0.7",
+ "vaul": "^1.1.2"
},
"devDependencies": {
+ "@formatjs/icu-messageformat-parser": "^3.5.17",
"@tailwindcss/postcss": "^4",
"@tanstack/eslint-plugin-query": "^5.91.2",
"@types/better-sqlite3": "^7.6.13",
diff --git a/proxy.ts b/proxy.ts
index 40d9ae6..dd221d3 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -79,6 +79,67 @@ async function getCachedHealthStatus(): Promise<"healthy" | "unhealthy"> {
return status;
}
+function redirectToLogin(request: NextRequest) {
+ const { pathname, search } = request.nextUrl;
+ const loginUrl = new URL("/login", request.url);
+ loginUrl.searchParams.set("returnUrl", pathname + search);
+ return NextResponse.redirect(loginUrl);
+}
+
+const IS_DEV = process.env.NODE_ENV === "development";
+const BYPASS_STRICT_DYNAMIC = process.env.CSP_STRICT_DYNAMIC_BYPASS === "true";
+
+/**
+ * Every route is already dynamically rendered (next-intl's request config reads
+ * cookies()/headers()), so a fresh nonce per request costs nothing extra here.
+ * 'unsafe-inline' stays in style-src because Radix sets inline `style` attributes
+ * at runtime, which a nonce cannot cover.
+ *
+ * 'strict-dynamic' drops host-based sources like 'self' for script-src by spec,
+ * which also blocks same-origin scripts a reverse proxy injects into the HTML
+ * (e.g. Cloudflare Rocket Loader's cdn-cgi/scripts/... loader) since they never
+ * carry our nonce. Rocket Loader turned out to go further than that: it
+ * reconstructs every inline <script> on the page (Next's own hydration
+ * bootstrap included) to "activate" it, and drops the nonce attribute while
+ * doing so -- so dropping only 'strict-dynamic' still leaves those blocked and
+ * the app fails to hydrate. CSP_STRICT_DYNAMIC_BYPASS=true therefore drops
+ * the nonce entirely and falls back to 'unsafe-inline', same as our other apps.
+ */
+function buildCsp(nonce: string | null) {
+ const scriptSrc = nonce
+ ? `'self' 'nonce-${nonce}' 'strict-dynamic'`
+ : "'self' 'unsafe-inline'";
+ return [
+ "default-src 'self'",
+ `script-src ${scriptSrc}${IS_DEV ? " 'unsafe-eval'" : ""}`,
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data: https:",
+ "font-src 'self' data:",
+ "connect-src 'self'",
+ "frame-ancestors 'none'",
+ "object-src 'none'",
+ "base-uri 'self'",
+ "form-action 'self'",
+ ].join("; ");
+}
+
+/**
+ * NextResponse.next() carrying the request-side x-nonce header and the CSP
+ * response header. Only the paths that actually render pay for this; the
+ * redirect branches above return before it.
+ */
+function nextWithNonce(request: NextRequest) {
+ const nonce = BYPASS_STRICT_DYNAMIC
+ ? null
+ : Buffer.from(crypto.randomUUID()).toString("base64");
+
+ const requestHeaders = new Headers(request.headers);
+ if (nonce) requestHeaders.set("x-nonce", nonce);
+ const response = NextResponse.next({ request: { headers: requestHeaders } });
+ response.headers.set("Content-Security-Policy", buildCsp(nonce));
+ return response;
+}
+
/**
* Proxy for authentication and route protection (Next.js 16)
*
@@ -120,7 +181,7 @@ export async function proxy(request: NextRequest) {
}
// System is unhealthy - allow access to error page
- return NextResponse.next();
+ return nextWithNonce(request);
} catch (error) {
// Log the error instead of silently swallowing it
console.error(
@@ -128,7 +189,7 @@ export async function proxy(request: NextRequest) {
error instanceof Error ? error.message : String(error)
);
// Always treat fetch failures/timeouts as "unhealthy" to allow access to error page
- return NextResponse.next();
+ return nextWithNonce(request);
}
}
@@ -226,7 +287,7 @@ export async function proxy(request: NextRequest) {
// If auth is disabled, allow all routes
if (!isAuthEnabled()) {
- return NextResponse.next();
+ return nextWithNonce(request);
}
// Public routes that don't require authentication
@@ -237,6 +298,7 @@ export async function proxy(request: NextRequest) {
"/api/version", // Version info (always public)
"/api/releases", // Changelog/releases (always public)
"/api/health", // Health check endpoint
+ "/manifest.json", // Browsers fetch the PWA manifest without cookies
];
// Check if the current route is public
@@ -246,7 +308,7 @@ export async function proxy(request: NextRequest) {
// Allow public routes
if (isPublicRoute) {
- return NextResponse.next();
+ return nextWithNonce(request);
}
// =====================================================
@@ -261,9 +323,7 @@ export async function proxy(request: NextRequest) {
if (!sessionToken) {
// Not authenticated - redirect to login
- const loginUrl = new URL("/login", request.url);
- loginUrl.searchParams.set("returnUrl", pathname);
- return NextResponse.redirect(loginUrl);
+ return redirectToLogin(request);
}
// Validate session and check admin role
@@ -272,9 +332,7 @@ export async function proxy(request: NextRequest) {
if (!session?.user) {
// Invalid session - redirect to login
- const loginUrl = new URL("/login", request.url);
- loginUrl.searchParams.set("returnUrl", pathname);
- return NextResponse.redirect(loginUrl);
+ return redirectToLogin(request);
}
// Check if user is admin
@@ -303,9 +361,7 @@ export async function proxy(request: NextRequest) {
} catch (error) {
console.error("[Proxy] Admin access check failed:", error);
// Session validation failed - redirect to login
- const loginUrl = new URL("/login", request.url);
- loginUrl.searchParams.set("returnUrl", pathname);
- return NextResponse.redirect(loginUrl);
+ return redirectToLogin(request);
}
}
@@ -319,22 +375,20 @@ export async function proxy(request: NextRequest) {
if (!sessionToken) {
// If guest access is enabled, allow viewing without login
if (allowGuestAccess()) {
- return NextResponse.next();
+ return nextWithNonce(request);
}
// Otherwise, redirect to login with return URL
- const loginUrl = new URL("/login", request.url);
- loginUrl.searchParams.set("returnUrl", pathname);
- return NextResponse.redirect(loginUrl);
+ return redirectToLogin(request);
}
// Session token validation happens in API routes via getSessionUser()
// Middleware only checks for cookie presence (fast routing decision)
- // Security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy,
- // X-XSS-Protection, Content-Security-Policy) are set globally in next.config.ts
- // so they apply to every response, not just this fall-through branch.
- return NextResponse.next();
+ // The remaining security headers (X-Content-Type-Options, X-Frame-Options,
+ // Referrer-Policy, X-XSS-Protection) are set globally in next.config.ts;
+ // only the nonce-based Content-Security-Policy has to be per-request.
+ return nextWithNonce(request);
}
// Configure which routes to run proxy on
diff --git a/scripts/changelog.sh b/scripts/changelog.sh
new file mode 100755
index 0000000..21cbe39
--- /dev/null
+++ b/scripts/changelog.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+
+# Render the release changelog between two refs as markdown on stdout.
+# Used by .github/workflows/release.yml and by .LOCAL/test-changelog.sh, so a
+# local preview always matches what the release will publish.
+#
+# Usage: scripts/changelog.sh <from-ref> <to-ref>
+
+set -euo pipefail
+
+FROM_REF="${1:?usage: changelog.sh <from-ref> <to-ref>}"
+TO_REF="${2:?usage: changelog.sh <from-ref> <to-ref>}"
+
+COMMITS=$(git log "$FROM_REF".."$TO_REF" --pretty=format:"%s|%h" --no-merges)
+
+if [ -z "$COMMITS" ]; then
+ echo "_No changes._"
+ exit 0
+fi
+
+# `npm version` puts a bump commit whose subject is the bare version number on
+# top of the tag. Drop it only when it is actually there — a hand-made tag has
+# a real commit in that position.
+NEWEST=$(echo "$COMMITS" | head -n 1 | cut -d'|' -f1)
+if [[ "$NEWEST" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ COMMITS=$(echo "$COMMITS" | tail -n +2)
+ if [ -z "$COMMITS" ]; then
+ echo "_No changes._"
+ exit 0
+ fi
+fi
+
+# Types that describe internal work only. They stay in the git history but are
+# not part of what a release note tells users.
+INTERNAL_TYPES="refactor|ci|style|test|build"
+KNOWN_TYPES="feat|fix|perf|docs|chore|$INTERNAL_TYPES"
+
+render() {
+ local heading="$1" body="$2"
+ if [ -n "$body" ]; then
+ printf '### %s\n\n%s\n\n' "$heading" "$body"
+ fi
+}
+
+section() {
+ render "$1" "$(echo "$COMMITS" | grep -E "$2" | sed 's/|/ /;s/^/- /' || true)"
+}
+
+# Breaking changes are marked with a `!` before the colon (feat!:, chore(x)!:).
+# Listed first and again under their own type, so an upgrade note is never
+# buried in a long list.
+section "⚠️ Breaking Changes" "^[a-z]+(\([^)]*\))?!:"
+section "✨ Features" "^feat(\([^)]*\))?!?:"
+section "🐛 Bug Fixes" "^fix(\([^)]*\))?!?:"
+section "⚡ Performance" "^perf(\([^)]*\))?!?:"
+section "📝 Documentation" "^docs(\([^)]*\))?!?:"
+section "🔧 Chores" "^chore(\([^)]*\))?!?:"
+
+# Anything that follows no convention at all. Internal types are matched here
+# as well and thrown away with it, so they drop out of the changelog entirely.
+render "🔀 Other Changes" \
+ "$(echo "$COMMITS" \
+ | grep -vE "^($KNOWN_TYPES)(\([^)]*\))?!?:" \
+ | sed 's/|/ /;s/^/- /' || true)"
diff --git a/scripts/i18n-checks.ts b/scripts/i18n-checks.ts
index 1300574..c4c0d2b 100644
--- a/scripts/i18n-checks.ts
+++ b/scripts/i18n-checks.ts
@@ -9,11 +9,18 @@
* 3. Reports keys that are never used
* 4. Reports keys that are used in code but missing in de.json
* 5. Checks if en.json and it.json are synchronized with de.json
+ * 6. Validates the message values themselves: ICU syntax, placeholder names
+ * against de.json, and empty strings
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
+import {
+ parse,
+ TYPE,
+ type MessageFormatElement,
+} from "@formatjs/icu-messageformat-parser";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -74,6 +81,125 @@ function getAvailableLocales(): string[] {
.sort();
}
+/**
+ * Flatten a locale file to dot-notation key -> string value
+ */
+function getTranslationValues(locale: string): Map<string, string> {
+ const messagesPath = path.join(rootDir, "messages", `${locale}.json`);
+ const messages = JSON.parse(fs.readFileSync(messagesPath, "utf-8"));
+ const values = new Map<string, string>();
+
+ const walk = (obj: Record<string, unknown>, prefix = "") => {
+ for (const [key, value] of Object.entries(obj)) {
+ const fullKey = prefix ? `${prefix}.${key}` : key;
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ walk(value as Record<string, unknown>, fullKey);
+ } else if (typeof value === "string") {
+ values.set(fullKey, value);
+ }
+ }
+ };
+
+ walk(messages);
+ return values;
+}
+
+/**
+ * Collect every placeholder name an ICU message references, including the ones
+ * nested inside plural/select branches and rich-text tags.
+ */
+function collectPlaceholders(
+ elements: MessageFormatElement[],
+ found = new Set<string>(),
+): Set<string> {
+ for (const el of elements) {
+ switch (el.type) {
+ case TYPE.argument:
+ case TYPE.number:
+ case TYPE.date:
+ case TYPE.time:
+ found.add(el.value);
+ break;
+ case TYPE.select:
+ case TYPE.plural:
+ found.add(el.value);
+ for (const option of Object.values(el.options)) {
+ collectPlaceholders(option.value, found);
+ }
+ break;
+ case TYPE.tag:
+ found.add(el.value);
+ collectPlaceholders(el.children, found);
+ break;
+ }
+ }
+
+ return found;
+}
+
+type ValueIssue = { key: string; problem: string };
+
+/**
+ * Validate message values across all locales. Key presence is checked
+ * elsewhere; this catches the failures that only surface when a message is
+ * actually rendered.
+ */
+function checkMessageValues(): { [locale: string]: ValueIssue[] } {
+ const locales = getAvailableLocales();
+ const deValues = getTranslationValues("de");
+
+ // de.json is the source of truth for placeholder names, so parse it first.
+ const dePlaceholders = new Map<string, Set<string>>();
+ for (const [key, value] of deValues) {
+ try {
+ dePlaceholders.set(key, collectPlaceholders(parse(value)));
+ } catch {
+ // Reported as a de.json ICU error in the loop below.
+ }
+ }
+
+ const results: { [locale: string]: ValueIssue[] } = {};
+
+ for (const locale of locales) {
+ const issues: ValueIssue[] = [];
+ const values = locale === "de" ? deValues : getTranslationValues(locale);
+
+ for (const [key, value] of values) {
+ if (value.trim() === "") {
+ issues.push({ key, problem: "empty string" });
+ continue;
+ }
+
+ let placeholders: Set<string>;
+ try {
+ placeholders = collectPlaceholders(parse(value));
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : String(error);
+ issues.push({ key, problem: `invalid ICU syntax (${message})` });
+ continue;
+ }
+
+ const expected = dePlaceholders.get(key);
+ if (!expected || locale === "de") continue;
+
+ const missing = [...expected].filter((p) => !placeholders.has(p));
+ const unexpected = [...placeholders].filter((p) => !expected.has(p));
+ if (missing.length > 0 || unexpected.length > 0) {
+ const parts: string[] = [];
+ if (missing.length > 0) parts.push(`missing {${missing.join("}, {")}}`);
+ if (unexpected.length > 0)
+ parts.push(`unknown {${unexpected.join("}, {")}}`);
+ issues.push({ key, problem: `placeholder mismatch: ${parts.join(", ")}` });
+ }
+ }
+
+ results[locale] = issues;
+ }
+
+ return results;
+}
+
/**
* Recursively find all files with given extensions in a directory
*/
@@ -582,6 +708,34 @@ function main() {
}
}
+ // 4. Validate the message values themselves
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.log("4️⃣ MESSAGE VALUES (ICU syntax, placeholders, empty strings)");
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
+
+ const valueResults = checkMessageValues();
+ const totalValueIssues = Object.values(valueResults).reduce(
+ (sum, issues) => sum + issues.length,
+ 0,
+ );
+
+ if (totalValueIssues === 0) {
+ console.log("✅ All message values are valid!\n");
+ } else {
+ hasIssues = true;
+
+ for (const locale of allLocales) {
+ const issues = valueResults[locale];
+ if (issues.length === 0) continue;
+
+ console.log(`❌ ${locale}.json (${issues.length} issues):`);
+ for (const { key, problem } of issues) {
+ console.log(` - ${key}: ${problem}`);
+ }
+ console.log();
+ }
+ }
+
// Summary
console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.log("📊 SUMMARY");
@@ -598,7 +752,8 @@ function main() {
unusedKeys.length +
phantomKeys.length +
missingKeys.length +
- totalSyncIssuesInSummary;
+ totalSyncIssuesInSummary +
+ totalValueIssues;
const healthScore =
totalIssues === 0 ? 100 : Math.max(0, 100 - totalIssues * 2);
const healthIcon =
@@ -640,6 +795,14 @@ function main() {
}
console.log();
+ console.log("🔤 Message Values:");
+ for (const locale of allLocales) {
+ const issues = valueResults[locale].length;
+ const status = issues === 0 ? "✅ Valid" : `❌ ${issues} issues`;
+ console.log(` ${locale}.json: ${status}`);
+ }
+ console.log();
+
if (!hasIssues) {
console.log("✅ All checks passed!");
} else {
diff --git a/scripts/migrate.mjs b/scripts/migrate.mjs
index d7a710b..edb3d4d 100644
--- a/scripts/migrate.mjs
+++ b/scripts/migrate.mjs
@@ -19,6 +19,9 @@ import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import { resolveDatabasePath } from "../lib/db/db-path.mjs";
+// Match `next dev`, which reads .env; the Docker image ships none. Existing env vars win.
+if (fs.existsSync(".env")) process.loadEnvFile(".env");
+
const dbPath = resolveDatabasePath();
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
@@ -28,7 +31,7 @@ try {
migrate(drizzle(sqlite), {
migrationsFolder: path.join(process.cwd(), "drizzle"),
});
- console.log(`[Migrate] Schema is up to date: ${dbPath}`);
+ console.log(`[Migrate] Schema is up to date: ${path.resolve(dbPath)}`);
} finally {
sqlite.close();
}