Initial release v1.0.0

HealthLog — personal health-tracking PWA with weight, blood pressure,
pulse, mood tracking, medication compliance, Withings integration,
doctor report PDF export, and Dracula-themed UI.
This commit is contained in:
Marc-André Bombeck committed 2026-03-10 20:14:33 +01:00
commit 38309932f3
301 files changed
+60041

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
"use client";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { ComplianceHeatmap } from "./compliance-heatmap";
import { ComplianceLineChart } from "./compliance-line-chart";
interface DailyData {
expected: number;
taken: number;
skipped: number;
onTime?: number;
late?: number;
veryLate?: number;
}
interface ComplianceData {
dailyCompliance: Record<string, DailyData>;
}
interface Medication {
id: string;
name: string;
dose: string;
active: boolean;
}
interface ComplianceChartsProps {
medications: Medication[];
}
export function ComplianceCharts({ medications }: ComplianceChartsProps) {
const { t } = useTranslations();
const [selectedId, setSelectedId] = useState(medications[0]?.id ?? "");
const [rangePoints, setRangePoints] = useState<30 | 90 | 0>(30);
const { data, isLoading } = useQuery({
queryKey: ["compliance-chart", selectedId],
queryFn: async () => {
const res = await fetch(`/api/medications/${selectedId}/compliance`);
if (!res.ok) return null;
const json = await res.json();
return json.data as ComplianceData;
},
enabled: !!selectedId,
staleTime: 60 * 1000,
});
if (medications.length === 0) return null;
return (
<div className="bg-card border-border space-y-4 rounded-xl border p-4 md:p-6">
<div className="flex justify-end">
<Select value={selectedId} onValueChange={setSelectedId}>
<SelectTrigger className="w-full sm:w-64">
<SelectValue placeholder={t("charts.selectMedication")} />
</SelectTrigger>
<SelectContent>
{medications.map((m) => (
<SelectItem key={m.id} value={m.id}>
{m.name} ({m.dose})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{isLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !data?.dailyCompliance ? (
<div className="text-muted-foreground flex h-48 items-center justify-center rounded-lg border border-dashed text-sm">
{t("charts.noComplianceData")}
</div>
) : (
<div className="grid gap-4 lg:grid-cols-2">
<div className="min-w-0 space-y-2">
<div className="flex h-7 items-center">
<h3 className="text-muted-foreground text-sm font-medium">
{t("charts.complianceDays90")}
</h3>
</div>
<ComplianceHeatmap dailyCompliance={data.dailyCompliance} />
</div>
<div className="min-w-0 space-y-2">
<div className="flex h-7 items-center justify-between gap-2">
<h3 className="text-muted-foreground text-sm font-medium">
{t("charts.history")}
</h3>
<div className="flex items-center gap-1">
<Button
type="button"
variant={rangePoints === 30 ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setRangePoints(30)}
title={t("charts.points30Title")}
>
{t("charts.points30Label")}
</Button>
<Button
type="button"
variant={rangePoints === 90 ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setRangePoints(90)}
title={t("charts.points90Title")}
>
{t("charts.points90Label")}
</Button>
<Button
type="button"
variant={rangePoints === 0 ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setRangePoints(0)}
title={t("charts.pointsAllTitle")}
>
{t("charts.pointsAllLabel")}
</Button>
</div>
</div>
<ComplianceLineChart
dailyCompliance={data.dailyCompliance}
rangePoints={rangePoints}
onRangePointsChange={setRangePoints}
showRangeControls={false}
/>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,293 @@
"use client";
import { useState, useMemo, useEffect, useRef } from "react";
interface DailyData {
expected: number;
taken: number;
skipped: number;
onTime?: number;
late?: number;
veryLate?: number;
}
interface ComplianceHeatmapProps {
dailyCompliance: Record<string, DailyData>;
days?: number;
stretch?: boolean;
}
const CELL_SIZE = 18;
const GAP = 3;
const WEEKDAY_LABELS = ["Mo", "", "Mi", "", "Fr", "", "So"];
const MONTH_LABELS = [
"Jan",
"Feb",
"Mär",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez",
];
function getColor(data: DailyData): string {
if (data.expected === 0) return "var(--secondary)";
const taken = data.taken;
if (taken === 0) return "var(--dracula-red)";
// When timing data is available, use it for color selection
const hasTimingData =
data.onTime !== undefined ||
data.late !== undefined ||
data.veryLate !== undefined;
if (hasTimingData) {
const veryLate = data.veryLate ?? 0;
const late = data.late ?? 0;
const missed = Math.max(0, data.expected - taken - data.skipped);
// Any missed doses → red
if (missed > 0) return "var(--dracula-red)";
// Any very late → deep orange
if (veryLate > 0) return "var(--dracula-orange)";
// Any late → yellow
if (late > 0) return "var(--dracula-yellow)";
// All on time → green
return "var(--dracula-green)";
}
// Fallback: rate-based coloring (no timing data)
const rate = (taken / data.expected) * 100;
if (rate >= 100) return "var(--dracula-green)";
if (rate >= 50) return "var(--dracula-yellow)";
if (rate > 0) return "var(--dracula-orange)";
return "var(--dracula-red)";
}
function formatDateDE(dateStr: string): string {
const d = new Date(dateStr + "T00:00:00");
return `${d.getDate()}.${d.getMonth() + 1}.${d.getFullYear()}`;
}
export function ComplianceHeatmap({
dailyCompliance,
days = 90,
stretch = false,
}: ComplianceHeatmapProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const [containerWidth, setContainerWidth] = useState(0);
const [tooltip, setTooltip] = useState<{
x: number;
y: number;
text: string;
} | null>(null);
useEffect(() => {
if (!stretch) return;
const element = containerRef.current;
if (!element) return;
const updateWidth = () => {
setContainerWidth(element.clientWidth);
};
updateWidth();
const observer = new ResizeObserver(updateWidth);
observer.observe(element);
return () => {
observer.disconnect();
};
}, [stretch]);
const { cells, weeks, monthMarkers } = useMemo(() => {
const now = new Date();
const cellList: Array<{
dateKey: string;
col: number;
row: number;
color: string;
data: DailyData;
}> = [];
// Build array of dates from oldest to newest
const dates: Date[] = [];
for (let d = days - 1; d >= 0; d--) {
const date = new Date(now.getTime() - d * 24 * 60 * 60 * 1000);
dates.push(date);
}
// Start from the first date, align to Monday
const firstDate = dates[0];
const firstDow = (firstDate.getDay() + 6) % 7; // Monday = 0
let col = 0;
const markers: Array<{ col: number; label: string }> = [];
let lastMonth = -1;
for (let i = 0; i < dates.length; i++) {
const date = dates[i];
const dow = (date.getDay() + 6) % 7; // Monday = 0
const currentCol = Math.floor((i + firstDow) / 7);
const row = dow;
const dateKey = date.toISOString().slice(0, 10);
const data = dailyCompliance[dateKey] ?? {
expected: 0,
taken: 0,
skipped: 0,
};
// Track month boundaries
const month = date.getMonth();
if (month !== lastMonth) {
markers.push({ col: currentCol, label: MONTH_LABELS[month] });
lastMonth = month;
}
cellList.push({
dateKey,
col: currentCol,
row,
color: getColor(data),
data,
});
col = Math.max(col, currentCol);
}
return { cells: cellList, weeks: col + 1, monthMarkers: markers };
}, [dailyCompliance, days]);
const labelWidth = stretch ? 0 : 76;
const headerHeight = 18;
const cellSize =
stretch && containerWidth > 0
? Math.max(
8,
(containerWidth - labelWidth - Math.max(0, weeks - 1) * GAP) /
Math.max(weeks, 1),
)
: CELL_SIZE;
const step = cellSize + GAP;
const svgWidth = labelWidth + weeks * cellSize + Math.max(0, weeks - 1) * GAP;
const svgHeight = headerHeight + 7 * cellSize + 6 * GAP;
return (
<div className={`relative ${stretch ? "w-full" : ""}`} ref={containerRef}>
<div className={stretch ? "w-full" : "overflow-x-auto"}>
<svg
width={svgWidth}
height={svgHeight}
className={stretch ? "block w-full" : "block"}
onMouseLeave={() => setTooltip(null)}
>
{/* Month labels */}
{monthMarkers.map((m, i) => (
<text
key={i}
x={labelWidth + m.col * step}
y={11}
className="fill-muted-foreground"
fontSize={10}
>
{m.label}
</text>
))}
{/* Weekday labels */}
{!stretch &&
WEEKDAY_LABELS.map(
(label, i) =>
label && (
<text
key={i}
x={labelWidth - 6}
y={headerHeight + i * step + cellSize * 0.65}
textAnchor="end"
className="fill-muted-foreground"
fontSize={10}
>
{label}
</text>
),
)}
{/* Cells */}
{cells.map((cell) => (
<rect
key={cell.dateKey}
x={labelWidth + cell.col * step}
y={headerHeight + cell.row * step}
width={cellSize}
height={cellSize}
rx={2}
fill={cell.color}
className="cursor-pointer"
onMouseEnter={(e) => {
const rate =
cell.data.expected > 0
? Math.min(
100,
Math.round(
(cell.data.taken / cell.data.expected) * 100,
),
)
: 0;
const hasTimingData =
cell.data.onTime !== undefined ||
cell.data.late !== undefined ||
cell.data.veryLate !== undefined;
const timingInfo = hasTimingData
? ` | ${cell.data.onTime ?? 0} pünktlich, ${cell.data.late ?? 0} spät, ${cell.data.veryLate ?? 0} sehr spät`
: "";
setTooltip({
x: e.clientX,
y: e.clientY,
text: `${formatDateDE(cell.dateKey)}: ${cell.data.taken}/${cell.data.expected} (${rate}%)${timingInfo}`,
});
}}
onMouseLeave={() => setTooltip(null)}
/>
))}
</svg>
</div>
{/* Tooltip */}
{tooltip && (
<div
className="bg-popover text-popover-foreground border-border pointer-events-none fixed z-50 rounded-md border px-2 py-1 text-xs shadow-md"
style={{ left: tooltip.x + 10, top: tooltip.y - 30 }}
>
{tooltip.text}
</div>
)}
{/* Legend */}
<div
className="text-muted-foreground mt-2 flex flex-wrap items-center gap-3 text-xs"
style={{ marginLeft: stretch ? 0 : labelWidth }}
>
{[
{ color: "var(--dracula-green)", label: "Pünktlich" },
{ color: "var(--dracula-yellow)", label: "Spät" },
{ color: "var(--dracula-orange)", label: "Sehr spät" },
{ color: "var(--dracula-red)", label: "Verpasst" },
].map(({ color, label }) => (
<span key={label} className="flex items-center gap-1">
<div
className="h-3 w-3 rounded-sm"
style={{ backgroundColor: color }}
/>
{label}
</span>
))}
</div>
</div>
);
}
@@ -0,0 +1,147 @@
"use client";
import { useMemo, useState } from "react";
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ReferenceLine,
} from "recharts";
import { Button } from "@/components/ui/button";
import { formatDateShort } from "@/lib/format";
interface DailyData {
expected: number;
taken: number;
skipped: number;
onTime?: number;
late?: number;
veryLate?: number;
}
interface ComplianceLineChartProps {
dailyCompliance: Record<string, DailyData>;
rangePoints?: 30 | 90 | 0;
onRangePointsChange?: (value: 30 | 90 | 0) => void;
showRangeControls?: boolean;
}
const TIME_RANGES = [
{ label: "30M", points: 30, title: "Die dreissig letzten Messpunkte" },
{ label: "90M", points: 90, title: "Die neunzig letzten Messpunkte" },
{ label: "Alle", points: 0, title: "Alle verfuegbaren Messpunkte" },
] as const;
export function ComplianceLineChart({
dailyCompliance,
rangePoints,
onRangePointsChange,
showRangeControls = true,
}: ComplianceLineChartProps) {
const [internalRangePoints, setInternalRangePoints] = useState<30 | 90 | 0>(
30,
);
const activeRangePoints = rangePoints ?? internalRangePoints;
const setActiveRangePoints = onRangePointsChange ?? setInternalRangePoints;
const chartData = useMemo(() => {
const points = Object.entries(dailyCompliance)
.filter(([, data]) => data.expected > 0)
.sort(([a], [b]) => a.localeCompare(b))
.map(([dateKey, data]) => {
const date = new Date(`${dateKey}T12:00:00.000Z`);
return {
date: formatDateShort(date, true),
rate: Math.min(100, Math.round((data.taken / data.expected) * 100)),
timestamp: date.getTime(),
};
});
return activeRangePoints > 0 ? points.slice(-activeRangePoints) : points;
}, [dailyCompliance, activeRangePoints]);
return (
<div>
{showRangeControls ? (
<div className="mb-3 flex justify-end gap-1">
{TIME_RANGES.map((r) => (
<Button
key={r.label}
variant={activeRangePoints === r.points ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setActiveRangePoints(r.points)}
title={r.title}
>
{r.label}
</Button>
))}
</div>
) : null}
{chartData.length === 0 ? (
<div className="text-muted-foreground flex h-48 items-center justify-center rounded-lg border border-dashed text-sm">
Keine Daten im gewählten Zeitraum
</div>
) : (
<ResponsiveContainer width="100%" height={180}>
<LineChart data={chartData}>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--border)"
opacity={0.5}
/>
<XAxis
dataKey="date"
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
/>
<YAxis
domain={[0, 100]}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
unit="%"
/>
<Tooltip
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "0.5rem",
fontSize: "0.875rem",
}}
formatter={(value) => [`${value}%`, "Compliance"]}
/>
<ReferenceLine
y={80}
stroke="var(--dracula-green)"
strokeDasharray="5 5"
strokeOpacity={0.7}
label={{
value: "Ziel 80%",
position: "right",
fill: "var(--muted-foreground)",
fontSize: 10,
}}
/>
<Line
type="monotone"
dataKey="rate"
name="Compliance"
stroke="var(--dracula-purple)"
strokeWidth={2}
dot={{ r: 2, fill: "var(--dracula-purple)" }}
activeDot={{ r: 4 }}
connectNulls
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
);
}
+827
View File
@@ -0,0 +1,827 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ReferenceLine,
ReferenceArea,
} from "recharts";
import { Loader2 } from "lucide-react";
import { useState, useMemo, useId } from "react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { formatDateShort } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
const TIME_RANGES_KEYS = [
{
labelKey: "charts.points7Label",
points: 7,
titleKey: "charts.points7Title",
},
{
labelKey: "charts.points30Label",
points: 30,
titleKey: "charts.points30Title",
},
{
labelKey: "charts.points90Label",
points: 90,
titleKey: "charts.points90Title",
},
{
labelKey: "charts.pointsAllLabel",
points: 0,
titleKey: "charts.pointsAllTitle",
},
] as const;
interface HealthChartProps {
types: string[];
title: string;
colors?: string[];
unit?: string;
yAxisUnit?: string;
valueMode?: "raw" | "bmi";
yAxisWidth?: number;
showYAxisUnit?: boolean;
valueBands?: Array<{
min: number;
max: number;
color: string;
opacity?: number;
strokeOpacity?: number;
}>;
targetZones?: Array<{
min: number;
max: number;
color: string;
opacity?: number;
label?: string;
textColor?: string;
lineOpacity?: number;
}>;
}
interface ChartDataPoint {
date: string;
timestamp: number;
pointIndex?: number;
[key: string]: string | number | undefined;
}
interface MeasurementApiRow {
measuredAt: string;
value: number;
}
interface VisibleTargetZone {
key: string;
low: number;
high: number;
topPct: number;
heightPct: number;
color: string;
opacity: number;
label: string | undefined;
textColor: string | undefined;
lineOpacity: number;
}
const BASE_TYPE_LABEL_KEYS: Record<string, string> = {
WEIGHT: "charts.weight",
BLOOD_PRESSURE_SYS: "charts.systolic",
BLOOD_PRESSURE_DIA: "charts.diastolic",
PULSE: "charts.pulse",
BODY_FAT: "charts.bodyFat",
SLEEP_DURATION: "charts.sleep",
ACTIVITY_STEPS: "charts.steps",
};
function getTypeLabel(
type: string,
valueMode: "raw" | "bmi",
t: (key: string) => string,
): string {
if (type === "WEIGHT" && valueMode === "bmi") {
return "BMI";
}
const key = BASE_TYPE_LABEL_KEYS[type];
return key ? t(key) : type;
}
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
function toBerlinDayKey(value: string): string {
const parts = BERLIN_DAY_FORMATTER.formatToParts(new Date(value));
const year = parts.find((part) => part.type === "year")?.value;
const month = parts.find((part) => part.type === "month")?.value;
const day = parts.find((part) => part.type === "day")?.value;
if (!year || !month || !day) {
throw new Error("Could not derive day key for chart");
}
return `${year}-${month}-${day}`;
}
function dayKeyToTimestamp(dayKey: string): number {
const [year, month, day] = dayKey.split("-").map(Number);
return Date.UTC(year, month - 1, day, 12, 0, 0);
}
function movingAverageByPoints(
data: Array<{ date: Date; value: number }>,
windowSize: number,
): Array<{ date: Date; value: number }> {
if (data.length === 0) return [];
const sorted = [...data].sort((a, b) => a.date.getTime() - b.date.getTime());
return sorted.map((point, index) => {
const start = Math.max(0, index - windowSize + 1);
const window = sorted.slice(start, index + 1);
const avg =
window.reduce((sum, item) => sum + item.value, 0) / window.length;
return {
date: point.date,
value: Math.round(avg * 100) / 100,
};
});
}
function buildTrendSeriesByTime(data: Array<{ date: Date; value: number }>): {
points: Array<{ date: Date; value: number }>;
slopePerDay: number;
} | null {
if (data.length < 2) return null;
const sorted = [...data].sort((a, b) => a.date.getTime() - b.date.getTime());
const startTime = sorted[0].date.getTime();
const points = sorted.map((p) => ({
x: (p.date.getTime() - startTime) / 86400000,
y: p.value,
}));
const n = points.length;
const sumX = points.reduce((s, p) => s + p.x, 0);
const sumY = points.reduce((s, p) => s + p.y, 0);
const sumXY = points.reduce((s, p) => s + p.x * p.y, 0);
const sumXX = points.reduce((s, p) => s + p.x * p.x, 0);
const denominator = n * sumXX - sumX * sumX;
if (denominator === 0) return null;
const slope = (n * sumXY - sumX * sumY) / denominator;
const intercept = (sumY - slope * sumX) / n;
return {
points: sorted.map((p) => ({
date: p.date,
value:
Math.round(
(intercept + slope * ((p.date.getTime() - startTime) / 86400000)) *
100,
) / 100,
})),
slopePerDay: slope,
};
}
export function HealthChart({
types,
title,
colors = ["#bd93f9", "#ff79c6", "#8be9fd"],
unit,
yAxisUnit,
valueMode = "raw",
yAxisWidth = 76,
showYAxisUnit = true,
valueBands,
targetZones,
}: HealthChartProps) {
const { isAuthenticated, user } = useAuth();
const { t } = useTranslations();
const [rangePoints, setRangePoints] = useState(30);
const [showMA, setShowMA] = useState(false);
const [showTrend, setShowTrend] = useState(false);
const [showBands, setShowBands] = useState(false);
const maToggleId = useId();
const trendToggleId = useId();
const bandsToggleId = useId();
const bmiDivisor =
valueMode === "bmi" && user?.heightCm ? (user.heightCm / 100) ** 2 : null;
const { data, isLoading } = useQuery({
queryKey: [
"chart-data",
types.join(","),
valueMode,
bmiDivisor ?? "no-bmi",
],
queryFn: async () => {
const params = new URLSearchParams();
params.set("sortBy", "measuredAt");
params.set("sortDir", "asc");
const dailyAggregates = new Map<
string,
{
timestamp: number;
values: Record<string, { sum: number; count: number }>;
}
>();
async function fetchAllMeasurementsByType(type: string) {
const pageSize = 500;
let offset = 0;
while (true) {
const typeParams = new URLSearchParams(params);
typeParams.set("type", type);
typeParams.set("limit", String(pageSize));
typeParams.set("offset", String(offset));
const res = await fetch(`/api/measurements?${typeParams}`);
if (!res.ok) break;
const json = await res.json();
const page = (json.data?.measurements ?? []) as MeasurementApiRow[];
const total = Number(json.data?.meta?.total ?? page.length);
for (const measurement of page) {
const rawValue = measurement.value;
const value =
valueMode === "bmi"
? bmiDivisor
? rawValue / bmiDivisor
: null
: rawValue;
if (value == null || !Number.isFinite(value)) {
continue;
}
const dayKey = toBerlinDayKey(measurement.measuredAt);
const bucket = dailyAggregates.get(dayKey) ?? {
timestamp: dayKeyToTimestamp(dayKey),
values: {},
};
const current = bucket.values[type] ?? { sum: 0, count: 0 };
current.sum += value;
current.count += 1;
bucket.values[type] = current;
dailyAggregates.set(dayKey, bucket);
}
offset += page.length;
if (page.length === 0 || offset >= total || page.length < pageSize) {
break;
}
}
}
await Promise.all(types.map(fetchAllMeasurementsByType));
const allData: ChartDataPoint[] = Array.from(dailyAggregates.values())
.map((bucket) => {
const point: ChartDataPoint = {
date: formatDateShort(new Date(bucket.timestamp)),
timestamp: bucket.timestamp,
};
for (const [type, stats] of Object.entries(bucket.values)) {
point[type] = stats.sum / stats.count;
}
return point;
})
.sort((a, b) => a.timestamp - b.timestamp);
return allData;
},
enabled: isAuthenticated,
});
const chartData = useMemo(() => {
if (!data?.length) return data;
const visibleData = rangePoints > 0 ? data.slice(-rangePoints) : [...data];
const enriched: ChartDataPoint[] = visibleData.map((d, index) => ({
...d,
pointIndex: index,
}));
if (showMA) {
for (const type of types) {
const typeData = enriched
.filter((d) => d[type] !== undefined)
.map((d) => ({
date: new Date(d.timestamp),
value: d[type] as number,
}));
if (typeData.length >= 2) {
const ma = movingAverageByPoints(typeData, 7);
for (const point of ma) {
const pointTimestamp = point.date.getTime();
const existing = enriched.find(
(d) => d.timestamp === pointTimestamp,
);
if (existing) {
existing[`${type}_ma`] = point.value;
}
}
}
}
}
if (showTrend) {
for (const type of types) {
const typeData = enriched
.filter((d) => d[type] !== undefined)
.map((d) => ({
date: new Date(d.timestamp),
value: d[type] as number,
}));
if (typeData.length >= 2) {
const trend = buildTrendSeriesByTime(typeData);
if (trend) {
for (const point of trend.points) {
const pointTimestamp = point.date.getTime();
const existing = enriched.find(
(d) => d.timestamp === pointTimestamp,
);
if (existing) {
existing[`${type}_trend`] = point.value;
}
}
}
}
}
}
return enriched;
}, [data, rangePoints, showMA, showTrend, types]);
const yDomain = useMemo<[number, number] | undefined>(() => {
if (!chartData?.length) return undefined;
const keys = [...types];
if (showMA) keys.push(...types.map((type) => `${type}_ma`));
if (showTrend) keys.push(...types.map((type) => `${type}_trend`));
const values = chartData
.flatMap((point) => keys.map((key) => point[key]))
.filter((value): value is number => typeof value === "number")
.filter((value) => Number.isFinite(value));
if (!values.length) return undefined;
const min = Math.min(...values);
const max = Math.max(...values);
if (min === max) {
const delta = Math.max(Math.abs(min) * 0.05, 1);
return [min - delta, max + delta * 1.35];
}
const span = max - min;
const paddingBottom = Math.max(span * 0.08, 0.5);
const paddingTop = Math.max(span * 0.16, 1);
return [min - paddingBottom, max + paddingTop];
}, [chartData, showMA, showTrend, types]);
const visibleBands = useMemo(() => {
if (!showBands || !valueBands?.length || !yDomain) return [];
const [domainMin, domainMax] = yDomain;
const span = domainMax - domainMin;
if (!Number.isFinite(span) || span <= 0) return [];
return valueBands
.map((band, index) => {
const low = Math.max(Math.min(band.min, band.max), domainMin);
const high = Math.min(Math.max(band.min, band.max), domainMax);
if (high <= low) return null;
const topPct = ((domainMax - high) / span) * 100;
const heightPct = ((high - low) / span) * 100;
return {
key: `${band.min}-${band.max}-${index}`,
topPct,
heightPct,
color: band.color,
opacity: band.opacity ?? 0.2,
strokeOpacity: band.strokeOpacity ?? 0.35,
};
})
.filter(
(
entry,
): entry is {
key: string;
topPct: number;
heightPct: number;
color: string;
opacity: number;
strokeOpacity: number;
} => entry !== null && entry.heightPct > 0,
);
}, [showBands, valueBands, yDomain]);
const visibleTargetZones = useMemo<VisibleTargetZone[]>(() => {
if (!showBands || !targetZones?.length || !yDomain) return [];
const [domainMin, domainMax] = yDomain;
const span = domainMax - domainMin;
if (!Number.isFinite(span) || span <= 0) return [];
const zones: Array<{
key: string;
low: number;
high: number;
topPct: number;
heightPct: number;
color: string;
opacity: number;
label: string | undefined;
textColor: string | undefined;
lineOpacity: number;
}> = [];
for (const [index, zone] of targetZones.entries()) {
const low = Math.max(Math.min(zone.min, zone.max), domainMin);
const high = Math.min(Math.max(zone.min, zone.max), domainMax);
if (high <= low) continue;
const topPct = ((domainMax - high) / span) * 100;
const heightPct = ((high - low) / span) * 100;
zones.push({
key: `${zone.min}-${zone.max}-${index}`,
low,
high,
topPct,
heightPct,
color: zone.color,
opacity: zone.opacity ?? 0.3,
label: zone.label ?? undefined,
textColor: zone.textColor ?? undefined,
lineOpacity: zone.lineOpacity ?? 0.42,
});
}
return zones;
}, [showBands, targetZones, yDomain]);
const formatAxisValue = (value: number) =>
new Intl.NumberFormat("de-DE", {
maximumFractionDigits: 0,
}).format(value);
const formatTooltipValue = (value: number) =>
new Intl.NumberFormat("de-DE", {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(value);
const trendInfo = useMemo(() => {
if (!showTrend || !chartData?.length) return [];
const formatSigned = (value: number) => {
const formatted = new Intl.NumberFormat("de-DE", {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(Math.abs(value));
return `${value > 0 ? "+" : value < 0 ? "-" : ""}${formatted}`;
};
return types
.map((type) => {
const series = chartData.filter(
(point) =>
typeof point[type] === "number" &&
typeof point[`${type}_trend`] === "number",
);
if (series.length < 2) return null;
const first = series[0];
const last = series[series.length - 1];
const days = (last.timestamp - first.timestamp) / 86400000;
if (!Number.isFinite(days) || days <= 0) return null;
const firstTrend = first[`${type}_trend`] as number;
const lastTrend = last[`${type}_trend`] as number;
const weeklyDelta = ((lastTrend - firstTrend) / days) * 7;
const base = first[type] as number;
const weeklyPct =
Math.abs(base) > Number.EPSILON
? (weeklyDelta / Math.abs(base)) * 100
: null;
const unitSuffix = unit ? ` ${unit}` : "";
return `${getTypeLabel(type, valueMode, t)}: ${formatSigned(
weeklyDelta,
)}${unitSuffix}${t("charts.perWeek")}${
weeklyPct != null
? ` (${formatSigned(weeklyPct)} %${t("charts.perWeek")})`
: ""
}`;
})
.filter((entry): entry is string => entry !== null);
}, [chartData, showTrend, types, unit, valueMode, t]);
if (!isLoading && !data?.length) return null;
const maxPointIndex = Math.max(0, (chartData?.length ?? 1) - 1);
const showContextDetails = showMA || showTrend || showBands;
return (
<div className="bg-card border-border rounded-xl border p-4 md:p-6">
<div className="mb-4 flex items-center justify-between">
<h3 className="text-sm font-semibold">{title}</h3>
<div className="flex flex-wrap justify-end gap-1">
{TIME_RANGES_KEYS.map((r) => (
<Button
key={r.labelKey}
variant={rangePoints === r.points ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setRangePoints(r.points)}
title={t(r.titleKey)}
>
{t(r.labelKey)}
</Button>
))}
</div>
</div>
<div className="text-muted-foreground mb-3 flex items-center gap-4 text-xs">
<div className="flex items-center gap-1.5">
<Switch
id={maToggleId}
checked={showMA}
onCheckedChange={setShowMA}
className="scale-75"
/>
<Label htmlFor={maToggleId} className="cursor-pointer text-xs">
{t("charts.movingAverage7d")}
</Label>
</div>
<div className="flex items-center gap-1.5">
<Switch
id={trendToggleId}
checked={showTrend}
onCheckedChange={setShowTrend}
className="scale-75"
/>
<Label htmlFor={trendToggleId} className="cursor-pointer text-xs">
{t("charts.trend")}
</Label>
</div>
{valueBands?.length || targetZones?.length ? (
<div className="flex items-center gap-1.5">
<Switch
id={bandsToggleId}
checked={showBands}
onCheckedChange={setShowBands}
className="scale-75"
/>
<Label htmlFor={bandsToggleId} className="cursor-pointer text-xs">
{t("charts.targetRanges")}
</Label>
</div>
) : null}
</div>
{showTrend && trendInfo.length > 0 ? (
<div className="text-muted-foreground mb-3 flex flex-wrap gap-3 text-xs">
{trendInfo.map((info) => (
<span key={info}>{info}</span>
))}
</div>
) : null}
{isLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !chartData?.length ? null : (
<div className="relative h-[240px]">
{visibleBands.length > 0 ? (
<div
className="pointer-events-none absolute"
style={{
left: `${8 + yAxisWidth}px`,
right: "18px",
top: "10px",
bottom: "32px",
zIndex: 0,
}}
>
{visibleBands.map((band) => (
<div
key={band.key}
className="absolute right-0 left-0"
style={{
top: `${band.topPct}%`,
height: `${band.heightPct}%`,
backgroundColor: band.color,
opacity: band.opacity,
borderTop: `1px solid ${band.color}`,
borderBottom: `1px solid ${band.color}`,
}}
/>
))}
</div>
) : null}
<div className="relative z-10 h-full">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={chartData}
margin={{ top: 10, right: 8, bottom: 8, left: 8 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--border)"
opacity={0.5}
/>
<XAxis
type="number"
dataKey="pointIndex"
domain={[0, maxPointIndex]}
allowDecimals={false}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
tickFormatter={(value) =>
formatDateShort(
new Date(
chartData?.[Math.round(value)]?.timestamp ?? Date.now(),
),
true,
)
}
interval="preserveStartEnd"
padding={{ left: 10, right: 10 }}
tickMargin={10}
/>
<YAxis
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
width={yAxisWidth}
tickMargin={10}
domain={yDomain}
tickFormatter={(value) =>
typeof value === "number"
? formatAxisValue(Math.round(value))
: String(value)
}
unit={
showYAxisUnit && (yAxisUnit ?? unit)
? ` ${yAxisUnit ?? unit}`
: undefined
}
/>
{visibleTargetZones.map((zone) => (
<ReferenceArea
key={`${zone.key}-fill`}
x1={0}
x2={maxPointIndex}
y1={zone.low}
y2={zone.high}
fill={zone.color}
fillOpacity={zone.opacity}
strokeOpacity={0}
ifOverflow="discard"
/>
))}
{visibleTargetZones.map((zone) => (
<ReferenceLine
key={`${zone.key}-low`}
y={zone.low}
stroke={zone.color}
strokeDasharray="6 4"
strokeWidth={1.75}
strokeOpacity={zone.lineOpacity}
/>
))}
{visibleTargetZones.map((zone) => (
<ReferenceLine
key={`${zone.key}-high`}
y={zone.high}
stroke={zone.color}
strokeDasharray="6 4"
strokeWidth={1.75}
strokeOpacity={zone.lineOpacity}
label={
zone.label
? {
value: zone.label,
position: "right",
fill: zone.textColor ?? zone.color,
fontSize: 10,
}
: undefined
}
/>
))}
<Tooltip
filterNull={false}
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "0.5rem",
fontSize: "0.875rem",
}}
formatter={(value) =>
typeof value === "number"
? `${formatTooltipValue(value)}${unit ? ` ${unit}` : ""}`
: value
}
labelFormatter={(_label, payload) =>
payload?.[0]?.payload?.timestamp
? formatDateShort(
new Date(payload[0].payload.timestamp),
true,
)
: ""
}
/>
{showContextDetails && (
<Legend
wrapperStyle={{
fontSize: "0.875rem",
fontFamily: "inherit",
fontWeight: "normal",
}}
/>
)}
{types.map((type, i) => (
<Line
key={type}
type="monotone"
dataKey={type}
name={getTypeLabel(type, valueMode, t)}
stroke={colors[i % colors.length]}
strokeWidth={2}
dot={{ r: 3, fill: colors[i % colors.length] }}
activeDot={{ r: 5 }}
connectNulls
/>
))}
{showMA &&
types.map((type, i) => (
<Line
key={`${type}_ma`}
type="monotone"
dataKey={`${type}_ma`}
name={`${getTypeLabel(type, valueMode, t)} (${t("charts.movingAverage7d")})`}
stroke={colors[i % colors.length]}
strokeWidth={1.5}
strokeDasharray="5 5"
strokeOpacity={0.7}
dot={false}
connectNulls
/>
))}
{showTrend &&
types.map((type) => (
<Line
key={`${type}_trend`}
type="linear"
dataKey={`${type}_trend`}
name={`${getTypeLabel(type, valueMode, t)} (${t("charts.trend")})`}
stroke="var(--muted-foreground)"
strokeWidth={1}
strokeDasharray="8 4"
dot={false}
connectNulls
/>
))}
</LineChart>
</ResponsiveContainer>
</div>
</div>
)}
</div>
);
}
+439
View File
@@ -0,0 +1,439 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ReferenceArea,
} from "recharts";
import { Loader2 } from "lucide-react";
import { useState, useMemo, useId } from "react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import {
Card,
CardHeader,
CardTitle,
CardContent,
} from "@/components/ui/card";
import { formatDateShort } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import type { DataSummary } from "@/lib/analytics/trends";
// --- Types ---
interface MoodAnalyticsData {
entries: Array<{ date: string; score: number; samples: number }>;
summary: DataSummary;
}
interface ChartDataPoint {
date: string;
timestamp: number;
pointIndex: number;
score: number;
ma?: number;
trend?: number;
}
interface MoodChartProps {
title?: string;
}
// --- Constants ---
const TIME_RANGES_KEYS = [
{ labelKey: "charts.points7Label", points: 7, titleKey: "charts.points7Title" },
{ labelKey: "charts.points30Label", points: 30, titleKey: "charts.points30Title" },
{ labelKey: "charts.points90Label", points: 90, titleKey: "charts.points90Title" },
{ labelKey: "charts.pointsAllLabel", points: 0, titleKey: "charts.pointsAllTitle" },
] as const;
const MOOD_LABELS: Record<number, string> = {
1: "Lausig",
2: "Schlecht",
3: "Okay",
4: "Gut",
5: "Super",
};
const VALUE_BANDS = [
{ min: 1, max: 2, color: "#ff5555", opacity: 0.16 },
{ min: 2, max: 3, color: "#ffb86c", opacity: 0.18 },
{ min: 3, max: 5, color: "#50fa7b", opacity: 0.2 },
] as const;
const COLOR_MAIN = "#d6acff";
const COLOR_MA = "#ff79c6";
const COLOR_TREND = "#8be9fd";
// --- Helpers ---
function dayKeyToTimestamp(dayKey: string): number {
const [year, month, day] = dayKey.split("-").map(Number);
return Date.UTC(year, month - 1, day, 12, 0, 0);
}
function movingAverageByPoints(
data: Array<{ date: Date; value: number }>,
windowSize: number,
): Array<{ date: Date; value: number }> {
if (data.length === 0) return [];
const sorted = [...data].sort((a, b) => a.date.getTime() - b.date.getTime());
return sorted.map((point, index) => {
const start = Math.max(0, index - windowSize + 1);
const window = sorted.slice(start, index + 1);
const avg =
window.reduce((sum, item) => sum + item.value, 0) / window.length;
return {
date: point.date,
value: Math.round(avg * 100) / 100,
};
});
}
function buildTrendLine(
data: Array<{ date: Date; value: number }>,
): { points: Array<{ date: Date; value: number }>; slopePerDay: number } | null {
if (data.length < 2) return null;
const sorted = [...data].sort((a, b) => a.date.getTime() - b.date.getTime());
const startTime = sorted[0].date.getTime();
const points = sorted.map((p) => ({
x: (p.date.getTime() - startTime) / 86400000,
y: p.value,
}));
const n = points.length;
const sumX = points.reduce((s, p) => s + p.x, 0);
const sumY = points.reduce((s, p) => s + p.y, 0);
const sumXY = points.reduce((s, p) => s + p.x * p.y, 0);
const sumXX = points.reduce((s, p) => s + p.x * p.x, 0);
const denominator = n * sumXX - sumX * sumX;
if (denominator === 0) return null;
const slope = (n * sumXY - sumX * sumY) / denominator;
const intercept = (sumY - slope * sumX) / n;
return {
points: sorted.map((p) => ({
date: p.date,
value:
Math.round(
(intercept + slope * ((p.date.getTime() - startTime) / 86400000)) *
100,
) / 100,
})),
slopePerDay: slope,
};
}
// --- Component ---
export function MoodChart({ title }: MoodChartProps) {
const { isAuthenticated } = useAuth();
const { t } = useTranslations();
const [rangePoints, setRangePoints] = useState(30);
const [showMA, setShowMA] = useState(false);
const [showTrend, setShowTrend] = useState(false);
const [showBands, setShowBands] = useState(false);
const maToggleId = useId();
const trendToggleId = useId();
const bandsToggleId = useId();
const displayTitle = title ?? t("charts.mood");
const { data, isLoading } = useQuery({
queryKey: ["mood-chart-data"],
queryFn: async (): Promise<MoodAnalyticsData> => {
const res = await fetch("/api/mood/analytics");
if (!res.ok) throw new Error("Failed to fetch mood analytics");
const json = await res.json();
return json.data as MoodAnalyticsData;
},
enabled: isAuthenticated,
});
const chartData = useMemo((): ChartDataPoint[] | undefined => {
if (!data?.entries?.length) return undefined;
const allPoints: ChartDataPoint[] = data.entries
.map((entry) => ({
date: formatDateShort(new Date(dayKeyToTimestamp(entry.date))),
timestamp: dayKeyToTimestamp(entry.date),
pointIndex: 0,
score: entry.score,
}))
.sort((a, b) => a.timestamp - b.timestamp);
const visibleData =
rangePoints > 0 ? allPoints.slice(-rangePoints) : allPoints;
const enriched: ChartDataPoint[] = visibleData.map((d, index) => ({
...d,
pointIndex: index,
}));
if (showMA) {
const scoreData = enriched.map((d) => ({
date: new Date(d.timestamp),
value: d.score,
}));
if (scoreData.length >= 2) {
const ma = movingAverageByPoints(scoreData, 7);
for (const point of ma) {
const pointTimestamp = point.date.getTime();
const existing = enriched.find(
(d) => d.timestamp === pointTimestamp,
);
if (existing) {
existing.ma = point.value;
}
}
}
}
if (showTrend) {
const scoreData = enriched.map((d) => ({
date: new Date(d.timestamp),
value: d.score,
}));
if (scoreData.length >= 2) {
const trend = buildTrendLine(scoreData);
if (trend) {
for (const point of trend.points) {
const pointTimestamp = point.date.getTime();
const existing = enriched.find(
(d) => d.timestamp === pointTimestamp,
);
if (existing) {
existing.trend = point.value;
}
}
}
}
}
return enriched;
}, [data, rangePoints, showMA, showTrend]);
const maxPointIndex = Math.max(0, (chartData?.length ?? 1) - 1);
const formatMoodTick = (value: number): string => {
return MOOD_LABELS[value] ?? String(value);
};
const formatTooltipValue = (value: number): string => {
const rounded = Math.round(value * 10) / 10;
const label = MOOD_LABELS[Math.round(value)];
return label ? `${rounded} (${label})` : String(rounded);
};
if (!isLoading && !data?.entries?.length) return null;
return (
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-base font-medium">
{displayTitle}
</CardTitle>
<div className="flex gap-1">
{TIME_RANGES_KEYS.map((r) => (
<Button
key={r.labelKey}
variant={rangePoints === r.points ? "default" : "ghost"}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setRangePoints(r.points)}
title={t(r.titleKey)}
>
{t(r.labelKey)}
</Button>
))}
</div>
</div>
<div className="flex items-center gap-4 text-xs">
<div className="flex items-center gap-1.5">
<Switch
id={maToggleId}
checked={showMA}
onCheckedChange={setShowMA}
className="scale-75"
/>
<Label htmlFor={maToggleId} className="cursor-pointer text-xs">
{t("charts.moodMA")}
</Label>
</div>
<div className="flex items-center gap-1.5">
<Switch
id={trendToggleId}
checked={showTrend}
onCheckedChange={setShowTrend}
className="scale-75"
/>
<Label htmlFor={trendToggleId} className="cursor-pointer text-xs">
{t("charts.trend")}
</Label>
</div>
<div className="flex items-center gap-1.5">
<Switch
id={bandsToggleId}
checked={showBands}
onCheckedChange={setShowBands}
className="scale-75"
/>
<Label htmlFor={bandsToggleId} className="cursor-pointer text-xs">
{t("charts.targetRanges")}
</Label>
</div>
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !chartData?.length ? (
<div className="text-muted-foreground flex h-48 items-center justify-center text-sm">
{t("charts.noData")}
</div>
) : (
<div className="h-[280px]">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={chartData}
margin={{ top: 10, right: 8, bottom: 8, left: 8 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="hsl(var(--border))"
opacity={0.5}
/>
{showBands &&
VALUE_BANDS.map((band) => (
<ReferenceArea
key={`band-${band.min}-${band.max}`}
y1={band.min}
y2={band.max}
fill={band.color}
fillOpacity={band.opacity}
strokeOpacity={0}
ifOverflow="discard"
/>
))}
<XAxis
type="number"
dataKey="pointIndex"
domain={[0, maxPointIndex]}
allowDecimals={false}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
tickFormatter={(value: number) =>
formatDateShort(
new Date(
chartData[Math.round(value)]?.timestamp ?? Date.now(),
),
true,
)
}
interval="preserveStartEnd"
padding={{ left: 10, right: 10 }}
tickMargin={10}
/>
<YAxis
domain={[1, 5]}
ticks={[1, 2, 3, 4, 5]}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
width={65}
tickMargin={6}
tickFormatter={formatMoodTick}
/>
<Tooltip
contentStyle={{
backgroundColor: "var(--card)",
border: "1px solid var(--border)",
borderRadius: "0.5rem",
fontSize: "0.875rem",
}}
formatter={(value, name) => {
if (typeof value !== "number") return String(value);
if (name === "score") {
return [formatTooltipValue(value), t("charts.moodScore")];
}
if (name === "ma") {
return [formatTooltipValue(value), t("charts.moodMA")];
}
if (name === "trend") {
return [formatTooltipValue(value), t("charts.trend")];
}
return [String(value), String(name)];
}}
labelFormatter={(_label, payload) =>
payload?.[0]?.payload?.timestamp
? formatDateShort(
new Date(
(payload[0].payload as ChartDataPoint).timestamp,
),
true,
)
: ""
}
/>
<Line
type="monotone"
dataKey="score"
name="score"
stroke={COLOR_MAIN}
strokeWidth={2}
dot={{ r: 3, fill: COLOR_MAIN }}
activeDot={{ r: 5 }}
connectNulls
/>
{showMA && (
<Line
type="monotone"
dataKey="ma"
name="ma"
stroke={COLOR_MA}
strokeWidth={1.5}
strokeDasharray="5 5"
dot={false}
connectNulls
/>
)}
{showTrend && (
<Line
type="linear"
dataKey="trend"
name="trend"
stroke={COLOR_TREND}
strokeWidth={1}
strokeDasharray="8 4"
dot={false}
connectNulls
/>
)}
</LineChart>
</ResponsiveContainer>
</div>
)}
</CardContent>
</Card>
);
}
+124
View File
@@ -0,0 +1,124 @@
"use client";
import { ArrowDown, ArrowRight, ArrowUp, Minus } from "lucide-react";
import type { TrendSlope } from "@/lib/analytics/trends";
import { cn } from "@/lib/utils";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
interface TrendCardProps {
label: string;
latest: number | null;
unit: string;
avg7: number | null;
avg30: number | null;
avg7ColorClass?: string;
avg30ColorClass?: string;
avg7Hint?: React.ReactNode;
avg30Hint?: React.ReactNode;
slope30: TrendSlope | null;
icon: React.ComponentType<{ className?: string }>;
}
export function TrendCard({
label,
latest,
unit,
avg7,
avg30,
avg7ColorClass,
avg30ColorClass,
avg7Hint,
avg30Hint,
slope30,
icon: Icon,
}: TrendCardProps) {
const TrendIcon =
slope30?.direction === "up"
? ArrowUp
: slope30?.direction === "down"
? ArrowDown
: slope30
? ArrowRight
: Minus;
const trendColor =
slope30?.direction === "up"
? "text-dracula-orange"
: slope30?.direction === "down"
? "text-dracula-cyan"
: "text-muted-foreground";
const formatValue = (value: number) =>
new Intl.NumberFormat("de-DE", {
maximumFractionDigits: 1,
}).format(value);
return (
<div className="bg-card border-border rounded-xl border p-3">
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-sm font-medium">
{label}
</span>
<Icon className="text-muted-foreground h-4 w-4" />
</div>
<div className="mt-2 flex items-baseline gap-2">
<span className="text-2xl font-bold">
{latest !== null ? formatValue(latest) : "—"}
</span>
<span className="text-muted-foreground text-sm">{unit}</span>
{slope30 && <TrendIcon className={`h-4 w-4 ${trendColor}`} />}
</div>
<TooltipProvider>
<div className="text-muted-foreground mt-1 flex gap-3 text-xs">
{avg7 !== null && (
<span>
7T:{" "}
{avg7Hint ? (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn("font-medium", avg7ColorClass)}>
{formatValue(avg7)}
</span>
</TooltipTrigger>
<TooltipContent className="bg-muted border-border text-foreground">
<div className="space-y-1 text-xs">{avg7Hint}</div>
</TooltipContent>
</Tooltip>
) : (
<span className={cn("font-medium", avg7ColorClass)}>
{formatValue(avg7)}
</span>
)}
</span>
)}
{avg30 !== null && (
<span>
30T:{" "}
{avg30Hint ? (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn("font-medium", avg30ColorClass)}>
{formatValue(avg30)}
</span>
</TooltipTrigger>
<TooltipContent className="bg-muted border-border text-foreground">
<div className="space-y-1 text-xs">{avg30Hint}</div>
</TooltipContent>
</Tooltip>
) : (
<span className={cn("font-medium", avg30ColorClass)}>
{formatValue(avg30)}
</span>
)}
</span>
)}
</div>
</TooltipProvider>
</div>
);
}
@@ -0,0 +1,130 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { Trophy } from "lucide-react";
import { useEffect, useMemo, useRef } from "react";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import type { AchievementProgress } from "@/lib/gamification/achievements";
const STORAGE_KEY_PREFIX = "healthlog-achievements-seen";
interface AchievementsPayload {
achievements: AchievementProgress[];
}
interface AchievementUnlockNotifierProps {
userId: string;
}
function parseStoredIds(raw: string | null): Set<string> {
if (!raw) return new Set();
try {
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) return new Set();
return new Set(
parsed.filter((item): item is string => typeof item === "string"),
);
} catch {
return new Set();
}
}
function readSeenIds(storageKey: string): {
seenIds: Set<string>;
hasSnapshot: boolean;
} {
try {
const raw = localStorage.getItem(storageKey);
return {
seenIds: parseStoredIds(raw),
hasSnapshot: raw !== null,
};
} catch {
return {
seenIds: new Set<string>(),
hasSnapshot: true,
};
}
}
function writeSeenIds(storageKey: string, seenIds: Set<string>) {
try {
localStorage.setItem(storageKey, JSON.stringify(Array.from(seenIds)));
} catch {
// Ignore storage failures (privacy mode / quota) and keep notifier in-memory.
}
}
export function AchievementUnlockNotifier({
userId,
}: AchievementUnlockNotifierProps) {
const { t } = useTranslations();
const storageKey = useMemo(() => `${STORAGE_KEY_PREFIX}:${userId}`, [userId]);
const seenIdsRef = useRef<Set<string>>(new Set());
const localStateReadyRef = useRef(false);
const hasSnapshotRef = useRef(false);
const { data } = useQuery({
queryKey: ["gamification", "achievements", "unlock-notifier", userId],
queryFn: async () => {
try {
const response = await fetch("/api/gamification/achievements");
if (!response.ok) {
return { achievements: [] } satisfies AchievementsPayload;
}
const json = await response.json();
return (json.data ?? { achievements: [] }) as AchievementsPayload;
} catch {
return { achievements: [] } satisfies AchievementsPayload;
}
},
staleTime: 60 * 1000,
refetchInterval: 2 * 60 * 1000,
refetchOnWindowFocus: false,
});
useEffect(() => {
const state = readSeenIds(storageKey);
seenIdsRef.current = state.seenIds;
hasSnapshotRef.current = state.hasSnapshot;
localStateReadyRef.current = true;
}, [storageKey]);
useEffect(() => {
if (!localStateReadyRef.current || !data) return;
const unlocked = data.achievements.filter(
(achievement) => achievement.unlocked,
);
const unlockedIds = unlocked.map((achievement) => achievement.id);
if (!hasSnapshotRef.current) {
seenIdsRef.current = new Set(unlockedIds);
writeSeenIds(storageKey, seenIdsRef.current);
hasSnapshotRef.current = true;
return;
}
const newlyUnlocked = unlocked.filter(
(achievement) => !seenIdsRef.current.has(achievement.id),
);
if (newlyUnlocked.length === 0) {
return;
}
for (const achievement of newlyUnlocked) {
toast(t(achievement.titleKey), {
description: t(achievement.descriptionKey),
icon: <Trophy className="size-4" />,
});
seenIdsRef.current.add(achievement.id);
}
writeSeenIds(storageKey, seenIdsRef.current);
}, [data, storageKey, t]);
return null;
}
+164
View File
@@ -0,0 +1,164 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Sparkles, RefreshCw, Loader2, AlertTriangle } from "lucide-react";
interface InsightsOutput {
changed: string;
stable: string;
drivers: string;
nextSteps: string;
confidence: "niedrig" | "mittel" | "hoch";
limitations: string;
}
interface InsightsResponse {
insights: InsightsOutput;
cached: boolean;
cachedAt?: string;
}
const CONFIDENCE_COLORS: Record<string, string> = {
niedrig: "bg-orange-500/20 text-orange-400",
mittel: "bg-yellow-500/20 text-yellow-400",
hoch: "bg-green-500/20 text-green-400",
};
export function InsightsCard() {
const { isAuthenticated } = useAuth();
const queryClient = useQueryClient();
const [error, setError] = useState<string | null>(null);
// Check if insights are configured
const { data: settings } = useQuery({
queryKey: ["insights", "settings"],
queryFn: async () => {
const res = await fetch("/api/insights/settings");
if (!res.ok) return null;
const json = await res.json();
return json.data as {
hasKey: boolean;
privacyMode: string;
lastInsightAt: string | null;
};
},
enabled: isAuthenticated,
});
const generate = useMutation({
mutationFn: async (force: boolean) => {
const res = await fetch("/api/insights/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ force }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error);
return json.data as InsightsResponse;
},
onSuccess: () => {
setError(null);
queryClient.invalidateQueries({ queryKey: ["insights"] });
},
onError: (err: Error) => {
setError(err.message);
},
});
// Don't show if no API key configured
if (!settings?.hasKey) return null;
const insights = generate.data?.insights;
return (
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Sparkles className="text-dracula-purple h-5 w-5" />
<CardTitle className="text-lg">KI-Insights</CardTitle>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => generate.mutate(!insights)}
disabled={generate.isPending}
>
{generate.isPending ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="mr-1 h-3.5 w-3.5" />
)}
{insights ? "Aktualisieren" : "Generieren"}
</Button>
</div>
</CardHeader>
<CardContent>
{error && (
<div className="bg-destructive/10 text-destructive flex items-center gap-2 rounded-lg p-3 text-sm">
<AlertTriangle className="h-4 w-4 shrink-0" />
{error}
</div>
)}
{generate.isPending && !insights && (
<div className="flex items-center justify-center py-8">
<Loader2 className="text-dracula-purple h-6 w-6 animate-spin" />
<span className="text-muted-foreground ml-2 text-sm">
Analysiere Gesundheitsdaten...
</span>
</div>
)}
{insights && (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Badge className={CONFIDENCE_COLORS[insights.confidence] ?? ""}>
Konfidenz: {insights.confidence}
</Badge>
{generate.data?.cached && (
<Badge variant="outline" className="text-xs">
Gecacht
</Badge>
)}
</div>
<Section title="Was hat sich verändert" text={insights.changed} />
<Section title="Was ist stabil" text={insights.stable} />
<Section title="Mögliche Zusammenhänge" text={insights.drivers} />
<Section title="Nächste Schritte" text={insights.nextSteps} />
<div className="bg-muted/50 rounded-lg p-3">
<p className="text-muted-foreground text-xs">
<AlertTriangle className="mr-1 inline h-3 w-3" />
{insights.limitations}
</p>
</div>
</div>
)}
{!insights && !generate.isPending && !error && (
<p className="text-muted-foreground py-4 text-center text-sm">
Klicke auf &quot;Generieren&quot; für KI-basierte Insights deiner
Gesundheitsdaten.
</p>
)}
</CardContent>
</Card>
);
}
function Section({ title, text }: { title: string; text: string }) {
return (
<div>
<h4 className="mb-1 text-sm font-medium">{title}</h4>
<p className="text-muted-foreground text-sm">{text}</p>
</div>
);
}
+140
View File
@@ -0,0 +1,140 @@
"use client";
import { Loader2 } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import { AchievementUnlockNotifier } from "@/components/gamification/achievement-unlock-notifier";
import { useAuth } from "@/hooks/use-auth";
import { useTranslations } from "@/lib/i18n/context";
import { BottomNav } from "./bottom-nav";
import { SidebarNav } from "./sidebar-nav";
import { TopBar } from "./top-bar";
const PUBLIC_PATHS = ["/auth/login", "/auth/register"];
export function AuthShell({ children }: { children: React.ReactNode }) {
const { user, isAuthenticated, isLoading } = useAuth();
const { t } = useTranslations();
const pathname = usePathname();
const router = useRouter();
const isPublicPage = PUBLIC_PATHS.some((p) => pathname.startsWith(p));
const isAdminPage = pathname.startsWith("/admin");
const isOnboardingPage = pathname === "/onboarding";
const showUnlockNotifier = isAuthenticated && !isPublicPage && !!user?.id;
useEffect(() => {
if (!isLoading && !isAuthenticated && !isPublicPage) {
router.replace("/auth/login");
}
}, [isLoading, isAuthenticated, isPublicPage, router]);
// Redirect non-admins away from /admin
useEffect(() => {
if (
!isLoading &&
isAuthenticated &&
isAdminPage &&
user?.role !== "ADMIN"
) {
router.replace("/");
}
}, [isLoading, isAuthenticated, isAdminPage, user?.role, router]);
// Redirect to onboarding if not completed
useEffect(() => {
if (
!isLoading &&
isAuthenticated &&
!isOnboardingPage &&
!isPublicPage &&
user &&
!user.onboardingCompletedAt
) {
router.replace("/onboarding");
}
}, [
isLoading,
isAuthenticated,
isOnboardingPage,
isPublicPage,
user,
router,
]);
// Loading state
if (isLoading) {
return (
<div className="flex h-dvh items-center justify-center" role="status">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
<span className="sr-only">{t("nav.loadingScreen")}</span>
</div>
);
}
// Public pages (login, register) — render without any nav
if (isPublicPage) {
return (
<main
id="main-content"
className="flex h-dvh items-center justify-center px-4"
>
{children}
</main>
);
}
// Not authenticated, waiting for redirect
if (!isAuthenticated) {
return (
<div className="flex h-dvh items-center justify-center" role="status">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
<span className="sr-only">{t("nav.loadingScreen")}</span>
</div>
);
}
// Onboarding page — minimal shell, no sidebar/nav
if (isOnboardingPage) {
return (
<>
{showUnlockNotifier && user?.id ? (
<AchievementUnlockNotifier userId={user.id} />
) : null}
<div className="flex min-h-dvh items-center justify-center px-4 py-8">
{children}
</div>
</>
);
}
// Authenticated — full app shell
return (
<>
{showUnlockNotifier && user?.id ? (
<AchievementUnlockNotifier userId={user.id} />
) : null}
<a
href="#main-content"
className="bg-primary text-primary-foreground fixed left-2 top-2 z-[100] rounded-md px-4 py-2 text-sm font-medium opacity-0 focus:opacity-100"
>
{t("nav.skipToContent")}
</a>
<div className="flex h-dvh flex-col md:flex-row">
<SidebarNav />
<div className="flex min-h-0 flex-1 flex-col">
<TopBar />
<main
id="main-content"
className="flex-1 overflow-y-auto pb-[calc(5rem+env(safe-area-inset-bottom,0px))] md:pb-0"
>
<div className="mx-auto max-w-[76.8rem] px-4 py-6 md:px-6">
{children}
</div>
</main>
</div>
<BottomNav />
</div>
</>
);
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import {
Activity,
Home,
Lightbulb,
Pill,
Target,
Trophy,
Waves,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
const navItems = [
{ href: "/", tKey: "nav.dashboard", icon: Home },
{ href: "/measurements", tKey: "nav.measurements", icon: Activity },
{ href: "/stimmung", tKey: "nav.mood", icon: Waves },
{ href: "/medications", tKey: "nav.medications", icon: Pill },
{ href: "/insights", tKey: "nav.insights", icon: Lightbulb },
{ href: "/zielwerte", tKey: "nav.targets", icon: Target },
{ href: "/achievements", tKey: "nav.achievements", icon: Trophy },
];
export function BottomNav() {
const pathname = usePathname();
const { t } = useTranslations();
const items = navItems;
return (
<nav aria-label={t("nav.mobileNavigation")} className="bg-card/80 border-border fixed bottom-0 left-0 z-50 w-full border-t pb-[env(safe-area-inset-bottom)] backdrop-blur-md md:hidden">
<div className="mx-auto flex h-14 max-w-lg items-center justify-around px-2">
{items.map((item) => {
const isActive =
item.href === "/"
? pathname === "/"
: pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
aria-label={t(item.tKey)}
aria-current={isActive ? "page" : undefined}
className={cn(
"relative flex items-center justify-center rounded-lg p-2.5 transition-colors",
isActive
? "text-primary"
: "text-muted-foreground hover:text-foreground",
)}
>
<item.icon className="h-5 w-5" />
{isActive && (
<span className="bg-primary absolute -bottom-1 h-1 w-1 rounded-full" />
)}
</Link>
);
})}
</div>
</nav>
);
}
+438
View File
@@ -0,0 +1,438 @@
"use client";
import { useState } from "react";
import {
Activity,
Bell,
Bug,
ChevronsLeft,
ChevronsRight,
Home,
Lightbulb,
LogOut,
Monitor,
Moon,
MoreVertical,
Pill,
Settings,
Sun,
Target,
Trophy,
Waves,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { Logo } from "@/components/ui/logo";
import { useAuth, useLogout } from "@/hooks/use-auth";
import { useTheme } from "@/components/providers";
import { useTranslations } from "@/lib/i18n/context";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
const STORAGE_KEY = "healthlog-sidebar-collapsed";
const navItems = [
{ href: "/", tKey: "nav.dashboard", icon: Home },
{ href: "/measurements", tKey: "nav.measurements", icon: Activity },
{ href: "/stimmung", tKey: "nav.mood", icon: Waves },
{ href: "/medications", tKey: "nav.medications", icon: Pill },
{ href: "/insights", tKey: "nav.insights", icon: Lightbulb },
{ href: "/zielwerte", tKey: "nav.targets", icon: Target },
{ href: "/achievements", tKey: "nav.achievements", icon: Trophy },
];
function getInitials(name: string): string {
return name
.split(/[\s._-]+/)
.slice(0, 2)
.map((s) => s[0]?.toUpperCase() ?? "")
.join("");
}
function SidebarUserSection({ collapsed }: { collapsed: boolean }) {
const { user } = useAuth();
const logout = useLogout();
const { theme, setTheme } = useTheme();
const { t } = useTranslations();
const gravatarUrl = user?.gravatarUrl ?? null;
if (!user) return null;
const themeIcon =
theme === "system" ? (
<Monitor className="h-4 w-4" />
) : theme === "dark" ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
);
const dropdownContent = (
<DropdownMenuContent
side="right"
align="end"
className="w-56"
sideOffset={8}
>
<div className="flex items-center gap-3 px-2 py-2">
<Avatar className="h-9 w-9 shrink-0">
{gravatarUrl && <AvatarImage src={gravatarUrl} alt={user.username} />}
<AvatarFallback className="bg-primary/15 text-primary text-xs font-medium">
{getInitials(user.username)}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{user.username}</p>
{user.email && (
<p className="text-muted-foreground truncate text-xs">
{user.email}
</p>
)}
</div>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/notifications" className="cursor-pointer">
<Bell className="mr-2 h-4 w-4" />
{t("nav.notifications")}
</Link>
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
{themeIcon}
<span className="ml-2">{t("nav.theme")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem onClick={() => setTheme("system")}>
<Monitor className="mr-2 h-4 w-4" />
{t("nav.themeSystem")}
{theme === "system" && (
<span className="text-primary ml-auto text-xs">&#10003;</span>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon className="mr-2 h-4 w-4" />
{t("nav.themeDark")}
{theme === "dark" && (
<span className="text-primary ml-auto text-xs">&#10003;</span>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun className="mr-2 h-4 w-4" />
{t("nav.themeLight")}
{theme === "light" && (
<span className="text-primary ml-auto text-xs">&#10003;</span>
)}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => logout.mutate()}
className="text-destructive focus:text-destructive focus:bg-destructive/10 cursor-pointer"
>
<LogOut className="mr-2 h-4 w-4" />
{t("nav.logout")}
</DropdownMenuItem>
</DropdownMenuContent>
);
if (collapsed) {
return (
<div className="border-sidebar-border border-t p-3">
<div className="flex items-center justify-center">
<DropdownMenu>
<DropdownMenuTrigger aria-label={t("nav.userMenu")} className="hover:bg-accent shrink-0 rounded-md p-1.5 transition-colors focus-visible:ring-ring/50 focus-visible:ring-[3px] focus:outline-none">
<Avatar className="h-8 w-8">
{gravatarUrl && (
<AvatarImage src={gravatarUrl} alt={user.username} />
)}
<AvatarFallback className="bg-primary/15 text-primary text-xs font-medium">
{getInitials(user.username)}
</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
{dropdownContent}
</DropdownMenu>
</div>
</div>
);
}
return (
<div className="border-sidebar-border border-t p-3">
<div className="flex items-center gap-3 px-2 py-1">
<Avatar className="h-8 w-8 shrink-0">
{gravatarUrl && <AvatarImage src={gravatarUrl} alt={user.username} />}
<AvatarFallback className="bg-primary/15 text-primary text-xs font-medium">
{getInitials(user.username)}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{user.username}</p>
{user.email && (
<p className="text-muted-foreground truncate text-xs">
{user.email}
</p>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger aria-label={t("nav.userMenu")} className="text-muted-foreground hover:text-foreground hover:bg-accent shrink-0 rounded-md p-1.5 transition-colors focus-visible:ring-ring/50 focus-visible:ring-[3px] focus:outline-none">
<MoreVertical className="h-4 w-4" />
</DropdownMenuTrigger>
{dropdownContent}
</DropdownMenu>
</div>
</div>
);
}
export function SidebarNav() {
const pathname = usePathname();
const { t } = useTranslations();
const [collapsed, setCollapsed] = useState(() => {
if (typeof window === "undefined") return false;
try {
return localStorage.getItem(STORAGE_KEY) === "true";
} catch {
return false;
}
});
function toggleCollapsed() {
setCollapsed((prev) => {
const next = !prev;
try {
localStorage.setItem(STORAGE_KEY, String(next));
} catch {
// Ignore storage errors
}
return next;
});
}
function renderCollapseToggle(className?: string) {
return (
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={toggleCollapsed}
className={cn(
"text-muted-foreground/80 hover:text-foreground hover:bg-accent z-20 rounded-md p-1 transition-colors",
className,
)}
aria-label={t("nav.collapseSidebar")}
aria-expanded={!collapsed}
>
{collapsed ? (
<ChevronsRight className="h-3.5 w-3.5" />
) : (
<ChevronsLeft className="h-3.5 w-3.5" />
)}
</button>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{t("nav.collapseSidebar")}
</TooltipContent>
</Tooltip>
);
}
return (
<TooltipProvider delayDuration={0}>
<aside
aria-label={t("nav.sidebar")}
className={cn(
"bg-sidebar border-sidebar-border relative hidden h-full flex-shrink-0 border-r transition-[width] duration-200 md:flex md:flex-col",
collapsed ? "w-16" : "w-64",
)}
>
{/* Logo */}
<div
className={cn(
"border-sidebar-border border-b",
collapsed ? "px-3" : "px-6",
)}
>
<Link
href="/"
className={cn(
"flex h-16 items-center",
collapsed ? "justify-center px-0" : "gap-2",
)}
>
<Logo className="text-primary shrink-0" size={24} />
{!collapsed && (
<span className="text-lg font-bold tracking-tight">
HealthLog
</span>
)}
</Link>
</div>
<nav
aria-label={t("nav.mainNavigation")}
className={cn("flex-1 overflow-y-auto", collapsed ? "p-1.5" : "p-3")}
>
{collapsed ? (
<div className="mb-1 flex justify-center">
{renderCollapseToggle()}
</div>
) : (
<div className="relative mb-1">
<p className="text-foreground/75 px-3 text-xs font-semibold tracking-wider uppercase">
{t("nav.home")}
</p>
<div className="absolute top-1/2 -right-1 -translate-y-1/2">
{renderCollapseToggle()}
</div>
</div>
)}
<div className="space-y-1">
{navItems.map((item) => {
const isActive =
item.href === "/"
? pathname === "/"
: pathname.startsWith(item.href);
const label = t(item.tKey);
if (collapsed) {
return (
<Tooltip key={item.href}>
<TooltipTrigger asChild>
<Link
href={item.href}
aria-current={isActive ? "page" : undefined}
className={cn(
"flex items-center justify-center rounded-lg p-2.5 transition-colors",
isActive
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<item.icon className="h-4 w-4" />
</Link>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{label}
</TooltipContent>
</Tooltip>
);
}
return (
<Link
key={item.href}
href={item.href}
aria-current={isActive ? "page" : undefined}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
isActive
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<item.icon className="h-4 w-4" />
{label}
</Link>
);
})}
</div>
</nav>
{/* Bottom utility links */}
<div className={cn("space-y-1 pb-1", collapsed ? "px-1.5" : "px-3")}>
{collapsed ? (
<>
<Tooltip>
<TooltipTrigger asChild>
<Link
href="/bugreport"
aria-current={pathname === "/bugreport" ? "page" : undefined}
className={cn(
"flex items-center justify-center rounded-lg p-2.5 transition-colors",
pathname === "/bugreport"
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<Bug className="h-4 w-4" />
</Link>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{t("nav.bugreport")}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Link
href="/settings"
aria-current={pathname === "/settings" ? "page" : undefined}
className={cn(
"flex items-center justify-center rounded-lg p-2.5 transition-colors",
pathname === "/settings"
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<Settings className="h-4 w-4" />
</Link>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>
{t("nav.settings")}
</TooltipContent>
</Tooltip>
</>
) : (
<>
<Link
href="/bugreport"
aria-current={pathname === "/bugreport" ? "page" : undefined}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
pathname === "/bugreport"
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<Bug className="h-4 w-4" />
{t("nav.bugreport")}
</Link>
<Link
href="/settings"
aria-current={pathname === "/settings" ? "page" : undefined}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
pathname === "/settings"
? "bg-primary/10 text-primary"
: "text-foreground hover:bg-accent",
)}
>
<Settings className="h-4 w-4" />
{t("nav.settings")}
</Link>
</>
)}
</div>
<SidebarUserSection collapsed={collapsed} />
</aside>
</TooltipProvider>
);
}
+137
View File
@@ -0,0 +1,137 @@
"use client";
import {
Bell,
ChevronDown,
LogIn,
LogOut,
Monitor,
Moon,
Settings,
Sun,
User,
} from "lucide-react";
import { Logo } from "@/components/ui/logo";
import Link from "next/link";
import { useAuth, useLogout } from "@/hooks/use-auth";
import { useTheme } from "@/components/providers";
import { useTranslations } from "@/lib/i18n/context";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
export function TopBar() {
const { user, isLoading } = useAuth();
const logout = useLogout();
const { theme, setTheme } = useTheme();
const { t } = useTranslations();
const themeIcon =
theme === "system" ? (
<Monitor className="h-4 w-4" />
) : theme === "dark" ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
);
return (
<header className="bg-card/80 border-border sticky top-0 z-40 flex h-16 items-center justify-between border-b px-4 backdrop-blur-md md:px-6">
{/* Mobile logo */}
<Link href="/" className="flex items-center gap-2 md:hidden">
<Logo className="text-primary" size={20} />
<span className="font-bold tracking-tight">HealthLog</span>
</Link>
{/* Desktop: empty spacer (user controls are in sidebar) */}
<div className="hidden md:block" />
{/* Mobile-only auth section (desktop uses sidebar user section) */}
<div className="flex items-center gap-2 md:hidden">
{isLoading ? (
<div className="bg-muted h-4 w-20 animate-pulse rounded" />
) : user ? (
<DropdownMenu>
<DropdownMenuTrigger className="text-muted-foreground hover:text-foreground flex items-center gap-1.5 rounded-md px-2 py-1.5 text-sm transition-colors focus:outline-none">
<User className="h-4 w-4" />
<span className="hidden sm:inline">{user.username}</span>
<ChevronDown className="h-3 w-3 opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem asChild>
<Link href="/settings" className="cursor-pointer">
<Settings className="mr-2 h-4 w-4" />
{t("nav.settings")}
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/notifications" className="cursor-pointer">
<Bell className="mr-2 h-4 w-4" />
{t("nav.notifications")}
</Link>
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
{themeIcon}
<span className="ml-2">{t("nav.theme")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem onClick={() => setTheme("system")}>
<Monitor className="mr-2 h-4 w-4" />
{t("nav.themeSystem")}
{theme === "system" && (
<span className="text-primary ml-auto text-xs">
&#10003;
</span>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon className="mr-2 h-4 w-4" />
{t("nav.themeDark")}
{theme === "dark" && (
<span className="text-primary ml-auto text-xs">
&#10003;
</span>
)}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun className="mr-2 h-4 w-4" />
{t("nav.themeLight")}
{theme === "light" && (
<span className="text-primary ml-auto text-xs">
&#10003;
</span>
)}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => logout.mutate()}
className="text-destructive focus:text-destructive focus:bg-destructive/10 cursor-pointer"
>
<LogOut className="mr-2 h-4 w-4" />
{t("nav.logout")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
<Link
href="/auth/login"
className="text-muted-foreground hover:text-foreground flex items-center gap-2 text-sm transition-colors"
>
<LogIn className="h-4 w-4" />
<span className="hidden sm:inline">{t("nav.login")}</span>
</Link>
)}
</div>
</header>
);
}
@@ -0,0 +1,378 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Loader2, MoreHorizontal, Plus, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
const MAX_COMMENT_LENGTH = 25;
const MEASUREMENT_TYPES = [
{
value: "BLOOD_PRESSURE",
labelKey: "measurements.typeBloodPressure",
unit: "mmHg",
},
{
value: "WEIGHT",
labelKey: "measurements.typeWeight",
unit: "kg",
placeholder: "75.5",
},
{
value: "PULSE",
labelKey: "measurements.typePulse",
unit: "bpm",
placeholder: "72",
},
{
value: "BODY_FAT",
labelKey: "measurements.typeBodyFat",
unit: "%",
placeholder: "22",
},
{
value: "SLEEP_DURATION",
labelKey: "measurements.typeSleep",
unitKey: "measurements.unitHours",
placeholder: "7.5",
},
{
value: "ACTIVITY_STEPS",
labelKey: "measurements.typeSteps",
unitKey: "measurements.unitSteps",
placeholder: "8000",
},
] as const;
interface MeasurementFormProps {
onSuccess?: () => void;
onCancel?: () => void;
defaultType?: string;
}
function getDefaultMeasuredAtValue() {
const now = new Date();
const offset = now.getTimezoneOffset();
const local = new Date(now.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
export function MeasurementForm({
onSuccess,
onCancel,
defaultType,
}: MeasurementFormProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
// Normalize legacy BP types to combined mode
const normalizedDefault =
defaultType === "BLOOD_PRESSURE_SYS" || defaultType === "BLOOD_PRESSURE_DIA"
? "BLOOD_PRESSURE"
: defaultType;
const [type, setType] = useState(normalizedDefault || "BLOOD_PRESSURE");
const [value, setValue] = useState("");
const [sysBp, setSysBp] = useState("");
const [diaBp, setDiaBp] = useState("");
const [pulse, setPulse] = useState("");
const [notes, setNotes] = useState("");
const [measuredAt, setMeasuredAt] = useState(getDefaultMeasuredAtValue);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const typeInfo = MEASUREMENT_TYPES.find((t) => t.value === type);
const isBpMode = type === "BLOOD_PRESSURE";
function resetForm() {
setType(normalizedDefault || "BLOOD_PRESSURE");
setValue("");
setSysBp("");
setDiaBp("");
setPulse("");
setNotes("");
setMeasuredAt(getDefaultMeasuredAtValue());
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
try {
const timestamp = new Date(measuredAt).toISOString();
if (isBpMode) {
// Batch: Sys + Dia + optional Pulse
const batch: Array<{
type: string;
value: number;
measuredAt: string;
notes?: string;
}> = [
{
type: "BLOOD_PRESSURE_SYS",
value: parseFloat(sysBp),
measuredAt: timestamp,
notes: notes || undefined,
},
{
type: "BLOOD_PRESSURE_DIA",
value: parseFloat(diaBp),
measuredAt: timestamp,
notes: notes || undefined,
},
];
if (pulse) {
batch.push({
type: "PULSE",
value: parseFloat(pulse),
measuredAt: timestamp,
notes: notes || undefined,
});
}
const res = await fetch("/api/measurements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(batch),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
} else {
// Single measurement
const res = await fetch("/api/measurements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type,
value: parseFloat(value),
measuredAt: timestamp,
notes: notes || undefined,
}),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
}
// Reset form
setValue("");
setSysBp("");
setDiaBp("");
setPulse("");
setNotes("");
await queryClient.invalidateQueries({ queryKey: ["measurements"] });
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("measurements.saveError"));
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="flex items-center gap-3">
<Label htmlFor="measurement-type" className="shrink-0">
{t("measurements.type")}
</Label>
<Select value={type} onValueChange={setType}>
<SelectTrigger id="measurement-type" className="flex-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
{MEASUREMENT_TYPES.map((mt) => (
<SelectItem key={mt.value} value={mt.value}>
{t(mt.labelKey)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{isBpMode ? (
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-2">
<Label htmlFor="sys">{t("measurements.systolicLabel")}</Label>
<Input
id="sys"
type="number"
step="1"
value={sysBp}
onChange={(e) => setSysBp(e.target.value)}
placeholder="120"
required
min={60}
max={280}
/>
</div>
<div className="space-y-2">
<Label htmlFor="dia">{t("measurements.diastolicLabel")}</Label>
<Input
id="dia"
type="number"
step="1"
value={diaBp}
onChange={(e) => setDiaBp(e.target.value)}
placeholder="80"
required
min={30}
max={200}
/>
</div>
<div className="space-y-2">
<Label htmlFor="puls">{t("measurements.pulseLabel")}</Label>
<Input
id="puls"
type="number"
step="1"
value={pulse}
onChange={(e) => setPulse(e.target.value)}
placeholder="72"
min={30}
max={220}
/>
</div>
</div>
) : (
<div className="space-y-2">
<Label htmlFor="value">
{t("measurements.valueWithUnit", {
unit: typeInfo
? "unitKey" in typeInfo
? t(typeInfo.unitKey)
: typeInfo.unit
: "",
})}
</Label>
<Input
id="value"
type="number"
step="any"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={
typeInfo && "placeholder" in typeInfo
? typeInfo.placeholder
: undefined
}
required
/>
</div>
)}
<div className="space-y-2">
<Label htmlFor="measuredAt">{t("measurements.timestamp")}</Label>
<Input
id="measuredAt"
type="datetime-local"
value={measuredAt}
onChange={(e) => setMeasuredAt(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="notes">
{t("measurements.notes")}{" "}
<span className="text-muted-foreground font-normal">
({t("common.optional")})
</span>
</Label>
<span className="text-muted-foreground text-xs">
{notes.length}/{MAX_COMMENT_LENGTH}
</span>
</div>
<Input
id="notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder={t("measurements.notesPlaceholder")}
maxLength={MAX_COMMENT_LENGTH}
/>
</div>
{error && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{error}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={loading}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem onClick={resetForm}>
<RotateCcw className="mr-2 h-4 w-4" />
{t("measurements.formReset")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={loading}
>
{t("common.cancel")}
</Button>
)}
<Button type="submit" disabled={loading}>
{loading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{t("common.save")}
</Button>
</div>
</div>
</form>
);
}
@@ -0,0 +1,748 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Loader2,
Pencil,
Trash2,
ChevronLeft,
ChevronRight,
ArrowUp,
ArrowDown,
ArrowUpDown,
MoreHorizontal,
Scale,
Heart,
Activity,
Droplets,
Moon,
Footprints,
} from "lucide-react";
import { useState } from "react";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
const TYPE_LABEL_KEYS: Record<string, string> = {
WEIGHT: "measurements.typeWeight",
BLOOD_PRESSURE_SYS: "measurements.typeBpSys",
BLOOD_PRESSURE_DIA: "measurements.typeBpDia",
PULSE: "measurements.typePulse",
BODY_FAT: "measurements.typeBodyFat",
SLEEP_DURATION: "measurements.typeSleep",
ACTIVITY_STEPS: "measurements.typeSteps",
};
const TYPE_ICONS: Record<
string,
React.ComponentType<{ className?: string }>
> = {
WEIGHT: Scale,
BLOOD_PRESSURE_SYS: Heart,
BLOOD_PRESSURE_DIA: Heart,
PULSE: Activity,
BODY_FAT: Droplets,
SLEEP_DURATION: Moon,
ACTIVITY_STEPS: Footprints,
};
const TYPE_COLORS: Record<string, string> = {
WEIGHT: "bg-chart-1/20 text-chart-1",
BLOOD_PRESSURE_SYS: "bg-chart-3/20 text-chart-3",
BLOOD_PRESSURE_DIA: "bg-chart-3/20 text-chart-3",
PULSE: "bg-chart-5/20 text-chart-5",
BODY_FAT: "bg-chart-4/20 text-chart-4",
SLEEP_DURATION: "bg-chart-2/20 text-chart-2",
ACTIVITY_STEPS: "bg-chart-2/20 text-chart-2",
};
interface Measurement {
id: string;
type: string;
value: number;
unit: string;
source: string;
measuredAt: string;
notes: string | null;
}
interface MeasurementListProps {
onEdit?: (m: Measurement) => void;
}
const PAGE_SIZE = 25;
const MAX_COMMENT_LENGTH = 25;
function truncateComment(comment: string): string {
if (comment.length <= MAX_COMMENT_LENGTH) return comment;
return `${comment.slice(0, MAX_COMMENT_LENGTH - 1)}…`;
}
function toDateTimeLocalValue(isoString: string): string {
const date = new Date(isoString);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
export function MeasurementList({ onEdit }: MeasurementListProps) {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
const queryClient = useQueryClient();
const [typeFilter, setTypeFilterRaw] = useState<string>("ALL");
const [page, setPage] = useState(1);
const [sortBy, setSortBy] = useState<string>("measuredAt");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
const [editing, setEditing] = useState<Measurement | null>(null);
const [editValue, setEditValue] = useState("");
const [editMeasuredAt, setEditMeasuredAt] = useState("");
const [editNotes, setEditNotes] = useState("");
const [editError, setEditError] = useState<string | null>(null);
const [editDeleteDialogOpen, setEditDeleteDialogOpen] = useState(false);
const setTypeFilter = (value: string) => {
setTypeFilterRaw(value);
setPage(1);
};
function toggleSort(column: string) {
if (sortBy === column) {
setSortDir((d) => (d === "asc" ? "desc" : "asc"));
} else {
setSortBy(column);
setSortDir(column === "measuredAt" ? "desc" : "asc");
}
setPage(1);
}
const { data, isLoading } = useQuery({
queryKey: [
"measurements",
typeFilter === "ALL" ? undefined : typeFilter,
page,
sortBy,
sortDir,
],
queryFn: async () => {
const params = new URLSearchParams();
if (typeFilter !== "ALL") params.set("type", typeFilter);
params.set("limit", String(PAGE_SIZE));
params.set("offset", String((page - 1) * PAGE_SIZE));
params.set("sortBy", sortBy);
params.set("sortDir", sortDir);
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data as {
measurements: Measurement[];
meta: { total: number };
};
},
enabled: isAuthenticated,
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/measurements/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Delete failed");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["measurements"] });
},
});
const updateMutation = useMutation({
mutationFn: async ({
id,
value,
measuredAt,
notes,
}: {
id: string;
value: number;
measuredAt: string;
notes: string | null;
}) => {
const res = await fetch(`/api/measurements/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
value,
measuredAt,
notes,
}),
});
const json = await res.json();
if (!res.ok) {
throw new Error(json.error ?? "Update failed");
}
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["measurements"] });
setEditing(null);
setEditError(null);
},
onError: (err) => {
setEditError(
err instanceof Error ? err.message : t("measurements.saveError"),
);
},
});
const totalPages = data ? Math.ceil(data.meta.total / PAGE_SIZE) : 0;
function startEdit(measurement: Measurement) {
if (onEdit) {
onEdit(measurement);
return;
}
setEditing(measurement);
setEditValue(String(measurement.value));
setEditMeasuredAt(toDateTimeLocalValue(measurement.measuredAt));
setEditNotes((measurement.notes ?? "").slice(0, MAX_COMMENT_LENGTH));
setEditError(null);
}
function closeEdit() {
if (updateMutation.isPending || deleteMutation.isPending) return;
setEditing(null);
setEditError(null);
setEditDeleteDialogOpen(false);
}
async function deleteEditingMeasurement() {
if (!editing) return;
try {
setEditError(null);
await deleteMutation.mutateAsync(editing.id);
closeEdit();
} catch {
setEditError(t("measurements.deleteError"));
}
}
async function submitEdit(e: React.FormEvent) {
e.preventDefault();
if (!editing) return;
const parsedValue = Number(editValue);
if (!Number.isFinite(parsedValue)) {
setEditError(t("measurements.invalidValue"));
return;
}
const measuredDate = new Date(editMeasuredAt);
if (Number.isNaN(measuredDate.getTime())) {
setEditError(t("measurements.invalidTimestamp"));
return;
}
setEditError(null);
updateMutation.mutate({
id: editing.id,
value: parsedValue,
measuredAt: measuredDate.toISOString(),
notes: editNotes.trim() ? editNotes.trim() : null,
});
}
if (!isAuthenticated) {
return (
<p className="text-muted-foreground text-sm">
{t("measurements.loginRequired")}
</p>
);
}
return (
<>
<div className="space-y-4">
<div className="flex items-center justify-between">
<Select value={typeFilter} onValueChange={setTypeFilter}>
<SelectTrigger className="w-48">
<SelectValue placeholder={t("measurements.allTypes")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">{t("measurements.allTypes")}</SelectItem>
{Object.entries(TYPE_LABEL_KEYS).map(([val, labelKey]) => (
<SelectItem key={val} value={val}>
{t(labelKey)}
</SelectItem>
))}
</SelectContent>
</Select>
{data?.meta.total !== undefined && (
<span className="text-muted-foreground text-sm">
{t("measurements.measurementCount", {
count: data.meta.total.toLocaleString("de-DE"),
})}
</span>
)}
</div>
{isLoading ? (
<div className="flex h-32 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !data?.measurements.length ? (
<div className="text-muted-foreground flex h-32 items-center justify-center rounded-lg border border-dashed">
{t("measurements.noMeasurements")}
</div>
) : (
<>
{/* Desktop table */}
<div className="bg-card border-border hidden overflow-hidden rounded-lg border md:block">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-28 pl-4">
{t("measurements.type")}
</TableHead>
<SortableHead
column="value"
label={t("measurements.value")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
/>
<SortableHead
column="measuredAt"
label={t("measurements.date")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
/>
<TableHead className="w-56">
{t("measurements.comment")}
</TableHead>
<SortableHead
column="source"
label={t("measurements.source")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
className="w-20"
/>
<TableHead className="w-20 pr-4 text-right">
{t("measurements.actions")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.measurements.map((m) => (
<TableRow key={m.id}>
<TableCell className="pl-4">
<Badge
variant="secondary"
className={TYPE_COLORS[m.type] ?? ""}
>
{TYPE_LABEL_KEYS[m.type]
? t(TYPE_LABEL_KEYS[m.type])
: m.type}
</Badge>
</TableCell>
<TableCell className="font-semibold tabular-nums">
{m.value} {m.unit}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{formatDateTime(m.measuredAt)}
</TableCell>
<TableCell className="text-sm">
{m.notes ? (
<span title={m.notes}>
{truncateComment(m.notes)}
</span>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell>
{m.source !== "MANUAL" && (
<Badge variant="outline" className="text-xs">
{m.source}
</Badge>
)}
</TableCell>
<TableCell className="pr-4 text-right">
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() => deleteMutation.mutate(m.id)}
/>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Mobile list */}
<div className="space-y-2 md:hidden">
{data.measurements.map((m) => {
const Icon = TYPE_ICONS[m.type];
return (
<div
key={m.id}
className="bg-card border-border flex items-center justify-between rounded-lg border p-3"
>
<div className="flex items-center gap-2.5 overflow-hidden">
{Icon && (
<div
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${TYPE_COLORS[m.type] ?? ""}`}
>
<Icon className="h-4 w-4" />
</div>
)}
<div className="min-w-0">
<span className="font-semibold tabular-nums">
{m.value} {m.unit}
</span>
<p className="text-muted-foreground truncate text-xs">
{formatDateTime(m.measuredAt)}
</p>
{m.notes && (
<p className="text-muted-foreground truncate text-xs">
{truncateComment(m.notes)}
</p>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() => deleteMutation.mutate(m.id)}
/>
</div>
</div>
);
})}
</div>
</>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-sm">
{t("measurements.pageInfo", {
page: String(page),
total: String(totalPages),
})}
</span>
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
<Dialog open={!!editing} onOpenChange={(open) => !open && closeEdit()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("measurements.editMeasurement")}</DialogTitle>
</DialogHeader>
{editing && (
<form onSubmit={submitEdit} className="space-y-4">
<div className="flex items-center gap-1.5">
<Label className="shrink-0">{t("measurements.type")}</Label>
<span className="text-sm leading-none font-medium">
{TYPE_LABEL_KEYS[editing.type]
? t(TYPE_LABEL_KEYS[editing.type])
: editing.type}
</span>
</div>
<div className="space-y-2">
<Label htmlFor="edit-value">
{t("measurements.valueWithUnit", { unit: editing.unit })}
</Label>
<Input
id="edit-value"
type="number"
step="any"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-measuredAt">
{t("measurements.timestamp")}
</Label>
<Input
id="edit-measuredAt"
type="datetime-local"
value={editMeasuredAt}
onChange={(e) => setEditMeasuredAt(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="edit-notes">
{t("measurements.notes")} ({t("common.optional")})
</Label>
<span className="text-muted-foreground text-xs">
{editNotes.length}/{MAX_COMMENT_LENGTH}
</span>
</div>
<Input
id="edit-notes"
value={editNotes}
onChange={(e) => setEditNotes(e.target.value)}
maxLength={MAX_COMMENT_LENGTH}
/>
</div>
{editError && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{editError}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem
variant="destructive"
onClick={() => setEditDeleteDialogOpen(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
{t("common.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={closeEdit}
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
{t("common.cancel")}
</Button>
<Button
type="submit"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
{updateMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("common.save")}
</Button>
</div>
</div>
<AlertDialog
open={editDeleteDialogOpen}
onOpenChange={setEditDeleteDialogOpen}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("measurements.deleteConfirmTitle")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("measurements.deleteConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteMutation.isPending}>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={deleteEditingMeasurement}
disabled={deleteMutation.isPending}
>
{deleteMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</form>
)}
</DialogContent>
</Dialog>
</>
);
}
function SortableHead({
column,
label,
currentSort,
currentDir,
onSort,
className,
}: {
column: string;
label: string;
currentSort: string;
currentDir: "asc" | "desc";
onSort: (col: string) => void;
className?: string;
}) {
const isActive = currentSort === column;
return (
<TableHead className={className}>
<button
type="button"
onClick={() => onSort(column)}
className="hover:text-foreground inline-flex items-center gap-1 transition-colors"
>
{label}
{isActive ? (
currentDir === "asc" ? (
<ArrowUp className="h-3.5 w-3.5" />
) : (
<ArrowDown className="h-3.5 w-3.5" />
)
) : (
<ArrowUpDown className="h-3.5 w-3.5 opacity-40" />
)}
</button>
</TableHead>
);
}
function DeleteButton({ onConfirm }: { onConfirm: () => void }) {
const { t } = useTranslations();
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-destructive h-8 w-8"
aria-label={t("common.delete")}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("measurements.deleteConfirmTitle")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("measurements.deleteConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={onConfirm}
>
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -0,0 +1,832 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Loader2,
Pencil,
Trash2,
ChevronLeft,
ChevronRight,
ArrowUp,
ArrowDown,
ArrowUpDown,
MoreHorizontal,
Check,
SkipForward,
AlertTriangle,
} from "lucide-react";
import { useState, useCallback } from "react";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
interface IntakeEvent {
id: string;
medicationId: string;
scheduledFor: string;
takenAt: string | null;
skipped: boolean;
source: string;
createdAt: string;
}
interface IntakeHistoryListProps {
medicationId: string;
createOpen?: boolean;
onCreateOpenChange?: (open: boolean) => void;
}
const SOURCE_LABELS: Record<string, string> = {
WEB: "Webseite",
API: "Externe API",
REMINDER: "Telegram / Erinnerung",
IMPORT: "CSV-Import",
};
const PAGE_SIZE = 25;
function toDateTimeLocalValue(isoString: string): string {
const date = new Date(isoString);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
function dateTimeLocalToISO(value: string): string {
return new Date(value).toISOString();
}
export function IntakeHistoryList({ medicationId, createOpen, onCreateOpenChange }: IntakeHistoryListProps) {
const { isAuthenticated } = useAuth();
const queryClient = useQueryClient();
const { t } = useTranslations();
const [page, setPage] = useState(1);
const [sortBy, setSortBy] = useState<string>("scheduledFor");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
// Edit state
const [editing, setEditing] = useState<IntakeEvent | null>(null);
const [editScheduledFor, setEditScheduledFor] = useState("");
const [editTakenAt, setEditTakenAt] = useState("");
const [editSkipped, setEditSkipped] = useState(false);
const [editError, setEditError] = useState<string | null>(null);
const [editDeleteDialogOpen, setEditDeleteDialogOpen] = useState(false);
// Create state — controlled via props or internal
const [internalCreating, setInternalCreating] = useState(false);
const creating = createOpen ?? internalCreating;
const [createScheduledFor, setCreateScheduledFor] = useState("");
const [createTakenAt, setCreateTakenAt] = useState("");
const [createSkipped, setCreateSkipped] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const setCreatingRaw = onCreateOpenChange ?? setInternalCreating;
const setCreating = useCallback((open: boolean) => {
if (open) {
const now = toDateTimeLocalValue(new Date().toISOString());
setCreateScheduledFor(now);
setCreateTakenAt(now);
setCreateSkipped(false);
setCreateError(null);
}
setCreatingRaw(open);
}, [setCreatingRaw]);
function toggleSort(column: string) {
if (sortBy === column) {
setSortDir((d) => (d === "asc" ? "desc" : "asc"));
} else {
setSortBy(column);
setSortDir(column === "scheduledFor" ? "desc" : "asc");
}
setPage(1);
}
const { data, isLoading } = useQuery({
queryKey: [
"medications",
medicationId,
"intake",
page,
sortBy,
sortDir,
],
queryFn: async () => {
const params = new URLSearchParams();
params.set("limit", String(PAGE_SIZE));
params.set("offset", String((page - 1) * PAGE_SIZE));
params.set("sortBy", sortBy);
params.set("sortDir", sortDir);
const res = await fetch(
`/api/medications/${medicationId}/intake?${params}`,
);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data as {
events: IntakeEvent[];
meta: { total: number; limit: number; offset: number };
};
},
enabled: isAuthenticated,
});
const deleteMutation = useMutation({
mutationFn: async (eventId: string) => {
const res = await fetch(
`/api/medications/${medicationId}/intake/${eventId}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Delete failed");
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "intake"],
});
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "compliance"],
});
},
});
const updateMutation = useMutation({
mutationFn: async ({
eventId,
takenAt,
skipped,
scheduledFor,
}: {
eventId: string;
takenAt: string | null;
skipped: boolean;
scheduledFor: string;
}) => {
const res = await fetch(
`/api/medications/${medicationId}/intake/${eventId}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ takenAt, skipped, scheduledFor }),
},
);
const json = await res.json();
if (!res.ok) throw new Error(json.error ?? "Update failed");
},
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "intake"],
});
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "compliance"],
});
setEditing(null);
setEditError(null);
},
onError: (err) => {
setEditError(
err instanceof Error ? err.message : "Fehler beim Speichern",
);
},
});
const createMutation = useMutation({
mutationFn: async ({
scheduledFor,
takenAt,
skipped,
}: {
scheduledFor: string;
takenAt: string | null;
skipped: boolean;
}) => {
const res = await fetch(
`/api/medications/${medicationId}/intake`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scheduledFor, takenAt, skipped }),
},
);
const json = await res.json();
if (!res.ok) throw new Error(json.error ?? "Create failed");
},
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "intake"],
});
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "compliance"],
});
setCreating(false);
setCreateError(null);
},
onError: (err) => {
setCreateError(
err instanceof Error ? err.message : "Fehler beim Speichern",
);
},
});
const totalPages = data ? Math.ceil(data.meta.total / PAGE_SIZE) : 0;
function startEdit(event: IntakeEvent) {
setEditing(event);
setEditScheduledFor(toDateTimeLocalValue(event.scheduledFor));
setEditTakenAt(event.takenAt ? toDateTimeLocalValue(event.takenAt) : "");
setEditSkipped(event.skipped);
setEditError(null);
}
function closeEdit() {
if (updateMutation.isPending || deleteMutation.isPending) return;
setEditing(null);
setEditError(null);
setEditDeleteDialogOpen(false);
}
function closeCreate() {
if (createMutation.isPending) return;
setCreating(false);
setCreateError(null);
}
async function deleteEditingEvent() {
if (!editing) return;
try {
setEditError(null);
await deleteMutation.mutateAsync(editing.id);
closeEdit();
} catch {
setEditError("Fehler beim Löschen");
}
}
async function submitEdit(e: React.FormEvent) {
e.preventDefault();
if (!editing) return;
const scheduledDate = new Date(editScheduledFor);
if (Number.isNaN(scheduledDate.getTime())) {
setEditError("Bitte einen gültigen Zeitpunkt wählen.");
return;
}
setEditError(null);
updateMutation.mutate({
eventId: editing.id,
scheduledFor: dateTimeLocalToISO(editScheduledFor),
takenAt: editSkipped || !editTakenAt
? null
: dateTimeLocalToISO(editTakenAt),
skipped: editSkipped,
});
}
async function submitCreate(e: React.FormEvent) {
e.preventDefault();
const scheduledDate = new Date(createScheduledFor);
if (Number.isNaN(scheduledDate.getTime())) {
setCreateError("Bitte einen gültigen Zeitpunkt wählen.");
return;
}
setCreateError(null);
createMutation.mutate({
scheduledFor: dateTimeLocalToISO(createScheduledFor),
takenAt: createSkipped || !createTakenAt
? null
: dateTimeLocalToISO(createTakenAt),
skipped: createSkipped,
});
}
function getStatusBadge(event: IntakeEvent) {
if (event.skipped) {
return (
<Badge variant="outline" className="text-muted-foreground gap-1">
<SkipForward className="h-3 w-3" />
{t("medications.intakeStatusSkipped")}
</Badge>
);
}
if (event.takenAt) {
return (
<Badge variant="secondary" className="gap-1 bg-green-500/20 text-green-400">
<Check className="h-3 w-3" />
{t("medications.intakeStatusTaken")}
</Badge>
);
}
return (
<Badge variant="secondary" className="gap-1 bg-red-500/20 text-red-400">
<AlertTriangle className="h-3 w-3" />
{t("medications.intakeStatusMissed")}
</Badge>
);
}
if (!isAuthenticated) {
return (
<p className="text-muted-foreground text-sm">
Bitte anmelden, um Einnahmen zu sehen.
</p>
);
}
return (
<>
<div className="space-y-3">
<div className="flex items-center justify-end">
{data?.meta.total !== undefined && (
<span className="text-muted-foreground text-sm">
{t("medications.intakeCount", { count: data.meta.total })}
</span>
)}
</div>
{isLoading ? (
<div className="flex h-32 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !data?.events.length ? (
<div className="text-muted-foreground flex h-32 items-center justify-center rounded-lg border border-dashed">
Noch keine Einnahmen vorhanden
</div>
) : (
<>
{/* Desktop table */}
<div className="bg-card border-border hidden overflow-hidden rounded-lg border md:block">
<Table>
<TableHeader>
<TableRow>
<SortableHead
column="scheduledFor"
label={t("medications.intakeScheduledFor")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
/>
<SortableHead
column="takenAt"
label={t("medications.intakeTakenAt")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
/>
<TableHead className="w-32">{t("medications.intakeStatus")}</TableHead>
<SortableHead
column="source"
label={t("medications.intakeSource")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
className="w-28"
/>
<TableHead className="w-20 pr-4 text-right">
Aktionen
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.events.map((event) => (
<TableRow key={event.id}>
<TableCell className="text-sm tabular-nums">
{formatDateTime(event.scheduledFor)}
</TableCell>
<TableCell className="text-muted-foreground text-sm tabular-nums">
{event.takenAt
? formatDateTime(event.takenAt)
: "—"}
</TableCell>
<TableCell>{getStatusBadge(event)}</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{SOURCE_LABELS[event.source] ?? event.source}
</Badge>
</TableCell>
<TableCell className="pr-4 text-right">
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(event)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
label={t("medications.intakeDeleteConfirm")}
description={t("medications.intakeDeleteDescription")}
onConfirm={() => deleteMutation.mutate(event.id)}
/>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Mobile cards */}
<div className="space-y-2 md:hidden">
{data.events.map((event) => (
<div
key={event.id}
className="bg-card border-border rounded-lg border p-3"
>
<div className="flex items-start justify-between">
<div className="min-w-0 space-y-1">
<p className="text-sm font-medium tabular-nums">
{formatDateTime(event.scheduledFor)}
</p>
{event.takenAt && (
<p className="text-muted-foreground text-xs tabular-nums">
{t("medications.intakeTakenAt")}: {formatDateTime(event.takenAt)}
</p>
)}
<div className="flex items-center gap-1.5">
{getStatusBadge(event)}
<Badge variant="outline" className="text-xs">
{SOURCE_LABELS[event.source] ?? event.source}
</Badge>
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(event)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
label={t("medications.intakeDeleteConfirm")}
description={t("medications.intakeDeleteDescription")}
onConfirm={() => deleteMutation.mutate(event.id)}
/>
</div>
</div>
</div>
))}
</div>
</>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-sm">
Seite {page} von {totalPages}
</span>
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
{/* Edit Dialog */}
<Dialog open={!!editing} onOpenChange={(open) => !open && closeEdit()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("medications.editIntake")}</DialogTitle>
</DialogHeader>
{editing && (
<form onSubmit={submitEdit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="edit-scheduledFor">
{t("medications.intakeScheduledFor")}
</Label>
<Input
id="edit-scheduledFor"
type="datetime-local"
value={editScheduledFor}
onChange={(e) => setEditScheduledFor(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-takenAt">{t("medications.intakeTakenAt")}</Label>
<Input
id="edit-takenAt"
type="datetime-local"
value={editTakenAt}
onChange={(e) => setEditTakenAt(e.target.value)}
disabled={editSkipped}
/>
</div>
<div className="flex items-center gap-2">
<Switch
id="edit-skipped"
checked={editSkipped}
onCheckedChange={(checked) => {
setEditSkipped(checked);
if (checked) setEditTakenAt("");
}}
/>
<Label htmlFor="edit-skipped">
{t("medications.intakeStatusSkipped")}
</Label>
</div>
{editError && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{editError}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem
variant="destructive"
onClick={() => setEditDeleteDialogOpen(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
Löschen
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={closeEdit}
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
Abbrechen
</Button>
<Button
type="submit"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
{updateMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Speichern
</Button>
</div>
</div>
<AlertDialog
open={editDeleteDialogOpen}
onOpenChange={setEditDeleteDialogOpen}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("medications.intakeDeleteConfirm")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("medications.intakeDeleteDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteMutation.isPending}>
Abbrechen
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={deleteEditingEvent}
disabled={deleteMutation.isPending}
>
{deleteMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Löschen
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</form>
)}
</DialogContent>
</Dialog>
{/* Create Dialog */}
<Dialog open={creating} onOpenChange={(open) => !open && closeCreate()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("medications.newIntake")}</DialogTitle>
</DialogHeader>
<form onSubmit={submitCreate} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="create-scheduledFor">
{t("medications.intakeScheduledFor")}
</Label>
<Input
id="create-scheduledFor"
type="datetime-local"
value={createScheduledFor}
onChange={(e) => setCreateScheduledFor(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="create-takenAt">{t("medications.intakeTakenAt")}</Label>
<Input
id="create-takenAt"
type="datetime-local"
value={createTakenAt}
onChange={(e) => setCreateTakenAt(e.target.value)}
disabled={createSkipped}
/>
</div>
<div className="flex items-center gap-2">
<Switch
id="create-skipped"
checked={createSkipped}
onCheckedChange={(checked) => {
setCreateSkipped(checked);
if (checked) setCreateTakenAt("");
}}
/>
<Label htmlFor="create-skipped">
{t("medications.intakeStatusSkipped")}
</Label>
</div>
{createError && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{createError}
</div>
)}
<div className="flex items-center justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={closeCreate}
disabled={createMutation.isPending}
>
Abbrechen
</Button>
<Button type="submit" disabled={createMutation.isPending}>
{createMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
Speichern
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</>
);
}
function SortableHead({
column,
label,
currentSort,
currentDir,
onSort,
className,
}: {
column: string;
label: string;
currentSort: string;
currentDir: "asc" | "desc";
onSort: (col: string) => void;
className?: string;
}) {
const isActive = currentSort === column;
return (
<TableHead className={className}>
<button
type="button"
onClick={() => onSort(column)}
className="hover:text-foreground inline-flex items-center gap-1 transition-colors"
>
{label}
{isActive ? (
currentDir === "asc" ? (
<ArrowUp className="h-3.5 w-3.5" />
) : (
<ArrowDown className="h-3.5 w-3.5" />
)
) : (
<ArrowUpDown className="h-3.5 w-3.5 opacity-40" />
)}
</button>
</TableHead>
);
}
function DeleteButton({
label,
description,
onConfirm,
}: {
label: string;
description: string;
onConfirm: () => void;
}) {
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-destructive h-8 w-8"
aria-label="Löschen"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{label}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={onConfirm}
>
Löschen
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
@@ -0,0 +1,163 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Badge } from "@/components/ui/badge";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Check, SkipForward, Loader2, X } from "lucide-react";
import { formatDateWithWeekday, formatTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
interface IntakeEvent {
id: string;
medicationId: string;
scheduledFor: string;
takenAt: string | null;
skipped: boolean;
source: string;
createdAt: string;
}
interface IntakeTimelineProps {
medicationId: string;
medicationName: string;
}
export function IntakeTimeline({
medicationId,
medicationName,
}: IntakeTimelineProps) {
const queryClient = useQueryClient();
const { t } = useTranslations();
const { data: events, isLoading } = useQuery({
queryKey: ["medications", medicationId, "intake"],
queryFn: async () => {
const res = await fetch(
`/api/medications/${medicationId}/intake?limit=50`,
);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data.events as IntakeEvent[];
},
});
const deleteMutation = useMutation({
mutationFn: async (eventId: string) => {
const res = await fetch(
`/api/medications/${medicationId}/intake/${eventId}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Delete failed");
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "intake"],
});
queryClient.invalidateQueries({
queryKey: ["medications", medicationId, "compliance"],
});
},
});
if (isLoading) {
return (
<div className="flex h-20 items-center justify-center">
<Loader2 className="text-muted-foreground h-4 w-4 animate-spin" />
</div>
);
}
if (!events?.length) {
return (
<p className="text-muted-foreground py-4 text-center text-sm">
{`${t("medications.noIntakesForMedication")} ${medicationName}`}
</p>
);
}
// Group by day
const grouped = new Map<string, IntakeEvent[]>();
for (const event of events) {
const day = formatDateWithWeekday(event.scheduledFor);
const list = grouped.get(day) ?? [];
list.push(event);
grouped.set(day, list);
}
return (
<div className="space-y-2.5">
{[...grouped.entries()].map(([day, dayEvents]) => (
<div key={day} className="space-y-1.5">
<p className="text-muted-foreground text-xs font-medium">{day}</p>
<div className="flex flex-wrap gap-1.5">
{dayEvents.map((event) => (
<div key={event.id} className="group relative inline-flex">
<Badge
variant={event.skipped ? "outline" : "secondary"}
className={
event.skipped
? "text-muted-foreground gap-1 pr-6"
: "gap-1 bg-green-500/20 pr-6 text-green-400"
}
>
{event.skipped ? (
<SkipForward className="h-3 w-3" />
) : (
<Check className="h-3 w-3" />
)}
{formatTime(event.scheduledFor)}
{event.source !== "WEB" && (
<span className="text-[10px] opacity-60">
{event.source}
</span>
)}
</Badge>
<AlertDialog>
<AlertDialogTrigger asChild>
<button
className="text-destructive absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity group-hover:opacity-100"
aria-label={t("medications.deleteIntakeAriaLabel")}
>
<X className="h-3 w-3" />
</button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("medications.intakeDeleteConfirm")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("medications.intakeDeleteDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => deleteMutation.mutate(event.id)}
>
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
))}
</div>
</div>
))}
</div>
);
}
@@ -0,0 +1,568 @@
"use client";
import { useState, useEffect, useReducer } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import { formatDateTime, formatTime } from "@/lib/format";
import {
Check,
SkipForward,
Flame,
Pencil,
Loader2,
History,
} from "lucide-react";
import Link from "next/link";
import { useTranslations } from "@/lib/i18n/context";
interface Schedule {
id: string;
windowStart: string;
windowEnd: string;
label: string | null;
dose: string | null;
daysOfWeek: string | null;
}
interface Medication {
id: string;
name: string;
dose: string;
category: string;
active: boolean;
notificationsEnabled: boolean;
pausedAt: string | null;
lastTakenAt: string | null;
todayEventCount?: number;
schedules: Schedule[];
}
interface ComplianceData {
compliance7: {
totalExpected: number;
taken: number;
skipped: number;
missed: number;
rate: number;
streak: number;
};
compliance30: {
rate: number;
};
}
interface MedicationCardProps {
medication: Medication;
onEdit: (med: Medication) => void;
}
function parseTimeToMinutes(value: string): number {
const [h, m] = value.split(":").map(Number);
if (
!Number.isFinite(h) ||
!Number.isFinite(m) ||
h < 0 ||
h > 23 ||
m < 0 ||
m > 59
) {
return 0;
}
return h * 60 + m;
}
function toBerlinDate(date: Date): Date {
return new Date(
date.toLocaleString("en-US", {
timeZone: "Europe/Berlin",
}),
);
}
function getNextOccurrenceTimestamp(
schedule: Schedule,
nowBerlin: Date,
): number | null {
const recurrence = parseScheduleRecurrence(schedule.daysOfWeek);
const baseDay = new Date(nowBerlin);
baseDay.setHours(0, 0, 0, 0);
const nowMinutes = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
const weekMs = 7 * 24 * 60 * 60 * 1000;
const baseWeekIndex = Math.floor(baseDay.getTime() / weekMs);
const startMinutes = parseTimeToMinutes(schedule.windowStart);
for (let offset = 0; offset <= 400; offset += 1) {
const candidate = new Date(baseDay);
candidate.setDate(baseDay.getDate() + offset);
const candidateWeekIndex = Math.floor(candidate.getTime() / weekMs);
const isAllowedWeek =
recurrence.intervalWeeks <= 1 ||
candidateWeekIndex % recurrence.intervalWeeks ===
baseWeekIndex % recurrence.intervalWeeks;
if (!isAllowedWeek) continue;
if (
recurrence.daysOfWeek.length > 0 &&
!recurrence.daysOfWeek.includes(candidate.getDay())
) {
continue;
}
if (offset === 0 && startMinutes <= nowMinutes) {
continue;
}
return candidate.getTime() + startMinutes * 60 * 1000;
}
return null;
}
type MedicationWindowStatus = "in_window" | "late" | "very_late" | null;
function getWindowStatus(
schedule: Schedule,
nowBerlin: Date,
lateMinutes: number,
missedMinutes: number,
): MedicationWindowStatus {
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedNow =
nowMins < startMins && endMins > 24 * 60 ? nowMins + 24 * 60 : nowMins;
// Currently in window
if (adjustedNow >= startMins && adjustedNow <= endMins) return "in_window";
// Past window end: check late thresholds
const minutesPastEnd = adjustedNow - endMins;
if (minutesPastEnd > 0 && minutesPastEnd <= lateMinutes) return "late";
if (minutesPastEnd > lateMinutes && minutesPastEnd <= missedMinutes)
return "very_late";
return null;
}
function isLastIntakeInCurrentWindow(
lastTakenAt: string | null,
schedule: Schedule,
nowBerlin: Date,
): boolean {
if (!lastTakenAt) return false;
const intake = toBerlinDate(new Date(lastTakenAt));
// Must be same calendar day
if (
intake.getFullYear() !== nowBerlin.getFullYear() ||
intake.getMonth() !== nowBerlin.getMonth() ||
intake.getDate() !== nowBerlin.getDate()
) {
return false;
}
const intakeMins = intake.getHours() * 60 + intake.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedIntake =
intakeMins < startMins && endMins > 24 * 60
? intakeMins + 24 * 60
: intakeMins;
return adjustedIntake >= startMins && adjustedIntake <= endMins;
}
export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
const queryClient = useQueryClient();
const { t } = useTranslations();
const [intakeLoading, setIntakeLoading] = useState<string | null>(null);
const { data: compliance } = useQuery({
queryKey: ["medications", medication.id, "compliance"],
queryFn: async () => {
const res = await fetch(`/api/medications/${medication.id}/compliance`);
if (!res.ok) return null;
const json = await res.json();
return json.data as ComplianceData;
},
staleTime: 30 * 1000,
});
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
const { data: thresholds } = useQuery({
queryKey: ["settings", "reminder-thresholds"],
queryFn: async () => {
const res = await fetch("/api/settings/reminder-thresholds");
if (!res.ok) return null;
const json = await res.json();
return json.data as { lateMinutes: number; missedMinutes: number };
},
staleTime: 5 * 60 * 1000,
});
useEffect(() => {
const interval = setInterval(forceUpdate, 60_000);
return () => clearInterval(interval);
}, []);
async function recordIntake(skipped: boolean) {
const key = skipped ? "skip" : "take";
setIntakeLoading(key);
try {
const res = await fetch(`/api/medications/${medication.id}/intake`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ skipped }),
});
if (res.ok) {
await queryClient.invalidateQueries({
queryKey: ["medications"],
});
await queryClient.invalidateQueries({
queryKey: ["gamification", "achievements"],
});
}
} finally {
setIntakeLoading(null);
}
}
const rate7 = compliance?.compliance7.rate ?? 0;
const rate30 = compliance?.compliance30.rate ?? 0;
const streak = compliance?.compliance7.streak ?? 0;
const categoryLabels: Record<string, string> = {
BLOOD_PRESSURE: t("medications.categoryBloodPressure"),
VITAMIN: t("medications.categoryVitamin"),
SUPPLEMENT: t("medications.categorySupplement"),
PAIN_RELIEF: t("medications.categoryPainRelief"),
ALLERGY: t("medications.categoryAllergy"),
DIGESTIVE: t("medications.categoryDigestive"),
THYROID: t("medications.categoryThyroid"),
HORMONE: t("medications.categoryHormone"),
SKIN: t("medications.categorySkin"),
SLEEP_AID: t("medications.categorySleepAid"),
OTHER: t("medications.categoryOther"),
};
const categoryLabel =
categoryLabels[medication.category] ?? t("medications.categoryOther");
const sortedSchedules = [...medication.schedules].sort(
(a, b) =>
a.windowStart.localeCompare(b.windowStart) ||
a.windowEnd.localeCompare(b.windowEnd),
);
const nowBerlin = toBerlinDate(new Date());
const nextOccurrence =
sortedSchedules.length > 0
? (sortedSchedules
.map((schedule) => ({
schedule,
nextAt: getNextOccurrenceTimestamp(schedule, nowBerlin),
}))
.filter((entry): entry is { schedule: Schedule; nextAt: number } =>
Number.isFinite(entry.nextAt),
)
.sort((a, b) => a.nextAt - b.nextAt)[0] ?? null)
: null;
const nextSchedule = nextOccurrence?.schedule ?? sortedSchedules[0] ?? null;
const lateMinutes = thresholds?.lateMinutes ?? 120;
const missedMinutes = thresholds?.missedMinutes ?? 240;
// Count schedules that are past their window (overdue today)
const passedScheduleCount = medication.active
? sortedSchedules.filter((s) => {
const recurrence = parseScheduleRecurrence(s.daysOfWeek);
if (
recurrence.daysOfWeek.length > 0 &&
!recurrence.daysOfWeek.includes(nowBerlin.getDay())
) {
return false;
}
const endMins = parseTimeToMinutes(s.windowEnd);
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
return nowMins > endMins;
}).length
: 0;
const todayEvents = medication.todayEventCount ?? 0;
const hasUncoveredOverdue = todayEvents < passedScheduleCount;
const currentWindowStatus = medication.active
? sortedSchedules.reduce<{
status: MedicationWindowStatus;
schedule: Schedule | null;
}>(
(best, s) => {
const status = getWindowStatus(
s,
nowBerlin,
lateMinutes,
missedMinutes,
);
if (!status) return best;
// Don't show late/very_late if all overdue schedules are covered by events
if (status !== "in_window" && !hasUncoveredOverdue) return best;
// Don't show in_window if last intake is already within this window today
if (status === "in_window" && isLastIntakeInCurrentWindow(medication.lastTakenAt, s, nowBerlin)) return best;
const priority = { in_window: 3, late: 2, very_late: 1 };
if (!best.status || priority[status] > priority[best.status]) {
return { status, schedule: s };
}
return best;
},
{ status: null, schedule: null },
)
: { status: null, schedule: null };
function formatLastTakenAt(value: string): string {
const dayFormatter = new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const now = new Date();
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const intakeDay = dayFormatter.format(new Date(value));
const todayDay = dayFormatter.format(now);
const yesterdayDay = dayFormatter.format(yesterday);
const time = formatTime(value);
if (intakeDay === todayDay) return `${t("medications.today")}, ${time}`;
if (intakeDay === yesterdayDay)
return `${t("medications.yesterday")}, ${time}`;
return formatDateTime(value);
}
return (
<Card className={medication.active ? "" : "opacity-60"}>
<CardHeader className="pb-2.5">
<div className="flex items-start justify-between">
<div className="space-y-1">
<CardTitle className="text-lg">{medication.name}</CardTitle>
<div className="text-muted-foreground flex items-center gap-2 text-sm">
<span>{medication.dose}</span>
<Badge variant="outline" className="text-xs">
{categoryLabel}
</Badge>
{!medication.notificationsEnabled && (
<Badge variant="secondary" className="text-xs">
{t("medications.withoutNotification")}
</Badge>
)}
{!medication.active && (
<Badge variant="secondary" className="text-xs">
{medication.pausedAt
? `${t("medications.pausedSince")} ${formatDateTime(medication.pausedAt)}`
: t("medications.inactive")}
</Badge>
)}
</div>
</div>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-8 w-8" asChild aria-label={t("medications.intakeHistory")}>
<Link href={`/medications/${medication.id}/history`}>
<History className="h-3.5 w-3.5" />
</Link>
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => onEdit(medication)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
</div>
</div>
</CardHeader>
<CardContent className="space-y-3.5">
{/* Status, last & next intake info */}
{currentWindowStatus.status && (
<p className="text-sm">
<span
className={
currentWindowStatus.status === "in_window"
? "text-dracula-green font-medium"
: currentWindowStatus.status === "late"
? "text-dracula-yellow font-medium"
: "text-dracula-orange font-medium"
}
>
{currentWindowStatus.status === "in_window"
? t("medications.takeNow")
: currentWindowStatus.status === "late"
? t("medications.overdue")
: t("medications.veryOverdue")}
</span>
<span className="text-muted-foreground hidden sm:inline">
{" "}
—{" "}
{formatTimeWindowRange(
currentWindowStatus.schedule!.windowStart,
currentWindowStatus.schedule!.windowEnd,
)}
</span>
</p>
)}
{nextSchedule &&
currentWindowStatus.status !== "in_window" &&
(() => {
const s = nextSchedule;
const nextAt = nextOccurrence?.nextAt;
// Format day label relative to today
let dayLabel = "";
if (nextAt) {
const nextDate = toBerlinDate(new Date(nextAt));
const todayStr = `${nowBerlin.getFullYear()}-${nowBerlin.getMonth()}-${nowBerlin.getDate()}`;
const nextStr = `${nextDate.getFullYear()}-${nextDate.getMonth()}-${nextDate.getDate()}`;
const tomorrow = new Date(nowBerlin);
tomorrow.setDate(tomorrow.getDate() + 1);
const tomorrowStr = `${tomorrow.getFullYear()}-${tomorrow.getMonth()}-${tomorrow.getDate()}`;
const diffDays = Math.round(
(nextDate.getTime() - nowBerlin.getTime()) /
(24 * 60 * 60 * 1000),
);
if (nextStr === todayStr) {
dayLabel = t("medications.today");
} else if (nextStr === tomorrowStr) {
dayLabel = t("medications.tomorrow");
} else if (diffDays <= 5) {
const weekdayLabels = [
t("medications.weekdaySunday"),
t("medications.weekdayMonday"),
t("medications.weekdayTuesday"),
t("medications.weekdayWednesday"),
t("medications.weekdayThursday"),
t("medications.weekdayFriday"),
t("medications.weekdaySaturday"),
];
dayLabel = weekdayLabels[nextDate.getDay()];
} else {
dayLabel = nextDate.toLocaleDateString("de-DE", {
weekday: "short",
day: "numeric",
month: "short",
});
}
}
return (
<p className="text-muted-foreground text-sm">
<span className="font-medium">
{t("medications.nextIntake")}
</span>{" "}
{dayLabel && `${dayLabel}, `}
{formatTimeWindowRange(s.windowStart, s.windowEnd)}
{s.label && (
<span className="hidden sm:inline"> ({s.label})</span>
)}
{s.dose && (
<span className="hidden font-medium text-purple-400 sm:inline">
{" "}
— {s.dose}
</span>
)}
</p>
);
})()}
{medication.lastTakenAt && (
<p className="text-muted-foreground text-sm">
<span className="font-medium">{t("medications.lastIntake")}</span>{" "}
{formatLastTakenAt(medication.lastTakenAt)}
</p>
)}
{/* Compliance bar */}
{medication.active && compliance && (
<div className="space-y-2.5">
<div className="space-y-1.5">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{t("medications.compliance7d")}
</span>
<span className="font-medium">{rate7}%</span>
</div>
<Progress value={rate7} className="h-2" />
</div>
<div className="space-y-1.5">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{t("medications.compliance30d")}
</span>
<span className="font-medium">{rate30}%</span>
</div>
<Progress value={rate30} className="h-2" />
</div>
<div className="flex items-center gap-4 text-xs">
{streak > 0 && (
<span className="flex items-center gap-1 font-medium text-orange-400">
<Flame className="h-3.5 w-3.5" />
{streak} {t("medications.dayStreak")}
</span>
)}
</div>
</div>
)}
{/* Quick actions */}
{medication.active && (
<div className="flex gap-2">
<Button
size="sm"
className="flex-1"
onClick={() => recordIntake(false)}
disabled={!!intakeLoading}
>
{intakeLoading === "take" ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<Check className="mr-1 h-3.5 w-3.5" />
)}
{t("medications.taken")}
</Button>
<Button
size="sm"
variant="outline"
onClick={() => recordIntake(true)}
disabled={!!intakeLoading}
>
{intakeLoading === "skip" ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<SkipForward className="mr-1 h-3.5 w-3.5" />
)}
{t("medications.skipped")}
</Button>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,902 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
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 {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Bell,
BellOff,
Clock,
Eraser,
Loader2,
MoreHorizontal,
MoreVertical,
Pause,
Play,
Plus,
RotateCcw,
Settings2,
Terminal,
Trash2,
Upload,
} from "lucide-react";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { PhaseConfigDialog } from "@/components/medications/phase-config-dialog";
const DOSE_UNITS = [
"mg",
"g",
"ml",
"Tropfen",
"Tablette(n)",
"Kapsel(n)",
"Stück",
"IE",
"µg",
] as const;
type TranslateFn = (
key: string,
params?: Record<string, string | number>,
) => string;
function getDayLabelsShort(t: TranslateFn): string[] {
return [
t("medications.daysSun"),
t("medications.daysMon"),
t("medications.daysTue"),
t("medications.daysWed"),
t("medications.daysThu"),
t("medications.daysFri"),
t("medications.daysSat"),
];
}
function getDayLabelsLong(t: TranslateFn): string[] {
return [
t("medications.weekdaySundayPlural"),
t("medications.weekdayMondayPlural"),
t("medications.weekdayTuesdayPlural"),
t("medications.weekdayWednesdayPlural"),
t("medications.weekdayThursdayPlural"),
t("medications.weekdayFridayPlural"),
t("medications.weekdaySaturdayPlural"),
];
}
function getNextRecurrenceDate(schedule: Schedule): Date | null {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const weekMs = 7 * 24 * 60 * 60 * 1000;
const startWeekIndex = Math.floor(start.getTime() / weekMs);
for (let offset = 0; offset <= 400; offset++) {
const candidate = new Date(start);
candidate.setDate(start.getDate() + offset);
const candidateWeekIndex = Math.floor(candidate.getTime() / weekMs);
const isIntervalWeek =
schedule.intervalWeeks <= 1 ||
candidateWeekIndex % schedule.intervalWeeks ===
startWeekIndex % schedule.intervalWeeks;
if (!isIntervalWeek) continue;
if (
schedule.daysOfWeek.length === 0 ||
schedule.daysOfWeek.includes(candidate.getDay())
) {
return candidate;
}
}
return null;
}
function formatRecurrenceSummary(schedule: Schedule, t: TranslateFn): string {
const dayLabelsShort = getDayLabelsShort(t);
const dayLabelsLong = getDayLabelsLong(t);
const dayText =
schedule.daysOfWeek.length === 0
? t("medications.scheduleDaily")
: schedule.daysOfWeek.length === 1
? dayLabelsLong[schedule.daysOfWeek[0]]
: schedule.daysOfWeek.map((day) => dayLabelsShort[day]).join(", ");
const intervalText =
schedule.intervalWeeks === 1
? t("medications.scheduleEveryWeek")
: `${t("medications.scheduleEveryNWeeks").replace("{n}", String(schedule.intervalWeeks))}`;
return `${t("medications.scheduleIntervalPrefix")} ${dayText} - ${intervalText}`;
}
function formatNextWindowSummary(schedule: Schedule, t: TranslateFn): string {
const isSimpleDaily =
schedule.daysOfWeek.length === 0 && schedule.intervalWeeks === 1;
if (isSimpleDaily) {
return `${t("medications.nextSchedulePrefix")} ${t("medications.nextScheduleDaily")}, ${formatTimeWindowRange(schedule.windowStart, schedule.windowEnd)}`;
}
const nextDate = getNextRecurrenceDate(schedule);
const nextText = nextDate
? `${new Intl.DateTimeFormat("de-DE", {
day: "2-digit",
month: "2-digit",
}).format(
nextDate,
)}, ${formatTimeWindowRange(schedule.windowStart, schedule.windowEnd)}`
: "—";
return `${t("medications.nextSchedulePrefix")} ${nextText}`;
}
interface Schedule {
windowStart: string;
windowEnd: string;
label: string;
dose: string;
daysOfWeek: number[];
intervalWeeks: number;
showAdvanced: boolean;
}
interface MedicationFormProps {
onSuccess?: () => void;
onCancel?: () => void;
editActions?: {
onImportIntakes: () => void;
onApiAccess: () => void;
};
initial?: {
id: string;
name: string;
dose: string;
category: string;
active: boolean;
notificationsEnabled?: boolean;
schedules: Array<{
windowStart: string;
windowEnd: string;
label: string;
dose: string;
daysOfWeek?: number[];
intervalWeeks?: number;
}>;
};
}
const DEFAULT_SCHEDULE: Schedule = {
windowStart: "08:00",
windowEnd: "09:00",
label: "",
dose: "",
daysOfWeek: [],
intervalWeeks: 1,
showAdvanced: false,
};
/** Try to split "400mg" into ["400", "mg"] */
function parseDose(dose: string): { amount: string; unit: string } {
const match = /^(\d+(?:[.,]\d+)?)\s*(.*)$/.exec(dose.trim());
if (match) return { amount: match[1], unit: match[2] };
return { amount: "", unit: dose };
}
function parseTimeToMinutes(value: string): number | null {
const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value);
if (!m) return null;
return Number(m[1]) * 60 + Number(m[2]);
}
function sortSchedules(list: Schedule[]): Schedule[] {
return [...list]
.map((schedule, index) => ({ schedule, index }))
.sort((a, b) => {
const aStart = parseTimeToMinutes(a.schedule.windowStart);
const bStart = parseTimeToMinutes(b.schedule.windowStart);
if (aStart === null && bStart === null) return a.index - b.index;
if (aStart === null) return 1;
if (bStart === null) return -1;
if (aStart !== bStart) return aStart - bStart;
const aEnd = parseTimeToMinutes(a.schedule.windowEnd);
const bEnd = parseTimeToMinutes(b.schedule.windowEnd);
if (aEnd === null && bEnd === null) return a.index - b.index;
if (aEnd === null) return 1;
if (bEnd === null) return -1;
if (aEnd !== bEnd) return aEnd - bEnd;
return a.index - b.index;
})
.map((item) => item.schedule);
}
export function MedicationForm({
onSuccess,
onCancel,
editActions,
initial,
}: MedicationFormProps) {
const queryClient = useQueryClient();
const { t } = useTranslations();
const [name, setName] = useState(initial?.name ?? "");
const initialDose = parseDose(initial?.dose ?? "");
const [doseAmount, setDoseAmount] = useState(initialDose.amount);
const [doseUnit, setDoseUnit] = useState(initialDose.unit);
const [category, setCategory] = useState(initial?.category ?? "OTHER");
const [active, setActive] = useState(initial?.active ?? true);
const [notificationsEnabled, setNotificationsEnabled] = useState(
initial?.notificationsEnabled ?? true,
);
const [schedules, setSchedules] = useState<Schedule[]>(
sortSchedules(
initial?.schedules.length
? initial.schedules.map((s) => {
const recurrence = {
daysOfWeek: s.daysOfWeek ?? [],
intervalWeeks: s.intervalWeeks ?? 1,
};
const hasCustomRecurrence =
recurrence.daysOfWeek.length > 0 || recurrence.intervalWeeks > 1;
return {
...s,
daysOfWeek: recurrence.daysOfWeek,
intervalWeeks: recurrence.intervalWeeks,
showAdvanced: hasCustomRecurrence,
};
})
: [{ ...DEFAULT_SCHEDULE }],
),
);
const [loading, setLoading] = useState(false);
const [deleting, setDeleting] = useState(false);
const [purging, setPurging] = useState(false);
const [error, setError] = useState<string | null>(null);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [purgeDialogOpen, setPurgeDialogOpen] = useState(false);
const [phaseConfigOpen, setPhaseConfigOpen] = useState(false);
const isEdit = !!initial;
const dose = doseAmount
? `${doseAmount}${doseUnit ? ` ${doseUnit}` : ""}`
: doseUnit;
function updateSchedule(
index: number,
field: keyof Schedule,
value: string | number[] | number | boolean,
) {
setSchedules((prev) =>
sortSchedules(
prev.map((s, i) => (i === index ? { ...s, [field]: value } : s)),
),
);
}
function toggleDay(scheduleIndex: number, day: number) {
setSchedules((prev) =>
prev.map((s, i) => {
if (i !== scheduleIndex) return s;
const days = s.daysOfWeek.includes(day)
? s.daysOfWeek.filter((d) => d !== day)
: [...s.daysOfWeek, day].sort();
return { ...s, daysOfWeek: days };
}),
);
}
function addSchedule() {
setSchedules((prev) => sortSchedules([...prev, { ...DEFAULT_SCHEDULE }]));
}
function toggleAdvanced(scheduleIndex: number) {
setSchedules((prev) =>
prev.map((s, i) =>
i === scheduleIndex ? { ...s, showAdvanced: !s.showAdvanced } : s,
),
);
}
function removeSchedule(index: number) {
if (schedules.length <= 1) return;
setSchedules((prev) => prev.filter((_, i) => i !== index));
}
function resetCreateForm() {
if (isEdit) return;
setName("");
setDoseAmount("");
setDoseUnit("");
setCategory("OTHER");
setActive(true);
setNotificationsEnabled(true);
setSchedules([{ ...DEFAULT_SCHEDULE }]);
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
const url = isEdit ? `/api/medications/${initial.id}` : "/api/medications";
const method = isEdit ? "PUT" : "POST";
try {
const res = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
dose,
category,
...(isEdit
? {
active,
...(notificationsEnabled !==
(initial?.notificationsEnabled ?? true) && {
notificationsEnabled,
}),
}
: {}),
schedules: sortSchedules(schedules).map((s) => ({
windowStart: s.windowStart,
windowEnd: s.windowEnd,
label: s.label || undefined,
dose: s.dose || undefined,
daysOfWeek: s.daysOfWeek.length > 0 ? s.daysOfWeek : undefined,
intervalWeeks: s.intervalWeeks,
})),
}),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
await queryClient.invalidateQueries({ queryKey: ["medications"] });
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("medications.saveError"));
} finally {
setLoading(false);
}
}
async function handleDelete() {
if (!initial) return;
setError(null);
setDeleting(true);
try {
const res = await fetch(`/api/medications/${initial.id}`, {
method: "DELETE",
});
const json = await res.json().catch(() => null);
if (!res.ok) {
setError(json?.error ?? t("medications.deleteError"));
return;
}
await queryClient.invalidateQueries({ queryKey: ["medications"] });
onSuccess?.();
} catch {
setError(t("medications.deleteError"));
} finally {
setDeleting(false);
}
}
async function handlePurge() {
if (!initial) return;
setError(null);
setPurging(true);
try {
const res = await fetch(`/api/medications/${initial.id}/intake/purge`, {
method: "DELETE",
});
const json = await res.json().catch(() => null);
if (!res.ok) {
setError(json?.error ?? t("medications.purgeError"));
return;
}
await queryClient.invalidateQueries({ queryKey: ["medications"] });
setPurgeDialogOpen(false);
} catch {
setError(t("medications.purgeError"));
} finally {
setPurging(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="med-name">{t("medications.name")}</Label>
<Input
id="med-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="z.B. Ibuprofen"
required
maxLength={100}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="med-category">{t("medications.formType")}</Label>
<Select value={category} onValueChange={setCategory}>
<SelectTrigger id="med-category" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="BLOOD_PRESSURE">
{t("medications.categoryBloodPressure")}
</SelectItem>
<SelectItem value="VITAMIN">
{t("medications.categoryVitamin")}
</SelectItem>
<SelectItem value="SUPPLEMENT">
{t("medications.categorySupplement")}
</SelectItem>
<SelectItem value="PAIN_RELIEF">
{t("medications.categoryPainRelief")}
</SelectItem>
<SelectItem value="ALLERGY">
{t("medications.categoryAllergy")}
</SelectItem>
<SelectItem value="DIGESTIVE">
{t("medications.categoryDigestive")}
</SelectItem>
<SelectItem value="THYROID">
{t("medications.categoryThyroid")}
</SelectItem>
<SelectItem value="HORMONE">
{t("medications.categoryHormone")}
</SelectItem>
<SelectItem value="SKIN">
{t("medications.categorySkin")}
</SelectItem>
<SelectItem value="SLEEP_AID">
{t("medications.categorySleepAid")}
</SelectItem>
<SelectItem value="OTHER">
{t("medications.categoryOther")}
</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label htmlFor="med-dose-amount">{t("medications.formDose")}</Label>
<Input
id="med-dose-amount"
type="text"
inputMode="decimal"
value={doseAmount}
onChange={(e) => setDoseAmount(e.target.value)}
placeholder="z.B. 400"
required
maxLength={20}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="med-dose-unit">{t("medications.formUnit")}</Label>
<Input
id="med-dose-unit"
list="dose-units"
value={doseUnit}
onChange={(e) => setDoseUnit(e.target.value)}
placeholder="mg"
maxLength={30}
className="w-full"
/>
</div>
</div>
<datalist id="dose-units">
{DOSE_UNITS.map((u) => (
<option key={u} value={u} />
))}
</datalist>
<div className="space-y-2">
<div className="flex h-8 items-center justify-between">
<Label className="text-sm leading-none">
{t("medications.formSchedule")}
</Label>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8"
onClick={addSchedule}
>
<Plus className="mr-1 h-3.5 w-3.5" />
{t("medications.newSchedule")}
</Button>
</div>
{schedules.map((s, i) => (
<div
key={i}
className="bg-card border-border/70 rounded-xl border p-3.5"
>
<div className="flex items-center justify-between">
<p className="flex-1 pr-2 pl-1 text-xs leading-5 break-words">
<span className="font-medium">
{s.label.trim() ||
`${t("medications.formSchedule")} ${i + 1}`}
</span>{" "}
<span className="text-foreground/70 font-normal">
({formatNextWindowSummary(s, t)})
</span>
</p>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={t("common.moreOptions")}
>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => toggleAdvanced(i)}>
<Settings2 className="mr-2 h-4 w-4" />
{s.showAdvanced
? t("medications.advancedEditingHide")
: t("medications.advancedEditing")}
</DropdownMenuItem>
{schedules.length > 1 && (
<DropdownMenuItem
variant="destructive"
onClick={() => removeSchedule(i)}
>
<Trash2 className="mr-2 h-4 w-4" />
{t("medications.removeSchedule")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="mt-1 grid items-end gap-2 sm:grid-cols-2 xl:grid-cols-4">
<div className="space-y-1.5">
<Label className="text-xs font-normal">
{t("medications.scheduleFrom")}
</Label>
<Input
type="text"
inputMode="numeric"
pattern="[0-2][0-9]:[0-5][0-9]"
placeholder="08:00"
value={s.windowStart}
className="h-8 text-xs md:text-xs"
onChange={(e) =>
updateSchedule(i, "windowStart", e.target.value)
}
required
maxLength={5}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-normal">
{t("medications.scheduleTo")}
</Label>
<Input
type="text"
inputMode="numeric"
pattern="[0-2][0-9]:[0-5][0-9]"
placeholder="09:00"
value={s.windowEnd}
className="h-8 text-xs md:text-xs"
onChange={(e) =>
updateSchedule(i, "windowEnd", e.target.value)
}
required
maxLength={5}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-normal">
{t("medications.scheduleLabel")}
</Label>
<Input
value={s.label}
className="h-8 text-xs md:text-xs"
onChange={(e) => updateSchedule(i, "label", e.target.value)}
placeholder="z.B. Morgens"
maxLength={50}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs font-normal">
{t("medications.dose")}
</Label>
<Input
value={s.dose}
className="h-8 text-xs md:text-xs"
onChange={(e) => updateSchedule(i, "dose", e.target.value)}
placeholder={dose || "Standard"}
maxLength={50}
/>
</div>
</div>
{s.showAdvanced && (
<p className="text-muted-foreground mt-2 pl-1 text-xs leading-4">
{formatRecurrenceSummary(s, t)}
</p>
)}
{/* Day-of-week selection */}
{s.showAdvanced && (
<div className="border-border/60 mt-2.5 space-y-2.5 border-t pt-2.5">
<div className="space-y-1.5">
<Label className="text-sm">
{t("medications.scheduleInterval")}
</Label>
<div className="grid grid-cols-4 gap-1">
{[1, 2, 3, 4].map((weeks) => (
<button
key={weeks}
type="button"
onClick={() =>
updateSchedule(i, "intervalWeeks", weeks)
}
className={`h-8 rounded-md border text-xs font-medium transition-colors ${
s.intervalWeeks === weeks
? "border-primary bg-primary text-primary-foreground"
: "border-border/70 bg-muted text-foreground/70 hover:bg-accent hover:text-foreground"
}`}
>
{weeks}W
</button>
))}
</div>
</div>
<div className="space-y-1.5">
<Label className="text-sm">
{t("medications.scheduleDays")}
</Label>
<div className="flex w-full gap-1">
<button
type="button"
onClick={() => updateSchedule(i, "daysOfWeek", [])}
className={`h-8 min-w-24 rounded-md border px-3 text-xs font-medium transition-colors ${
s.daysOfWeek.length === 0
? "border-primary bg-primary text-primary-foreground"
: "border-border/70 bg-muted text-foreground/70 hover:bg-accent hover:text-foreground"
}`}
>
{t("medications.scheduleDaily")}
</button>
{getDayLabelsShort(t).map((label, dayIndex) => {
const isSelected = s.daysOfWeek.includes(dayIndex);
return (
<button
key={dayIndex}
type="button"
onClick={() => toggleDay(i, dayIndex)}
className={`h-8 flex-1 rounded-md border text-xs font-medium transition-colors ${
isSelected
? "border-primary bg-primary text-primary-foreground"
: "border-border/70 bg-muted text-foreground/75 hover:bg-accent hover:text-foreground"
}`}
title={
s.daysOfWeek.includes(dayIndex)
? `${label} deaktivieren`
: `${label} aktivieren`
}
>
{label}
</button>
);
})}
</div>
</div>
</div>
)}
</div>
))}
</div>
{error && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{error}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={loading || deleting}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{isEdit ? (
<>
{editActions && (
<>
<DropdownMenuItem onClick={editActions.onImportIntakes}>
<Upload className="mr-2 h-4 w-4" />
{t("medications.importIntakesAction")}
</DropdownMenuItem>
<DropdownMenuItem onClick={editActions.onApiAccess}>
<Terminal className="mr-2 h-4 w-4" />
{t("medications.apiEndpointAction")}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setPhaseConfigOpen(true)}>
<Clock className="mr-2 h-4 w-4" />
{t("medications.phaseConfig")}
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
<DropdownMenuItem onClick={() => setActive((prev) => !prev)}>
{active ? (
<Pause className="mr-2 h-4 w-4" />
) : (
<Play className="mr-2 h-4 w-4" />
)}
{active ? t("medications.pause") : t("medications.activate")}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setNotificationsEnabled((prev) => !prev)}
>
{notificationsEnabled ? (
<BellOff className="mr-2 h-4 w-4" />
) : (
<Bell className="mr-2 h-4 w-4" />
)}
{notificationsEnabled
? t("medications.disableNotifications")
: t("medications.enableNotifications")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() => setPurgeDialogOpen(true)}
>
<Eraser className="mr-2 h-4 w-4" />
{t("medications.purgeRecords")}
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => setDeleteDialogOpen(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
{t("common.delete")}
</DropdownMenuItem>
</>
) : (
<DropdownMenuItem onClick={resetCreateForm}>
<RotateCcw className="mr-2 h-4 w-4" />
{t("medications.formReset")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={loading || deleting}
>
{t("common.cancel")}
</Button>
)}
<Button type="submit" disabled={loading || deleting}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isEdit ? t("common.save") : t("medications.createMedication")}
</Button>
</div>
</div>
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("medications.deleteConfirm")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("medications.deleteConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={handleDelete}
>
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={purgeDialogOpen} onOpenChange={setPurgeDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("medications.purgeConfirmTitle")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("medications.purgeConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={purging}>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={handlePurge}
disabled={purging}
>
{purging ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("medications.purgeRecords")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{isEdit && initial?.id && (
<PhaseConfigDialog
medicationId={initial.id}
open={phaseConfigOpen}
onOpenChange={setPhaseConfigOpen}
/>
)}
</form>
);
}
@@ -0,0 +1,239 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2, RotateCcw } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
interface PhaseConfigData {
greenValue: number;
greenMode: "MINUTES" | "PERCENT";
yellowValue: number;
yellowMode: "MINUTES" | "PERCENT";
orangeValue: number;
orangeMode: "MINUTES" | "PERCENT";
redValue: number;
redMode: "MINUTES" | "PERCENT";
}
const DEFAULTS: PhaseConfigData = {
greenValue: 60,
greenMode: "MINUTES",
yellowValue: 30,
yellowMode: "MINUTES",
orangeValue: 0,
orangeMode: "MINUTES",
redValue: 240,
redMode: "MINUTES",
};
interface PhaseConfigDialogProps {
medicationId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
type PhaseKey = "green" | "yellow" | "orange" | "red";
const PHASES: {
key: PhaseKey;
color: string;
dotClass: string;
direction: "before" | "after";
}[] = [
{ key: "green", color: "green", dotClass: "bg-green-500", direction: "before" },
{ key: "yellow", color: "yellow", dotClass: "bg-yellow-500", direction: "before" },
{ key: "orange", color: "orange", dotClass: "bg-orange-500", direction: "after" },
{ key: "red", color: "red", dotClass: "bg-red-500", direction: "after" },
];
export function PhaseConfigDialog({
medicationId,
open,
onOpenChange,
}: PhaseConfigDialogProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const [localForm, setLocalForm] = useState<PhaseConfigData | null>(null);
const [statusMessage, setStatusMessage] = useState<string | null>(null);
const { data, isLoading } = useQuery({
queryKey: ["phase-config", medicationId],
queryFn: async () => {
const res = await fetch(`/api/medications/${medicationId}/phase-config`);
const json = await res.json();
return json.data as PhaseConfigData;
},
enabled: open,
});
// Use local overrides if user has edited, otherwise use fetched data or defaults
const form = localForm ?? data ?? DEFAULTS;
const saveMutation = useMutation({
mutationFn: async (config: PhaseConfigData) => {
const res = await fetch(`/api/medications/${medicationId}/phase-config`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(config),
});
if (!res.ok) throw new Error("Save failed");
return res.json();
},
onSuccess: () => {
setLocalForm(null);
queryClient.invalidateQueries({ queryKey: ["phase-config", medicationId] });
setStatusMessage(t("medications.phaseSaved"));
setTimeout(() => setStatusMessage(null), 2000);
},
});
const resetMutation = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/medications/${medicationId}/phase-config`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Reset failed");
return res.json();
},
onSuccess: () => {
setLocalForm(null);
queryClient.invalidateQueries({ queryKey: ["phase-config", medicationId] });
setStatusMessage(t("medications.phaseReset"));
setTimeout(() => setStatusMessage(null), 2000);
},
});
function updateValue(phase: PhaseKey, value: number) {
const valueKey = `${phase}Value` as keyof PhaseConfigData;
setLocalForm({ ...form, [valueKey]: value });
}
function toggleMode(phase: PhaseKey) {
const modeKey = `${phase}Mode` as keyof PhaseConfigData;
setLocalForm({
...form,
[modeKey]: form[modeKey] === "MINUTES" ? "PERCENT" : "MINUTES",
});
}
const phaseLabel = (key: PhaseKey): string => {
switch (key) {
case "green": return t("medications.phaseGreen");
case "yellow": return t("medications.phaseYellow");
case "orange": return t("medications.phaseOrange");
case "red": return t("medications.phaseRed");
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t("medications.phaseConfig")}</DialogTitle>
<DialogDescription>
{t("medications.phaseConfigDescription")}
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : (
<div className="space-y-3">
{PHASES.map(({ key, dotClass, direction }) => {
const valueKey = `${key}Value` as keyof PhaseConfigData;
const modeKey = `${key}Mode` as keyof PhaseConfigData;
const value = form[valueKey] as number;
const mode = form[modeKey] as "MINUTES" | "PERCENT";
return (
<div key={key} className="flex items-center gap-2">
<div className={`h-3 w-3 rounded-full ${dotClass} shrink-0`} />
<span className="w-14 text-sm font-medium shrink-0">
{phaseLabel(key)}
</span>
<Input
type="number"
min={0}
max={1440}
value={value}
onChange={(e) =>
updateValue(key, parseInt(e.target.value, 10) || 0)
}
className="w-20 h-8 text-sm"
/>
<Button
type="button"
variant="outline"
size="sm"
className="h-8 w-12 text-xs px-0"
onClick={() => toggleMode(key)}
>
{mode === "MINUTES"
? t("medications.phaseMinutes")
: t("medications.phasePercent")}
</Button>
<span className="text-muted-foreground text-xs shrink-0">
{direction === "before"
? t("medications.phaseBeforeEnd")
: t("medications.phaseAfterEnd")}
</span>
</div>
);
})}
</div>
)}
{statusMessage && (
<div className="text-sm text-green-500 text-center">
{statusMessage}
</div>
)}
<DialogFooter className="flex-row justify-between sm:justify-between gap-2">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => resetMutation.mutate()}
disabled={resetMutation.isPending}
>
<RotateCcw className="mr-2 h-4 w-4" />
{t("medications.phaseResetDefaults")}
</Button>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
{t("common.cancel")}
</Button>
<Button
type="button"
onClick={() => saveMutation.mutate(form)}
disabled={saveMutation.isPending}
>
{saveMutation.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
{t("common.save")}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+50
View File
@@ -0,0 +1,50 @@
"use client";
import { useEffect, useState } from "react";
import { UmamiScript } from "@/components/monitoring/umami-script";
import { GlitchtipReporter } from "@/components/monitoring/glitchtip-reporter";
interface MonitoringSettings {
umamiEnabled: boolean;
umamiWebsiteId: string | null;
glitchtipEnabled: boolean;
}
export function MonitoringBootstrap() {
const [settings, setSettings] = useState<MonitoringSettings | null>(null);
useEffect(() => {
let active = true;
fetch("/api/monitoring/settings", { cache: "no-store" })
.then((response) => (response.ok ? response.json() : null))
.then((json) => {
if (!active || !json?.data) return;
setSettings(json.data as MonitoringSettings);
})
.catch(() => {
if (!active) return;
setSettings({
umamiEnabled: false,
umamiWebsiteId: null,
glitchtipEnabled: false,
});
});
return () => {
active = false;
};
}, []);
if (!settings) return null;
return (
<>
<UmamiScript
enabled={settings.umamiEnabled}
websiteId={settings.umamiWebsiteId}
/>
<GlitchtipReporter enabled={settings.glitchtipEnabled} />
</>
);
}
@@ -0,0 +1,72 @@
"use client";
import { useEffect } from "react";
interface GlitchtipReporterProps {
enabled: boolean;
}
function sendClientError(payload: {
message: string;
stack?: string;
level?: "error" | "warning" | "info";
type?: string;
}) {
fetch("/api/monitoring/glitchtip", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...payload,
url: window.location.href,
userAgent: navigator.userAgent,
}),
keepalive: true,
}).catch(() => {});
}
export function GlitchtipReporter({ enabled }: GlitchtipReporterProps) {
useEffect(() => {
if (!enabled) return;
function onError(event: ErrorEvent) {
sendClientError({
message: event.message || "Unhandled client error",
stack: event.error?.stack,
level: "error",
type: event.error?.name ?? "Error",
});
}
function onUnhandledRejection(event: PromiseRejectionEvent) {
const reason = event.reason as unknown;
if (reason instanceof Error) {
sendClientError({
message: reason.message || "Unhandled promise rejection",
stack: reason.stack,
level: "error",
type: reason.name || "UnhandledRejection",
});
return;
}
sendClientError({
message:
typeof reason === "string"
? reason
: "Unhandled promise rejection (non-error value)",
level: "error",
type: "UnhandledRejection",
});
}
window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onUnhandledRejection);
return () => {
window.removeEventListener("error", onError);
window.removeEventListener("unhandledrejection", onUnhandledRejection);
};
}, [enabled]);
return null;
}
@@ -0,0 +1,41 @@
"use client";
import { useEffect } from "react";
interface UmamiScriptProps {
enabled: boolean;
websiteId: string | null;
}
const SCRIPT_ID = "healthlog-umami-script";
export function UmamiScript({ enabled, websiteId }: UmamiScriptProps) {
useEffect(() => {
const existing = document.getElementById(SCRIPT_ID);
if (!enabled || !websiteId) {
existing?.remove();
return;
}
const script = document.createElement("script");
script.id = SCRIPT_ID;
script.defer = true;
script.src = "/api/monitoring/umami-script";
script.setAttribute("data-website-id", websiteId);
// Force same-origin tracking endpoint so CSP stays strict.
script.setAttribute("data-host-url", window.location.origin);
if (existing) {
existing.replaceWith(script);
} else {
document.head.appendChild(script);
}
return () => {
const current = document.getElementById(SCRIPT_ID);
current?.remove();
};
}, [enabled, websiteId]);
return null;
}
+214
View File
@@ -0,0 +1,214 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, MoreHorizontal, Plus, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
const MOOD_LEVELS = [
{ value: "SUPER_GUT", score: 5, labelKey: "mood.levelSuperGut" },
{ value: "GUT", score: 4, labelKey: "mood.levelGut" },
{ value: "OKAY", score: 3, labelKey: "mood.levelOkay" },
{ value: "SCHLECHT", score: 2, labelKey: "mood.levelSchlecht" },
{ value: "LAUSIG", score: 1, labelKey: "mood.levelLausig" },
] as const;
interface MoodFormProps {
onSuccess?: () => void;
onCancel?: () => void;
}
function getDefaultMoodLoggedAtValue() {
const now = new Date();
const offset = now.getTimezoneOffset();
const local = new Date(now.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
export function MoodForm({ onSuccess, onCancel }: MoodFormProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const [mood, setMood] = useState("");
const [tagsInput, setTagsInput] = useState("");
const [moodLoggedAt, setMoodLoggedAt] = useState(getDefaultMoodLoggedAtValue);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
function resetForm() {
setMood("");
setTagsInput("");
setMoodLoggedAt(getDefaultMoodLoggedAtValue());
setError(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!mood) return;
setError(null);
setLoading(true);
try {
const timestamp = new Date(moodLoggedAt).toISOString();
const tags = tagsInput
.split(",")
.map((t) => t.trim())
.filter(Boolean);
const res = await fetch("/api/mood-entries", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
mood,
tags: tags.length > 0 ? tags : undefined,
moodLoggedAt: timestamp,
}),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
resetForm();
await queryClient.invalidateQueries({ queryKey: ["mood-entries"] });
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("mood.saveError"));
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label id="mood-level-label">{t("mood.moodLevel")}</Label>
<div
role="radiogroup"
aria-labelledby="mood-level-label"
className="grid grid-cols-5 gap-2"
>
{MOOD_LEVELS.map((level) => {
const isSelected = mood === level.value;
return (
<button
key={level.value}
type="button"
role="radio"
aria-checked={isSelected}
onClick={() => setMood(level.value)}
className={`flex flex-col items-center gap-1 rounded-lg border p-2 text-center transition-colors ${
isSelected
? "border-primary bg-primary/10 text-primary border-2"
: "border-border hover:bg-accent"
}`}
>
<span className="text-lg font-semibold tabular-nums">
{level.score}
</span>
<span className="text-[10px] leading-tight sm:text-xs">
{t(level.labelKey)}
</span>
</button>
);
})}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="mood-logged-at">{t("mood.timestamp")}</Label>
<Input
id="mood-logged-at"
type="datetime-local"
value={moodLoggedAt}
onChange={(e) => setMoodLoggedAt(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="tags">
{t("mood.tags")}{" "}
<span className="text-muted-foreground font-normal">
({t("common.optional")})
</span>
</Label>
<span className="text-muted-foreground text-xs">
{t("mood.tagsHelp")}
</span>
</div>
<Input
id="tags"
value={tagsInput}
onChange={(e) => setTagsInput(e.target.value)}
placeholder={t("mood.tagsPlaceholder")}
/>
</div>
{error && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{error}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={loading}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem onClick={resetForm}>
<RotateCcw className="mr-2 h-4 w-4" />
{t("mood.formReset")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={loading}
>
{t("common.cancel")}
</Button>
)}
<Button type="submit" disabled={loading || !mood}>
{loading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{t("common.save")}
</Button>
</div>
</div>
</form>
);
}
+697
View File
@@ -0,0 +1,697 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Loader2,
Pencil,
Trash2,
ChevronLeft,
ChevronRight,
ArrowUp,
ArrowDown,
ArrowUpDown,
MoreHorizontal,
} from "lucide-react";
import { useState } from "react";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
const MOOD_SCORES: Record<string, number> = {
SUPER_GUT: 5,
GUT: 4,
OKAY: 3,
SCHLECHT: 2,
LAUSIG: 1,
};
const MOOD_LABEL_KEYS: Record<string, string> = {
SUPER_GUT: "mood.levelSuperGut",
GUT: "mood.levelGut",
OKAY: "mood.levelOkay",
SCHLECHT: "mood.levelSchlecht",
LAUSIG: "mood.levelLausig",
};
interface MoodEntry {
id: string;
date: string;
mood: string;
score: number;
tags: string[];
source: string;
moodLoggedAt: string;
}
const PAGE_SIZE = 25;
const MOOD_LEVELS_LIST = [
"SUPER_GUT",
"GUT",
"OKAY",
"SCHLECHT",
"LAUSIG",
] as const;
function toDateTimeLocalValue(isoString: string): string {
const date = new Date(isoString);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
export function MoodList() {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
const queryClient = useQueryClient();
const [moodFilter, setMoodFilterRaw] = useState<string>("ALL");
const [page, setPage] = useState(1);
const [sortBy, setSortBy] = useState<string>("moodLoggedAt");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
const [editing, setEditing] = useState<MoodEntry | null>(null);
const [editMood, setEditMood] = useState("");
const [editTagsInput, setEditTagsInput] = useState("");
const [editMoodLoggedAt, setEditMoodLoggedAt] = useState("");
const [editError, setEditError] = useState<string | null>(null);
const [editDeleteDialogOpen, setEditDeleteDialogOpen] = useState(false);
const setMoodFilter = (value: string) => {
setMoodFilterRaw(value);
setPage(1);
};
function toggleSort(column: string) {
if (sortBy === column) {
setSortDir((d) => (d === "asc" ? "desc" : "asc"));
} else {
setSortBy(column);
setSortDir(column === "moodLoggedAt" ? "desc" : "asc");
}
setPage(1);
}
const { data, isLoading } = useQuery({
queryKey: [
"mood-entries",
moodFilter === "ALL" ? undefined : moodFilter,
page,
sortBy,
sortDir,
],
queryFn: async () => {
const params = new URLSearchParams();
if (moodFilter !== "ALL") params.set("mood", moodFilter);
params.set("limit", String(PAGE_SIZE));
params.set("offset", String((page - 1) * PAGE_SIZE));
params.set("sortBy", sortBy);
params.set("sortDir", sortDir);
const res = await fetch(`/api/mood-entries?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data as {
entries: MoodEntry[];
meta: { total: number };
};
},
enabled: isAuthenticated,
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/mood-entries/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Delete failed");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["mood-entries"] });
},
});
const updateMutation = useMutation({
mutationFn: async ({
id,
mood,
tags,
moodLoggedAt,
}: {
id: string;
mood: string;
tags: string[] | null;
moodLoggedAt: string;
}) => {
const res = await fetch(`/api/mood-entries/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mood, tags, moodLoggedAt }),
});
const json = await res.json();
if (!res.ok) {
throw new Error(json.error ?? "Update failed");
}
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["mood-entries"] });
setEditing(null);
setEditError(null);
},
onError: (err) => {
setEditError(err instanceof Error ? err.message : t("mood.saveError"));
},
});
const totalPages = data ? Math.ceil(data.meta.total / PAGE_SIZE) : 0;
function startEdit(entry: MoodEntry) {
setEditing(entry);
setEditMood(entry.mood);
setEditTagsInput(entry.tags.join(", "));
setEditMoodLoggedAt(toDateTimeLocalValue(entry.moodLoggedAt));
setEditError(null);
}
function closeEdit() {
if (updateMutation.isPending || deleteMutation.isPending) return;
setEditing(null);
setEditError(null);
setEditDeleteDialogOpen(false);
}
async function deleteEditingEntry() {
if (!editing) return;
try {
setEditError(null);
await deleteMutation.mutateAsync(editing.id);
closeEdit();
} catch {
setEditError(t("mood.deleteError"));
}
}
async function submitEdit(e: React.FormEvent) {
e.preventDefault();
if (!editing || !editMood) return;
const measuredDate = new Date(editMoodLoggedAt);
if (Number.isNaN(measuredDate.getTime())) {
setEditError(t("mood.invalidTimestamp"));
return;
}
const tags = editTagsInput
.split(",")
.map((t) => t.trim())
.filter(Boolean);
setEditError(null);
updateMutation.mutate({
id: editing.id,
mood: editMood,
tags: tags.length > 0 ? tags : null,
moodLoggedAt: measuredDate.toISOString(),
});
}
if (!isAuthenticated) {
return (
<p className="text-muted-foreground text-sm">{t("mood.loginRequired")}</p>
);
}
return (
<>
<div className="space-y-4">
<div className="flex items-center justify-between">
<Select value={moodFilter} onValueChange={setMoodFilter}>
<SelectTrigger className="w-48">
<SelectValue placeholder={t("mood.allMoods")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">{t("mood.allMoods")}</SelectItem>
{MOOD_LEVELS_LIST.map((val) => (
<SelectItem key={val} value={val}>
{MOOD_SCORES[val]} ({t(MOOD_LABEL_KEYS[val])})
</SelectItem>
))}
</SelectContent>
</Select>
{data?.meta.total !== undefined && (
<span className="text-muted-foreground text-sm">
{t("mood.entryCount", {
count: data.meta.total.toLocaleString("de-DE"),
})}
</span>
)}
</div>
{isLoading ? (
<div className="flex h-32 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !data?.entries.length ? (
<div className="text-muted-foreground flex h-32 items-center justify-center rounded-lg border border-dashed">
{t("mood.noEntries")}
</div>
) : (
<>
{/* Desktop table */}
<div className="bg-card border-border hidden overflow-hidden rounded-lg border md:block">
<Table>
<TableHeader>
<TableRow>
<SortableHead
column="mood"
label={t("mood.moodLevel")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
className="w-36 pl-4"
/>
<TableHead>{t("mood.tags")}</TableHead>
<SortableHead
column="moodLoggedAt"
label={t("mood.date")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
/>
<SortableHead
column="source"
label={t("mood.source")}
currentSort={sortBy}
currentDir={sortDir}
onSort={toggleSort}
className="w-20"
/>
<TableHead className="w-20 pr-4 text-right">
{t("mood.actions")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.entries.map((entry) => (
<TableRow key={entry.id}>
<TableCell className="pl-4 font-semibold tabular-nums">
{entry.score}{" "}
<span className="text-muted-foreground font-normal">
({MOOD_LABEL_KEYS[entry.mood] ? t(MOOD_LABEL_KEYS[entry.mood]) : entry.mood})
</span>
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{entry.tags.length > 0 ? entry.tags.join(", ") : "-"}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{formatDateTime(entry.moodLoggedAt)}
</TableCell>
<TableCell>
{entry.source !== "MANUAL" && (
<Badge variant="outline" className="text-xs">
{t("mood.sourceMoodlog")}
</Badge>
)}
</TableCell>
<TableCell className="pr-4 text-right">
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(entry)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() => deleteMutation.mutate(entry.id)}
/>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* Mobile list */}
<div className="space-y-2 md:hidden">
{data.entries.map((entry) => (
<div
key={entry.id}
className="bg-card border-border flex items-center justify-between rounded-lg border p-3"
>
<div className="flex items-center gap-2.5 overflow-hidden">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-muted">
<span className="text-lg font-bold tabular-nums">
{entry.score}
</span>
</div>
<div className="min-w-0">
<span className="text-sm font-semibold tabular-nums">
{entry.score}{" "}
<span className="text-muted-foreground font-normal">
({MOOD_LABEL_KEYS[entry.mood] ? t(MOOD_LABEL_KEYS[entry.mood]) : entry.mood})
</span>
</span>
<p className="text-muted-foreground truncate text-xs">
{formatDateTime(entry.moodLoggedAt)}
</p>
{entry.tags.length > 0 && (
<p className="text-muted-foreground truncate text-xs">
{entry.tags.join(", ")}
</p>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => startEdit(entry)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() => deleteMutation.mutate(entry.id)}
/>
</div>
</div>
))}
</div>
</>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-sm">
{t("mood.pageInfo", {
page: String(page),
total: String(totalPages),
})}
</span>
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
{/* Edit dialog */}
<Dialog open={!!editing} onOpenChange={(open) => !open && closeEdit()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("mood.editEntry")}</DialogTitle>
</DialogHeader>
{editing && (
<form onSubmit={submitEdit} className="space-y-4">
<div className="space-y-2">
<Label id="edit-mood-level-label">{t("mood.moodLevel")}</Label>
<div role="radiogroup" aria-labelledby="edit-mood-level-label" className="grid grid-cols-5 gap-2">
{MOOD_LEVELS_LIST.map((level) => {
const isSelected = editMood === level;
return (
<button
key={level}
type="button"
role="radio"
aria-checked={isSelected}
onClick={() => setEditMood(level)}
className={`flex flex-col items-center gap-1 rounded-lg border p-2 text-center transition-colors ${
isSelected
? "border-primary bg-primary/10 text-primary border-2"
: "border-border hover:bg-accent"
}`}
>
<span className="text-lg font-semibold tabular-nums">
{MOOD_SCORES[level]}
</span>
<span className="text-[10px] leading-tight sm:text-xs">
{t(MOOD_LABEL_KEYS[level])}
</span>
</button>
);
})}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="edit-mood-logged-at">
{t("mood.timestamp")}
</Label>
<Input
id="edit-mood-logged-at"
type="datetime-local"
value={editMoodLoggedAt}
onChange={(e) => setEditMoodLoggedAt(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<Label htmlFor="edit-tags">
{t("mood.tags")} ({t("common.optional")})
</Label>
<span className="text-muted-foreground text-xs">
{t("mood.tagsHelp")}
</span>
</div>
<Input
id="edit-tags"
value={editTagsInput}
onChange={(e) => setEditTagsInput(e.target.value)}
placeholder={t("mood.tagsPlaceholder")}
/>
</div>
{editError && (
<div role="alert" aria-live="assertive" className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm">
{editError}
</div>
)}
<div className="flex items-center justify-between gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
className="h-9 w-9"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
aria-label={t("common.moreOptions")}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem
variant="destructive"
onClick={() => setEditDeleteDialogOpen(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
{t("common.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
onClick={closeEdit}
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
{t("common.cancel")}
</Button>
<Button
type="submit"
disabled={
updateMutation.isPending || deleteMutation.isPending
}
>
{updateMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("common.save")}
</Button>
</div>
</div>
<AlertDialog
open={editDeleteDialogOpen}
onOpenChange={setEditDeleteDialogOpen}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("mood.deleteConfirmTitle")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("mood.deleteConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteMutation.isPending}>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={deleteEditingEntry}
disabled={deleteMutation.isPending}
>
{deleteMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : null}
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</form>
)}
</DialogContent>
</Dialog>
</>
);
}
function SortableHead({
column,
label,
currentSort,
currentDir,
onSort,
className,
}: {
column: string;
label: string;
currentSort: string;
currentDir: "asc" | "desc";
onSort: (col: string) => void;
className?: string;
}) {
const isActive = currentSort === column;
return (
<TableHead className={className}>
<button
type="button"
onClick={() => onSort(column)}
className="hover:text-foreground inline-flex items-center gap-1 transition-colors"
>
{label}
{isActive ? (
currentDir === "asc" ? (
<ArrowUp className="h-3.5 w-3.5" />
) : (
<ArrowDown className="h-3.5 w-3.5" />
)
) : (
<ArrowUpDown className="h-3.5 w-3.5 opacity-40" />
)}
</button>
</TableHead>
);
}
function DeleteButton({ onConfirm }: { onConfirm: () => void }) {
const { t } = useTranslations();
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-destructive h-8 w-8"
aria-label={t("common.delete")}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("mood.deleteConfirmTitle")}</AlertDialogTitle>
<AlertDialogDescription>
{t("mood.deleteConfirmDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={onConfirm}
>
{t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
+128
View File
@@ -0,0 +1,128 @@
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
type ReactNode,
} from "react";
import { I18nProvider } from "@/lib/i18n/context";
import { Toaster } from "@/components/ui/sonner";
// ── Theme Context ────────────────────────────────────
type Theme = "dark" | "light" | "system";
interface ThemeContextValue {
theme: Theme;
resolvedTheme: "dark" | "light";
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue>({
theme: "system",
resolvedTheme: "dark",
setTheme: () => {},
});
export function useTheme() {
return useContext(ThemeContext);
}
function getSystemTheme(): "dark" | "light" {
if (typeof window === "undefined") return "dark";
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function applyTheme(resolved: "dark" | "light") {
document.documentElement.classList.remove("dark", "light");
document.documentElement.classList.add(resolved);
}
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
if (typeof window === "undefined") return "system";
const saved = localStorage.getItem("healthlog-theme") as Theme | null;
return saved === "light" || saved === "dark" ? saved : "system";
});
const [resolvedTheme, setResolvedTheme] = useState<"dark" | "light">(() => {
if (typeof window === "undefined") return "dark";
const saved = localStorage.getItem("healthlog-theme") as Theme | null;
const t = saved === "light" || saved === "dark" ? saved : "system";
return t === "system" ? getSystemTheme() : t;
});
// Apply theme on mount (inline script handles FOUC, this ensures classes are in sync)
useEffect(() => {
applyTheme(resolvedTheme);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Listen for OS preference changes when in system mode
useEffect(() => {
if (theme !== "system") return;
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (e: MediaQueryListEvent) => {
const resolved = e.matches ? "dark" : "light";
setResolvedTheme(resolved);
applyTheme(resolved);
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [theme]);
const setTheme = useCallback((next: Theme) => {
setThemeState(next);
if (next === "system") {
localStorage.removeItem("healthlog-theme");
const resolved = getSystemTheme();
setResolvedTheme(resolved);
applyTheme(resolved);
} else {
localStorage.setItem("healthlog-theme", next);
setResolvedTheme(next);
applyTheme(next);
}
}, []);
return (
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// ── Root Providers ───────────────────────────────────
export function Providers({ children }: { children: ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
refetchOnWindowFocus: false,
retry: 1,
},
},
}),
);
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<I18nProvider>
{children}
<Toaster position="bottom-right" richColors />
</I18nProvider>
</ThemeProvider>
</QueryClientProvider>
);
}
+196
View File
@@ -0,0 +1,196 @@
"use client";
import * as React from "react";
import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm";
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className,
)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className,
)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"bg-muted mb-2 inline-flex size-16 items-center justify-center rounded-md sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className,
)}
{...props}
/>
);
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
);
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
);
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
};
+109
View File
@@ -0,0 +1,109 @@
"use client";
import * as React from "react";
import { Avatar as AvatarPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Avatar({
className,
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: "default" | "sm" | "lg";
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
className,
)}
{...props}
/>
);
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",
className,
)}
{...props}
/>
);
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"bg-primary text-primary-foreground ring-background absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full ring-2 select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className,
)}
{...props}
/>
);
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",
className,
)}
{...props}
/>
);
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className,
)}
{...props}
/>
);
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarBadge,
AvatarGroup,
AvatarGroupCount,
};
+48
View File
@@ -0,0 +1,48 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span";
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };
+64
View File
@@ -0,0 +1,64 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot.Root : "button";
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
+92
View File
@@ -0,0 +1,92 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};
+161
View File
@@ -0,0 +1,161 @@
"use client";
import * as React from "react";
import { XIcon } from "lucide-react";
import { Dialog as DialogPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus-visible:border-ring focus-visible:ring-ring/50 text-muted-foreground hover:bg-accent hover:text-foreground absolute top-5 right-6 inline-flex h-6 w-6 items-center justify-center rounded-md transition-colors focus-visible:ring-[3px] focus-visible:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn(
"flex flex-col gap-2 pr-9 text-left",
className,
)}
{...props}
/>
);
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};
+257
View File
@@ -0,0 +1,257 @@
"use client";
import * as React from "react";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
);
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className,
)}
{...props}
/>
);
}
export { Input };
+26
View File
@@ -0,0 +1,26 @@
"use client";
import * as React from "react";
import { Label as LabelPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Label({
className,
noColon = false,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root> & { noColon?: boolean }) {
return (
<LabelPrimitive.Root
data-slot="label"
data-no-colon={noColon}
className={cn(
"inline-flex items-center pl-1 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50 after:content-[':'] data-[no-colon=true]:after:content-none",
className,
)}
{...props}
/>
);
}
export { Label };
+43
View File
@@ -0,0 +1,43 @@
import { cn } from "@/lib/utils";
interface LogoProps {
className?: string;
size?: number;
}
export function Logo({ className, size = 24 }: LogoProps) {
return (
<svg
viewBox="0 0 24 24"
width={size}
height={size}
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
className={cn("shrink-0", className)}
aria-hidden="true"
>
<defs>
<clipPath id="heart-clip">
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</clipPath>
</defs>
{/* Heart shape */}
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
fill="currentColor"
fillOpacity="0.15"
stroke="currentColor"
strokeWidth={1.2}
/>
{/* EKG heartbeat line — clipped to heart shape */}
<polyline
points="3,12.5 8,12.5 9.5,9 11,16 12.5,7 14,12.5 15.5,12.5 21,12.5"
fill="none"
stroke="currentColor"
strokeWidth={1.5}
clipPath="url(#heart-clip)"
/>
</svg>
);
}
+113
View File
@@ -0,0 +1,113 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import { translateZxcvbn } from "@/lib/zxcvbn-de";
interface PasswordStrengthProps {
password: string;
minLength?: number;
}
const SCORE_CONFIG = [
{ label: "Sehr schwach", color: "bg-red-500", textColor: "text-red-500" },
{ label: "Schwach", color: "bg-orange-500", textColor: "text-orange-500" },
{
label: "Akzeptabel",
color: "bg-yellow-500",
textColor: "text-yellow-500",
},
{ label: "Stark", color: "bg-green-500", textColor: "text-green-500" },
{
label: "Sehr stark",
color: "bg-emerald-600",
textColor: "text-emerald-600",
},
];
export function PasswordStrength({
password,
minLength = 12,
}: PasswordStrengthProps) {
const [result, setResult] = useState<{
score: number;
feedback: { warning: string; suggestions: string[] };
} | null>(null);
const zxcvbnRef = useRef<typeof import("zxcvbn-typescript").default | null>(
null,
);
useEffect(() => {
if (!password) {
setResult(null);
return;
}
let cancelled = false;
(async () => {
if (!zxcvbnRef.current) {
const mod = await import("zxcvbn-typescript");
zxcvbnRef.current = mod.default;
}
if (!cancelled) {
setResult(zxcvbnRef.current(password));
}
})();
return () => {
cancelled = true;
};
}, [password]);
if (!password) return null;
const score = result?.score ?? 0;
const config = SCORE_CONFIG[score];
const tooShort = password.length < minLength;
// Collect feedback
const feedback: string[] = [];
if (tooShort) {
feedback.push(`Mindestens ${minLength} Zeichen erforderlich.`);
}
if (result?.feedback.warning) {
feedback.push(translateZxcvbn(result.feedback.warning));
}
if (result?.feedback.suggestions) {
feedback.push(...result.feedback.suggestions.map(translateZxcvbn));
}
return (
<div className="space-y-1.5">
{/* Bar segments */}
<div className="flex gap-1">
{[0, 1, 2, 3].map((i) => (
<div
key={i}
className={cn(
"h-1.5 flex-1 rounded-full transition-colors",
i <= score && !tooShort ? config.color : "bg-muted",
)}
/>
))}
</div>
{/* Label */}
<div className="flex items-center justify-between">
<span className={cn("text-xs font-medium", config.textColor)}>
{tooShort ? "Zu kurz" : config.label}
</span>
<span className="text-muted-foreground text-xs">
{password.length}/{minLength}+ Zeichen
</span>
</div>
{/* Feedback */}
{feedback.length > 0 && (
<ul className="text-muted-foreground space-y-0.5 text-xs">
{feedback.map((f, i) => (
<li key={i}>• {f}</li>
))}
</ul>
)}
</div>
);
}
+31
View File
@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import { Progress as ProgressPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
);
}
export { Progress };
+190
View File
@@ -0,0 +1,190 @@
"use client";
import * as React from "react";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { Select as SelectPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};
+28
View File
@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import { Separator as SeparatorPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className,
)}
{...props}
/>
);
}
export { Separator };
+143
View File
@@ -0,0 +1,143 @@
"use client";
import * as React from "react";
import { XIcon } from "lucide-react";
import { Dialog as SheetPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = "right",
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
showCloseButton?: boolean;
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
+37
View File
@@ -0,0 +1,37 @@
"use client";
import {
CircleCheckIcon,
InfoIcon,
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react";
import { Toaster as Sonner, type ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
return (
<Sonner
theme="dark"
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
{...props}
/>
);
};
export { Toaster };
+35
View File
@@ -0,0 +1,35 @@
"use client";
import * as React from "react";
import { Switch as SwitchPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Switch({
className,
size = "default",
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
size?: "sm" | "default";
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6",
className,
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block rounded-full ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitive.Root>
);
}
export { Switch };
+116
View File
@@ -0,0 +1,116 @@
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};
+91
View File
@@ -0,0 +1,91 @@
"use client";
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Tabs as TabsPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
className,
)}
{...props}
/>
);
}
const tabsListVariants = cva(
"rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
},
);
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
);
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/75 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground",
"after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
className,
)}
{...props}
/>
);
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };
+57
View File
@@ -0,0 +1,57 @@
"use client";
import * as React from "react";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground border-border animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md border px-3 py-1.5 text-xs text-balance shadow-md",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-popover fill-popover z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };