import React, { FC, useState, useRef, useEffect, Fragment } 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, ModuleDropdown, PriorityDropdown, ProjectDropdown, MemberDropdown, StateDropdown, } from "components/dropdowns"; // ui import { Button, CustomMenu, Input, Loader, 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, 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, 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(); // 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, }); } // 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) => { await onSubmit(formData, is_draft_issue); 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(); }} /> )}
handleFormSubmit(data))}>
{/* Don't show project selection if editing an issue */} {!data?.id && ( (
{ onChange(projectId); handleFormChange(); }} buttonVariant="border-with-text" // TODO: update tabIndex logic 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={ref} hasError={Boolean(errors.name)} placeholder="Issue Title" className="resize-none text-xl w-full" tabIndex={getTabIndex("name")} /> )} />
{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={2} /> )} />
)}
(
{ 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(); }} value={value} buttonVariant="border-with-text" tabIndex={getTabIndex("cycle_id")} />
)} /> )} {projectDetails?.module_view && workspaceSlug && ( (
{ onChange(moduleIds); handleFormChange(); }} 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} /> )} />
onCreateMoreToggleChange(!isCreateMoreToggleEnabled)} onKeyDown={(e) => { if (e.key === "Enter") onCreateMoreToggleChange(!isCreateMoreToggleEnabled); }} tabIndex={getTabIndex("create_more")} >
{}} size="sm" />
Create more
{isDraft && ( {data?.id ? ( ) : ( )} )}
); });