import React, { FC, useState, useRef, useEffect } from "react"; import { useRouter } from "next/router"; import { observer } from "mobx-react-lite"; import { Controller, useForm } from "react-hook-form"; import { LayoutPanelTop, Sparkle, X } from "lucide-react"; // editor import { RichTextEditorWithRef } from "@plane/rich-text-editor"; // hooks import { useApplication, useEstimate, useIssueDetail, useMention, useProject, useWorkspace } from "hooks/store"; import useToast from "hooks/use-toast"; // services import { AIService } from "services/ai.service"; import { FileService } from "services/file.service"; // components import { GptAssistantPopover } from "components/core"; import { ParentIssuesListModal } from "components/issues"; import { IssueLabelSelect } from "components/issues/select"; import { CreateLabelModal } from "components/labels"; import { CycleDropdown, DateDropdown, EstimateDropdown, ModuleSelectDropdown, PriorityDropdown, ProjectDropdown, ProjectMemberDropdown, StateDropdown, } from "components/dropdowns"; // ui import { Button, CustomMenu, Input, ToggleSwitch } from "@plane/ui"; // helpers import { renderFormattedPayloadDate } from "helpers/date-time.helper"; // types import type { TIssue, ISearchIssueResponse } from "@plane/types"; const defaultValues: Partial = { project_id: "", name: "", description_html: "", estimate_point: null, state_id: "", parent_id: null, priority: "none", assignee_ids: [], label_ids: [], cycle_id: null, module_ids: null, start_date: null, target_date: null, }; export interface IssueFormProps { data?: Partial; isCreateMoreToggleEnabled: boolean; onCreateMoreToggleChange: (value: boolean) => void; onChange?: (formData: Partial | null) => void; onClose: () => void; onSubmit: (values: Partial) => Promise; projectId: string; } // services const aiService = new AIService(); const fileService = new FileService(); export const IssueFormRoot: FC = observer((props) => { const { data, onChange, onClose, onSubmit, projectId: defaultProjectId, isCreateMoreToggleEnabled, onCreateMoreToggleChange, } = props; // states const [labelModal, setLabelModal] = useState(false); const [parentIssueListModalOpen, setParentIssueListModalOpen] = useState(false); const [selectedParentIssue, setSelectedParentIssue] = useState(null); const [gptAssistantModal, setGptAssistantModal] = useState(false); const [iAmFeelingLucky, setIAmFeelingLucky] = useState(false); // refs const editorRef = useRef(null); // router const router = useRouter(); const { workspaceSlug } = router.query; const workspaceStore = useWorkspace(); const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string; // store hooks const { config: { envConfig }, } = useApplication(); const { getProjectById } = useProject(); const { areEstimatesEnabledForProject } = useEstimate(); const { mentionHighlights, mentionSuggestions } = useMention(); const { issue: { getIssueById }, } = useIssueDetail(); // toast alert const { setToastAlert } = useToast(); // form info const { formState: { errors, isDirty, isSubmitting }, handleSubmit, reset, watch, control, getValues, setValue, } = useForm({ defaultValues: { ...defaultValues, project_id: defaultProjectId, ...data }, reValidateMode: "onChange", }); const projectId = watch("project_id"); //reset few fields on projectId change useEffect(() => { if (isDirty) { const formData = getValues(); reset({ ...defaultValues, project_id: projectId, name: formData.name, description_html: formData.description_html, priority: formData.priority, start_date: formData.start_date, target_date: formData.target_date, parent_id: formData.parent_id, }); } }, [projectId]); const issueName = watch("name"); const handleFormSubmit = async (formData: Partial) => { await onSubmit(formData); setGptAssistantModal(false); reset({ ...defaultValues, project_id: getValues("project_id"), }); editorRef?.current?.clearEditor(); }; const handleAiAssistance = async (response: string) => { if (!workspaceSlug || !projectId) return; setValue("description_html", `${watch("description_html")}

${response}

`); editorRef.current?.setEditorValue(`${watch("description_html")}`); }; const handleAutoGenerateDescription = async () => { if (!workspaceSlug || !projectId) return; setIAmFeelingLucky(true); aiService .createGptTask(workspaceSlug.toString(), projectId, { prompt: issueName, task: "Generate a proper description for this issue.", }) .then((res) => { if (res.response === "") setToastAlert({ type: "error", title: "Error!", message: "Issue title isn't informative enough to generate the description. Please try with a different title.", }); else handleAiAssistance(res.response_html); }) .catch((err) => { const error = err?.data?.error; if (err.status === 429) setToastAlert({ type: "error", title: "Error!", message: error || "You have reached the maximum number of requests of 50 requests per month per user.", }); else setToastAlert({ type: "error", title: "Error!", message: error || "Some error occurred. Please try again.", }); }) .finally(() => setIAmFeelingLucky(false)); }; const handleFormChange = () => { if (!onChange) return; if (isDirty && (watch("name") || watch("description_html"))) onChange(watch()); else onChange(null); }; const startDate = watch("start_date"); const targetDate = watch("target_date"); const minDate = startDate ? new Date(startDate) : null; minDate?.setDate(minDate.getDate()); const maxDate = targetDate ? new Date(targetDate) : null; maxDate?.setDate(maxDate.getDate()); const projectDetails = getProjectById(projectId); // executing this useEffect when the parent_id coming from the component prop useEffect(() => { const parentId = watch("parent_id") || undefined; if (!parentId) return; if (parentId === selectedParentIssue?.id || selectedParentIssue) return; const issue = getIssueById(parentId); if (!issue) return; const projectDetails = getProjectById(issue.project_id); if (!projectDetails) return; setSelectedParentIssue({ id: issue.id, name: issue.name, project_id: issue.project_id, project__identifier: projectDetails.identifier, project__name: projectDetails.name, sequence_id: issue.sequence_id, } as ISearchIssueResponse); }, [watch, getIssueById, getProjectById, selectedParentIssue]); return ( <> {projectId && ( setLabelModal(false)} projectId={projectId} onSuccess={(response) => { setValue("label_ids", [...watch("label_ids"), response.id]); handleFormChange(); }} /> )}
{/* Don't show project selection if editing an issue */} {!data?.id && ( (
{ onChange(projectId); handleFormChange(); }} buttonVariant="border-with-text" tabIndex={19} />
)} /> )}

{data?.id ? "Update" : "Create"} issue

{watch("parent_id") && selectedParentIssue && (
{selectedParentIssue.project__identifier}-{selectedParentIssue.sequence_id} {selectedParentIssue.name.substring(0, 50)} { setValue("parent_id", null); handleFormChange(); setSelectedParentIssue(null); }} tabIndex={20} />
)}
( { onChange(e.target.value); handleFormChange(); }} ref={ref} hasError={Boolean(errors.name)} placeholder="Issue Title" className="resize-none text-xl w-full" tabIndex={1} /> )} />
{issueName && issueName.trim() !== "" && envConfig?.has_openai_configured && ( )} {envConfig?.has_openai_configured && ( { setGptAssistantModal((prevData) => !prevData); // this is done so that the title do not reset after gpt popover closed reset(getValues()); }} onResponse={(response) => { handleAiAssistance(response); }} placement="top-end" button={ } /> )}
( { onChange(description_html); handleFormChange(); }} mentionHighlights={mentionHighlights} mentionSuggestions={mentionSuggestions} // tabIndex={2} /> )} />
(
{ onChange(stateId); handleFormChange(); }} projectId={projectId} buttonVariant="border-with-text" tabIndex={6} />
)} /> (
{ onChange(priority); handleFormChange(); }} buttonVariant="border-with-text" tabIndex={7} />
)} /> (
{ onChange(assigneeIds); handleFormChange(); }} buttonVariant={value?.length > 0 ? "transparent-without-text" : "border-with-text"} buttonClassName={value?.length > 0 ? "hover:bg-transparent px-0" : ""} placeholder="Assignees" multiple tabIndex={8} />
)} /> (
{ onChange(labelIds); handleFormChange(); }} projectId={projectId} tabIndex={9} />
)} /> (
{ onChange(date ? renderFormattedPayloadDate(date) : null); handleFormChange(); }} buttonVariant="border-with-text" placeholder="Start date" maxDate={maxDate ?? undefined} tabIndex={10} />
)} /> (
{ onChange(date ? renderFormattedPayloadDate(date) : null); handleFormChange(); }} buttonVariant="border-with-text" placeholder="Due date" minDate={minDate ?? undefined} tabIndex={11} />
)} /> {projectDetails?.cycle_view && ( (
{ onChange(cycleId); handleFormChange(); }} value={value} buttonVariant="border-with-text" tabIndex={12} />
)} /> )} {projectDetails?.module_view && workspaceSlug && ( (
{ onChange(moduleId); handleFormChange(); }} buttonVariant="border-with-text" tabIndex={13} multiple={true} showCount={true} />
)} /> )} {areEstimatesEnabledForProject(projectId) && ( (
{ onChange(estimatePoint); handleFormChange(); }} projectId={projectId} buttonVariant="border-with-text" tabIndex={14} />
)} /> )} {watch("parent_id") ? (
{selectedParentIssue && `${selectedParentIssue.project__identifier}- ${selectedParentIssue.sequence_id}`}
) : (
Add parent
)} } placement="bottom-start" tabIndex={15} > {watch("parent_id") ? ( <> setParentIssueListModalOpen(true)}> Change parent issue { setValue("parent_id", null); handleFormChange(); }} > Remove parent issue ) : ( setParentIssueListModalOpen(true)}> Select parent Issue )}
( setParentIssueListModalOpen(false)} onChange={(issue) => { onChange(issue.id); handleFormChange(); setSelectedParentIssue(issue); }} projectId={projectId} /> )} />
onCreateMoreToggleChange(!isCreateMoreToggleEnabled)} onKeyDown={(e) => { if (e.key === "Enter") onCreateMoreToggleChange(!isCreateMoreToggleEnabled); }} tabIndex={16} >
{}} size="sm" />
Create more
); });