Initial commit for Start9 packaging
This commit is contained in:
@@ -0,0 +1,731 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect, useMemo, useCallback } from "react";
|
||||
import { Search, Plus, X, Dumbbell } from "lucide-react";
|
||||
import { Exercise } from "@prisma/client";
|
||||
import { scoreExercise } from "@/lib/exerciseSearch";
|
||||
|
||||
const MUSCLE_GROUPS = [
|
||||
"Chest",
|
||||
"Back",
|
||||
"Shoulders",
|
||||
"Quads",
|
||||
"Hamstrings",
|
||||
"Glutes",
|
||||
"Biceps",
|
||||
"Triceps",
|
||||
"Forearms",
|
||||
"Core",
|
||||
"Calves",
|
||||
"Full Body",
|
||||
"Cardio",
|
||||
];
|
||||
|
||||
const EXERCISE_TYPES = [
|
||||
{ value: "barbell", label: "Barbell" },
|
||||
{ value: "dumbbell", label: "Dumbbell" },
|
||||
{ value: "machine", label: "Machine" },
|
||||
{ value: "cable", label: "Cable" },
|
||||
{ value: "bodyweight", label: "Bodyweight" },
|
||||
{ value: "cardio", label: "Cardio" },
|
||||
{ value: "kettlebell", label: "Kettlebell" },
|
||||
{ value: "other", label: "Other" },
|
||||
];
|
||||
|
||||
interface ExercisePickerProps {
|
||||
exercises: Exercise[];
|
||||
recentlyUsed?: string[];
|
||||
onSelect: (exercise: Exercise) => void;
|
||||
onExerciseCreated?: (exercise: Exercise) => void;
|
||||
}
|
||||
|
||||
// Search utilities imported from shared module
|
||||
|
||||
export default function ExercisePicker({
|
||||
exercises,
|
||||
recentlyUsed = [],
|
||||
onSelect,
|
||||
onExerciseCreated,
|
||||
}: ExercisePickerProps) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [highlightIndex, setHighlightIndex] = useState(0);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
const [newName, setNewName] = useState("");
|
||||
const [newType, setNewType] = useState("barbell");
|
||||
const [newMuscleGroups, setNewMuscleGroups] = useState<string[]>([]);
|
||||
const [newInputFields, setNewInputFields] = useState<string[]>(["sets", "reps", "weight"]);
|
||||
|
||||
// Derive custom types/muscles/fields from existing exercises
|
||||
const knownTypeValues = EXERCISE_TYPES.map((t) => t.value);
|
||||
const knownMuscleValues = MUSCLE_GROUPS.map((g) => g.toLowerCase());
|
||||
const knownFieldValues = ["sets", "reps", "weight", "duration", "distance", "calories", "notes"];
|
||||
|
||||
const derivedCustomTypes = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const ex of exercises) {
|
||||
const t = (ex.type || "").toLowerCase();
|
||||
if (t && !knownTypeValues.includes(t)) set.add(t);
|
||||
}
|
||||
return Array.from(set).map((v) => ({ value: v, label: v.charAt(0).toUpperCase() + v.slice(1) }));
|
||||
}, [exercises]);
|
||||
|
||||
const derivedCustomMuscles = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const ex of exercises) {
|
||||
try {
|
||||
const groups = JSON.parse(ex.muscleGroups || "[]") as string[];
|
||||
groups.forEach((g) => {
|
||||
const gl = g.toLowerCase();
|
||||
if (!knownMuscleValues.includes(gl)) set.add(g.charAt(0).toUpperCase() + g.slice(1).toLowerCase());
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
return Array.from(set);
|
||||
}, [exercises]);
|
||||
|
||||
const derivedCustomFields = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const ex of exercises) {
|
||||
try {
|
||||
const fields = JSON.parse((ex as any).inputFields || "[]") as string[];
|
||||
fields.forEach((f) => { if (!knownFieldValues.includes(f)) set.add(f); });
|
||||
} catch {}
|
||||
}
|
||||
return Array.from(set).map((v) => ({ value: v, label: v.charAt(0).toUpperCase() + v.slice(1) }));
|
||||
}, [exercises]);
|
||||
|
||||
// Custom "+" add state (session-only additions on top of derived)
|
||||
const [addingType, setAddingType] = useState(false);
|
||||
const [newTypeText, setNewTypeText] = useState("");
|
||||
const [sessionCustomTypes, setSessionCustomTypes] = useState<{ value: string; label: string }[]>([]);
|
||||
const [addingMuscle, setAddingMuscle] = useState(false);
|
||||
const [newMuscleText, setNewMuscleText] = useState("");
|
||||
const [sessionCustomMuscles, setSessionCustomMuscles] = useState<string[]>([]);
|
||||
const [addingField, setAddingField] = useState(false);
|
||||
const [newFieldText, setNewFieldText] = useState("");
|
||||
const [sessionCustomFields, setSessionCustomFields] = useState<{ value: string; label: string }[]>([]);
|
||||
|
||||
// Merge derived + session-added
|
||||
const customTypes = useMemo(() => {
|
||||
const all = [...derivedCustomTypes];
|
||||
for (const t of sessionCustomTypes) {
|
||||
if (!all.some((a) => a.value === t.value)) all.push(t);
|
||||
}
|
||||
return all;
|
||||
}, [derivedCustomTypes, sessionCustomTypes]);
|
||||
|
||||
const customMuscles = useMemo(() => {
|
||||
const all = [...derivedCustomMuscles];
|
||||
for (const m of sessionCustomMuscles) {
|
||||
if (!all.map((a) => a.toLowerCase()).includes(m.toLowerCase())) all.push(m);
|
||||
}
|
||||
return all;
|
||||
}, [derivedCustomMuscles, sessionCustomMuscles]);
|
||||
|
||||
const customFieldOptions = useMemo(() => {
|
||||
const all = [...derivedCustomFields];
|
||||
for (const f of sessionCustomFields) {
|
||||
if (!all.some((a) => a.value === f.value)) all.push(f);
|
||||
}
|
||||
return all;
|
||||
}, [derivedCustomFields, sessionCustomFields]);
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const filteredExercises = useMemo(() => {
|
||||
if (!query.trim()) {
|
||||
const recent = exercises.filter((ex) => recentlyUsed.includes(ex.id));
|
||||
const others = exercises
|
||||
.filter((ex) => !recentlyUsed.includes(ex.id))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return [...recent, ...others].slice(0, 15);
|
||||
}
|
||||
|
||||
const scored = exercises
|
||||
.map((ex) => ({ exercise: ex, score: scoreExercise(query, ex.name) }))
|
||||
.filter((item) => item.score >= 0)
|
||||
.sort((a, b) => a.score - b.score);
|
||||
|
||||
return scored.map((s) => s.exercise).slice(0, 10);
|
||||
}, [exercises, query, recentlyUsed]);
|
||||
|
||||
const exactMatch = exercises.some(
|
||||
(ex) => ex.name.toLowerCase() === query.trim().toLowerCase()
|
||||
);
|
||||
const showCreateOption = query.trim().length > 0 && !exactMatch;
|
||||
const totalItems = filteredExercises.length + (showCreateOption ? 1 : 0);
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightIndex(0);
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (
|
||||
containerRef.current &&
|
||||
!containerRef.current.contains(e.target as Node)
|
||||
) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (dropdownRef.current) {
|
||||
const highlighted = dropdownRef.current.querySelector(
|
||||
'[data-highlighted="true"]'
|
||||
);
|
||||
if (highlighted) {
|
||||
highlighted.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
}
|
||||
}, [highlightIndex]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (!isOpen) {
|
||||
if (e.key === "ArrowDown" || e.key === "Enter") {
|
||||
setIsOpen(true);
|
||||
e.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (e.key) {
|
||||
case "ArrowDown":
|
||||
e.preventDefault();
|
||||
setHighlightIndex((prev) => Math.min(prev + 1, totalItems - 1));
|
||||
break;
|
||||
case "ArrowUp":
|
||||
e.preventDefault();
|
||||
setHighlightIndex((prev) => Math.max(prev - 1, 0));
|
||||
break;
|
||||
case "Enter":
|
||||
e.preventDefault();
|
||||
if (highlightIndex < filteredExercises.length) {
|
||||
handleSelect(filteredExercises[highlightIndex]);
|
||||
} else if (showCreateOption) {
|
||||
openCreateForm();
|
||||
}
|
||||
break;
|
||||
case "Escape":
|
||||
setIsOpen(false);
|
||||
inputRef.current?.blur();
|
||||
break;
|
||||
}
|
||||
},
|
||||
[isOpen, highlightIndex, filteredExercises, totalItems, showCreateOption]
|
||||
);
|
||||
|
||||
const handleSelect = (exercise: Exercise) => {
|
||||
onSelect(exercise);
|
||||
setQuery("");
|
||||
setIsOpen(false);
|
||||
inputRef.current?.blur();
|
||||
};
|
||||
|
||||
const openCreateForm = () => {
|
||||
setNewName(query.trim());
|
||||
setNewType("barbell");
|
||||
setNewMuscleGroups([]);
|
||||
setNewInputFields(["sets", "reps", "weight"]);
|
||||
setShowCreateForm(true);
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim()) return;
|
||||
|
||||
setCreating(true);
|
||||
try {
|
||||
const response = await fetch("/api/exercises", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: newName.trim(),
|
||||
type: newType,
|
||||
muscleGroups: newMuscleGroups,
|
||||
inputFields: newInputFields,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json();
|
||||
alert(err.error || "Failed to create exercise");
|
||||
return;
|
||||
}
|
||||
|
||||
const exercise: Exercise = await response.json();
|
||||
onExerciseCreated?.(exercise);
|
||||
onSelect(exercise);
|
||||
setShowCreateForm(false);
|
||||
setQuery("");
|
||||
} catch (error) {
|
||||
console.error("Failed to create exercise:", error);
|
||||
alert("Failed to create exercise. Please try again.");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMuscleGroup = (group: string) => {
|
||||
setNewMuscleGroups((prev) =>
|
||||
prev.includes(group) ? prev.filter((g) => g !== group) : [...prev, group]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleInputField = (field: string) => {
|
||||
setNewInputFields((prev) => {
|
||||
// "sets" is always included
|
||||
if (field === "sets") return prev;
|
||||
return prev.includes(field)
|
||||
? prev.filter((f) => f !== field)
|
||||
: [...prev, field];
|
||||
});
|
||||
};
|
||||
|
||||
const handleTypeChange = (type: string) => {
|
||||
setNewType(type);
|
||||
// Auto-set sensible input field defaults based on type
|
||||
if (type === "cardio") {
|
||||
setNewInputFields(["sets", "duration", "distance", "calories"]);
|
||||
} else {
|
||||
setNewInputFields(["sets", "reps", "weight"]);
|
||||
}
|
||||
};
|
||||
|
||||
const highlightMatch = (name: string) => {
|
||||
if (!query.trim()) return name;
|
||||
const q = query.toLowerCase();
|
||||
const idx = name.toLowerCase().indexOf(q);
|
||||
if (idx >= 0) {
|
||||
return (
|
||||
<>
|
||||
{name.slice(0, idx)}
|
||||
<span className="font-bold text-white">
|
||||
{name.slice(idx, idx + q.length)}
|
||||
</span>
|
||||
{name.slice(idx + q.length)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return name;
|
||||
};
|
||||
|
||||
const parseMuscleGroups = (json: string | null): string[] => {
|
||||
if (!json) return [];
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// --- Create Form ---
|
||||
if (showCreateForm) {
|
||||
return (
|
||||
<div className="border border-zinc-700 rounded-lg bg-zinc-900 p-4 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="font-semibold text-white flex items-center gap-2">
|
||||
<Plus className="w-4 h-4 text-zinc-400" />
|
||||
New Exercise
|
||||
</h4>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreateForm(false)}
|
||||
className="p-1 hover:bg-zinc-800 rounded"
|
||||
>
|
||||
<X className="w-4 h-4 text-zinc-500" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-zinc-700 rounded-lg bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Equipment */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Equipment
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[...EXERCISE_TYPES, ...customTypes].map((t) => (
|
||||
<button
|
||||
key={t.value}
|
||||
type="button"
|
||||
onClick={() => handleTypeChange(t.value)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
newType === t.value
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white border border-zinc-700"
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
{addingType ? (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const val = newTypeText.trim().toLowerCase();
|
||||
if (val && !EXERCISE_TYPES.some((t) => t.value === val) && !customTypes.some((t) => t.value === val)) {
|
||||
setSessionCustomTypes((p) => [...p, { value: val, label: val.charAt(0).toUpperCase() + val.slice(1) }]);
|
||||
handleTypeChange(val);
|
||||
}
|
||||
setNewTypeText("");
|
||||
setAddingType(false);
|
||||
}}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={newTypeText}
|
||||
onChange={(e) => setNewTypeText(e.target.value)}
|
||||
onBlur={() => {
|
||||
const val = newTypeText.trim().toLowerCase();
|
||||
if (val && !EXERCISE_TYPES.some((t) => t.value === val) && !customTypes.some((t) => t.value === val)) {
|
||||
setSessionCustomTypes((p) => [...p, { value: val, label: val.charAt(0).toUpperCase() + val.slice(1) }]);
|
||||
handleTypeChange(val);
|
||||
}
|
||||
setNewTypeText("");
|
||||
setAddingType(false);
|
||||
}}
|
||||
placeholder="New type"
|
||||
className="w-24 px-2 py-1.5 bg-zinc-800 border border-zinc-600 rounded-lg text-sm text-white focus:outline-none focus:ring-1 focus:ring-white/30"
|
||||
/>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddingType(true)}
|
||||
className="px-2.5 py-1.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-500 hover:text-white border border-dashed border-zinc-600 transition"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Muscle Groups */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Muscle Groups
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[...MUSCLE_GROUPS, ...customMuscles].map((group) => (
|
||||
<button
|
||||
key={group}
|
||||
type="button"
|
||||
onClick={() => toggleMuscleGroup(group.toLowerCase())}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
newMuscleGroups.includes(group.toLowerCase())
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white border border-zinc-700"
|
||||
}`}
|
||||
>
|
||||
{group}
|
||||
</button>
|
||||
))}
|
||||
{addingMuscle ? (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const val = newMuscleText.trim();
|
||||
const valLower = val.toLowerCase();
|
||||
if (val && !MUSCLE_GROUPS.map((g) => g.toLowerCase()).includes(valLower) && !customMuscles.map((g) => g.toLowerCase()).includes(valLower)) {
|
||||
const display = val.charAt(0).toUpperCase() + val.slice(1);
|
||||
setSessionCustomMuscles((p) => [...p, display]);
|
||||
}
|
||||
if (valLower && !newMuscleGroups.includes(valLower)) {
|
||||
setNewMuscleGroups((p) => [...p, valLower]);
|
||||
}
|
||||
setNewMuscleText("");
|
||||
setAddingMuscle(false);
|
||||
}}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={newMuscleText}
|
||||
onChange={(e) => setNewMuscleText(e.target.value)}
|
||||
onBlur={() => {
|
||||
const val = newMuscleText.trim();
|
||||
const valLower = val.toLowerCase();
|
||||
if (val && !MUSCLE_GROUPS.map((g) => g.toLowerCase()).includes(valLower) && !customMuscles.map((g) => g.toLowerCase()).includes(valLower)) {
|
||||
const display = val.charAt(0).toUpperCase() + val.slice(1);
|
||||
setSessionCustomMuscles((p) => [...p, display]);
|
||||
}
|
||||
if (valLower && !newMuscleGroups.includes(valLower)) {
|
||||
setNewMuscleGroups((p) => [...p, valLower]);
|
||||
}
|
||||
setNewMuscleText("");
|
||||
setAddingMuscle(false);
|
||||
}}
|
||||
placeholder="New group"
|
||||
className="w-24 px-2 py-1.5 bg-zinc-800 border border-zinc-600 rounded-lg text-sm text-white focus:outline-none focus:ring-1 focus:ring-white/30"
|
||||
/>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddingMuscle(true)}
|
||||
className="px-2.5 py-1.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-500 hover:text-white border border-dashed border-zinc-600 transition"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Input Fields */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Tracking Fields
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
{ value: "reps", label: "Reps" },
|
||||
{ value: "weight", label: "Weight" },
|
||||
{ value: "duration", label: "Time" },
|
||||
{ value: "distance", label: "Distance" },
|
||||
{ value: "calories", label: "Calories" },
|
||||
{ value: "notes", label: "Notes" },
|
||||
...customFieldOptions,
|
||||
].map((field) => (
|
||||
<button
|
||||
key={field.value}
|
||||
type="button"
|
||||
onClick={() => toggleInputField(field.value)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
newInputFields.includes(field.value)
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white border border-zinc-700"
|
||||
}`}
|
||||
>
|
||||
{field.label}
|
||||
</button>
|
||||
))}
|
||||
{addingField ? (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const val = newFieldText.trim().toLowerCase();
|
||||
const knownValues = ["sets", "reps", "weight", "duration", "distance", "calories", "notes"];
|
||||
if (val && !knownValues.includes(val) && !customFieldOptions.some((f) => f.value === val)) {
|
||||
setSessionCustomFields((p) => [...p, { value: val, label: val.charAt(0).toUpperCase() + val.slice(1) }]);
|
||||
}
|
||||
if (val && !newInputFields.includes(val)) {
|
||||
setNewInputFields((p) => [...p, val]);
|
||||
}
|
||||
setNewFieldText("");
|
||||
setAddingField(false);
|
||||
}}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={newFieldText}
|
||||
onChange={(e) => setNewFieldText(e.target.value)}
|
||||
onBlur={() => {
|
||||
const val = newFieldText.trim().toLowerCase();
|
||||
const knownValues = ["sets", "reps", "weight", "duration", "distance", "calories", "notes"];
|
||||
if (val && !knownValues.includes(val) && !customFieldOptions.some((f) => f.value === val)) {
|
||||
setSessionCustomFields((p) => [...p, { value: val, label: val.charAt(0).toUpperCase() + val.slice(1) }]);
|
||||
}
|
||||
if (val && !newInputFields.includes(val)) {
|
||||
setNewInputFields((p) => [...p, val]);
|
||||
}
|
||||
setNewFieldText("");
|
||||
setAddingField(false);
|
||||
}}
|
||||
placeholder="New field"
|
||||
className="w-24 px-2 py-1.5 bg-zinc-800 border border-zinc-600 rounded-lg text-sm text-white focus:outline-none focus:ring-1 focus:ring-white/30"
|
||||
/>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddingField(true)}
|
||||
className="px-2.5 py-1.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-500 hover:text-white border border-dashed border-zinc-600 transition"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreate}
|
||||
disabled={!newName.trim() || creating}
|
||||
className="flex-1 py-2.5 bg-white text-black font-semibold rounded-lg hover:bg-zinc-200 disabled:bg-zinc-700 disabled:text-zinc-500 disabled:cursor-not-allowed transition"
|
||||
>
|
||||
{creating ? "Creating..." : "Create & Add"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreateForm(false)}
|
||||
className="px-4 py-2.5 border border-zinc-700 rounded-lg text-zinc-400 hover:text-white hover:border-zinc-600 transition"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Main Autocomplete Input ---
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-zinc-500 pointer-events-none" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setIsOpen(true);
|
||||
}}
|
||||
onFocus={() => setIsOpen(true)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Type to search or add an exercise..."
|
||||
className="w-full pl-10 pr-10 py-3 border border-zinc-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-white/20 text-base bg-zinc-800 text-white placeholder:text-zinc-500"
|
||||
autoComplete="off"
|
||||
/>
|
||||
{query && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setQuery("");
|
||||
setIsOpen(false);
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 rounded text-zinc-500 hover:text-white transition-colors"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Dropdown */}
|
||||
{isOpen && (query.trim() || filteredExercises.length > 0) && (
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="absolute z-50 w-full mt-1 bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl max-h-72 overflow-y-auto"
|
||||
>
|
||||
{/* Recently used label */}
|
||||
{!query.trim() &&
|
||||
recentlyUsed.length > 0 &&
|
||||
filteredExercises.some((ex) =>
|
||||
recentlyUsed.includes(ex.id)
|
||||
) && (
|
||||
<div className="px-3 py-1.5 text-xs font-semibold text-zinc-500 uppercase tracking-wide bg-zinc-800/50 border-b border-zinc-800">
|
||||
Recently Used
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filteredExercises.map((exercise, index) => {
|
||||
const isRecent = recentlyUsed.includes(exercise.id);
|
||||
const muscles = parseMuscleGroups(exercise.muscleGroups);
|
||||
|
||||
const isFirstNonRecent =
|
||||
!query.trim() &&
|
||||
!isRecent &&
|
||||
index > 0 &&
|
||||
recentlyUsed.includes(filteredExercises[index - 1].id);
|
||||
|
||||
return (
|
||||
<div key={exercise.id}>
|
||||
{isFirstNonRecent && (
|
||||
<div className="px-3 py-1.5 text-xs font-semibold text-zinc-500 uppercase tracking-wide bg-zinc-800/50 border-t border-b border-zinc-800">
|
||||
All Exercises
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
data-highlighted={highlightIndex === index}
|
||||
onClick={() => handleSelect(exercise)}
|
||||
onMouseEnter={() => setHighlightIndex(index)}
|
||||
className={`w-full text-left px-3 py-2.5 flex items-center gap-3 transition-colors ${
|
||||
highlightIndex === index
|
||||
? "bg-zinc-800"
|
||||
: "hover:bg-zinc-800/50"
|
||||
}`}
|
||||
>
|
||||
<Dumbbell className="w-4 h-4 text-zinc-500 flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-zinc-300">
|
||||
{highlightMatch(exercise.name)}
|
||||
</div>
|
||||
{muscles.length > 0 && (
|
||||
<div className="text-xs text-zinc-600 mt-0.5">
|
||||
{muscles.join(" · ")} · {exercise.type}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Create new exercise option */}
|
||||
{showCreateOption && (
|
||||
<button
|
||||
type="button"
|
||||
data-highlighted={highlightIndex === filteredExercises.length}
|
||||
onClick={openCreateForm}
|
||||
onMouseEnter={() =>
|
||||
setHighlightIndex(filteredExercises.length)
|
||||
}
|
||||
className={`w-full text-left px-3 py-3 flex items-center gap-3 border-t border-zinc-800 transition-colors ${
|
||||
highlightIndex === filteredExercises.length
|
||||
? "bg-zinc-800"
|
||||
: "hover:bg-zinc-800/50"
|
||||
}`}
|
||||
>
|
||||
<div className="w-6 h-6 rounded-full bg-zinc-700 flex items-center justify-center flex-shrink-0">
|
||||
<Plus className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-white">
|
||||
Create “{query.trim()}”
|
||||
</div>
|
||||
<div className="text-xs text-zinc-500">
|
||||
Add as a new exercise
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* No results */}
|
||||
{filteredExercises.length === 0 && !showCreateOption && (
|
||||
<div className="px-3 py-6 text-center text-sm text-zinc-500">
|
||||
No exercises found
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2, Check, Pencil, CornerDownLeft } from "lucide-react";
|
||||
import { useState, useCallback } from "react";
|
||||
|
||||
export type InputField = "sets" | "reps" | "weight" | "duration" | "distance" | "calories" | "notes";
|
||||
|
||||
export interface SetRowProps {
|
||||
setNumber: number;
|
||||
inputFields?: InputField[];
|
||||
weightUnit?: string;
|
||||
initialReps?: number;
|
||||
initialWeight?: number;
|
||||
initialRpe?: number;
|
||||
initialNotes?: string;
|
||||
initialDuration?: number;
|
||||
initialDistance?: number;
|
||||
initialCalories?: number;
|
||||
initialLocked?: boolean;
|
||||
autoFocus?: boolean;
|
||||
onUpdate: (data: {
|
||||
reps?: number;
|
||||
weight?: number;
|
||||
rpe?: number;
|
||||
notes?: string;
|
||||
durationSeconds?: number;
|
||||
distance?: number;
|
||||
calories?: number;
|
||||
}) => void;
|
||||
onConfirm?: () => void;
|
||||
onNextSet?: (currentValues: {
|
||||
weight?: string;
|
||||
reps?: string;
|
||||
rpe?: string;
|
||||
notes?: string;
|
||||
duration?: string;
|
||||
distance?: string;
|
||||
calories?: string;
|
||||
}) => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
export default function SetRow({
|
||||
setNumber,
|
||||
inputFields = ["sets", "reps", "weight"],
|
||||
weightUnit = "lbs",
|
||||
initialReps,
|
||||
initialWeight,
|
||||
initialRpe,
|
||||
initialNotes,
|
||||
initialDuration,
|
||||
initialDistance,
|
||||
initialCalories,
|
||||
initialLocked = false,
|
||||
autoFocus = false,
|
||||
onUpdate,
|
||||
onConfirm,
|
||||
onNextSet,
|
||||
onDelete,
|
||||
}: SetRowProps) {
|
||||
const [reps, setReps] = useState(initialReps?.toString() || "");
|
||||
const [weight, setWeight] = useState(initialWeight?.toString() || "");
|
||||
const [rpe, setRpe] = useState(initialRpe?.toString() || "");
|
||||
const [notes, setNotes] = useState(initialNotes || "");
|
||||
const [duration, setDuration] = useState(initialDuration?.toString() || "");
|
||||
const [distance, setDistance] = useState(initialDistance?.toString() || "");
|
||||
const [calories, setCalories] = useState(initialCalories?.toString() || "");
|
||||
const [showNotes, setShowNotes] = useState(!!initialNotes);
|
||||
const [locked, setLocked] = useState(initialLocked);
|
||||
|
||||
const showReps = inputFields.includes("reps");
|
||||
const showWeight = inputFields.includes("weight");
|
||||
const showDuration = inputFields.includes("duration");
|
||||
const showDistance = inputFields.includes("distance");
|
||||
const showCalories = inputFields.includes("calories");
|
||||
const showNotesField = inputFields.includes("notes");
|
||||
|
||||
const emitUpdate = useCallback(
|
||||
(overrides: {
|
||||
reps?: string;
|
||||
weight?: string;
|
||||
rpe?: string;
|
||||
notes?: string;
|
||||
duration?: string;
|
||||
distance?: string;
|
||||
calories?: string;
|
||||
}) => {
|
||||
const r = overrides.reps ?? reps;
|
||||
const w = overrides.weight ?? weight;
|
||||
const p = overrides.rpe ?? rpe;
|
||||
const n = overrides.notes ?? notes;
|
||||
const dur = overrides.duration ?? duration;
|
||||
const dist = overrides.distance ?? distance;
|
||||
const cal = overrides.calories ?? calories;
|
||||
|
||||
onUpdate({
|
||||
reps: r ? parseInt(r) : undefined,
|
||||
weight: w ? parseFloat(w) : undefined,
|
||||
rpe: p ? parseInt(p) : undefined,
|
||||
notes: n || undefined,
|
||||
durationSeconds: dur ? parseInt(dur) : undefined,
|
||||
distance: dist ? parseFloat(dist) : undefined,
|
||||
calories: cal ? parseInt(cal) : undefined,
|
||||
});
|
||||
},
|
||||
[reps, weight, rpe, notes, duration, distance, calories, onUpdate]
|
||||
);
|
||||
|
||||
const handleConfirm = () => {
|
||||
emitUpdate({});
|
||||
setLocked(true);
|
||||
onConfirm?.();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}
|
||||
};
|
||||
|
||||
const handleUnlock = () => {
|
||||
setLocked(false);
|
||||
};
|
||||
|
||||
const handleNextSet = () => {
|
||||
emitUpdate({});
|
||||
setLocked(true);
|
||||
onNextSet?.({ weight, reps, rpe, notes, duration, distance, calories });
|
||||
};
|
||||
|
||||
// Build a summary string for the locked view
|
||||
const buildSummary = () => {
|
||||
const parts: string[] = [];
|
||||
if (showWeight && weight) parts.push(`${weight} ${weightUnit}`);
|
||||
if (showReps && reps) parts.push(`${reps} reps`);
|
||||
if (showDuration && duration) parts.push(`${duration}s`);
|
||||
if (showDistance && distance) parts.push(`${distance} mi`);
|
||||
if (showCalories && calories) parts.push(`${calories} cal`);
|
||||
if (rpe) parts.push(`RPE ${rpe}`);
|
||||
if (showNotesField && notes) parts.push(notes);
|
||||
return parts.length > 0 ? parts.join(" · ") : "No data";
|
||||
};
|
||||
|
||||
// ---------- LOCKED VIEW ----------
|
||||
if (locked) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{/* Set number badge */}
|
||||
<div className="bg-white text-black rounded-full w-6 h-6 flex items-center justify-center font-semibold text-xs flex-shrink-0">
|
||||
{setNumber}
|
||||
</div>
|
||||
|
||||
{/* Summary text */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-zinc-300 truncate">{buildSummary()}</p>
|
||||
{!showNotesField && notes && (
|
||||
<p className="text-[10px] text-zinc-500 truncate mt-0.5">{notes}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit (unlock) button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleUnlock}
|
||||
className="p-1.5 rounded-md flex-shrink-0 transition-colors text-zinc-400 hover:text-white hover:bg-zinc-800"
|
||||
aria-label="Edit set"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{/* Delete button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDelete}
|
||||
className="p-1.5 text-red-500 hover:bg-red-950/30 rounded-md flex-shrink-0 active:bg-red-900/30"
|
||||
aria-label="Delete set"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Determine which field gets autoFocus
|
||||
const firstField = showWeight ? "weight" : showReps ? "reps" : showDuration ? "duration" : showDistance ? "distance" : showCalories ? "calories" : null;
|
||||
|
||||
// ---------- EDIT VIEW ----------
|
||||
return (
|
||||
<div className="space-y-1.5" onKeyDown={handleKeyDown}>
|
||||
<div className="flex items-end gap-1.5">
|
||||
{/* Set number badge */}
|
||||
<div className="bg-white text-black rounded-full w-6 h-6 flex items-center justify-center font-semibold text-xs flex-shrink-0 mb-0.5">
|
||||
{setNumber}
|
||||
</div>
|
||||
|
||||
{/* Weight input */}
|
||||
{showWeight && (
|
||||
<div className="flex-1 min-w-[55px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
Weight
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.5"
|
||||
autoFocus={autoFocus && firstField === "weight"}
|
||||
value={weight}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setWeight(val);
|
||||
emitUpdate({ weight: val });
|
||||
}}
|
||||
placeholder="0"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reps input */}
|
||||
{showReps && (
|
||||
<div className="flex-1 min-w-[55px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
Reps
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
autoFocus={autoFocus && firstField === "reps"}
|
||||
value={reps}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setReps(val);
|
||||
emitUpdate({ reps: val });
|
||||
}}
|
||||
placeholder="0"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Duration input (seconds) */}
|
||||
{showDuration && (
|
||||
<div className="flex-1 min-w-[55px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
Time (s)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
autoFocus={autoFocus && firstField === "duration"}
|
||||
value={duration}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setDuration(val);
|
||||
emitUpdate({ duration: val });
|
||||
}}
|
||||
placeholder="0"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Distance input */}
|
||||
{showDistance && (
|
||||
<div className="flex-1 min-w-[55px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
Dist (mi)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.1"
|
||||
autoFocus={autoFocus && firstField === "distance"}
|
||||
value={distance}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setDistance(val);
|
||||
emitUpdate({ distance: val });
|
||||
}}
|
||||
placeholder="0"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Calories input */}
|
||||
{showCalories && (
|
||||
<div className="flex-1 min-w-[55px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
Cals
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
autoFocus={autoFocus && firstField === "calories"}
|
||||
value={calories}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setCalories(val);
|
||||
emitUpdate({ calories: val });
|
||||
}}
|
||||
placeholder="0"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* RPE select — always shown */}
|
||||
<div className="flex-1 min-w-[50px] max-w-[60px]">
|
||||
<label className="block text-[10px] font-medium text-zinc-500 mb-0.5">
|
||||
RPE
|
||||
</label>
|
||||
<select
|
||||
value={rpe}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setRpe(val);
|
||||
emitUpdate({ rpe: val });
|
||||
}}
|
||||
className="w-full px-1.5 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20"
|
||||
>
|
||||
<option value="">-</option>
|
||||
<option value="6">6</option>
|
||||
<option value="7">7</option>
|
||||
<option value="8">8</option>
|
||||
<option value="9">9</option>
|
||||
<option value="10">10</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Next set button — confirm + add new pre-filled set */}
|
||||
{onNextSet && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleNextSet}
|
||||
className="p-1.5 rounded-md flex-shrink-0 transition-colors text-zinc-400 hover:text-blue-400 hover:bg-blue-950/30"
|
||||
aria-label="Save and start next set"
|
||||
>
|
||||
<CornerDownLeft className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Confirm button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConfirm}
|
||||
className="p-1.5 rounded-md flex-shrink-0 transition-colors text-zinc-400 hover:text-green-400 hover:bg-green-950/30"
|
||||
aria-label="Confirm set"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{/* Delete button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDelete}
|
||||
className="p-1.5 text-red-500 hover:bg-red-950/30 rounded-md flex-shrink-0 active:bg-red-900/30"
|
||||
aria-label="Delete set"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Notes — always visible when configured as input field */}
|
||||
{showNotesField && (
|
||||
<div className="ml-8">
|
||||
<input
|
||||
type="text"
|
||||
value={notes}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setNotes(val);
|
||||
emitUpdate({ notes: val });
|
||||
}}
|
||||
placeholder="e.g. weighted vest, ankle weights..."
|
||||
className="w-full px-2 py-1 border border-zinc-700 rounded-md text-xs bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Toggle notes button (fallback when notes is not a configured input field) */}
|
||||
{!showNotesField && showNotes && (
|
||||
<div className="ml-8">
|
||||
<input
|
||||
type="text"
|
||||
value={notes}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
setNotes(val);
|
||||
emitUpdate({ notes: val });
|
||||
}}
|
||||
placeholder="Add notes (optional)"
|
||||
className="w-full px-2 py-1 border border-zinc-700 rounded-md text-xs bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!showNotesField && !showNotes && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowNotes(true)}
|
||||
className="text-[10px] text-zinc-500 hover:text-zinc-300 ml-8"
|
||||
>
|
||||
+ Add notes
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { WorkoutWithSets } from "@/types";
|
||||
import { formatSetsSummary } from "@/lib/formatSets";
|
||||
|
||||
interface WorkoutCardProps {
|
||||
workout: WorkoutWithSets;
|
||||
}
|
||||
|
||||
export default function WorkoutCard({ workout }: WorkoutCardProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
// Calculate total volume
|
||||
const totalVolume = workout.setLogs.reduce((sum, set) => {
|
||||
if (set.weight && set.reps) return sum + set.weight * set.reps;
|
||||
return sum;
|
||||
}, 0);
|
||||
|
||||
const uniqueExercises = new Set(workout.setLogs.map((s) => s.exerciseId)).size;
|
||||
|
||||
const date = new Date(workout.date);
|
||||
const formattedDate = date.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const caloriesBurned = (workout as any).caloriesBurned as number | null | undefined;
|
||||
|
||||
// Build compact stats chips
|
||||
const stats: string[] = [];
|
||||
stats.push(`${uniqueExercises} exercise${uniqueExercises !== 1 ? "s" : ""}`);
|
||||
const totalSets = workout.setLogs.length;
|
||||
stats.push(`${totalSets} set${totalSets !== 1 ? "s" : ""}`);
|
||||
if (totalVolume > 0) stats.push(`${Math.round(totalVolume)} lbs`);
|
||||
if (workout.durationMinutes) stats.push(`${workout.durationMinutes} min`);
|
||||
if (caloriesBurned) stats.push(`${caloriesBurned} cal`);
|
||||
if (workout.difficulty) stats.push(`${workout.difficulty}/10`);
|
||||
|
||||
// Group sets by exercise
|
||||
const exerciseGroups = (() => {
|
||||
const groups: Array<{
|
||||
exerciseId: string;
|
||||
exerciseName: string;
|
||||
sets: Array<{ weight?: number | null; reps?: number | null; weightUnit?: string | null }>;
|
||||
setCount: number;
|
||||
}> = [];
|
||||
const indexMap = new Map<string, number>();
|
||||
|
||||
for (const set of workout.setLogs) {
|
||||
const existing = indexMap.get(set.exerciseId);
|
||||
if (existing !== undefined) {
|
||||
groups[existing].sets.push({ weight: set.weight, reps: set.reps, weightUnit: set.weightUnit });
|
||||
groups[existing].setCount++;
|
||||
} else {
|
||||
indexMap.set(set.exerciseId, groups.length);
|
||||
groups.push({
|
||||
exerciseId: set.exerciseId,
|
||||
exerciseName: set.exercise.name,
|
||||
sets: [{ weight: set.weight, reps: set.reps, weightUnit: set.weightUnit }],
|
||||
setCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
})();
|
||||
|
||||
return (
|
||||
<div className="border border-zinc-800 bg-zinc-900 rounded-lg overflow-hidden">
|
||||
{/* Single-line card */}
|
||||
<div className="flex items-center gap-2 px-3 py-2.5">
|
||||
{/* Clickable area — navigates to detail page */}
|
||||
<Link
|
||||
href={`/main/workouts/${workout.id}`}
|
||||
className="flex-1 min-w-0 flex items-center gap-2 hover:opacity-80 transition-opacity"
|
||||
>
|
||||
<span className="text-xs text-zinc-500 flex-shrink-0">
|
||||
{formattedDate}
|
||||
</span>
|
||||
<span className="font-medium text-white text-sm truncate flex-shrink min-w-0">
|
||||
{workout.name || "Unnamed Workout"}
|
||||
</span>
|
||||
<span className="text-xs text-zinc-500 flex-shrink-0 hidden sm:inline">
|
||||
·
|
||||
</span>
|
||||
<span className="text-xs text-zinc-400 truncate hidden sm:inline">
|
||||
{stats.join(" · ")}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{/* Expand/collapse chevron */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded((prev) => !prev)}
|
||||
className="p-1 rounded-md text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700/50 transition-colors flex-shrink-0"
|
||||
aria-label={expanded ? "Hide details" : "Show details"}
|
||||
>
|
||||
{expanded ? (
|
||||
<ChevronUp className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Mobile stats row (visible only on small screens) */}
|
||||
<div className="px-3 pb-2 -mt-1 sm:hidden">
|
||||
<Link href={`/main/workouts/${workout.id}`}>
|
||||
<span className="text-xs text-zinc-400">
|
||||
{stats.join(" · ")}
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Expanded exercise detail */}
|
||||
{expanded && (
|
||||
<div className="border-t border-zinc-800 px-3 py-2.5 space-y-1.5">
|
||||
{exerciseGroups.map((group) => {
|
||||
const summary = formatSetsSummary(group.sets);
|
||||
return (
|
||||
<div key={group.exerciseId} className="flex items-baseline gap-2">
|
||||
<span className="text-sm font-medium text-white truncate flex-shrink min-w-0">
|
||||
{group.exerciseName}
|
||||
</span>
|
||||
<span className="text-xs text-zinc-500 flex-shrink-0">
|
||||
{group.setCount}s
|
||||
</span>
|
||||
{summary && (
|
||||
<span className="text-xs text-zinc-400 truncate">
|
||||
— {summary}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useRef, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Exercise } from "@prisma/client";
|
||||
import { ChevronDown, ChevronUp, Loader, Trash2, Plus, Save, Pencil, Check, ArrowUp, ArrowDown, Clock, X } from "lucide-react";
|
||||
import ExercisePicker from "./ExercisePicker";
|
||||
import SetRow, { InputField } from "./SetRow";
|
||||
import { formatSetsSummary } from "@/lib/formatSets";
|
||||
|
||||
// --------------- Exercise History Popup ---------------
|
||||
function ExerciseHistoryPopup({
|
||||
exerciseId,
|
||||
onClose,
|
||||
}: {
|
||||
exerciseId: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [history, setHistory] = useState<
|
||||
Array<{ workout: { id: string; date: string; name?: string }; sets: Array<{ weight?: number; reps?: number; weightUnit?: string }> }>
|
||||
>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const popupRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/exercises/${exerciseId}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (!cancelled) setHistory(data.history || []);
|
||||
}
|
||||
} catch {}
|
||||
if (!cancelled) setLoading(false);
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [exerciseId]);
|
||||
|
||||
// Close on outside click
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => {
|
||||
if (popupRef.current && !popupRef.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", handler);
|
||||
return () => document.removeEventListener("mousedown", handler);
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={popupRef}
|
||||
className="absolute left-0 right-0 top-full mt-1 z-50 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl max-h-64 overflow-y-auto"
|
||||
>
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-zinc-800 sticky top-0 bg-zinc-900">
|
||||
<span className="text-xs font-semibold text-zinc-400 uppercase tracking-wider">Recent History</span>
|
||||
<button type="button" onClick={onClose} className="p-0.5 text-zinc-500 hover:text-white">
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader className="w-4 h-4 animate-spin text-zinc-500" />
|
||||
</div>
|
||||
) : history.length === 0 ? (
|
||||
<p className="text-xs text-zinc-500 text-center py-4">No history yet</p>
|
||||
) : (
|
||||
<div className="divide-y divide-zinc-800/50">
|
||||
{history.slice(0, 10).map((entry) => {
|
||||
const d = new Date(entry.workout.date);
|
||||
const dateStr = d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
|
||||
const summary = formatSetsSummary(entry.sets);
|
||||
return (
|
||||
<div key={entry.workout.id} className="px-3 py-2">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-[11px] text-zinc-500 flex-shrink-0">{dateStr}</span>
|
||||
<span className="text-[11px] text-zinc-600">·</span>
|
||||
<span className="text-[11px] text-zinc-500">{entry.sets.length} set{entry.sets.length !== 1 ? "s" : ""}</span>
|
||||
</div>
|
||||
{summary && (
|
||||
<p className="text-xs text-zinc-300 mt-0.5">{summary}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseInputFields(exercise: Exercise): InputField[] {
|
||||
try {
|
||||
const raw = (exercise as any).inputFields;
|
||||
if (raw && typeof raw === "string") {
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
} catch {}
|
||||
return ["sets", "reps", "weight"];
|
||||
}
|
||||
|
||||
interface ExerciseWithSets {
|
||||
exercise: Exercise;
|
||||
sets: Array<{
|
||||
setNumber: number;
|
||||
reps?: number;
|
||||
weight?: number;
|
||||
rpe?: number;
|
||||
notes?: string;
|
||||
forceEdit?: boolean; // When true, start in edit mode even if data is pre-filled
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface EditWorkoutData {
|
||||
id: string;
|
||||
name: string;
|
||||
date: string; // ISO string
|
||||
durationMinutes?: number | null;
|
||||
difficulty?: number | null;
|
||||
caloriesBurned?: number | null;
|
||||
notes?: string | null;
|
||||
exercises: Array<{
|
||||
exercise: Exercise;
|
||||
sets: Array<{
|
||||
setNumber: number;
|
||||
reps?: number;
|
||||
weight?: number;
|
||||
rpe?: number;
|
||||
notes?: string;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface WorkoutFormProps {
|
||||
exercises: Exercise[];
|
||||
recentlyUsedExercises?: string[];
|
||||
editWorkout?: EditWorkoutData;
|
||||
}
|
||||
|
||||
export default function WorkoutForm({
|
||||
exercises: initialExercises,
|
||||
recentlyUsedExercises = [],
|
||||
editWorkout,
|
||||
}: WorkoutFormProps) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [exercises, setExercises] = useState<Exercise[]>(initialExercises);
|
||||
|
||||
const [workoutName, setWorkoutName] = useState(editWorkout?.name || "");
|
||||
const [workoutDate, setWorkoutDate] = useState(() => {
|
||||
if (editWorkout?.date) {
|
||||
return new Date(editWorkout.date).toISOString().split("T")[0];
|
||||
}
|
||||
return new Date().toISOString().split("T")[0];
|
||||
});
|
||||
const [duration, setDuration] = useState(editWorkout?.durationMinutes?.toString() || "");
|
||||
const [difficulty, setDifficulty] = useState(editWorkout?.difficulty?.toString() || "");
|
||||
const [workoutCalories, setWorkoutCalories] = useState(editWorkout?.caloriesBurned?.toString() || "");
|
||||
const [notes, setNotes] = useState(editWorkout?.notes || "");
|
||||
const [notesLocked, setNotesLocked] = useState(!!editWorkout?.notes);
|
||||
const [addedExercises, setAddedExercises] = useState<ExerciseWithSets[]>(
|
||||
editWorkout?.exercises || []
|
||||
);
|
||||
const [expandedExercise, setExpandedExercise] = useState<string | null>(null);
|
||||
const [historyPopupExercise, setHistoryPopupExercise] = useState<string | null>(null);
|
||||
|
||||
// Header lock state (name + date lock after first save, or immediately for edits)
|
||||
const [headerLocked, setHeaderLocked] = useState(!!editWorkout);
|
||||
|
||||
// Auto-save state — if editing, start with existing workout ID
|
||||
const [savedWorkoutId, setSavedWorkoutId] = useState<string | null>(editWorkout?.id || null);
|
||||
const [autoSaving, setAutoSaving] = useState(false);
|
||||
const [showSavedFlash, setShowSavedFlash] = useState(false);
|
||||
const savingRef = useRef(false);
|
||||
const savedFlashTimer = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Flash "Saved ✓" briefly after each successful save
|
||||
const triggerSavedFlash = useCallback(() => {
|
||||
setShowSavedFlash(true);
|
||||
if (savedFlashTimer.current) clearTimeout(savedFlashTimer.current);
|
||||
savedFlashTimer.current = setTimeout(() => setShowSavedFlash(false), 2000);
|
||||
}, []);
|
||||
|
||||
// Cleanup timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (savedFlashTimer.current) clearTimeout(savedFlashTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ---------- Build payload from current state ----------
|
||||
const buildPayload = useCallback(
|
||||
(currentExercises?: ExerciseWithSets[]) => {
|
||||
const exs = currentExercises ?? addedExercises;
|
||||
return {
|
||||
name: workoutName,
|
||||
durationMinutes: duration ? parseInt(duration) : undefined,
|
||||
difficulty: difficulty ? parseInt(difficulty) : undefined,
|
||||
caloriesBurned: workoutCalories ? parseInt(workoutCalories) : undefined,
|
||||
notes: notes || undefined,
|
||||
date: new Date(workoutDate + "T12:00:00").toISOString(),
|
||||
sets: exs.flatMap((e) =>
|
||||
e.sets.map((s) => ({
|
||||
exerciseId: e.exercise.id,
|
||||
setNumber: s.setNumber,
|
||||
reps: s.reps,
|
||||
weight: s.weight,
|
||||
weightUnit: (e.exercise as any).defaultWeightUnit || "lbs",
|
||||
rpe: s.rpe,
|
||||
notes: s.notes,
|
||||
}))
|
||||
),
|
||||
};
|
||||
},
|
||||
[workoutName, workoutDate, duration, difficulty, workoutCalories, notes, addedExercises]
|
||||
);
|
||||
|
||||
// ---------- Auto-save: create or update ----------
|
||||
const autoSave = useCallback(
|
||||
async (overrideExercises?: ExerciseWithSets[]) => {
|
||||
if (savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
setAutoSaving(true);
|
||||
|
||||
try {
|
||||
const payload = buildPayload(overrideExercises);
|
||||
|
||||
if (!savedWorkoutId) {
|
||||
// First save — POST to create
|
||||
const response = await fetch("/api/workouts", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const created = await response.json();
|
||||
setSavedWorkoutId(created.id);
|
||||
triggerSavedFlash();
|
||||
setHeaderLocked(true);
|
||||
}
|
||||
} else {
|
||||
// Subsequent save — PATCH to update
|
||||
const response = await fetch(`/api/workouts/${savedWorkoutId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...payload,
|
||||
durationMinutes: payload.durationMinutes ?? null,
|
||||
difficulty: payload.difficulty ?? null,
|
||||
caloriesBurned: payload.caloriesBurned ?? null,
|
||||
notes: payload.notes ?? null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
triggerSavedFlash();
|
||||
setHeaderLocked(true);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Auto-save failed:", error);
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
setAutoSaving(false);
|
||||
}
|
||||
},
|
||||
[buildPayload, savedWorkoutId, triggerSavedFlash]
|
||||
);
|
||||
|
||||
// ---------- Exercise handlers ----------
|
||||
const handleAddExercise = (exercise: Exercise) => {
|
||||
if (addedExercises.some((e) => e.exercise.id === exercise.id)) {
|
||||
setExpandedExercise(exercise.id);
|
||||
return;
|
||||
}
|
||||
|
||||
setAddedExercises((prev) => [
|
||||
...prev,
|
||||
{
|
||||
exercise,
|
||||
sets: [{ setNumber: 1, reps: undefined, weight: undefined }],
|
||||
},
|
||||
]);
|
||||
setExpandedExercise(exercise.id);
|
||||
};
|
||||
|
||||
const handleExerciseCreated = (exercise: Exercise) => {
|
||||
setExercises((prev) => [...prev, exercise]);
|
||||
};
|
||||
|
||||
const handleMoveExercise = (exerciseId: string, direction: "up" | "down") => {
|
||||
setAddedExercises((prev) => {
|
||||
const idx = prev.findIndex((e) => e.exercise.id === exerciseId);
|
||||
if (idx < 0) return prev;
|
||||
const swapIdx = direction === "up" ? idx - 1 : idx + 1;
|
||||
if (swapIdx < 0 || swapIdx >= prev.length) return prev;
|
||||
const updated = [...prev];
|
||||
[updated[idx], updated[swapIdx]] = [updated[swapIdx], updated[idx]];
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemoveExercise = (exerciseId: string) => {
|
||||
setAddedExercises((prev) => {
|
||||
const updated = prev.filter((e) => e.exercise.id !== exerciseId);
|
||||
// Auto-save after removing exercise
|
||||
setTimeout(() => autoSave(updated), 0);
|
||||
return updated;
|
||||
});
|
||||
if (expandedExercise === exerciseId) setExpandedExercise(null);
|
||||
};
|
||||
|
||||
const handleAddSet = (exerciseId: string) => {
|
||||
setAddedExercises((prev) =>
|
||||
prev.map((e) => {
|
||||
if (e.exercise.id === exerciseId) {
|
||||
const nextSetNumber =
|
||||
Math.max(...e.sets.map((s) => s.setNumber), 0) + 1;
|
||||
return {
|
||||
...e,
|
||||
sets: [
|
||||
...e.sets,
|
||||
{ setNumber: nextSetNumber, reps: undefined, weight: undefined },
|
||||
],
|
||||
};
|
||||
}
|
||||
return e;
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const handleRemoveSet = (exerciseId: string, setNumber: number) => {
|
||||
setAddedExercises((prev) => {
|
||||
const updated = prev.map((e) => {
|
||||
if (e.exercise.id === exerciseId) {
|
||||
return {
|
||||
...e,
|
||||
sets: e.sets.filter((s) => s.setNumber !== setNumber),
|
||||
};
|
||||
}
|
||||
return e;
|
||||
});
|
||||
// Auto-save after removing set
|
||||
setTimeout(() => autoSave(updated), 0);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdateSet = (
|
||||
exerciseId: string,
|
||||
setNumber: number,
|
||||
data: { reps?: number; weight?: number; rpe?: number; notes?: string }
|
||||
) => {
|
||||
setAddedExercises((prev) =>
|
||||
prev.map((e) => {
|
||||
if (e.exercise.id === exerciseId) {
|
||||
return {
|
||||
...e,
|
||||
sets: e.sets.map((s) =>
|
||||
s.setNumber === setNumber ? { ...s, ...data } : s
|
||||
),
|
||||
};
|
||||
}
|
||||
return e;
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
// Called when user confirms a set (check icon) — triggers auto-save
|
||||
// Also clears forceEdit so the set stays locked when the exercise is collapsed/re-expanded
|
||||
const handleSetConfirmed = (exerciseId?: string, setNumber?: number) => {
|
||||
if (exerciseId && setNumber !== undefined) {
|
||||
setAddedExercises((prev) =>
|
||||
prev.map((e) => {
|
||||
if (e.exercise.id === exerciseId) {
|
||||
return {
|
||||
...e,
|
||||
sets: e.sets.map((s) =>
|
||||
s.setNumber === setNumber ? { ...s, forceEdit: false } : s
|
||||
),
|
||||
};
|
||||
}
|
||||
return e;
|
||||
})
|
||||
);
|
||||
}
|
||||
// Small delay to let state settle after the SetRow's emitUpdate
|
||||
setTimeout(() => autoSave(), 50);
|
||||
};
|
||||
|
||||
// Called when user taps "next set" arrow — confirm current set + add new pre-filled set
|
||||
const handleNextSet = (
|
||||
exerciseId: string,
|
||||
currentValues: {
|
||||
weight?: string;
|
||||
reps?: string;
|
||||
rpe?: string;
|
||||
notes?: string;
|
||||
duration?: string;
|
||||
distance?: string;
|
||||
calories?: string;
|
||||
}
|
||||
) => {
|
||||
setAddedExercises((prev) =>
|
||||
prev.map((e) => {
|
||||
if (e.exercise.id === exerciseId) {
|
||||
const nextSetNumber =
|
||||
Math.max(...e.sets.map((s) => s.setNumber), 0) + 1;
|
||||
return {
|
||||
...e,
|
||||
// Clear forceEdit on all existing sets (they're confirmed now)
|
||||
sets: [
|
||||
...e.sets.map((s) => (s.forceEdit ? { ...s, forceEdit: false } : s)),
|
||||
{
|
||||
setNumber: nextSetNumber,
|
||||
weight: currentValues.weight ? parseFloat(currentValues.weight) : undefined,
|
||||
reps: undefined, // User typically changes reps per set
|
||||
rpe: currentValues.rpe ? parseInt(currentValues.rpe) : undefined,
|
||||
notes: currentValues.notes || undefined,
|
||||
forceEdit: true, // Start in edit mode even though weight is pre-filled
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return e;
|
||||
})
|
||||
);
|
||||
// Auto-save after confirming the current set
|
||||
setTimeout(() => autoSave(), 50);
|
||||
};
|
||||
|
||||
// Called when user saves notes — triggers auto-save
|
||||
const handleNotesSave = () => {
|
||||
setNotesLocked(true);
|
||||
setTimeout(() => autoSave(), 50);
|
||||
};
|
||||
|
||||
// ---------- Save and Close ----------
|
||||
const handleSaveAndClose = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (addedExercises.length === 0) {
|
||||
alert("Please add at least one exercise");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
// Wait for any in-flight auto-save to finish to avoid race conditions
|
||||
// (both would delete-all-sets + recreate simultaneously)
|
||||
while (savingRef.current) {
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
// Prevent auto-saves from starting while we do the final save
|
||||
savingRef.current = true;
|
||||
|
||||
const payload = buildPayload();
|
||||
|
||||
if (!savedWorkoutId) {
|
||||
// Never saved before — create
|
||||
const response = await fetch("/api/workouts", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to save workout");
|
||||
} else {
|
||||
// Already saved — final update
|
||||
const response = await fetch(`/api/workouts/${savedWorkoutId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...payload,
|
||||
durationMinutes: payload.durationMinutes ?? null,
|
||||
difficulty: payload.difficulty ?? null,
|
||||
caloriesBurned: payload.caloriesBurned ?? null,
|
||||
notes: payload.notes ?? null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to save workout");
|
||||
}
|
||||
|
||||
// Navigate back: to detail page if editing, otherwise to list
|
||||
if (editWorkout) {
|
||||
router.push(`/main/workouts/${savedWorkoutId || editWorkout.id}`);
|
||||
} else {
|
||||
router.push("/main/workouts");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error saving workout:", error);
|
||||
alert("Failed to save workout. Please try again.");
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSaveAndClose}
|
||||
onKeyDown={(e) => {
|
||||
// Prevent Enter from submitting form when editing inputs
|
||||
if (e.key === "Enter") {
|
||||
const target = e.target as HTMLElement;
|
||||
const tag = target.tagName.toLowerCase();
|
||||
// Allow submit only from the submit button itself
|
||||
if (tag === "input" || tag === "textarea" || tag === "select") {
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="space-y-6"
|
||||
>
|
||||
{/* Auto-save indicator — fixed height to prevent layout shift */}
|
||||
<div className="h-4 flex items-center justify-center">
|
||||
<div className={`flex items-center gap-1.5 text-[10px] transition-opacity duration-300 ${autoSaving || showSavedFlash ? "opacity-100" : "opacity-0"} ${autoSaving ? "text-zinc-500" : "text-green-500"}`}>
|
||||
{autoSaving ? (
|
||||
<>
|
||||
<Loader className="w-3 h-3 animate-spin" />
|
||||
<span>Saving...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Check className="w-3 h-3" />
|
||||
<span>Saved</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Workout name & date */}
|
||||
{headerLocked ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-lg font-bold text-white truncate">{workoutName || "Unnamed Workout"}</h2>
|
||||
<p className="text-sm text-zinc-400">
|
||||
{new Date(workoutDate + "T12:00:00").toLocaleDateString("en-US", {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setHeaderLocked(false)}
|
||||
className="p-2 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors flex-shrink-0"
|
||||
aria-label="Edit name and date"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Workout Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={workoutName}
|
||||
onChange={(e) => setWorkoutName(e.target.value)}
|
||||
placeholder="- -"
|
||||
className="w-full px-4 py-3 border border-zinc-700 rounded-lg bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={workoutDate}
|
||||
onChange={(e) => setWorkoutDate(e.target.value)}
|
||||
className="w-full px-4 py-3 border border-zinc-700 rounded-lg bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 [color-scheme:dark]"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Exercises */}
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-3">
|
||||
Exercises
|
||||
</h3>
|
||||
|
||||
{/* Added exercises */}
|
||||
{addedExercises.length > 0 && (
|
||||
<div className="space-y-2 mb-4">
|
||||
{addedExercises.map((item, exIdx) => (
|
||||
<div
|
||||
key={item.exercise.id}
|
||||
className="border border-zinc-800 rounded-lg bg-zinc-900 relative"
|
||||
>
|
||||
{/* Exercise header — compact with reorder */}
|
||||
<div className="flex items-center">
|
||||
{/* Reorder buttons */}
|
||||
{addedExercises.length > 1 && (
|
||||
<div className="flex flex-col pl-1.5 -mr-1 flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleMoveExercise(item.exercise.id, "up")}
|
||||
disabled={exIdx === 0}
|
||||
className="p-0.5 text-zinc-600 hover:text-zinc-300 disabled:opacity-20 disabled:hover:text-zinc-600 transition-colors"
|
||||
aria-label="Move exercise up"
|
||||
>
|
||||
<ArrowUp className="w-3 h-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleMoveExercise(item.exercise.id, "down")}
|
||||
disabled={exIdx === addedExercises.length - 1}
|
||||
className="p-0.5 text-zinc-600 hover:text-zinc-300 disabled:opacity-20 disabled:hover:text-zinc-600 transition-colors"
|
||||
aria-label="Move exercise down"
|
||||
>
|
||||
<ArrowDown className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setExpandedExercise(
|
||||
expandedExercise === item.exercise.id
|
||||
? null
|
||||
: item.exercise.id
|
||||
)
|
||||
}
|
||||
className="flex-1 flex items-center justify-between px-3 py-2.5 hover:bg-zinc-800/50 transition-colors rounded-lg min-w-0"
|
||||
>
|
||||
<div className="text-left flex-1 min-w-0">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<h4 className="font-semibold text-white text-sm truncate">
|
||||
{item.exercise.name}
|
||||
</h4>
|
||||
<span className="text-xs text-zinc-500 flex-shrink-0">
|
||||
{item.sets.length} set{item.sets.length !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
{item.sets.some((s) => s.reps || s.weight) && (
|
||||
<p className="text-xs text-zinc-400 mt-0.5 truncate">
|
||||
{formatSetsSummary(item.sets)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{expandedExercise === item.exercise.id ? (
|
||||
<ChevronUp className="w-4 h-4 text-zinc-500 flex-shrink-0 ml-2" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 text-zinc-500 flex-shrink-0 ml-2" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* History popup toggle */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setHistoryPopupExercise(
|
||||
historyPopupExercise === item.exercise.id ? null : item.exercise.id
|
||||
);
|
||||
}}
|
||||
className="p-2 mr-1 rounded-md flex-shrink-0 transition-colors text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800"
|
||||
aria-label="View exercise history"
|
||||
title="View history"
|
||||
>
|
||||
<Clock className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Exercise history popup */}
|
||||
{historyPopupExercise === item.exercise.id && (
|
||||
<ExerciseHistoryPopup
|
||||
exerciseId={item.exercise.id}
|
||||
onClose={() => setHistoryPopupExercise(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Exercise body (expanded) */}
|
||||
{expandedExercise === item.exercise.id && (
|
||||
<div className="border-t border-zinc-800 p-3 space-y-3">
|
||||
<div className="space-y-2">
|
||||
{item.sets.map((set, idx) => (
|
||||
<SetRow
|
||||
key={`${item.exercise.id}-${set.setNumber}`}
|
||||
setNumber={set.setNumber}
|
||||
inputFields={parseInputFields(item.exercise)}
|
||||
weightUnit={(item.exercise as any).defaultWeightUnit || "lbs"}
|
||||
initialReps={set.reps}
|
||||
initialWeight={set.weight}
|
||||
initialRpe={set.rpe}
|
||||
initialNotes={set.notes}
|
||||
initialLocked={set.forceEdit ? false : !!(set.reps || set.weight)}
|
||||
autoFocus={set.forceEdit || (idx === item.sets.length - 1 && !set.reps && !set.weight)}
|
||||
onUpdate={(data) =>
|
||||
handleUpdateSet(
|
||||
item.exercise.id,
|
||||
set.setNumber,
|
||||
data
|
||||
)
|
||||
}
|
||||
onConfirm={() => handleSetConfirmed(item.exercise.id, set.setNumber)}
|
||||
onNextSet={(vals) => handleNextSet(item.exercise.id, vals)}
|
||||
onDelete={() =>
|
||||
handleRemoveSet(item.exercise.id, set.setNumber)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleAddSet(item.exercise.id)}
|
||||
className="flex-1 py-1.5 border border-dashed border-zinc-700 rounded-lg text-zinc-400 text-sm font-medium hover:text-white hover:border-zinc-600 transition-colors flex items-center justify-center gap-1.5"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Set
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveExercise(item.exercise.id)}
|
||||
className="py-1.5 px-3 text-red-500 text-sm font-medium hover:bg-red-950/30 rounded-lg transition-colors flex items-center gap-1.5"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Inline exercise search */}
|
||||
<ExercisePicker
|
||||
exercises={exercises}
|
||||
recentlyUsed={recentlyUsedExercises}
|
||||
onSelect={handleAddExercise}
|
||||
onExerciseCreated={handleExerciseCreated}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Post-workout: Notes, Duration, Calories, Difficulty */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-zinc-400 uppercase tracking-wider">
|
||||
Post-Workout
|
||||
</h3>
|
||||
|
||||
{/* Notes — lockable */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-[10px] font-medium text-zinc-500">Notes</label>
|
||||
{notes && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={notesLocked ? () => setNotesLocked(false) : handleNotesSave}
|
||||
className="text-[10px] text-zinc-500 hover:text-zinc-300 transition-colors"
|
||||
>
|
||||
{notesLocked ? "Edit" : "Save"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{notesLocked ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNotesLocked(false)}
|
||||
className="w-full text-left px-3 py-2 border border-zinc-700 rounded-md bg-zinc-900 text-sm text-zinc-300 hover:bg-zinc-800 transition-colors"
|
||||
>
|
||||
<p className="line-clamp-2">{notes}</p>
|
||||
</button>
|
||||
) : (
|
||||
<textarea
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
placeholder="Type notes as you go..."
|
||||
className="w-full px-3 py-2 border border-zinc-700 rounded-md bg-zinc-800 text-sm text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600 resize-none"
|
||||
rows={2}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{/* Duration */}
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<label className="text-[10px] font-medium text-zinc-500 whitespace-nowrap">Duration</label>
|
||||
{duration && (
|
||||
<button type="button" onClick={() => setDuration("")} className="text-[9px] text-zinc-600 hover:text-zinc-400">✕</button>
|
||||
)}
|
||||
</div>
|
||||
{duration ? (
|
||||
<input
|
||||
type="number"
|
||||
value={duration}
|
||||
onChange={(e) => setDuration(e.target.value)}
|
||||
placeholder="min"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDuration("45")}
|
||||
className="w-full py-1.5 border border-dashed border-zinc-700 rounded-md text-zinc-500 text-xs hover:text-white hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
N/A
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Calories */}
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<label className="text-[10px] font-medium text-zinc-500 whitespace-nowrap">Calories</label>
|
||||
{workoutCalories && (
|
||||
<button type="button" onClick={() => setWorkoutCalories("")} className="text-[9px] text-zinc-600 hover:text-zinc-400">✕</button>
|
||||
)}
|
||||
</div>
|
||||
{workoutCalories ? (
|
||||
<input
|
||||
type="number"
|
||||
value={workoutCalories}
|
||||
onChange={(e) => setWorkoutCalories(e.target.value)}
|
||||
placeholder="kcal"
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20 placeholder:text-zinc-600"
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setWorkoutCalories("300")}
|
||||
className="w-full py-1.5 border border-dashed border-zinc-700 rounded-md text-zinc-500 text-xs hover:text-white hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
N/A
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Difficulty */}
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<label className="text-[10px] font-medium text-zinc-500 whitespace-nowrap">Difficulty</label>
|
||||
{difficulty && (
|
||||
<button type="button" onClick={() => setDifficulty("")} className="text-[9px] text-zinc-600 hover:text-zinc-400">✕</button>
|
||||
)}
|
||||
</div>
|
||||
{difficulty ? (
|
||||
<select
|
||||
value={difficulty}
|
||||
onChange={(e) => setDifficulty(e.target.value)}
|
||||
className="w-full px-2 py-1.5 border border-zinc-700 rounded-md text-sm bg-zinc-800 text-white focus:outline-none focus:ring-2 focus:ring-white/20"
|
||||
>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<option key={i + 1} value={String(i + 1)}>{i + 1}/10</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDifficulty("5")}
|
||||
className="w-full py-1.5 border border-dashed border-zinc-700 rounded-md text-zinc-500 text-xs hover:text-white hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
N/A
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Save and Close button */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full py-3 bg-white text-black font-semibold rounded-lg hover:bg-zinc-200 disabled:bg-zinc-700 disabled:text-zinc-500 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader className="w-5 h-5 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="w-4 h-4" />
|
||||
Save and Close
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user