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"; // 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"; // 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: "#ff0000", }; type Ref = HTMLDivElement; export const CreateUpdateLabelInline = forwardRef(function CreateUpdateLabelInline( { labelForm, setLabelForm, isUpdating, labelToUpdate }, ref ) { const router = useRouter(); const { workspaceSlug, projectId } = router.query; 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) .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 ) .then((res) => { console.log(res); 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 }) => ( <> {watch("color") && watch("color") !== "" && ( )} ( onChange(value.hex)} /> )} /> )}
{ reset(); setLabelForm(false); }} > Cancel {isUpdating ? ( {isSubmitting ? "Updating" : "Update"} ) : ( {isSubmitting ? "Adding" : "Add"} )}
); });