import React, { forwardRef, useEffect } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react-hook-form import { Controller, SubmitHandler, useForm } from "react-hook-form"; // hooks import useUserAuth from "hooks/use-user-auth"; // react-color import { TwitterPicker } from "react-color"; // headless ui import { Popover, Transition } from "@headlessui/react"; // services import issuesService from "services/issues.service"; // ui import { Input, PrimaryButton, SecondaryButton } from "components/ui"; // icons import { ChevronDownIcon } from "@heroicons/react/24/outline"; // types import { IIssueLabels } from "types"; // fetch-keys import { PROJECT_ISSUE_LABELS } from "constants/fetch-keys"; type Props = { labelForm: boolean; setLabelForm: React.Dispatch>; isUpdating: boolean; labelToUpdate: IIssueLabels | null; }; const defaultValues: Partial = { name: "", color: "rgb(var(--color-text-200))", }; type Ref = HTMLDivElement; export const CreateUpdateLabelInline = forwardRef(function CreateUpdateLabelInline( { labelForm, setLabelForm, isUpdating, labelToUpdate }, ref ) { const router = useRouter(); const { workspaceSlug, projectId } = router.query; const { user } = useUserAuth(); const { handleSubmit, control, register, reset, formState: { errors, isSubmitting }, watch, setValue, } = useForm({ defaultValues, }); const handleLabelCreate: SubmitHandler = async (formData) => { if (!workspaceSlug || !projectId || isSubmitting) return; await issuesService .createIssueLabel(workspaceSlug as string, projectId as string, formData, user) .then((res) => { mutate( PROJECT_ISSUE_LABELS(projectId as string), (prevData) => [res, ...(prevData ?? [])], false ); reset(defaultValues); setLabelForm(false); }); }; const handleLabelUpdate: SubmitHandler = async (formData) => { if (!workspaceSlug || !projectId || isSubmitting) return; await issuesService .patchIssueLabel( workspaceSlug as string, projectId as string, labelToUpdate?.id ?? "", formData, user ) .then(() => { reset(defaultValues); mutate( PROJECT_ISSUE_LABELS(projectId as string), (prevData) => prevData?.map((p) => (p.id === labelToUpdate?.id ? { ...p, ...formData } : p)), false ); setLabelForm(false); }); }; useEffect(() => { if (!labelForm && isUpdating) return; reset(); }, [labelForm, isUpdating, reset]); useEffect(() => { if (!labelToUpdate) return; setValue( "color", labelToUpdate.color && labelToUpdate.color !== "" ? labelToUpdate.color : "#000" ); setValue("name", labelToUpdate.name); }, [labelToUpdate, setValue]); return (
{({ open }) => ( <> ( onChange(value.hex)} /> )} /> )}
{ reset(); setLabelForm(false); }} > Cancel {isUpdating ? ( {isSubmitting ? "Updating" : "Update"} ) : ( {isSubmitting ? "Adding" : "Add"} )}
); });