import { Listbox, Transition } from "@headlessui/react"; import { Fragment, useEffect } from "react"; import { Controller, useForm } from "react-hook-form"; import { HiChevronUpDown, HiXMark } from "react-icons/hi2"; import { colours } from "@kan/shared/constants"; import Button from "~/components/Button"; import Input from "~/components/Input"; import Toggle from "~/components/Toggle"; import { useModal } from "~/providers/modal"; import { api } from "~/utils/api"; interface LabelFormInput { name: string; colour: Colour; isCreateAnotherEnabled?: boolean; } interface Colour { name: string; code: string; } export function LabelForm({ boardPublicId, refetch, isEdit, }: { boardPublicId: string; refetch: () => void; isEdit?: boolean; }) { const { closeModal, entityId, openModal } = useModal(); const label = api.label.byPublicId.useQuery( { labelPublicId: entityId, }, { enabled: isEdit && !!entityId, }, ); const { control, register, reset, handleSubmit, setValue, watch } = useForm({ values: { name: isEdit && label.data?.name ? label.data.name : "", colour: (isEdit && label.data?.colourCode ? colours.find((c) => c.code === label.data?.colourCode) : colours[0]) as Colour, isCreateAnotherEnabled: false, }, }); const isCreateAnotherEnabled = watch("isCreateAnotherEnabled"); const createLabel = api.label.create.useMutation({ onSuccess: () => { const currentColourIndex = colours.findIndex( (c) => c.code === watch("colour").code, ); try { refetch(); if (!isCreateAnotherEnabled) closeModal(); reset({ name: "", colour: colours[(currentColourIndex + 1) % colours.length], isCreateAnotherEnabled, }); } catch (e) { console.log(e); } }, }); const updateLabel = api.label.update.useMutation({ onSuccess: () => { refetch(); closeModal(); reset({ name: "", colour: colours[0], }); }, }); const onSubmit = (values: LabelFormInput) => { if (!values.colour.code) return; if (isEdit) { updateLabel.mutate({ labelPublicId: label.data?.publicId ?? "", name: values.name, colourCode: values.colour.code, }); } else { createLabel.mutate({ name: values.name, colourCode: values.colour.code, boardPublicId, }); } }; useEffect(() => { const nameElement: HTMLElement | null = document.querySelector("#label-name"); if (nameElement) nameElement.focus(); }, []); return (

{isEdit ? "Edit label" : "New label"}

{ if (e.key === "Enter") { e.preventDefault(); await handleSubmit(onSubmit)(); } }} /> ( {({ open }) => ( <>
{field.value.name} {colours.map((colour, index) => ( {() => ( <>
)}
))}
)}
)} />
{!isEdit && ( setValue("isCreateAnotherEnabled", !isCreateAnotherEnabled) } /> )}
{isEdit && ( )}
); }