import { forwardRef, useEffect, Fragment } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; 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 { IssueLabelService } from "services/issue"; // ui import { Button, Input } from "@plane/ui"; // types import { IIssueLabels } from "types"; // fetch-keys import { PROJECT_ISSUE_LABELS } from "constants/fetch-keys"; import { getRandomLabelColor, LABEL_COLOR_OPTIONS } from "constants/label"; type Props = { labelForm: boolean; setLabelForm: React.Dispatch>; isUpdating: boolean; labelToUpdate: IIssueLabels | null; onClose?: () => void; }; const defaultValues: Partial = { name: "", color: "rgb(var(--color-text-200))", }; const issueLabelService = new IssueLabelService(); export const CreateUpdateLabelInline = forwardRef(function CreateUpdateLabelInline(props, ref) { const { labelForm, setLabelForm, isUpdating, labelToUpdate, onClose } = props; const router = useRouter(); const { workspaceSlug, projectId } = router.query; const { user } = useUserAuth(); const { handleSubmit, control, reset, formState: { errors, isSubmitting }, watch, setValue, } = useForm({ defaultValues, }); const handleClose = () => { setLabelForm(false); reset(defaultValues); if (onClose) onClose(); }; const handleLabelCreate: SubmitHandler = async (formData) => { if (!workspaceSlug || !projectId || isSubmitting) return; await issueLabelService .createIssueLabel(workspaceSlug as string, projectId as string, formData, user) .then((res) => { mutate( PROJECT_ISSUE_LABELS(projectId as string), (prevData) => [res, ...(prevData ?? [])], false ); handleClose(); }); }; const handleLabelUpdate: SubmitHandler = async (formData) => { if (!workspaceSlug || !projectId || isSubmitting) return; await issueLabelService .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 ); handleClose(); }); }; 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]); useEffect(() => { if (labelToUpdate) { setValue("color", labelToUpdate.color && labelToUpdate.color !== "" ? labelToUpdate.color : "#000"); return; } setValue("color", getRandomLabelColor()); }, [labelToUpdate, setValue]); return (
{({ open }) => ( <> ( onChange(value.hex)} /> )} /> )}
( )} />
{isUpdating ? ( ) : ( )}
); });