"use client"; import { useState } from "react"; import type { TFunction } from "i18next"; import { useTranslation } from "react-i18next"; import { Card, CardContent } from "@kandev/ui/card"; import { Button } from "@kandev/ui/button"; import { Badge } from "@kandev/ui/badge"; import { Spinner } from "@kandev/ui/spinner"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@kandev/ui/table"; import { IconDownload, IconTrash, IconArchive, IconRotateClockwise } from "@tabler/icons-react"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { useIsAdmin } from "@/hooks/domains/auth/use-is-admin"; import { useBackups } from "@/hooks/domains/system/use-backups"; import { buildBackupDownloadUrl, createBackup, deleteBackup } from "@/lib/api/domains/system-api"; import { formatDateTime } from "@/lib/i18n/formats"; import { formatBytes } from "@/lib/utils/format-bytes"; import { JobProgressIndicator } from "./job-progress-indicator"; import { RestoreDialog } from "./restore-dialog"; import type { SnapshotInfo, SnapshotKind } from "@/lib/types/system"; import { SettingsCardHeader } from "@/components/settings/settings-card-header"; import { SettingsErrorText, SettingsFieldDescription, } from "@/components/settings/settings-typography"; import { settingsActionClassName } from "@/components/settings/settings-control"; const BACKUP_CREATE_TIMEOUT_MS = 15_000; const BACKUP_CREATE_POLL_MS = 250; /** * How many snapshots the backend keeps. Only referenced by the help text, but * it travels as a `count` so the sentence inflects in every locale rather than * hardcoding the English plural. */ const BACKUP_RETENTION_COUNT = 2; const BACKUP_ROW_ACTION_CLASS_NAME = "h-6 w-6 cursor-pointer p-0 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"; function formatTimestamp(iso: string): string { if (!iso) return "-"; const d = new Date(iso); if (Number.isNaN(d.getTime())) return iso; return formatDateTime(d); } /** `kind` is the wire enum; only its badge label is copy. */ const KIND_LABEL_KEYS: Record = { auto: "system:backupsKindAuto", manual: "system:backupsKindManual", }; function BackupRowActions({ row, onRestore, onDelete, }: { row: SnapshotInfo; onRestore: (name: string) => void; onDelete: (name: string) => void; }) { const { t } = useTranslation(); const downloadLabel = t("system:backupsDownloadLabel", { name: row.name }); const restoreLabel = t("system:backupsRestoreLabel", { name: row.name }); const deleteLabel = t("system:backupsDeleteLabel", { name: row.name }); const downloadTooltip = t("task:download"); const restoreTooltip = t("task:restore"); const deleteTooltip = t("task:delete"); return (
{downloadTooltip} {restoreTooltip} {deleteTooltip}
); } function BackupRow({ row, isAdmin, onRestore, onDelete, }: { row: SnapshotInfo; isAdmin: boolean; onRestore: (name: string) => void; onDelete: (name: string) => void; }) { const { t } = useTranslation(); return ( {/* The snapshot filename is a value. */} {row.name} {KIND_LABEL_KEYS[row.kind] ? t(KIND_LABEL_KEYS[row.kind]) : row.kind} {formatBytes(row.size_bytes)} {formatTimestamp(row.mtime)} {/* The whole cell goes, not just its contents: the Actions header is conditional too, and an empty fifth cell would leave the table with four headers and five cells: an unlabeled column for assistive technology and dead width on a phone. */} {isAdmin && ( )} ); } function BackupsList({ items, isAdmin, onRestore, onDelete, }: { items: SnapshotInfo[]; isAdmin: boolean; onRestore: (name: string) => void; onDelete: (name: string) => void; }) { const { t } = useTranslation(); return ( {t("system:backupsColumnName")} {t("system:backupsColumnKind")} {t("system:backupsColumnSize")} {t("system:backupsColumnCreated")} {isAdmin && ( {t("system:backupsColumnActions")} )} {items.map((row) => ( ))}
); } function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function waitForCreatedBackup( reload: () => Promise, previousNames: Set, t: TFunction, ): Promise { const deadline = Date.now() + BACKUP_CREATE_TIMEOUT_MS; while (Date.now() < deadline) { const items = await reload(); if (items.some((item) => item.kind === "manual" && !previousNames.has(item.name))) { return; } await sleep(BACKUP_CREATE_POLL_MS); } // This message is caught and rendered into the card's error line, so it is // display copy rather than a control-flow-only throw. throw new Error(t("system:backupsCreateTimeout", { seconds: BACKUP_CREATE_TIMEOUT_MS / 1_000 })); } export function BackupsTable() { const { t } = useTranslation(); const { backups, loaded, isLoading, reload } = useBackups(); // Creating, downloading, restoring, and deleting a snapshot are admin-only // on the backend: a snapshot is a copy of the whole multi-user database. // Members keep the read-only listing. const isAdmin = useIsAdmin(); const [creating, setCreating] = useState(false); const [restoreName, setRestoreName] = useState(null); const [error, setError] = useState(null); const onCreate = async () => { setCreating(true); setError(null); const previousNames = new Set(backups.map((backup) => backup.name)); try { await createBackup(); await waitForCreatedBackup(reload, previousNames, t); } catch (err) { setError(err instanceof Error ? err.message : t("system:backupsCreateFailed")); } finally { setCreating(false); } }; const onDelete = async (name: string) => { setError(null); try { await deleteBackup(name); await reload(); } catch (err) { setError(err instanceof Error ? err.message : t("system:backupsDeleteFailed")); } }; const items = backups; return ( {t("system:backupsTitle")} } actions={ isAdmin && ( ) } /> {t("system:backupsHelp")}{" "} {t("system:backupsRetention", { count: BACKUP_RETENTION_COUNT })} {!isAdmin && ( {t("system:backupsAdminOnly")} )} {error && {error}} {!loaded && isLoading && (
{t("system:backupsLoading")}
)} {loaded && items.length === 0 && (

{t("system:backupsEmpty")}

)} {items.length > 0 && ( setRestoreName(n)} onDelete={(n) => void onDelete(n)} /> )}
{ if (!open) setRestoreName(null); }} name={restoreName ?? ""} />
); }