feat(workouts): edit a hand-entered workout from its detail page

A workout logged by hand could only be deleted and logged again. The
detail page now offers an edit control beside delete for a MANUAL workout
carrying the form's `manual:` id, in one's own record. It opens the log
sheet on the stored values and saves by re-posting that id through
`POST /api/workouts/batch`, which already applies such a re-post as an
overwrite of that one row. No new route.

The overwrite nulls every overwritable column a re-post leaves out, and
the form has no fields for heart rate, steps, elevation or pauses. The
edit therefore sends those back as stored. A field left as shown sends the
stored value rather than one re-parsed from its display, so saving an
untouched edit keeps the start's seconds and a distance shown in miles at
its exact metres, and answers `duplicate`.

The detail read's `avgHr` / `maxHr` can come from a same-session twin;
the read now also serves the row's own `storedAvgHr` / `storedMaxHr`,
which is what the edit sends back.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 09:28:56 +02:00
1 parent ba99551faa
commit 2731c46399
13 files changed
+717 -22

No files matched your search

@@ -47,7 +47,10 @@ import {
canDeleteWorkout,
deleteManualWorkout,
} from "../delete-workout-button";
import type { ManualWorkoutEntry } from "@/lib/workouts/manual-entry";
import {
manualWorkoutOriginalFromRow,
type ManualWorkoutEntry,
} from "@/lib/workouts/manual-entry";
const ENTRY: ManualWorkoutEntry = {
sportType: "cycling",
@@ -251,3 +254,39 @@ describe("delete — a hand-entered workout in one's own record only", () => {
});
});
});
describe("<ManualWorkoutForm> — editing a stored workout (#1162)", () => {
const original = manualWorkoutOriginalFromRow(
{
sportType: "cycling",
startedAt: "2026-09-15T06:00:00.000Z",
endedAt: "2026-09-15T07:30:00.000Z",
durationSec: 5400,
distanceM: 32000,
activeEnergyKcal: 640,
minHr: null,
stepCount: null,
elevationM: null,
pauseDurationSec: null,
storedAvgHr: 131,
storedMaxHr: null,
},
{ timezone: "Europe/Berlin", unitPreference: "metric" },
);
it("opens on the stored values", () => {
const html = render(
<ManualWorkoutForm edit={{ externalId: ENTRY.externalId, original }} />,
);
expect(html).toContain('value="2026-09-15T08:00"');
expect(html).toContain('value="1"');
expect(html).toContain('value="30"');
expect(html).toContain('value="32"');
expect(html).toContain('value="640"');
});
it("opens empty when it is not editing", () => {
const html = render(<ManualWorkoutForm />);
expect(html).not.toContain('value="640"');
});
});
@@ -0,0 +1,83 @@
"use client";
import { useMemo, useState } from "react";
import { Pencil } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ManualWorkoutSheet } from "@/components/workouts/manual-workout-sheet";
import { useAuth } from "@/hooks/use-auth";
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
import { useUnitDisplay } from "@/hooks/use-unit-display";
import { useTranslations } from "@/lib/i18n/context";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { cn } from "@/lib/utils";
import {
canEditWorkout,
manualWorkoutOriginalFromRow,
type StoredManualWorkout,
} from "@/lib/workouts/manual-entry";
/**
* The detail page's edit control (#1162): a ghost icon beside delete that
* opens the "Log workout" sheet on the stored values. Renders nothing for a
* workout it may not edit (a synced one, or somebody else's record).
*
* Saving goes through the same `POST /api/workouts/batch` the form always
* used, re-posting the row's own `manual:` id, which the route applies as an
* overwrite of that one row. No separate edit route exists.
*/
export function EditWorkoutButton({
workout,
}: {
workout: StoredManualWorkout & {
source: string;
externalId: string | null;
};
}) {
const { t } = useTranslations();
const { user } = useAuth();
const { preference } = useUnitDisplay();
const capabilities = useRecordCapabilities();
const [open, setOpen] = useState(false);
const timezone = user?.timezone || DEFAULT_TIMEZONE;
const original = useMemo(
() =>
manualWorkoutOriginalFromRow(workout, {
timezone,
unitPreference: preference,
}),
[workout, timezone, preference],
);
if (!canEditWorkout(workout, capabilities) || !workout.externalId) {
return null;
}
return (
<>
<Button
type="button"
variant="ghost"
size="icon"
data-slot="workout-edit"
aria-label={t("insights.workouts.manual.editAction")}
title={t("insights.workouts.manual.editTitle")}
onClick={() => setOpen(true)}
className={cn(
"text-muted-foreground hover:text-foreground relative size-10",
"before:absolute before:-inset-1.5 before:content-['']",
)}
>
<Pencil className="size-4" aria-hidden="true" />
</Button>
{/* The sheet mounts its form only while open, so each opening starts
from the values the page shows at that moment. */}
<ManualWorkoutSheet
open={open}
onOpenChange={setOpen}
edit={{ externalId: workout.externalId, original }}
/>
</>
);
}
@@ -1,9 +1,9 @@
"use client";
import { useId, useMemo, useState } from "react";
import { useEffect, useId, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import { Loader2, Plus } from "lucide-react";
import { Check, Loader2, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toastWrittenOutcome } from "@/components/outcome/outcome-toast";
@@ -33,6 +33,7 @@ import {
type ManualWorkoutDraft,
type ManualWorkoutEntry,
type ManualWorkoutField,
type ManualWorkoutOriginal,
} from "@/lib/workouts/manual-entry";
import {
workoutSportTypeEnum,
@@ -49,10 +50,23 @@ import {
* `onSuccess` / `onCancel` close the sheet.
*/
/**
* Edit mode (#1162): the stored workout's own `manual:` id and the values it
* opens with. Saving re-posts that id, which the batch route applies as an
* overwrite of that one row.
*/
export interface ManualWorkoutEdit {
externalId: string;
original: ManualWorkoutOriginal;
}
interface ManualWorkoutFormProps {
onSuccess?: () => void;
onCancel?: () => void;
footerSlot?: HTMLElement | null;
edit?: ManualWorkoutEdit;
/** Whether the fields differ from what the form opened with. */
onDirtyChange?: (dirty: boolean) => void;
}
interface BatchResult {
@@ -104,6 +118,8 @@ export function ManualWorkoutForm({
onSuccess,
onCancel,
footerSlot,
edit,
onDirtyChange,
}: ManualWorkoutFormProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
@@ -114,10 +130,20 @@ export function ManualWorkoutForm({
// Minted once per opened form and sent with every submit, so a second tap
// or a retried request lands as a duplicate rather than a second row, and
// a submit after an edit updates the row the first submit stored.
const [externalId] = useState(newManualWorkoutExternalId);
const [draft, setDraft] = useState<ManualWorkoutDraft>(() =>
emptyManualWorkoutDraft(),
// An edit sends the stored row's own id instead.
const [externalId] = useState(
() => edit?.externalId ?? newManualWorkoutExternalId(),
);
const [initialDraft] = useState<ManualWorkoutDraft>(
() => edit?.original.draft ?? emptyManualWorkoutDraft(),
);
const [draft, setDraft] = useState<ManualWorkoutDraft>(initialDraft);
const dirty = (
Object.keys(initialDraft) as Array<keyof ManualWorkoutDraft>
).some((key) => draft[key] !== initialDraft[key]);
useEffect(() => {
onDirtyChange?.(dirty);
}, [dirty, onDirtyChange]);
const [errors, setErrors] = useState<
Partial<Record<ManualWorkoutField, string>>
>({});
@@ -158,6 +184,7 @@ export function ManualWorkoutForm({
unitPreference: preference,
externalId,
now: new Date(),
original: edit?.original,
});
if (!built.ok) {
setErrors(built.errors);
@@ -174,6 +201,8 @@ export function ManualWorkoutForm({
"empty",
t("insights.workouts.manual.alreadySaved"),
);
} else if (outcome === "updated") {
toastWrittenOutcome("success", t("insights.workouts.manual.updated"));
} else {
toastWrittenOutcome("success", t("common.saved"));
}
@@ -216,6 +245,8 @@ export function ManualWorkoutForm({
>
{saving ? (
<Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
) : edit ? (
<Check className="size-4" />
) : (
<Plus className="size-4" />
)}
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useCallback, useRef, useState } from "react";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import {
@@ -14,7 +14,10 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { sheetBodyHasUnsavedInput } from "@/components/dashboard/quick-entry-sheets";
import { ManualWorkoutForm } from "@/components/workouts/manual-workout-form";
import {
ManualWorkoutForm,
type ManualWorkoutEdit,
} from "@/components/workouts/manual-workout-form";
import { useTranslations } from "@/lib/i18n/context";
/**
@@ -23,21 +26,31 @@ import { useTranslations } from "@/lib/i18n/context";
* `ManualWorkoutForm` inside their own sheets, which already carry the same
* confirm-before-discard guard; this one carries it too, so a half-filled
* form is never dropped by a stray swipe.
*
* With `edit` it opens on a stored workout (#1162). Its fields start filled,
* so "has input" says nothing there; the guard asks the form whether anything
* differs from what it opened with.
*/
export function ManualWorkoutSheet({
open,
onOpenChange,
edit,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
edit?: ManualWorkoutEdit;
}) {
const { t } = useTranslations();
const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
const [confirmDiscardOpen, setConfirmDiscardOpen] = useState(false);
const editDirty = useRef(false);
const handleDirtyChange = useCallback((dirty: boolean) => {
editDirty.current = dirty;
}, []);
function handleOpenChange(next: boolean) {
if (next) return onOpenChange(true);
if (sheetBodyHasUnsavedInput()) {
if (edit ? editDirty.current : sheetBodyHasUnsavedInput()) {
setConfirmDiscardOpen(true);
return;
}
@@ -49,7 +62,11 @@ export function ManualWorkoutSheet({
<ResponsiveSheet
open={open}
onOpenChange={handleOpenChange}
title={t("insights.workouts.manual.sheetTitle")}
title={t(
edit
? "insights.workouts.manual.editTitle"
: "insights.workouts.manual.sheetTitle",
)}
description={t("insights.workouts.manual.sheetDescription")}
footer={<div ref={setFooterEl} className="flex w-full" />}
>
@@ -58,6 +75,8 @@ export function ManualWorkoutSheet({
onSuccess={() => onOpenChange(false)}
onCancel={() => onOpenChange(false)}
footerSlot={footerEl}
edit={edit}
onDirtyChange={edit ? handleDirtyChange : undefined}
/>
)}
</ResponsiveSheet>