mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
The client bundle carries only the active locale — resolved on the server and handed to the provider with no hydration flash, halving the dashboard route to under a megabyte parsed (288 KiB gzip). The auth shell renders the app chrome immediately instead of a spinner while the session resolves in parallel, the widgets request folds into the snapshot it duplicated, and insight pills prefetch their sub-pages — a first visit to a sub-page lands in about ninety milliseconds instead of nearly a second.
419 lines
14 KiB
TypeScript
419 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import Link from "next/link";
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { toast } from "sonner";
|
|
import { Eye, EyeOff, GripVertical, Loader2, RotateCcw } from "lucide-react";
|
|
import {
|
|
DndContext,
|
|
KeyboardSensor,
|
|
PointerSensor,
|
|
closestCenter,
|
|
useSensor,
|
|
useSensors,
|
|
type DragEndEvent,
|
|
} from "@dnd-kit/core";
|
|
import {
|
|
SortableContext,
|
|
sortableKeyboardCoordinates,
|
|
useSortable,
|
|
verticalListSortingStrategy,
|
|
} from "@dnd-kit/sortable";
|
|
import { CSS } from "@dnd-kit/utilities";
|
|
|
|
import { Button } from "@/components/ui/button";
|
|
import { cn } from "@/lib/utils";
|
|
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
|
|
import { useTranslations } from "@/lib/i18n/context";
|
|
import { queryKeys } from "@/lib/query-keys";
|
|
import { reorderById } from "@/lib/insights-layout-reorder";
|
|
import {
|
|
type InsightsLayout,
|
|
type InsightsSectionConfig,
|
|
type InsightsSectionId,
|
|
} from "@/lib/insights-layout";
|
|
import { apiDelete, apiPut } from "@/lib/api/api-fetch";
|
|
|
|
/**
|
|
* v1.15.11 W3 — inline "Anpassen" edit mode for the customizable Insights
|
|
* overview.
|
|
*
|
|
* Renders LIGHTWEIGHT edit cards (drag handle + localized title + eye toggle)
|
|
* instead of the live, heavy section content, so toggling into edit mode never
|
|
* refetches the section data — it swaps the JSX, not the queries. Edits mutate a
|
|
* local draft; "Fertig" PUTs the merged `{ version: 2, sections, tiles }` blob
|
|
* and invalidates `queryKeys.insightsLayout()`; "Zurücksetzen" DELETEs to
|
|
* defaults.
|
|
*
|
|
* Tile-level management (the per-metric detail pages + their nav pills)
|
|
* moved to Settings → Insights in v1.15.20 — the pill-order section there
|
|
* carries both sorting AND the eye toggles, so the disclosure this card used
|
|
* to nest under the Vitals row was a duplicate surface. The card keeps the
|
|
* draft's `tiles` untouched and links to the settings section instead.
|
|
*/
|
|
|
|
/** Localized title key per section id — used for the edit-card label. */
|
|
const SECTION_TITLE_KEYS: Record<InsightsSectionId, string> = {
|
|
"wellness-scores": "insights.derived.scores.sectionTitle",
|
|
"daily-briefing": "insights.dailyBriefing.title",
|
|
vitals: "insights.derived.vitals.sectionTitle",
|
|
trends: "insights.trendsRow.title",
|
|
"period-review": "insights.narrativeTitle",
|
|
"cycle-summary": "cycle.insightsSummary.title",
|
|
signals: "insights.derived.coincident.cardTitle",
|
|
"rhythm-events": "insights.rhythmEvents.sectionTitle",
|
|
};
|
|
|
|
interface InsightsEditModeProps {
|
|
/** Resolved layout currently in effect (server copy, defaults while loading). */
|
|
layout: InsightsLayout;
|
|
/**
|
|
* Which section ids are gated off right now (feature flag / data gate), so
|
|
* the edit row renders disabled with a hint rather than offering a toggle
|
|
* that does nothing.
|
|
*/
|
|
gatedOffSectionIds: ReadonlySet<InsightsSectionId>;
|
|
/** Close edit mode (the "Fertig" / save-success path calls this). */
|
|
onClose: () => void;
|
|
}
|
|
|
|
export function InsightsEditMode({
|
|
layout,
|
|
gatedOffSectionIds,
|
|
onClose,
|
|
}: InsightsEditModeProps) {
|
|
const { t } = useTranslations();
|
|
const queryClient = useQueryClient();
|
|
|
|
// Local draft seeded from the resolved layout. Edits mutate the draft only;
|
|
// "Fertig" flushes it via the PUT mutation. Sections/tiles are sorted by
|
|
// order for stable rendering.
|
|
const [draft, setDraft] = useState<InsightsLayout>(() => ({
|
|
version: layout.version,
|
|
sections: [...layout.sections].sort((a, b) => a.order - b.order),
|
|
// Tiles pass through the save verbatim — pill order + visibility are
|
|
// managed on Settings → Insights since v1.15.20.
|
|
tiles: [...layout.tiles].sort((a, b) => a.order - b.order),
|
|
}));
|
|
|
|
// v1.15.11 QA L5 — on mount move focus to the edit-card heading so keyboard /
|
|
// screen-reader users land on the surface they just opened (not the top of
|
|
// the document). Inline, not modal, so no focus trap — focus returns to the
|
|
// "Anpassen" toggle on close via the page's onClose handler.
|
|
const headingRef = useRef<HTMLHeadingElement | null>(null);
|
|
useEffect(() => {
|
|
headingRef.current?.focus();
|
|
}, []);
|
|
|
|
const sensors = useSensors(
|
|
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
|
useSensor(KeyboardSensor, {
|
|
coordinateGetter: sortableKeyboardCoordinates,
|
|
}),
|
|
);
|
|
|
|
const saveMutation = useMutation({
|
|
mutationFn: async (next: InsightsLayout) => {
|
|
return apiPut<InsightsLayout>("/api/insights/layout", {
|
|
version: 2,
|
|
sections: next.sections,
|
|
tiles: next.tiles,
|
|
});
|
|
},
|
|
onSuccess: (saved) => {
|
|
// Optimistic-style settle: write the server-resolved layout into the
|
|
// shared cache so the overview repaints in the new order, then close.
|
|
queryClient.setQueryData(queryKeys.insightsLayout(), saved);
|
|
void queryClient.invalidateQueries({
|
|
queryKey: queryKeys.insightsLayout(),
|
|
});
|
|
toast.success(t("insights.editMode.saveSuccess"));
|
|
onClose();
|
|
},
|
|
onError: () => toast.error(t("insights.editMode.saveError")),
|
|
});
|
|
|
|
const resetMutation = useMutation({
|
|
mutationFn: async () => {
|
|
return apiDelete<InsightsLayout>("/api/insights/layout");
|
|
},
|
|
onSuccess: (saved) => {
|
|
queryClient.setQueryData(queryKeys.insightsLayout(), saved);
|
|
void queryClient.invalidateQueries({
|
|
queryKey: queryKeys.insightsLayout(),
|
|
});
|
|
// Re-seed the draft so the open editor reflects the restored defaults.
|
|
setDraft({
|
|
version: saved.version,
|
|
sections: [...saved.sections].sort((a, b) => a.order - b.order),
|
|
tiles: [...saved.tiles].sort((a, b) => a.order - b.order),
|
|
});
|
|
toast.success(t("insights.editMode.resetSuccess"));
|
|
},
|
|
onError: () => toast.error(t("insights.editMode.saveError")),
|
|
});
|
|
|
|
const busy = saveMutation.isPending || resetMutation.isPending;
|
|
|
|
const sections = useMemo(
|
|
() => [...draft.sections].sort((a, b) => a.order - b.order),
|
|
[draft.sections],
|
|
);
|
|
const sectionIds = sections.map((s) => s.id);
|
|
|
|
function toggleSection(id: InsightsSectionId, visible: boolean) {
|
|
setDraft((d) => ({
|
|
...d,
|
|
sections: d.sections.map((s) => (s.id === id ? { ...s, visible } : s)),
|
|
}));
|
|
}
|
|
|
|
function handleSectionDragEnd(event: DragEndEvent) {
|
|
const { active, over } = event;
|
|
if (!over || active.id === over.id) return;
|
|
const reordered = reorderById<InsightsSectionConfig>(
|
|
draft.sections,
|
|
String(active.id),
|
|
String(over.id),
|
|
);
|
|
setDraft((d) => ({ ...d, sections: reordered }));
|
|
}
|
|
|
|
const allHidden = draft.sections.every((s) => !s.visible);
|
|
|
|
return (
|
|
<div
|
|
data-slot="insights-edit-mode"
|
|
className="bg-card border-border space-y-4 rounded-xl border p-4 sm:p-6"
|
|
>
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
|
|
<div>
|
|
<h2
|
|
ref={headingRef}
|
|
tabIndex={-1}
|
|
className="text-lg font-semibold focus-visible:outline-none"
|
|
>
|
|
{t("insights.editMode.title")}
|
|
</h2>
|
|
<p className="text-muted-foreground text-sm">
|
|
{t("insights.editMode.description")}
|
|
</p>
|
|
</div>
|
|
<div className="flex items-center gap-2 self-end sm:self-auto">
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => resetMutation.mutate()}
|
|
disabled={busy}
|
|
data-slot="insights-edit-reset"
|
|
>
|
|
{resetMutation.isPending ? (
|
|
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
|
|
) : (
|
|
<RotateCcw className="h-3.5 w-3.5" />
|
|
)}
|
|
{t("insights.editMode.reset")}
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
onClick={() => saveMutation.mutate(draft)}
|
|
disabled={busy}
|
|
data-slot="insights-edit-done"
|
|
>
|
|
{saveMutation.isPending && (
|
|
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
|
|
)}
|
|
{t("insights.editMode.done")}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{allHidden && (
|
|
<p
|
|
className="text-muted-foreground text-sm"
|
|
data-slot="insights-edit-all-hidden"
|
|
>
|
|
{t("insights.editMode.allHiddenHint")}
|
|
</p>
|
|
)}
|
|
|
|
<DndContext
|
|
sensors={sensors}
|
|
collisionDetection={closestCenter}
|
|
onDragEnd={handleSectionDragEnd}
|
|
>
|
|
<SortableContext
|
|
items={sectionIds}
|
|
strategy={verticalListSortingStrategy}
|
|
>
|
|
<div className="space-y-2">
|
|
{sections.map((section) => {
|
|
const gatedOff = gatedOffSectionIds.has(section.id);
|
|
return (
|
|
<SortableSectionRow
|
|
key={section.id}
|
|
section={section}
|
|
title={t(SECTION_TITLE_KEYS[section.id])}
|
|
gatedOff={gatedOff}
|
|
disabled={busy}
|
|
labels={{
|
|
dragHandle: t("insights.editMode.dragHandle"),
|
|
show: t("insights.editMode.show"),
|
|
hide: t("insights.editMode.hide"),
|
|
gatedHint: t("insights.editMode.gatedHint"),
|
|
}}
|
|
onToggle={toggleSection}
|
|
/>
|
|
);
|
|
})}
|
|
</div>
|
|
</SortableContext>
|
|
</DndContext>
|
|
|
|
{/* v1.15.20 — the per-detail-page manager (sort + show/hide) lives on
|
|
Settings → Insights; the disclosure this card used to nest under
|
|
the Vitals row duplicated it. Keep a quiet pointer instead. */}
|
|
<p className="text-muted-foreground text-xs">
|
|
<Link
|
|
href="/settings/insights#insights-pill-order"
|
|
data-slot="insights-edit-manage-link"
|
|
className="hover:text-foreground focus-visible:ring-ring rounded underline underline-offset-2 focus-visible:ring-2 focus-visible:outline-none"
|
|
>
|
|
{t("insights.editMode.manageInSettings")}
|
|
</Link>
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
interface RowLabels {
|
|
dragHandle: string;
|
|
show: string;
|
|
hide: string;
|
|
}
|
|
|
|
const DRAG_HANDLE_CLASS =
|
|
"text-muted-foreground hover:text-foreground focus-visible:ring-ring focus-visible:ring-offset-background relative inline-flex h-11 w-11 shrink-0 cursor-grab touch-none items-center justify-center rounded transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none sm:h-9 sm:w-9 sm:before:absolute sm:before:inset-[-6px] sm:before:content-['']";
|
|
|
|
function EyeToggle({
|
|
visible,
|
|
disabled,
|
|
label,
|
|
onClick,
|
|
slot,
|
|
}: {
|
|
visible: boolean;
|
|
disabled: boolean;
|
|
label: string;
|
|
onClick: () => void;
|
|
slot: string;
|
|
}) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={onClick}
|
|
disabled={disabled}
|
|
aria-disabled={disabled || undefined}
|
|
aria-pressed={visible}
|
|
aria-label={label}
|
|
title={label}
|
|
data-slot={slot}
|
|
data-visible={visible ? "true" : "false"}
|
|
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring focus-visible:ring-offset-background inline-flex h-11 w-11 shrink-0 items-center justify-center rounded transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none sm:h-9 sm:w-9"
|
|
>
|
|
{visible ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
|
|
</button>
|
|
);
|
|
}
|
|
|
|
interface SortableSectionRowProps {
|
|
section: InsightsSectionConfig;
|
|
title: string;
|
|
gatedOff: boolean;
|
|
disabled: boolean;
|
|
labels: RowLabels & { gatedHint: string };
|
|
onToggle: (id: InsightsSectionId, visible: boolean) => void;
|
|
}
|
|
|
|
function SortableSectionRow({
|
|
section,
|
|
title,
|
|
gatedOff,
|
|
disabled,
|
|
labels,
|
|
onToggle,
|
|
}: SortableSectionRowProps) {
|
|
const {
|
|
attributes,
|
|
listeners,
|
|
setNodeRef,
|
|
transform,
|
|
transition,
|
|
isDragging,
|
|
} = useSortable({ id: section.id });
|
|
|
|
const style: React.CSSProperties = {
|
|
transform: CSS.Transform.toString(transform),
|
|
transition: prefersReducedMotion() ? "none" : transition,
|
|
};
|
|
|
|
return (
|
|
<div
|
|
ref={setNodeRef}
|
|
style={style}
|
|
data-slot="insights-edit-section-row"
|
|
data-section={section.id}
|
|
data-dragging={isDragging ? "true" : undefined}
|
|
data-gated={gatedOff ? "true" : undefined}
|
|
className={cn(
|
|
"border-border bg-background/30 w-full rounded-md border px-2 py-2 sm:px-3",
|
|
isDragging && "ring-primary z-10 opacity-90 shadow-lg ring-2",
|
|
gatedOff && "opacity-60",
|
|
)}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
{...attributes}
|
|
{...listeners}
|
|
aria-label={`${labels.dragHandle} — ${title}`}
|
|
title={labels.dragHandle}
|
|
disabled={disabled}
|
|
data-slot="insights-edit-section-handle"
|
|
className={DRAG_HANDLE_CLASS}
|
|
>
|
|
<GripVertical className="h-4 w-4" />
|
|
</button>
|
|
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
|
<span className="truncate text-sm font-medium" title={title}>
|
|
{title}
|
|
</span>
|
|
{/* v1.15.11 QA M1-design — the gated hint reads as a caption BELOW the
|
|
title so the row's right-edge control position stays stable whether
|
|
the section is gated or not. */}
|
|
{gatedOff && (
|
|
<span
|
|
className="text-muted-foreground truncate text-xs"
|
|
data-slot="insights-edit-section-gated-hint"
|
|
>
|
|
{labels.gatedHint}
|
|
</span>
|
|
)}
|
|
</div>
|
|
{/* v1.15.11 QA M1-design — a gated section keeps a DISABLED eye toggle in
|
|
the SAME position rather than swapping it for a text span, so the row
|
|
layout never jumps. The section stays reorderable; only the toggle is
|
|
inert until the gate opens. */}
|
|
<EyeToggle
|
|
visible={section.visible}
|
|
disabled={disabled || gatedOff}
|
|
label={`${section.visible ? labels.hide : labels.show} — ${title}`}
|
|
onClick={() => onToggle(section.id, !section.visible)}
|
|
slot="insights-edit-section-eye"
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|