import { Fragment } from "react"; import { api } from "~/utils/api"; import { Menu, Transition } from "@headlessui/react"; import { HiMiniPlus } from "react-icons/hi2"; import { useForm } from "react-hook-form"; import { useModal } from "~/providers/modal"; import { HiEllipsisHorizontal } from "react-icons/hi2"; interface LabelSelectorProps { cardPublicId: string; labels: { publicId: string; name: string; selected: boolean; colourCode: string; }[]; isLoading: boolean; } export default function LabelSelector({ cardPublicId, labels, isLoading, }: LabelSelectorProps) { const { openModal } = useModal(); const utils = api.useUtils(); const refetchCard = () => utils.card.byId.refetch({ cardPublicId }); const addOrRemoveLabel = api.card.addOrRemoveLabel.useMutation({ onSuccess: async () => { await refetchCard(); }, }); const { register, handleSubmit, setValue, watch } = useForm({ values: Object.fromEntries( labels?.map((label) => [label.publicId, label.selected]) ?? [], ), }); const onSubmit = (values: Record) => { console.log({ values }); }; const selectedLabels = labels.filter((label) => label.selected); return ( <> {isLoading ? (
) : ( {selectedLabels.length ? ( <> {selectedLabels.map((label) => (
{label.name}
))} Add label ) : ( Add label )}
{labels?.map((label) => ( {() => (
{ const newValue = !watch(label.publicId); setValue(label.publicId, newValue); addOrRemoveLabel.mutate({ cardPublicId, labelPublicId: label.publicId, }); handleSubmit(onSubmit); }} > event.stopPropagation()} {...register(label.publicId)} checked={watch(label.publicId)} />
)}
))}
)} ); }