import React, { FC, useState, useRef, useEffect, Fragment } from "react"; import { observer } from "mobx-react-lite"; import { useRouter } from "next/router"; import { Controller, useForm } from "react-hook-form"; import { LayoutPanelTop, Sparkle, X } from "lucide-react"; import { RichTextEditorWithRef } from "@plane/rich-text-editor"; import type { TIssue, ISearchIssueResponse } from "@plane/types"; // editor // hooks import { Button, CustomMenu, Input, Loader, ToggleSwitch, TOAST_TYPE, setToast } from "@plane/ui"; import { GptAssistantPopover } from "@/components/core"; import { CycleDropdown, DateDropdown, EstimateDropdown, ModuleDropdown, PriorityDropdown, ProjectDropdown, MemberDropdown, StateDropdown, } from "@/components/dropdowns"; import { ParentIssuesListModal } from "@/components/issues"; import { IssueLabelSelect } from "@/components/issues/select"; import { CreateLabelModal } from "@/components/labels"; import { renderFormattedPayloadDate, getDate } from "@/helpers/date-time.helper"; import { getChangedIssuefields } from "@/helpers/issue.helper"; import { shouldRenderProject } from "@/helpers/project.helper"; import { useApplication, useEstimate, useIssueDetail, useMention, useProject, useWorkspace } from "@/hooks/store"; // services import { AIService } from "@/services/ai.service"; import { FileService } from "@/services/file.service"; // components // ui // helpers // 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; issueTitleRef: React.MutableRefObject; isCreateMoreToggleEnabled: boolean; onCreateMoreToggleChange: (value: boolean) => void; onChange?: (formData: Partial | null) => void; onClose: () => void; onSubmit: (values: Partial, is_draft_issue?: boolean) => Promise; projectId: string; isDraft: boolean; } // services const aiService = new AIService(); const fileService = new FileService(); const TAB_INDICES = [ "name", "description_html", "feeling_lucky", "ai_assistant", "state_id", "priority", "assignee_ids", "label_ids", "start_date", "target_date", "cycle_id", "module_ids", "estimate_point", "parent_id", "create_more", "discard_button", "draft_button", "submit_button", "project_id", "remove_parent", ]; const getTabIndex = (key: string) => TAB_INDICES.findIndex((tabIndex) => tabIndex === key) + 1; export const IssueFormRoot: FC = observer((props) => { const { data, issueTitleRef, onChange, onClose, onSubmit, projectId: defaultProjectId, isCreateMoreToggleEnabled, onCreateMoreToggleChange, isDraft, } = 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(); // form info const { formState: { errors, isDirty, isSubmitting, dirtyFields }, 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, }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [projectId]); useEffect(() => { if (data?.description_html) setValue("description_html", data?.description_html); }, [data?.description_html]); const issueName = watch("name"); const handleFormSubmit = async (formData: Partial, is_draft_issue = false) => { const submitData = !data?.id ? formData : { ...getChangedIssuefields(formData, dirtyFields as { [key: string]: boolean | undefined }), project_id: getValues("project_id"), id: data.id, description_html: formData.description_html ?? "

", }; // this condition helps to move the issues from draft to project issues if (formData.hasOwnProperty("is_draft")) submitData.is_draft = formData.is_draft; await onSubmit(submitData, is_draft_issue); setGptAssistantModal(false); reset({ ...defaultValues, project_id: getValues("project_id"), }); editorRef?.current?.clearEditor(); }; const handleAiAssistance = async (response: string) => { if (!workspaceSlug || !projectId) return; editorRef.current?.setEditorValueAtCursorPosition(response); }; 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 === "") setToast({ type: TOAST_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) setToast({ type: TOAST_TYPE.ERROR, title: "Error!", message: error || "You have reached the maximum number of requests of 50 requests per month per user.", }); else setToast({ type: TOAST_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 = getDate(startDate); minDate?.setDate(minDate.getDate()); const maxDate = getDate(targetDate); 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(); }} /> )}
handleFormSubmit(data))}>
{/* Don't show project selection if editing an issue */} {!data?.id && ( (
{ onChange(projectId); handleFormChange(); }} buttonVariant="border-with-text" renderCondition={(project) => shouldRenderProject(project)} tabIndex={getTabIndex("project_id")} />
)} /> )}

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

{watch("parent_id") && selectedParentIssue && (
{selectedParentIssue.project__identifier}-{selectedParentIssue.sequence_id} {selectedParentIssue.name.substring(0, 50)}
)}
( { onChange(e.target.value); handleFormChange(); }} ref={issueTitleRef || ref} hasError={Boolean(errors.name)} placeholder="Issue Title" className="w-full resize-none text-xl" tabIndex={getTabIndex("name")} autoFocus /> )} />
{data?.description_html === undefined ? (
) : (
{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={getTabIndex("description_html")} /> )} />
)}
(
{ onChange(stateId); handleFormChange(); }} projectId={projectId} buttonVariant="border-with-text" tabIndex={getTabIndex("state_id")} />
)} /> (
{ onChange(priority); handleFormChange(); }} buttonVariant="border-with-text" tabIndex={getTabIndex("priority")} />
)} /> (
{ 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={getTabIndex("assignee_ids")} />
)} /> (
{ onChange(labelIds); handleFormChange(); }} projectId={projectId} tabIndex={getTabIndex("label_ids")} />
)} /> (
onChange(date ? renderFormattedPayloadDate(date) : null)} buttonVariant="border-with-text" maxDate={maxDate ?? undefined} placeholder="Start date" tabIndex={getTabIndex("start_date")} />
)} /> (
onChange(date ? renderFormattedPayloadDate(date) : null)} buttonVariant="border-with-text" minDate={minDate ?? undefined} placeholder="Due date" tabIndex={getTabIndex("target_date")} />
)} /> {projectDetails?.cycle_view && ( (
{ onChange(cycleId); handleFormChange(); }} placeholder="Cycle" value={value} buttonVariant="border-with-text" tabIndex={getTabIndex("cycle_id")} />
)} /> )} {projectDetails?.module_view && workspaceSlug && ( (
{ onChange(moduleIds); handleFormChange(); }} placeholder="Modules" buttonVariant="border-with-text" tabIndex={getTabIndex("module_ids")} multiple showCount />
)} /> )} {areEstimatesEnabledForProject(projectId) && ( (
{ onChange(estimatePoint); handleFormChange(); }} projectId={projectId} buttonVariant="border-with-text" tabIndex={getTabIndex("estimate_point")} />
)} /> )} {watch("parent_id") ? (
{selectedParentIssue && `${selectedParentIssue.project__identifier}- ${selectedParentIssue.sequence_id}`}
) : (
Add parent
)} } placement="bottom-start" tabIndex={getTabIndex("parent_id")} > {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} issueId={data?.id} /> )} />
{!data?.id && (
onCreateMoreToggleChange(!isCreateMoreToggleEnabled)} onKeyDown={(e) => { if (e.key === "Enter") onCreateMoreToggleChange(!isCreateMoreToggleEnabled); }} tabIndex={getTabIndex("create_more")} >
{}} size="sm" />
Create more
)}
{isDraft && ( {data?.id ? ( ) : ( )} )}
); });