import React, { useEffect, useState } from "react"; import { useRouter } from "next/router"; import useSWR from "swr"; // react-hook-form import { useForm } from "react-hook-form"; // headless ui import { Combobox, Transition } from "@headlessui/react"; // icons import { RectangleGroupIcon, TagIcon } from "@heroicons/react/24/outline"; // services import issuesServices from "services/issues.service"; // types import type { IIssueLabels } from "types"; // fetch-keys import { PROJECT_ISSUE_LABELS } from "constants/fetch-keys"; type Props = { value: string[]; onChange: (value: string[]) => void; projectId: string; }; const defaultValues: Partial = { name: "", }; export const IssueLabelSelect: React.FC = ({ value, onChange, projectId }) => { // states const [query, setQuery] = useState(""); const router = useRouter(); const { workspaceSlug } = router.query; const [isOpen, setIsOpen] = useState(false); const { data: issueLabels, mutate: issueLabelsMutate } = useSWR( projectId ? PROJECT_ISSUE_LABELS(projectId) : null, workspaceSlug && projectId ? () => issuesServices.getIssueLabels(workspaceSlug as string, projectId) : null ); const onSubmit = async (data: IIssueLabels) => { if (!projectId || !workspaceSlug || isSubmitting) return; await issuesServices .createIssueLabel(workspaceSlug as string, projectId as string, data) .then((response) => { issueLabelsMutate((prevData) => [...(prevData ?? []), response], false); setIsOpen(false); reset(defaultValues); }) .catch((error) => { console.log(error); }); }; const { formState: { isSubmitting }, setFocus, reset, } = useForm({ defaultValues }); useEffect(() => { isOpen && setFocus("name"); }, [isOpen, setFocus]); const filteredOptions = query === "" ? issueLabels : issueLabels?.filter((l) => l.name.toLowerCase().includes(query.toLowerCase())); return ( <> onChange(val)} className="relative flex-shrink-0" multiple > {({ open }: any) => ( <> Labels {Array.isArray(value) ? value.map((v) => issueLabels?.find((l) => l.id === v)?.name).join(", ") || "Labels" : issueLabels?.find((l) => l.id === value)?.name || "Labels"} setQuery(event.target.value)} placeholder="Search" displayValue={(assigned: any) => assigned?.name} />
{issueLabels && filteredOptions ? ( filteredOptions.length > 0 ? ( filteredOptions.map((label) => { const children = issueLabels?.filter((l) => l.parent === label.id); if (children.length === 0) { if (!label.parent) return ( `${active ? "bg-indigo-50" : ""} ${ selected ? "bg-indigo-50 font-medium" : "" } flex cursor-pointer select-none items-center gap-2 truncate p-2 text-gray-900` } value={label.id} > {label.name} ); } else return (
{label.name}
{children.map((child) => ( `${active ? "bg-indigo-50" : ""} ${ selected ? "bg-indigo-50 font-medium" : "" } flex cursor-pointer select-none items-center gap-2 truncate p-2 text-gray-900` } value={child.id} > {child.name} ))}
); }) ) : (

No labels found

) ) : (

Loading...

)} {/*
{isOpen ? (
) : ( )}
*/}
)}
); };