feat(01-03): add PetForm and PetCard components

- PetForm: create/edit mode, species/breed from DB (never hardcoded)
- Species selector wired to listSpecies tRPC query
- Breed selector wired to listBreeds, resets on species change
- Bio (maxLength=150) + adoption story (maxLength=500) with char counters
- Pet name maxLength=30 with Zod validation via react-hook-form
- AvatarUploadZone stub (Plan 04 wires upload; disabled in create mode)
- PetCard: avatar with active orange ring, species badge, hover shadow
This commit is contained in:
admin committed 2026-06-06 10:11:54 +02:00
1 parent 69553b103b
commit 63d8c06b48
2 files changed
+426

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
"use client";
import { Card, CardContent } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
/**
* PetCard — renders a pet's identity card for the My Pets grid.
* Used in the /pets page for selecting and managing multiple pets.
* When isActive, displays an orange ring to indicate the active pet.
*/
interface PetCardProps {
pet: {
id: string;
name: string;
avatarKey?: string | null;
species: { id: string; name: string };
breed: { id: string; name: string } | null;
};
isActive: boolean;
onSelect: (petId: string) => void;
}
function getInitials(name: string): string {
return name.slice(0, 2).toUpperCase();
}
export function PetCard({ pet, isActive, onSelect }: PetCardProps) {
return (
<Card
className={`w-full cursor-pointer transition-shadow hover:shadow-md ${
isActive ? "ring-2 ring-orange-500" : ""
}`}
onClick={() => onSelect(pet.id)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onSelect(pet.id);
}
}}
aria-pressed={isActive}
aria-label={`${pet.name}${isActive ? " (active)" : ""}`}
>
<CardContent className="flex flex-col items-center gap-3 py-4">
{/* Avatar with active indicator */}
<div className="relative">
<Avatar
className={`size-24 ${
isActive ? "ring-2 ring-orange-500 ring-offset-2" : ""
}`}
>
{pet.avatarKey && (
<AvatarImage
src={`/api/avatar/${pet.avatarKey}`}
alt={pet.name}
/>
)}
<AvatarFallback className="text-base font-semibold">
{getInitials(pet.name)}
</AvatarFallback>
</Avatar>
{isActive && (
<span
className="absolute -bottom-1 -right-1 size-3 rounded-full bg-orange-500 ring-2 ring-background"
aria-hidden="true"
/>
)}
</div>
{/* Pet name */}
<p className="text-xl font-semibold text-center leading-tight">
{pet.name}
</p>
{/* Species badge */}
<Badge variant="secondary">{pet.species.name}</Badge>
{/* Active label */}
{isActive && (
<span className="text-xs text-orange-500 font-medium">Active</span>
)}
</CardContent>
</Card>
);
}
+338
View File
@@ -0,0 +1,338 @@
"use client";
import { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import { Loader2, Camera } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
/**
* PetForm — reusable create/edit form for pet profiles.
*
* Covers PET-01 (create) and PET-02 (edit) requirements.
* Species and breeds are fetched from DB — never hardcoded (anti-pattern prevention).
* Zod schema enforces character limits at the form layer (server-side also enforces via tRPC T-3-02).
* Avatar upload zone stub is rendered; wired in Plan 04.
*/
const petFormSchema = z.object({
name: z
.string()
.min(1, "This field is required.")
.max(30, "Pet name must be 30 characters or fewer."),
speciesId: z.string().min(1, "Please select a species."),
breedId: z.string().nullable().optional(),
bio: z
.string()
.max(150, "Bio must be 150 characters or fewer.")
.optional()
.nullable(),
adoptionStory: z
.string()
.max(500, "Adoption story must be 500 characters or fewer.")
.optional()
.nullable(),
});
type PetFormValues = z.infer<typeof petFormSchema>;
interface PetFormProps {
mode: "create" | "edit";
initialValues?: Partial<PetFormValues>;
petId?: string;
onSuccess?: (petId: string) => void;
}
/**
* Avatar upload zone stub — Plan 04 will wire the actual upload logic.
* In create mode, petId is undefined so upload is disabled.
*/
function AvatarUploadZone({ petId }: { petId?: string }) {
const isDisabled = !petId;
return (
<div
title={
isDisabled ? "Save your pet first to upload a photo." : undefined
}
className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-muted p-6 text-sm text-muted-foreground transition-colors ${
isDisabled
? "cursor-not-allowed opacity-50"
: "cursor-pointer hover:border-muted-foreground/50"
}`}
>
<Camera className="size-6" />
<span>Upload photo</span>
{isDisabled && (
<span className="text-xs">
Save your pet first to upload a photo.
</span>
)}
</div>
);
}
export function PetForm({
mode,
initialValues,
petId,
onSuccess,
}: PetFormProps) {
const trpc = useTRPC();
const queryClient = useQueryClient();
const [selectedSpeciesId, setSelectedSpeciesId] = useState<string>(
initialValues?.speciesId ?? ""
);
const { data: speciesList = [] } = useQuery({
...trpc.pets.listSpecies.queryOptions(),
staleTime: Infinity,
});
const { data: breedList = [] } = useQuery({
...trpc.pets.listBreeds.queryOptions(
{ speciesId: selectedSpeciesId || "__none__" },
),
enabled: !!selectedSpeciesId,
staleTime: Infinity,
});
const createMutation = useMutation({
...trpc.pets.create.mutationOptions(),
onSuccess: (pet) => {
void queryClient.invalidateQueries();
toast.success("Pet profile created");
onSuccess?.(pet.id);
},
onError: () => {
toast.error("Something went wrong. Please try again.");
},
});
const updateMutation = useMutation({
...trpc.pets.update.mutationOptions(),
onSuccess: () => {
void queryClient.invalidateQueries();
toast.success("Changes saved");
onSuccess?.(petId!);
},
onError: () => {
toast.error("Something went wrong. Please try again.");
},
});
const isLoading = createMutation.isPending || updateMutation.isPending;
const {
register,
handleSubmit,
control,
watch,
setValue,
formState: { errors },
} = useForm<PetFormValues>({
resolver: zodResolver(petFormSchema),
defaultValues: {
name: initialValues?.name ?? "",
speciesId: initialValues?.speciesId ?? "",
breedId: initialValues?.breedId ?? null,
bio: initialValues?.bio ?? "",
adoptionStory: initialValues?.adoptionStory ?? "",
},
});
const petName = watch("name");
const bioValue = watch("bio") ?? "";
const adoptionStoryValue = watch("adoptionStory") ?? "";
const onSubmit = (data: PetFormValues) => {
if (mode === "create") {
createMutation.mutate({
name: data.name,
speciesId: data.speciesId,
breedId: data.breedId ?? undefined,
bio: data.bio ?? undefined,
adoptionStory: data.adoptionStory ?? undefined,
});
} else {
updateMutation.mutate({
petId: petId!,
name: data.name,
breedId: data.breedId ?? null,
bio: data.bio ?? null,
adoptionStory: data.adoptionStory ?? null,
});
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
{/* Avatar upload zone (stub — Plan 04 wires actual upload) */}
<div className="flex flex-col gap-1.5">
<AvatarUploadZone petId={petId} />
</div>
{/* Pet name */}
<div className="flex flex-col gap-1.5">
<Label htmlFor="pet-name">Pet name</Label>
<Input
id="pet-name"
maxLength={30}
placeholder="Enter pet name"
aria-invalid={!!errors.name}
{...register("name")}
/>
{errors.name && (
<p className="text-xs text-destructive">{errors.name.message}</p>
)}
</div>
{/* Species selector */}
<div className="flex flex-col gap-1.5">
<Label htmlFor="species">Species</Label>
<Controller
name="speciesId"
control={control}
render={({ field }) => (
<Select
value={field.value || null}
onValueChange={(val) => {
const newVal = val ?? "";
field.onChange(newVal);
setSelectedSpeciesId(newVal);
// Reset breed when species changes (species and breed are coupled)
setValue("breedId", null);
}}
>
<SelectTrigger
id="species"
className="w-full"
aria-invalid={!!errors.speciesId}
>
<SelectValue placeholder="Select species" />
</SelectTrigger>
<SelectContent>
{speciesList.map((species) => (
<SelectItem key={species.id} value={species.id}>
{species.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
{errors.speciesId && (
<p className="text-xs text-destructive">
{errors.speciesId.message}
</p>
)}
</div>
{/* Breed selector */}
<div className="flex flex-col gap-1.5">
<Label htmlFor="breed">Breed</Label>
<Controller
name="breedId"
control={control}
render={({ field }) => (
<Select
value={field.value ?? null}
onValueChange={(val) => {
field.onChange(val ?? null);
}}
disabled={!selectedSpeciesId}
>
<SelectTrigger
id="breed"
className="w-full"
disabled={!selectedSpeciesId}
>
<SelectValue
placeholder={
selectedSpeciesId
? "Select breed (optional)"
: "Select a species first"
}
/>
</SelectTrigger>
<SelectContent>
{breedList.length === 0 ? (
<SelectItem value="__empty__" disabled>
No breeds found for this species.
</SelectItem>
) : (
breedList.map((breed) => (
<SelectItem key={breed.id} value={breed.id}>
{breed.name}
</SelectItem>
))
)}
</SelectContent>
</Select>
)}
/>
{errors.breedId && (
<p className="text-xs text-destructive">{errors.breedId.message}</p>
)}
</div>
{/* Bio */}
<div className="flex flex-col gap-1.5">
<Label htmlFor="bio">Bio</Label>
<Textarea
id="bio"
maxLength={150}
placeholder={`Tell us about ${petName || "your pet"}…`}
aria-invalid={!!errors.bio}
{...register("bio")}
/>
<span className="text-xs text-muted-foreground text-right">
{(bioValue ?? "").length}/150
</span>
{errors.bio && (
<p className="text-xs text-destructive">{errors.bio.message}</p>
)}
</div>
{/* Adoption story */}
<div className="flex flex-col gap-1.5">
<Label htmlFor="adoption-story">Adoption story</Label>
<Textarea
id="adoption-story"
maxLength={500}
placeholder={`How did ${petName || "your pet"} join your family?`}
aria-invalid={!!errors.adoptionStory}
{...register("adoptionStory")}
/>
<span className="text-xs text-muted-foreground text-right">
{(adoptionStoryValue ?? "").length}/500
</span>
{errors.adoptionStory && (
<p className="text-xs text-destructive">
{errors.adoptionStory.message}
</p>
)}
</div>
{/* Submit CTA */}
<Button type="submit" disabled={isLoading} className="w-full">
{isLoading && <Loader2 className="animate-spin" />}
{mode === "create" ? "Add Pet" : "Save changes"}
</Button>
</form>
);
}