Initial commit for Start9 packaging
This commit is contained in:
@@ -0,0 +1,256 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Exercise } from "@prisma/client";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
const EXERCISE_TYPES = [
|
||||
"barbell",
|
||||
"dumbbell",
|
||||
"machine",
|
||||
"cable",
|
||||
"bodyweight",
|
||||
"cardio",
|
||||
"kettlebell",
|
||||
"other",
|
||||
];
|
||||
|
||||
const MUSCLE_GROUPS = [
|
||||
"chest",
|
||||
"back",
|
||||
"shoulders",
|
||||
"biceps",
|
||||
"triceps",
|
||||
"forearms",
|
||||
"quads",
|
||||
"hamstrings",
|
||||
"glutes",
|
||||
"calves",
|
||||
"core",
|
||||
"cardio",
|
||||
];
|
||||
|
||||
const INPUT_FIELD_OPTIONS = [
|
||||
{ value: "sets", label: "Sets" },
|
||||
{ value: "reps", label: "Reps" },
|
||||
{ value: "weight", label: "Weight" },
|
||||
{ value: "duration", label: "Duration" },
|
||||
{ value: "distance", label: "Distance" },
|
||||
{ value: "calories", label: "Calories" },
|
||||
];
|
||||
|
||||
interface AddExerciseFormProps {
|
||||
onExerciseAdded: (exercise: Exercise) => void;
|
||||
}
|
||||
|
||||
export default function AddExerciseForm({
|
||||
onExerciseAdded,
|
||||
}: AddExerciseFormProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
type: "barbell",
|
||||
muscleGroups: [] as string[],
|
||||
inputFields: ["sets", "reps", "weight"] as string[],
|
||||
description: "",
|
||||
});
|
||||
|
||||
const handleMuscleGroupToggle = (group: string) => {
|
||||
setFormData((prev) => {
|
||||
const groups = prev.muscleGroups.includes(group)
|
||||
? prev.muscleGroups.filter((g) => g !== group)
|
||||
: [...prev.muscleGroups, group];
|
||||
return { ...prev, muscleGroups: groups };
|
||||
});
|
||||
};
|
||||
|
||||
const handleInputFieldToggle = (field: string) => {
|
||||
setFormData((prev) => {
|
||||
const fields = prev.inputFields.includes(field)
|
||||
? prev.inputFields.filter((f) => f !== field)
|
||||
: [...prev.inputFields, field];
|
||||
return { ...prev, inputFields: fields };
|
||||
});
|
||||
};
|
||||
|
||||
// Auto-set sensible input fields when type changes
|
||||
const handleTypeChange = (type: string) => {
|
||||
let defaultFields = ["sets", "reps", "weight"];
|
||||
if (type === "cardio") {
|
||||
defaultFields = ["sets", "duration", "calories"];
|
||||
} else if (type === "bodyweight") {
|
||||
defaultFields = ["sets", "reps"];
|
||||
}
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
type,
|
||||
inputFields: defaultFields,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/exercises", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: formData.name,
|
||||
type: formData.type,
|
||||
muscleGroups: formData.muscleGroups,
|
||||
inputFields: formData.inputFields,
|
||||
description: formData.description || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(data.error || "Failed to add exercise");
|
||||
}
|
||||
|
||||
const exercise = await response.json();
|
||||
onExerciseAdded(exercise);
|
||||
|
||||
setFormData({
|
||||
name: "",
|
||||
type: "barbell",
|
||||
muscleGroups: [],
|
||||
inputFields: ["sets", "reps", "weight"],
|
||||
description: "",
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "An error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{error && (
|
||||
<div className="bg-red-900/50 border border-red-800 rounded-lg p-3 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-zinc-400 uppercase tracking-wider mb-2">
|
||||
Exercise Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={formData.name}
|
||||
onChange={(e) =>
|
||||
setFormData((prev) => ({ ...prev, name: e.target.value }))
|
||||
}
|
||||
className="w-full px-4 py-3 bg-zinc-800 border border-zinc-700 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-white/20"
|
||||
placeholder="e.g., Barbell Bench Press"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Equipment */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-zinc-400 uppercase tracking-wider mb-2">
|
||||
Equipment
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{EXERCISE_TYPES.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
onClick={() => handleTypeChange(type)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
formData.type === type
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{type.charAt(0).toUpperCase() + type.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Input Fields */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-zinc-400 uppercase tracking-wider mb-1">
|
||||
Tracked Fields
|
||||
</label>
|
||||
<p className="text-xs text-zinc-600 mb-2">
|
||||
What data do you log for this exercise?
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{INPUT_FIELD_OPTIONS.map((field) => (
|
||||
<button
|
||||
key={field.value}
|
||||
type="button"
|
||||
onClick={() => handleInputFieldToggle(field.value)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
formData.inputFields.includes(field.value)
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{field.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Muscle Groups */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-zinc-400 uppercase tracking-wider mb-2">
|
||||
Muscle Groups
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{MUSCLE_GROUPS.map((group) => (
|
||||
<button
|
||||
key={group}
|
||||
type="button"
|
||||
onClick={() => handleMuscleGroupToggle(group)}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
formData.muscleGroups.includes(group)
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{group.charAt(0).toUpperCase() + group.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-zinc-400 uppercase tracking-wider mb-2">
|
||||
Description (optional)
|
||||
</label>
|
||||
<textarea
|
||||
value={formData.description}
|
||||
onChange={(e) =>
|
||||
setFormData((prev) => ({ ...prev, description: e.target.value }))
|
||||
}
|
||||
className="w-full px-4 py-3 bg-zinc-800 border border-zinc-700 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-white/20 resize-none"
|
||||
placeholder="Notes about form, tips, or variations..."
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !formData.name}
|
||||
className="w-full bg-white hover:bg-zinc-200 disabled:bg-zinc-700 disabled:text-zinc-500 text-black font-bold py-3 px-4 rounded-lg transition flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{loading ? "Adding..." : "Add Exercise"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import { Exercise } from "@prisma/client";
|
||||
import Link from "next/link";
|
||||
import { Dumbbell } from "lucide-react";
|
||||
|
||||
const TYPE_COLORS: Record<string, string> = {
|
||||
barbell: "bg-red-900/50 text-red-400",
|
||||
dumbbell: "bg-blue-900/50 text-blue-400",
|
||||
machine: "bg-purple-900/50 text-purple-400",
|
||||
cable: "bg-amber-900/50 text-amber-400",
|
||||
bodyweight: "bg-green-900/50 text-green-400",
|
||||
cardio: "bg-orange-900/50 text-orange-400",
|
||||
kettlebell: "bg-yellow-900/50 text-yellow-400",
|
||||
other: "bg-zinc-800 text-zinc-400",
|
||||
};
|
||||
|
||||
export default function ExerciseCard({ exercise }: { exercise: Exercise }) {
|
||||
const muscleGroups = JSON.parse(exercise.muscleGroups || "[]") as string[];
|
||||
const typeColor = TYPE_COLORS[exercise.type] || TYPE_COLORS.other;
|
||||
|
||||
return (
|
||||
<Link href={`/main/exercises/${exercise.id}`}>
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg hover:border-zinc-700 transition p-4 h-full flex flex-col cursor-pointer">
|
||||
<div className="flex items-start gap-3 mb-3">
|
||||
<div className="bg-zinc-800 p-2 rounded-lg">
|
||||
<Dumbbell className="w-5 h-5 text-zinc-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-white truncate">
|
||||
{exercise.name}
|
||||
</h3>
|
||||
<div
|
||||
className={`inline-block mt-1 px-2 py-0.5 rounded text-xs font-medium ${typeColor}`}
|
||||
>
|
||||
{exercise.type.charAt(0).toUpperCase() + exercise.type.slice(1)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{exercise.description && (
|
||||
<p className="text-sm text-zinc-500 mb-3 line-clamp-2">
|
||||
{exercise.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{muscleGroups.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 mt-auto">
|
||||
{muscleGroups.slice(0, 3).map((group) => (
|
||||
<span
|
||||
key={group}
|
||||
className="inline-block px-2 py-0.5 bg-zinc-800 text-zinc-400 rounded text-xs"
|
||||
>
|
||||
{group.charAt(0).toUpperCase() + group.slice(1)}
|
||||
</span>
|
||||
))}
|
||||
{muscleGroups.length > 3 && (
|
||||
<span className="inline-block px-2 py-0.5 bg-zinc-800 text-zinc-500 rounded text-xs">
|
||||
+{muscleGroups.length - 3}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Search, Plus, Loader2, Dumbbell, X } from "lucide-react";
|
||||
import ExerciseCard from "@/components/exercises/ExerciseCard";
|
||||
import AddExerciseForm from "@/components/exercises/AddExerciseForm";
|
||||
import { Exercise } from "@prisma/client";
|
||||
import { scoreExercise } from "@/lib/exerciseSearch";
|
||||
|
||||
export default function ExercisesClient() {
|
||||
const [exercises, setExercises] = useState<Exercise[]>([]);
|
||||
const [filteredExercises, setFilteredExercises] = useState<Exercise[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedMuscleGroup, setSelectedMuscleGroup] = useState<string | null>(
|
||||
null
|
||||
);
|
||||
const [selectedType, setSelectedType] = useState<string | null>(null);
|
||||
const [showAddForm, setShowAddForm] = useState(false);
|
||||
|
||||
// Build filter tags dynamically from all exercises
|
||||
const muscleGroups = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const ex of exercises) {
|
||||
try {
|
||||
const groups = JSON.parse(ex.muscleGroups || "[]") as string[];
|
||||
groups.forEach((g) => set.add(g.toLowerCase()));
|
||||
} catch {}
|
||||
}
|
||||
return Array.from(set).sort();
|
||||
}, [exercises]);
|
||||
|
||||
const equipmentTypes = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const ex of exercises) {
|
||||
if (ex.type) set.add(ex.type.toLowerCase());
|
||||
}
|
||||
return Array.from(set).sort();
|
||||
}, [exercises]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchExercises = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/exercises");
|
||||
const data = await response.json();
|
||||
setExercises(data);
|
||||
setFilteredExercises(data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch exercises:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchExercises();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let filtered = exercises;
|
||||
|
||||
// Apply muscle group filter
|
||||
if (selectedMuscleGroup) {
|
||||
filtered = filtered.filter((ex) => {
|
||||
try {
|
||||
const muscleGroups = JSON.parse(ex.muscleGroups || "[]");
|
||||
return muscleGroups.includes(selectedMuscleGroup);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Apply equipment type filter
|
||||
if (selectedType) {
|
||||
filtered = filtered.filter(
|
||||
(ex) => ex.type?.toLowerCase() === selectedType
|
||||
);
|
||||
}
|
||||
|
||||
// Apply fuzzy search with abbreviation expansion
|
||||
if (searchQuery.trim()) {
|
||||
filtered = filtered
|
||||
.map((ex) => ({ exercise: ex, score: scoreExercise(searchQuery, ex.name) }))
|
||||
.filter((item) => item.score >= 0)
|
||||
.sort((a, b) => a.score - b.score)
|
||||
.map((item) => item.exercise);
|
||||
} else {
|
||||
filtered = filtered.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
setFilteredExercises(filtered);
|
||||
}, [searchQuery, selectedMuscleGroup, selectedType, exercises]);
|
||||
|
||||
const handleExerciseAdded = (newExercise: Exercise) => {
|
||||
setExercises([...exercises, newExercise]);
|
||||
setShowAddForm(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-6 sm:px-6">
|
||||
{/* Controls */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-3 w-5 h-5 text-zinc-500" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search exercises..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-10 py-2.5 bg-zinc-900 border border-zinc-800 rounded-lg text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-white/20"
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSearchQuery("")}
|
||||
className="absolute right-3 top-3 p-0.5 rounded text-zinc-500 hover:text-white transition-colors"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowAddForm(!showAddForm)}
|
||||
className="bg-white hover:bg-zinc-200 text-black font-medium py-2.5 px-4 rounded-lg flex items-center justify-center gap-2 transition"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
Add Exercise
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Add Exercise Form */}
|
||||
{showAddForm && (
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6 mb-6">
|
||||
<h2 className="text-lg font-bold text-white mb-4">
|
||||
Add Custom Exercise
|
||||
</h2>
|
||||
<AddExerciseForm onExerciseAdded={handleExerciseAdded} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Equipment Type Filter */}
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
<span className="text-xs text-zinc-600 uppercase tracking-wider self-center mr-1">Equipment</span>
|
||||
{equipmentTypes.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
onClick={() =>
|
||||
setSelectedType(selectedType === type ? null : type)
|
||||
}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
selectedType === type
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-900 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{type.charAt(0).toUpperCase() + type.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Muscle Group Filter */}
|
||||
<div className="mb-6 flex flex-wrap gap-2">
|
||||
<span className="text-xs text-zinc-600 uppercase tracking-wider self-center mr-1">Muscle</span>
|
||||
{muscleGroups.map((group) => (
|
||||
<button
|
||||
key={group}
|
||||
onClick={() =>
|
||||
setSelectedMuscleGroup(
|
||||
selectedMuscleGroup === group ? null : group
|
||||
)
|
||||
}
|
||||
className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${
|
||||
selectedMuscleGroup === group
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-900 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{group.charAt(0).toUpperCase() + group.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Grid */}
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 text-zinc-500 animate-spin" />
|
||||
</div>
|
||||
) : filteredExercises.length === 0 ? (
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-12 text-center">
|
||||
<Dumbbell className="w-12 h-12 text-zinc-700 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-semibold text-white mb-2">
|
||||
No exercises found
|
||||
</h3>
|
||||
<p className="text-zinc-500">
|
||||
{searchQuery || selectedMuscleGroup || selectedType
|
||||
? "Try adjusting your filters"
|
||||
: "Add your first exercise to get started"}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredExercises.map((exercise) => (
|
||||
<ExerciseCard key={exercise.id} exercise={exercise} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,456 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { User } from "@prisma/client";
|
||||
import { Loader2, Eye, EyeOff, Upload, AlertTriangle, CheckCircle2 } from "lucide-react";
|
||||
|
||||
interface UserPreferences {
|
||||
theme: string;
|
||||
defaultWeightUnit: string;
|
||||
defaultRestSeconds: number;
|
||||
enableClaudeAI: boolean;
|
||||
claudeApiKey?: string;
|
||||
}
|
||||
|
||||
export default function SettingsForm({ user }: { user: User }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [showApiKey, setShowApiKey] = useState(false);
|
||||
const [preferences, setPreferences] = useState<UserPreferences>({
|
||||
theme: "system",
|
||||
defaultWeightUnit: "lbs",
|
||||
defaultRestSeconds: 90,
|
||||
enableClaudeAI: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPreferences = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/preferences");
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setPreferences(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch preferences:", err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPreferences();
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/preferences", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(preferences),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(data.error || "Failed to save preferences");
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
setTimeout(() => setSuccess(false), 3000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "An error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Status Messages */}
|
||||
{error && (
|
||||
<div className="bg-red-900/30 border border-red-800 rounded-lg p-4 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="bg-green-900/30 border border-green-800 rounded-lg p-4 text-green-400 text-sm">
|
||||
Settings saved successfully!
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Profile Section */}
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6">
|
||||
<h2 className="text-lg font-bold text-white mb-4">Profile</h2>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={user.name || ""}
|
||||
disabled
|
||||
className="w-full px-3 py-2 border border-zinc-700 rounded-lg bg-zinc-800 text-zinc-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={user.email}
|
||||
disabled
|
||||
className="w-full px-3 py-2 border border-zinc-700 rounded-lg bg-zinc-800 text-zinc-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preferences Section */}
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6">
|
||||
<h2 className="text-lg font-bold text-white mb-4">Preferences</h2>
|
||||
<div className="space-y-4">
|
||||
{/* Weight Unit */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-2">
|
||||
Default Weight Unit
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
{["lbs", "kg"].map((unit) => (
|
||||
<button
|
||||
key={unit}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setPreferences((prev) => ({
|
||||
...prev,
|
||||
defaultWeightUnit: unit,
|
||||
}))
|
||||
}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
|
||||
preferences.defaultWeightUnit === unit
|
||||
? "bg-white text-black"
|
||||
: "bg-zinc-800 text-zinc-400 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{unit === "lbs" ? "Pounds (lbs)" : "Kilograms (kg)"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-zinc-600 mt-1.5">
|
||||
Kettlebell exercises always default to kg
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-2">
|
||||
Theme
|
||||
</label>
|
||||
<select
|
||||
value={preferences.theme}
|
||||
onChange={(e) =>
|
||||
setPreferences((prev) => ({
|
||||
...prev,
|
||||
theme: 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"
|
||||
>
|
||||
<option value="system">System</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Claude AI Section */}
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6">
|
||||
<h2 className="text-lg font-bold text-white mb-4">
|
||||
Claude AI Integration
|
||||
</h2>
|
||||
<p className="text-sm text-zinc-500 mb-4">
|
||||
Enable Claude AI to get personalized workout recommendations and
|
||||
program optimization suggestions.
|
||||
</p>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Enable Toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-zinc-300">
|
||||
Enable Claude AI
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setPreferences((prev) => ({
|
||||
...prev,
|
||||
enableClaudeAI: !prev.enableClaudeAI,
|
||||
}))
|
||||
}
|
||||
className={`relative w-11 h-6 rounded-full transition ${
|
||||
preferences.enableClaudeAI ? "bg-white" : "bg-zinc-700"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full transition-transform ${
|
||||
preferences.enableClaudeAI
|
||||
? "translate-x-5 bg-black"
|
||||
: "translate-x-0 bg-zinc-400"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* API Key Input - Only show if enabled */}
|
||||
{preferences.enableClaudeAI && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-400 mb-1">
|
||||
Claude API Key
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showApiKey ? "text" : "password"}
|
||||
value={preferences.claudeApiKey || ""}
|
||||
onChange={(e) =>
|
||||
setPreferences((prev) => ({
|
||||
...prev,
|
||||
claudeApiKey: e.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="sk-..."
|
||||
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 pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowApiKey(!showApiKey)}
|
||||
className="absolute right-3 top-2.5 text-zinc-500 hover:text-zinc-300"
|
||||
>
|
||||
{showApiKey ? (
|
||||
<EyeOff className="w-5 h-5" />
|
||||
) : (
|
||||
<Eye className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-zinc-600 mt-1">
|
||||
Get your API key from{" "}
|
||||
<a
|
||||
href="https://console.anthropic.com"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-zinc-400 hover:text-white underline"
|
||||
>
|
||||
console.anthropic.com
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Save Button */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full bg-white hover:bg-zinc-200 disabled:bg-zinc-700 disabled:text-zinc-500 text-black font-medium py-2.5 px-4 rounded-lg transition flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{loading ? "Saving..." : "Save Settings"}
|
||||
</button>
|
||||
|
||||
{/* Database Import Section */}
|
||||
<DatabaseImport />
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Database Import Component ----------
|
||||
function DatabaseImport() {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
const [importSuccess, setImportSuccess] = useState<{
|
||||
message: string;
|
||||
stats: { users: number; exercises: number; workouts: number };
|
||||
} | null>(null);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setImportError(null);
|
||||
setImportSuccess(null);
|
||||
setSelectedFile(file);
|
||||
setConfirmOpen(true);
|
||||
};
|
||||
|
||||
const handleImport = async () => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setImporting(true);
|
||||
setImportError(null);
|
||||
setImportSuccess(null);
|
||||
setConfirmOpen(false);
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("database", selectedFile);
|
||||
|
||||
const response = await fetch("/api/settings/import-db", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || "Import failed");
|
||||
}
|
||||
|
||||
setImportSuccess({
|
||||
message: data.message,
|
||||
stats: data.stats,
|
||||
});
|
||||
|
||||
// Clear the file input
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
setSelectedFile(null);
|
||||
} catch (err) {
|
||||
setImportError(
|
||||
err instanceof Error ? err.message : "An error occurred during import"
|
||||
);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setConfirmOpen(false);
|
||||
setSelectedFile(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6">
|
||||
<h2 className="text-lg font-bold text-white mb-1">Import Database</h2>
|
||||
<p className="text-sm text-zinc-500 mb-4">
|
||||
Upload an existing Workout Planner database file (app.db) to restore
|
||||
your workout history. A backup of the current database will be created
|
||||
automatically.
|
||||
</p>
|
||||
|
||||
{/* Error message */}
|
||||
{importError && (
|
||||
<div className="bg-red-900/30 border border-red-800 rounded-lg p-3 mb-4 flex items-start gap-2">
|
||||
<AlertTriangle className="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-sm text-red-400">{importError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success message */}
|
||||
{importSuccess && (
|
||||
<div className="bg-green-900/30 border border-green-800 rounded-lg p-3 mb-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<CheckCircle2 className="w-4 h-4 text-green-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-green-400">{importSuccess.message}</p>
|
||||
<p className="text-xs text-green-500 mt-1">
|
||||
Imported: {importSuccess.stats.users} user(s),{" "}
|
||||
{importSuccess.stats.exercises} exercises,{" "}
|
||||
{importSuccess.stats.workouts} workouts
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
className="mt-3 w-full py-2 bg-green-800/50 text-green-300 text-sm font-medium rounded-lg hover:bg-green-800/70 transition"
|
||||
>
|
||||
Refresh Page to Load Imported Data
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Confirmation dialog */}
|
||||
{confirmOpen && selectedFile && (
|
||||
<div className="bg-yellow-900/20 border border-yellow-800/50 rounded-lg p-4 mb-4">
|
||||
<div className="flex items-start gap-2 mb-3">
|
||||
<AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-yellow-400 font-medium">
|
||||
Replace current database?
|
||||
</p>
|
||||
<p className="text-xs text-yellow-600 mt-1">
|
||||
File: {selectedFile.name} (
|
||||
{(selectedFile.size / 1024).toFixed(0)} KB)
|
||||
</p>
|
||||
<p className="text-xs text-yellow-600 mt-0.5">
|
||||
Your current database will be backed up before replacement.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleImport}
|
||||
className="flex-1 py-2 bg-yellow-700/50 text-yellow-200 text-sm font-medium rounded-lg hover:bg-yellow-700/70 transition"
|
||||
>
|
||||
Yes, Import
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
className="flex-1 py-2 bg-zinc-800 text-zinc-400 text-sm font-medium rounded-lg hover:bg-zinc-700 transition"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File input and upload button */}
|
||||
{!confirmOpen && (
|
||||
<div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".db,.sqlite,.sqlite3"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
id="db-import-input"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={importing}
|
||||
className="w-full py-3 border border-dashed border-zinc-700 rounded-lg text-zinc-400 text-sm font-medium hover:text-white hover:border-zinc-500 disabled:opacity-50 transition flex items-center justify-center gap-2"
|
||||
>
|
||||
{importing ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Importing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="w-4 h-4" />
|
||||
Select Database File (.db)
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<p className="text-[10px] text-zinc-600 mt-2 text-center">
|
||||
Located at prisma/data/app.db in your local project
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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