Skip to content

armgit / plane

Public Imported from GitHub
0

πŸ”₯πŸ”₯πŸ”₯ Open-source Jira, Linear, Monday, and ClickUp alternative. Plane is a modern project management platform to manage tasks, sprints, docs, and triage.

[WEB-584] fix: draft issue management with workspace specific local storage (#3822)

guru_sainathec43c8e634b5
diff --git a/web/components/issues/delete-draft-issue-modal.tsx b/web/components/issues/delete-draft-issue-modal.tsx
deleted file mode 100644
index 6a2caba180..0000000000
--- a/web/components/issues/delete-draft-issue-modal.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import React, { useEffect, useState } from "react";
-import { useRouter } from "next/router";
-import { Dialog, Transition } from "@headlessui/react";
-// services
-import { IssueDraftService } from "services/issue";
-// hooks
-import useToast from "hooks/use-toast";
-// icons
-import { AlertTriangle } from "lucide-react";
-// ui
-import { Button } from "@plane/ui";
-// types
-import type { TIssue } from "@plane/types";
-import { useProject } from "hooks/store";
-
-type Props = {
- isOpen: boolean;
- handleClose: () => void;
- data: TIssue | null;
- onSubmit?: () => Promise<void> | void;
-};
-
-const issueDraftService = new IssueDraftService();
-
-export const DeleteDraftIssueModal: React.FC<Props> = (props) => {
- const { isOpen, handleClose, data, onSubmit } = props;
- // states
- const [isDeleteLoading, setIsDeleteLoading] = useState(false);
- // router
- const router = useRouter();
- const { workspaceSlug } = router.query;
- // toast alert
- const { setToastAlert } = useToast();
- // hooks
- const { getProjectById } = useProject();
-
- useEffect(() => {
- setIsDeleteLoading(false);
- }, [isOpen]);
-
- const onClose = () => {
- setIsDeleteLoading(false);
- handleClose();
- };
-
- const handleDeletion = async () => {
- if (!workspaceSlug || !data) return;
-
- setIsDeleteLoading(true);
-
- await issueDraftService
- .deleteDraftIssue(workspaceSlug.toString(), data.project_id, data.id)
- .then(() => {
- setIsDeleteLoading(false);
- handleClose();
-
- setToastAlert({
- title: "Success",
- message: "Draft Issue deleted successfully",
- type: "success",
- });
- })
- .catch((error) => {
- console.error(error);
- handleClose();
- setToastAlert({
- title: "Error",
- message: "Something went wrong",
- type: "error",
- });
- setIsDeleteLoading(false);
- });
- if (onSubmit) await onSubmit();
- };
-
- return (
- <Transition.Root show={isOpen} as={React.Fragment}>
- <Dialog as="div" className="relative z-20" onClose={onClose}>
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <div className="fixed inset-0 bg-custom-backdrop transition-opacity" />
- </Transition.Child>
-
- <div className="fixed inset-0 z-10 overflow-y-auto">
- <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- enterTo="opacity-100 translate-y-0 sm:scale-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100 translate-y-0 sm:scale-100"
- leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- >
- <Dialog.Panel className="relative transform overflow-hidden rounded-lg bg-custom-background-100 text-left shadow-custom-shadow-md transition-all sm:my-8 sm:w-full sm:max-w-2xl">
- <div className="flex flex-col gap-6 p-6">
- <div className="flex w-full items-center justify-start gap-6">
- <span className="place-items-center rounded-full bg-red-500/20 p-4">
- <AlertTriangle className="h-6 w-6 text-red-600" aria-hidden="true" />
- </span>
- <span className="flex items-center justify-start">
- <h3 className="text-xl font-medium 2xl:text-2xl">Delete Draft Issue</h3>
- </span>
- </div>
- <span>
- <p className="text-sm text-custom-text-200">
- Are you sure you want to delete issue{" "}
- <span className="break-words font-medium text-custom-text-100">
- {data && getProjectById(data?.project_id)?.identifier}-{data?.sequence_id}
- </span>
- {""}? All of the data related to the draft issue will be permanently removed. This action cannot
- be undone.
- </p>
- </span>
- <div className="flex justify-end gap-2">
- <Button variant="neutral-primary" size="sm" onClick={onClose}>
- Cancel
- </Button>
- <Button variant="danger" size="sm" tabIndex={1} onClick={handleDeletion} loading={isDeleteLoading}>
- {isDeleteLoading ? "Deleting..." : "Delete Issue"}
- </Button>
- </div>
- </div>
- </Dialog.Panel>
- </Transition.Child>
- </div>
- </div>
- </Dialog>
- </Transition.Root>
- );
-};
diff --git a/web/components/issues/draft-issue-form.tsx b/web/components/issues/draft-issue-form.tsx
deleted file mode 100644
index cfd6370fad..0000000000
--- a/web/components/issues/draft-issue-form.tsx
+++ /dev/null
@@ -1,668 +0,0 @@
-import React, { FC, useState, useEffect, useRef } from "react";
-import { useRouter } from "next/router";
-import { Controller, useForm } from "react-hook-form";
-import { observer } from "mobx-react-lite";
-import { Sparkle, X } from "lucide-react";
-// hooks
-import { useApplication, useEstimate, useMention, useProject, useWorkspace } from "hooks/store";
-import useToast from "hooks/use-toast";
-import useLocalStorage from "hooks/use-local-storage";
-// 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 { CreateStateModal } from "components/states";
-import { CreateLabelModal } from "components/labels";
-import { RichTextEditorWithRef } from "@plane/rich-text-editor";
-import {
- CycleDropdown,
- DateDropdown,
- EstimateDropdown,
- ModuleDropdown,
- 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 { IUser, TIssue, ISearchIssueResponse } from "@plane/types";
-
-const aiService = new AIService();
-const fileService = new FileService();
-
-const defaultValues: Partial<TIssue> = {
- project_id: "",
- name: "",
- description_html: "<p></p>",
- estimate_point: null,
- state_id: "",
- parent_id: null,
- priority: "none",
- assignee_ids: [],
- label_ids: [],
- start_date: undefined,
- target_date: undefined,
-};
-
-interface IssueFormProps {
- handleFormSubmit: (
- formData: Partial<TIssue>,
- action?: "createDraft" | "createNewIssue" | "updateDraft" | "convertToNewIssue"
- ) => Promise<void>;
- data?: Partial<TIssue> | null;
- isOpen: boolean;
- prePopulatedData?: Partial<TIssue> | null;
- projectId: string;
- setActiveProject: React.Dispatch<React.SetStateAction<string | null>>;
- createMore: boolean;
- setCreateMore: React.Dispatch<React.SetStateAction<boolean>>;
- handleClose: () => void;
- handleDiscard: () => void;
- status: boolean;
- user: IUser | undefined;
- fieldsToShow: (
- | "project"
- | "name"
- | "description"
- | "state"
- | "priority"
- | "assignee"
- | "label"
- | "startDate"
- | "dueDate"
- | "estimate"
- | "parent"
- | "all"
- )[];
-}
-
-export const DraftIssueForm: FC<IssueFormProps> = observer((props) => {
- const {
- handleFormSubmit,
- data,
- isOpen,
- prePopulatedData,
- projectId,
- setActiveProject,
- createMore,
- setCreateMore,
- status,
- fieldsToShow,
- handleDiscard,
- } = props;
- // states
- const [stateModal, setStateModal] = useState(false);
- const [labelModal, setLabelModal] = useState(false);
- const [parentIssueListModalOpen, setParentIssueListModalOpen] = useState(false);
- const [selectedParentIssue, setSelectedParentIssue] = useState<ISearchIssueResponse | null>(null);
- const [gptAssistantModal, setGptAssistantModal] = useState(false);
- const [iAmFeelingLucky, setIAmFeelingLucky] = useState(false);
- // store hooks
- const { areEstimatesEnabledForProject } = useEstimate();
- const { mentionHighlights, mentionSuggestions } = useMention();
- // hooks
- const { setValue: setLocalStorageValue } = useLocalStorage("draftedIssue", {});
- const { setToastAlert } = useToast();
- // refs
- const editorRef = useRef<any>(null);
- // router
- const router = useRouter();
- const { workspaceSlug } = router.query;
- const workspaceStore = useWorkspace();
- const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string;
-
- // store
- const {
- config: { envConfig },
- } = useApplication();
- const { getProjectById } = useProject();
- // form info
- const {
- formState: { errors, isSubmitting },
- handleSubmit,
- reset,
- watch,
- control,
- getValues,
- setValue,
- setFocus,
- } = useForm<TIssue>({
- defaultValues: prePopulatedData ?? defaultValues,
- reValidateMode: "onChange",
- });
-
- const issueName = watch("name");
-
- const payload: Partial<TIssue> = {
- name: watch("name"),
- description_html: watch("description_html"),
- state_id: watch("state_id"),
- priority: watch("priority"),
- assignee_ids: watch("assignee_ids"),
- label_ids: watch("label_ids"),
- start_date: watch("start_date"),
- target_date: watch("target_date"),
- project_id: watch("project_id"),
- parent_id: watch("parent_id"),
- cycle_id: watch("cycle_id"),
- module_ids: watch("module_ids"),
- };
-
- useEffect(() => {
- if (!isOpen || data) return;
-
- setLocalStorageValue(
- JSON.stringify({
- ...payload,
- })
- );
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [JSON.stringify(payload), isOpen, data]);
-
- // const onClose = () => {
- // handleClose();
- // };
-
- // const onClose = () => {
- // handleClose();
- // };
-
- const handleCreateUpdateIssue = async (
- formData: Partial<TIssue>,
- action: "createDraft" | "createNewIssue" | "updateDraft" | "convertToNewIssue" = "createDraft"
- ) => {
- await handleFormSubmit(
- {
- ...(data ?? {}),
- ...formData,
- // is_draft: action === "createDraft" || action === "updateDraft",
- },
- action
- );
- // TODO: check_with_backend
-
- setGptAssistantModal(false);
-
- reset({
- ...defaultValues,
- project_id: projectId,
- description_html: "<p></p>",
- });
- editorRef?.current?.clearEditor();
- };
-
- const handleAiAssistance = async (response: string) => {
- if (!workspaceSlug || !projectId) return;
-
- // setValue("description", {});
- setValue("description_html", `${watch("description_html")}<p>${response}</p>`);
- editorRef.current?.setEditorValue(`${watch("description_html")}`);
- };
-
- const handleAutoGenerateDescription = async () => {
- if (!workspaceSlug || !projectId) return;
-
- setIAmFeelingLucky(true);
-
- aiService
- .createGptTask(workspaceSlug as string, projectId as string, {
- 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));
- };
-
- useEffect(() => {
- setFocus("name");
- }, [setFocus]);
-
- // update projectId in form when projectId changes
- useEffect(() => {
- reset({
- ...getValues(),
- project_id: projectId,
- });
- }, [getValues, projectId, reset]);
-
- 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);
-
- return (
- <>
- {projectId && (
- <>
- <CreateStateModal isOpen={stateModal} handleClose={() => setStateModal(false)} projectId={projectId} />
- <CreateLabelModal
- isOpen={labelModal}
- handleClose={() => setLabelModal(false)}
- projectId={projectId}
- onSuccess={(response) => setValue("label_ids", [...watch("label_ids"), response.id])}
- />
- </>
- )}
- <form
- onSubmit={handleSubmit((formData) =>
- handleCreateUpdateIssue(formData, data ? "convertToNewIssue" : "createDraft")
- )}
- >
- <div className="space-y-5">
- <div className="flex items-center gap-x-2">
- {(fieldsToShow.includes("all") || fieldsToShow.includes("project")) && (
- <Controller
- control={control}
- name="project_id"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <ProjectDropdown
- value={value}
- onChange={(val) => {
- onChange(val);
- setActiveProject(val);
- }}
- buttonVariant="border-with-text"
- />
- </div>
- )}
- />
- )}
- <h3 className="text-xl font-semibold leading-6 text-custom-text-100">
- {status ? "Update" : "Create"} issue
- </h3>
- </div>
- {watch("parent_id") &&
- (fieldsToShow.includes("all") || fieldsToShow.includes("parent")) &&
- selectedParentIssue && (
- <div className="flex w-min items-center gap-2 whitespace-nowrap rounded bg-custom-background-80 p-2 text-xs">
- <div className="flex items-center gap-2">
- <span
- className="block h-1.5 w-1.5 rounded-full"
- style={{
- backgroundColor: selectedParentIssue.state__color,
- }}
- />
- <span className="flex-shrink-0 text-custom-text-200">
- {selectedParentIssue.project__identifier}-{selectedParentIssue.sequence_id}
- </span>
- <span className="truncate font-medium">{selectedParentIssue.name.substring(0, 50)}</span>
- <X
- className="h-3 w-3 cursor-pointer"
- onClick={() => {
- setValue("parent_id", null);
- setSelectedParentIssue(null);
- }}
- />
- </div>
- </div>
- )}
- <div className="space-y-3">
- <div className="mt-2 space-y-3">
- {(fieldsToShow.includes("all") || fieldsToShow.includes("name")) && (
- <div>
- <Controller
- control={control}
- name="name"
- rules={{
- required: "Title is required",
- maxLength: {
- value: 255,
- message: "Title should be less than 255 characters",
- },
- }}
- render={({ field: { value, onChange, ref } }) => (
- <Input
- id="name"
- name="name"
- type="text"
- value={value}
- onChange={onChange}
- ref={ref}
- hasError={Boolean(errors.name)}
- placeholder="Title"
- className="w-full resize-none text-xl"
- />
- )}
- />
- </div>
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("description")) && (
- <div className="relative">
- <div className="border-0.5 absolute bottom-3.5 right-3.5 flex items-center gap-2">
- {issueName && issueName !== "" && (
- <button
- type="button"
- className={`flex items-center gap-1 rounded px-1.5 py-1 text-xs bg-custom-background-80 ${
- iAmFeelingLucky ? "cursor-wait" : ""
- }`}
- onClick={handleAutoGenerateDescription}
- disabled={iAmFeelingLucky}
- >
- {iAmFeelingLucky ? (
- "Generating response..."
- ) : (
- <>
- <Sparkle className="h-3.5 w-3.5" />I{"'"}m feeling lucky
- </>
- )}
- </button>
- )}
- {envConfig?.has_openai_configured && (
- <GptAssistantPopover
- isOpen={gptAssistantModal}
- projectId={projectId}
- handleClose={() => {
- setGptAssistantModal((prevData) => !prevData);
- // this is done so that the title do not reset after gpt popover closed
- reset(getValues());
- }}
- onResponse={(response) => {
- handleAiAssistance(response);
- }}
- button={
- <button
- type="button"
- className="flex items-center gap-1 rounded px-1.5 py-1 text-xs bg-custom-background-80"
- onClick={() => setGptAssistantModal((prevData) => !prevData)}
- >
- <Sparkle className="h-3.5 w-3.5" />
- AI
- </button>
- }
- className=" !min-w-[38rem]"
- placement="top-end"
- />
- )}
- </div>
- <Controller
- name="description_html"
- control={control}
- render={({ field: { value, onChange } }) => (
- <RichTextEditorWithRef
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
- ref={editorRef}
- debouncedUpdatesEnabled={false}
- value={
- !value || value === "" || (typeof value === "object" && Object.keys(value).length === 0)
- ? watch("description_html")
- : value
- }
- customClassName="min-h-[150px]"
- onChange={(description: Object, description_html: string) => {
- onChange(description_html);
- }}
- mentionHighlights={mentionHighlights}
- mentionSuggestions={mentionSuggestions}
- />
- )}
- />
- </div>
- )}
- <div className="flex flex-wrap items-center gap-2">
- {(fieldsToShow.includes("all") || fieldsToShow.includes("state")) && (
- <Controller
- control={control}
- name="state_id"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <StateDropdown
- value={value}
- onChange={onChange}
- projectId={projectId}
- buttonVariant="border-with-text"
- />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("priority")) && (
- <Controller
- control={control}
- name="priority"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <PriorityDropdown value={value} onChange={onChange} buttonVariant="border-with-text" />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("assignee")) && (
- <Controller
- control={control}
- name="assignee_ids"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <ProjectMemberDropdown
- projectId={projectId}
- value={value}
- onChange={onChange}
- buttonVariant={value?.length > 0 ? "transparent-without-text" : "border-with-text"}
- buttonClassName={value?.length > 0 ? "hover:bg-transparent px-0" : ""}
- placeholder="Assignees"
- multiple
- />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("label")) && (
- <Controller
- control={control}
- name="label_ids"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <IssueLabelSelect
- setIsOpen={setLabelModal}
- value={value}
- onChange={onChange}
- projectId={projectId}
- />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("startDate")) && (
- <Controller
- control={control}
- name="start_date"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <DateDropdown
- value={value}
- onChange={(date) => onChange(date ? renderFormattedPayloadDate(date) : null)}
- buttonVariant="border-with-text"
- placeholder="Start date"
- maxDate={maxDate ?? undefined}
- />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("dueDate")) && (
- <Controller
- control={control}
- name="target_date"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <DateDropdown
- value={value}
- onChange={(date) => onChange(date ? renderFormattedPayloadDate(date) : null)}
- buttonVariant="border-with-text"
- placeholder="Due date"
- minDate={minDate ?? undefined}
- />
- </div>
- )}
- />
- )}
- {projectDetails?.cycle_view && (
- <Controller
- control={control}
- name="cycle_id"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <CycleDropdown
- projectId={projectId}
- onChange={(cycleId) => onChange(cycleId)}
- value={value}
- buttonVariant="border-with-text"
- />
- </div>
- )}
- />
- )}
-
- {projectDetails?.module_view && workspaceSlug && (
- <Controller
- control={control}
- name="module_ids"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <ModuleDropdown
- projectId={projectId}
- value={value ?? []}
- onChange={onChange}
- buttonVariant="border-with-text"
- multiple
- />
- </div>
- )}
- />
- )}
-
- {(fieldsToShow.includes("all") || fieldsToShow.includes("estimate")) &&
- areEstimatesEnabledForProject(projectId) && (
- <Controller
- control={control}
- name="estimate_point"
- render={({ field: { value, onChange } }) => (
- <div className="h-7">
- <EstimateDropdown
- value={value}
- onChange={onChange}
- projectId={projectId}
- buttonVariant="border-with-text"
- />
- </div>
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("parent")) && (
- <Controller
- control={control}
- name="parent_id"
- render={({ field: { onChange } }) => (
- <ParentIssuesListModal
- isOpen={parentIssueListModalOpen}
- handleClose={() => setParentIssueListModalOpen(false)}
- onChange={(issue) => {
- onChange(issue.id);
- setSelectedParentIssue(issue);
- }}
- projectId={projectId}
- />
- )}
- />
- )}
- {(fieldsToShow.includes("all") || fieldsToShow.includes("parent")) && (
- <CustomMenu ellipsis>
- {watch("parent_id") ? (
- <>
- <CustomMenu.MenuItem onClick={() => setParentIssueListModalOpen(true)}>
- Change parent issue
- </CustomMenu.MenuItem>
- <CustomMenu.MenuItem onClick={() => setValue("parent_id", null)}>
- Remove parent issue
- </CustomMenu.MenuItem>
- </>
- ) : (
- <CustomMenu.MenuItem onClick={() => setParentIssueListModalOpen(true)}>
- Select Parent Issue
- </CustomMenu.MenuItem>
- )}
- </CustomMenu>
- )}
- </div>
- </div>
- </div>
- </div>
- <div className="-mx-5 mt-5 flex items-center justify-between gap-2 border-t border-custom-border-200 px-5 pt-5">
- <div
- className="flex cursor-pointer items-center gap-1"
- onClick={() => setCreateMore((prevData) => !prevData)}
- >
- <span className="text-xs">Create more</span>
- <ToggleSwitch value={createMore} onChange={() => {}} size="md" />
- </div>
- <div className="flex items-center gap-2">
- <Button variant="neutral-primary" size="sm" onClick={handleDiscard}>
- Discard
- </Button>
- <Button
- variant="neutral-primary"
- size="sm"
- loading={isSubmitting}
- onClick={handleSubmit((formData) =>
- handleCreateUpdateIssue(formData, data?.id ? "updateDraft" : "createDraft")
- )}
- >
- {isSubmitting ? "Saving..." : "Save Draft"}
- </Button>
- <Button
- loading={isSubmitting}
- variant="primary"
- size="sm"
- onClick={handleSubmit((formData) =>
- handleCreateUpdateIssue(formData, data ? "convertToNewIssue" : "createNewIssue")
- )}
- >
- {isSubmitting ? "Saving..." : "Add Issue"}
- </Button>
- </div>
- </div>
- </form>
- </>
- );
-});
diff --git a/web/components/issues/draft-issue-modal.tsx b/web/components/issues/draft-issue-modal.tsx
deleted file mode 100644
index 40a79798e0..0000000000
--- a/web/components/issues/draft-issue-modal.tsx
+++ /dev/null
@@ -1,349 +0,0 @@
-import React, { useEffect, useState } from "react";
-import { useRouter } from "next/router";
-import { observer } from "mobx-react-lite";
-import { mutate } from "swr";
-import { Dialog, Transition } from "@headlessui/react";
-// services
-import { IssueService } from "services/issue";
-import { ModuleService } from "services/module.service";
-// hooks
-import useToast from "hooks/use-toast";
-import useLocalStorage from "hooks/use-local-storage";
-import { useIssues, useProject, useUser } from "hooks/store";
-// components
-import { DraftIssueForm } from "components/issues";
-// types
-import type { TIssue } from "@plane/types";
-import { EIssuesStoreType } from "constants/issue";
-// fetch-keys
-import { PROJECT_ISSUES_DETAILS, USER_ISSUE, SUB_ISSUES } from "constants/fetch-keys";
-
-interface IssuesModalProps {
- data?: TIssue | null;
- handleClose: () => void;
- isOpen: boolean;
- isUpdatingSingleIssue?: boolean;
- prePopulateData?: Partial<TIssue>;
- fieldsToShow?: (
- | "project"
- | "name"
- | "description"
- | "state"
- | "priority"
- | "assignee"
- | "label"
- | "startDate"
- | "dueDate"
- | "estimate"
- | "parent"
- | "all"
- )[];
- onSubmit?: (data: Partial<TIssue>) => Promise<void> | void;
-}
-
-// services
-const issueService = new IssueService();
-const moduleService = new ModuleService();
-
-export const CreateUpdateDraftIssueModal: React.FC<IssuesModalProps> = observer((props) => {
- const {
- data,
- handleClose,
- isOpen,
- isUpdatingSingleIssue = false,
- prePopulateData: prePopulateDataProps,
- fieldsToShow = ["all"],
- onSubmit,
- } = props;
-
- // states
- const [createMore, setCreateMore] = useState(false);
- const [activeProject, setActiveProject] = useState<string | null>(null);
- const [prePopulateData, setPreloadedData] = useState<Partial<TIssue> | undefined>(undefined);
- // router
- const router = useRouter();
- const { workspaceSlug, projectId, cycleId, moduleId } = router.query;
- // store
- const { issues: draftIssues } = useIssues(EIssuesStoreType.DRAFT);
- const { currentUser } = useUser();
- const { workspaceProjectIds: workspaceProjects } = useProject();
- // derived values
- const projects = workspaceProjects;
-
- const { clearValue: clearDraftIssueLocalStorage } = useLocalStorage("draftedIssue", {});
-
- const { setToastAlert } = useToast();
-
- const onClose = () => {
- handleClose();
- setActiveProject(null);
- };
-
- const onDiscard = () => {
- clearDraftIssueLocalStorage();
- onClose();
- };
-
- useEffect(() => {
- setPreloadedData(prePopulateDataProps ?? {});
-
- if (cycleId && !prePopulateDataProps?.cycle_id) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- cycle: cycleId.toString(),
- }));
- }
- if (moduleId && !prePopulateDataProps?.module_ids) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- module: moduleId.toString(),
- }));
- }
- if (
- (router.asPath.includes("my-issues") || router.asPath.includes("assigned")) &&
- !prePopulateDataProps?.assignee_ids
- ) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- assignees: prePopulateDataProps?.assignee_ids ?? [currentUser?.id ?? ""],
- }));
- }
- }, [prePopulateDataProps, cycleId, moduleId, router.asPath, currentUser?.id]);
-
- useEffect(() => {
- setPreloadedData(prePopulateDataProps ?? {});
-
- if (cycleId && !prePopulateDataProps?.cycle_id) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- cycle: cycleId.toString(),
- }));
- }
- if (moduleId && !prePopulateDataProps?.module_ids) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- module: moduleId.toString(),
- }));
- }
- if (
- (router.asPath.includes("my-issues") || router.asPath.includes("assigned")) &&
- !prePopulateDataProps?.assignee_ids
- ) {
- setPreloadedData((prevData) => ({
- ...(prevData ?? {}),
- ...prePopulateDataProps,
- assignees: prePopulateDataProps?.assignee_ids ?? [currentUser?.id ?? ""],
- }));
- }
- }, [prePopulateDataProps, cycleId, moduleId, router.asPath, currentUser?.id]);
-
- useEffect(() => {
- // if modal is closed, reset active project to null
- // and return to avoid activeProject being set to some other project
- if (!isOpen) {
- setActiveProject(null);
- return;
- }
-
- // if data is present, set active project to the project of the
- // issue. This has more priority than the project in the url.
- if (data && data.project_id) return setActiveProject(data.project_id);
-
- if (prePopulateData && prePopulateData.project_id && !activeProject)
- return setActiveProject(prePopulateData.project_id);
-
- if (prePopulateData && prePopulateData.project_id && !activeProject)
- return setActiveProject(prePopulateData.project_id);
-
- // if data is not present, set active project to the project
- // in the url. This has the least priority.
- if (projects && projects.length > 0 && !activeProject)
- setActiveProject(projects?.find((id) => id === projectId) ?? projects?.[0] ?? null);
- }, [activeProject, data, projectId, projects, isOpen, prePopulateData]);
-
- const createDraftIssue = async (payload: Partial<TIssue>) => {
- if (!workspaceSlug || !activeProject || !currentUser) return;
-
- await draftIssues
- .createIssue(workspaceSlug as string, activeProject ?? "", payload)
- .then(async () => {
- await draftIssues.fetchIssues(workspaceSlug as string, activeProject ?? "", "mutation");
- setToastAlert({
- type: "success",
- title: "Success!",
- message: "Issue created successfully.",
- });
-
- if (payload.assignee_ids?.some((assignee) => assignee === currentUser?.id))
- mutate(USER_ISSUE(workspaceSlug.toString()));
- })
- .catch(() => {
- setToastAlert({
- type: "error",
- title: "Error!",
- message: "Issue could not be created. Please try again.",
- });
- });
-
- if (!createMore) onClose();
- };
-
- const updateDraftIssue = async (payload: Partial<TIssue>) => {
- await draftIssues
- .updateIssue(workspaceSlug as string, activeProject ?? "", data?.id ?? "", payload)
- .then(() => {
- if (isUpdatingSingleIssue) {
- mutate<TIssue>(PROJECT_ISSUES_DETAILS, (prevData) => ({ ...prevData, ...payload } as TIssue), false);
- } else {
- if (payload.parent_id) mutate(SUB_ISSUES(payload.parent_id.toString()));
- }
-
- // if (!payload.is_draft) { // TODO: check_with_backend
- // if (payload.cycle_id && payload.cycle_id !== "") addIssueToCycle(res.id, payload.cycle_id);
- // if (payload.module_id && payload.module_id !== "") addIssueToModule(res.id, payload.module_id);
- // }
-
- if (!createMore) onClose();
-
- setToastAlert({
- type: "success",
- title: "Success!",
- message: "Issue updated successfully.",
- });
- })
- .catch(() => {
- setToastAlert({
- type: "error",
- title: "Error!",
- message: "Issue could not be updated. Please try again.",
- });
- });
- };
-
- const addIssueToCycle = async (issueId: string, cycleId: string) => {
- if (!workspaceSlug || !activeProject) return;
-
- await issueService.addIssueToCycle(workspaceSlug as string, activeProject ?? "", cycleId, {
- issues: [issueId],
- });
- };
-
- const addIssueToModule = async (issueId: string, moduleIds: string[]) => {
- if (!workspaceSlug || !activeProject) return;
-
- await moduleService.addModulesToIssue(workspaceSlug as string, activeProject ?? "", issueId as string, {
- modules: moduleIds,
- });
- };
-
- const createIssue = async (payload: Partial<TIssue>) => {
- if (!workspaceSlug || !activeProject) return;
-
- await issueService
- .createIssue(workspaceSlug.toString(), activeProject, payload)
- .then(async (res) => {
- if (payload.cycle_id && payload.cycle_id !== "") await addIssueToCycle(res.id, payload.cycle_id);
- if (payload.module_ids && payload.module_ids.length > 0) await addIssueToModule(res.id, payload.module_ids);
-
- setToastAlert({
- type: "success",
- title: "Success!",
- message: "Issue created successfully.",
- });
-
- if (!createMore) onClose();
-
- if (payload.assignee_ids?.some((assignee) => assignee === currentUser?.id))
- mutate(USER_ISSUE(workspaceSlug as string));
-
- if (payload.parent_id && payload.parent_id !== "") mutate(SUB_ISSUES(payload.parent_id));
- })
- .catch(() => {
- setToastAlert({
- type: "error",
- title: "Error!",
- message: "Issue could not be created. Please try again.",
- });
- });
- };
-
- const handleFormSubmit = async (
- formData: Partial<TIssue>,
- action: "createDraft" | "createNewIssue" | "updateDraft" | "convertToNewIssue" = "createDraft"
- ) => {
- if (!workspaceSlug || !activeProject) return;
-
- const payload: Partial<TIssue> = {
- ...formData,
- // description: formData.description ?? "",
- description_html: formData.description_html ?? "<p></p>",
- };
-
- if (action === "createDraft") await createDraftIssue(payload);
- else if (action === "updateDraft" || action === "convertToNewIssue") await updateDraftIssue(payload);
- else if (action === "createNewIssue") await createIssue(payload);
-
- clearDraftIssueLocalStorage();
-
- if (onSubmit) await onSubmit(payload);
- };
-
- if (!projects || projects.length === 0) return null;
-
- return (
- <>
- <Transition.Root show={isOpen} as={React.Fragment}>
- <Dialog as="div" className="relative z-20" onClose={onClose}>
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <div className="fixed inset-0 bg-custom-backdrop transition-opacity" />
- </Transition.Child>
-
- <div className="fixed inset-0 z-10 overflow-y-auto">
- <div className="my-10 flex items-center justify-center p-4 text-center sm:p-0 md:my-20">
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- enterTo="opacity-100 translate-y-0 sm:scale-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100 translate-y-0 sm:scale-100"
- leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- >
- <Dialog.Panel className="relative transform rounded-lg border border-custom-border-200 bg-custom-background-100 p-5 text-left shadow-custom-shadow-md transition-all sm:w-full sm:max-w-4xl">
- <DraftIssueForm
- isOpen={isOpen}
- handleFormSubmit={handleFormSubmit}
- prePopulatedData={prePopulateData}
- data={data}
- createMore={createMore}
- setCreateMore={setCreateMore}
- handleClose={onClose}
- handleDiscard={onDiscard}
- projectId={activeProject ?? ""}
- setActiveProject={setActiveProject}
- status={data ? true : false}
- user={currentUser ?? undefined}
- fieldsToShow={fieldsToShow}
- />
- </Dialog.Panel>
- </Transition.Child>
- </div>
- </div>
- </Dialog>
- </Transition.Root>
- </>
- );
-});
diff --git a/web/components/issues/index.ts b/web/components/issues/index.ts
index 3904049e9c..cab935a5dd 100644
--- a/web/components/issues/index.ts
+++ b/web/components/issues/index.ts
@@ -14,10 +14,5 @@ export * from "./issue-detail";
export * from "./peek-overview";
-// draft issue
-export * from "./draft-issue-form";
-export * from "./draft-issue-modal";
-export * from "./delete-draft-issue-modal";
-
// archived issue
export * from "./delete-archived-issue-modal";
diff --git a/web/components/issues/issue-layouts/kanban/headers/group-by-card.tsx b/web/components/issues/issue-layouts/kanban/headers/group-by-card.tsx
index ec9742bafd..440b379b86 100644
--- a/web/components/issues/issue-layouts/kanban/headers/group-by-card.tsx
+++ b/web/components/issues/issue-layouts/kanban/headers/group-by-card.tsx
@@ -3,7 +3,7 @@ import { useRouter } from "next/router";
// components
import { CustomMenu } from "@plane/ui";
import { ExistingIssuesListModal } from "components/core";
-import { CreateUpdateIssueModal, CreateUpdateDraftIssueModal } from "components/issues";
+import { CreateUpdateIssueModal } from "components/issues";
// lucide icons
import { Minimize2, Maximize2, Circle, Plus } from "lucide-react";
// hooks
diff --git a/web/components/issues/issue-layouts/list/headers/group-by-card.tsx b/web/components/issues/issue-layouts/list/headers/group-by-card.tsx
index 5a6b3c462d..8d9164b376 100644
--- a/web/components/issues/issue-layouts/list/headers/group-by-card.tsx
+++ b/web/components/issues/issue-layouts/list/headers/group-by-card.tsx
@@ -2,7 +2,7 @@ import { useRouter } from "next/router";
// lucide icons
import { CircleDashed, Plus } from "lucide-react";
// components
-import { CreateUpdateIssueModal, CreateUpdateDraftIssueModal } from "components/issues";
+import { CreateUpdateIssueModal } from "components/issues";
import { ExistingIssuesListModal } from "components/core";
import { CustomMenu } from "@plane/ui";
// mobx
diff --git a/web/components/issues/issue-layouts/spreadsheet/columns/cycle-column.tsx b/web/components/issues/issue-layouts/spreadsheet/columns/cycle-column.tsx
index 83b46baf6e..88fbf10546 100644
--- a/web/components/issues/issue-layouts/spreadsheet/columns/cycle-column.tsx
+++ b/web/components/issues/issue-layouts/spreadsheet/columns/cycle-column.tsx
@@ -30,7 +30,6 @@ export const SpreadsheetCycleColumn: React.FC<Props> = observer((props) => {
const handleCycle = useCallback(
async (cycleId: string | null) => {
- console.log("cycleId", cycleId);
if (!workspaceSlug || !issue || issue.cycle_id === cycleId) return;
if (cycleId) await addIssueToCycle(workspaceSlug.toString(), issue.project_id, cycleId, [issue.id]);
else await removeIssueFromCycle(workspaceSlug.toString(), issue.project_id, issue.cycle_id ?? "", issue.id);
diff --git a/web/components/issues/issue-modal/modal.tsx b/web/components/issues/issue-modal/modal.tsx
index 4c2833efa2..691f7da117 100644
--- a/web/components/issues/issue-modal/modal.tsx
+++ b/web/components/issues/issue-modal/modal.tsx
@@ -93,7 +93,9 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer((prop
// toast alert
const { setToastAlert } = useToast();
// local storage
- const { setValue: setLocalStorageDraftIssue } = useLocalStorage<any>("draftedIssue", {});
+ const { storedValue: localStorageDraftIssues, setValue: setLocalStorageDraftIssue } = useLocalStorage<
+ Record<string, Partial<TIssue>>
+ >("draftedIssue", {});
// current store details
const { store: currentIssueStore, viewId } = issueStores[storeType];
@@ -154,9 +156,14 @@ export const CreateUpdateIssueModal: React.FC<IssuesModalProps> = observer((prop
const handleClose = (saveDraftIssueInLocalStorage?: boolean) => {
if (changesMade && saveDraftIssueInLocalStorage) {
- const draftIssue = JSON.stringify(changesMade);
- setLocalStorageDraftIssue(draftIssue);
+ // updating the current edited issue data in the local storage
+ let draftIssues = localStorageDraftIssues ? localStorageDraftIssues : {};
+ if (workspaceSlug) {
+ draftIssues = { ...draftIssues, [workspaceSlug]: changesMade };
+ setLocalStorageDraftIssue(draftIssues);
+ }
}
+
setActiveProjectId(null);
onClose();
};
diff --git a/web/components/workspace/sidebar-quick-action.tsx b/web/components/workspace/sidebar-quick-action.tsx
index 28b57f0f5e..38d3e6b6aa 100644
--- a/web/components/workspace/sidebar-quick-action.tsx
+++ b/web/components/workspace/sidebar-quick-action.tsx
@@ -5,23 +5,29 @@ import { ChevronUp, PenSquare, Search } from "lucide-react";
import { useApplication, useEventTracker, useProject, useUser } from "hooks/store";
import useLocalStorage from "hooks/use-local-storage";
// components
-import { CreateUpdateDraftIssueModal } from "components/issues";
+import { CreateUpdateIssueModal } from "components/issues";
// constants
import { EUserWorkspaceRoles } from "constants/workspace";
import { EIssuesStoreType } from "constants/issue";
+// types
+import { TIssue } from "@plane/types";
export const WorkspaceSidebarQuickAction = observer(() => {
// states
const [isDraftIssueModalOpen, setIsDraftIssueModalOpen] = useState(false);
- const { theme: themeStore, commandPalette: commandPaletteStore } = useApplication();
+ const {
+ router: { workspaceSlug },
+ theme: themeStore,
+ commandPalette: commandPaletteStore,
+ } = useApplication();
const { setTrackElement } = useEventTracker();
const { joinedProjectIds } = useProject();
const {
membership: { currentWorkspaceRole },
} = useUser();
- const { storedValue, clearValue } = useLocalStorage<any>("draftedIssue", JSON.stringify({}));
+ const { storedValue, setValue } = useLocalStorage<Record<string, Partial<TIssue>>>("draftedIssue", {});
//useState control for displaying draft issue button instead of group hover
const [isDraftButtonOpen, setIsDraftButtonOpen] = useState(false);
@@ -45,18 +51,25 @@ export const WorkspaceSidebarQuickAction = observer(() => {
setIsDraftButtonOpen(false);
}, 300);
};
+
+ const workspaceDraftIssue = workspaceSlug ? storedValue?.[workspaceSlug] ?? undefined : undefined;
+
+ const removeWorkspaceDraftIssue = () => {
+ const draftIssues = storedValue ?? {};
+ if (workspaceSlug && draftIssues[workspaceSlug]) delete draftIssues[workspaceSlug];
+ setValue(draftIssues);
+ };
+
return (
<>
- <CreateUpdateDraftIssueModal
+ <CreateUpdateIssueModal
isOpen={isDraftIssueModalOpen}
- handleClose={() => setIsDraftIssueModalOpen(false)}
- prePopulateData={storedValue ? JSON.parse(storedValue) : {}}
- onSubmit={() => {
- localStorage.removeItem("draftedIssue");
- clearValue();
- }}
- fieldsToShow={["all"]}
+ onClose={() => setIsDraftIssueModalOpen(false)}
+ data={workspaceDraftIssue ?? {}}
+ // storeType={storeType}
+ isDraft={true}
/>
+
<div
className={`mt-4 flex w-full cursor-pointer items-center justify-between px-4 ${
isSidebarCollapsed ? "flex-col gap-1" : "gap-2"
@@ -87,7 +100,7 @@ export const WorkspaceSidebarQuickAction = observer(() => {
{!isSidebarCollapsed && <span className="text-sm font-medium">New Issue</span>}
</button>
- {!disabled && storedValue && Object.keys(JSON.parse(storedValue)).length > 0 && (
+ {!disabled && workspaceDraftIssue && (
<>
<div
className={`h-8 w-0.5 bg-custom-sidebar-background-80 ${isSidebarCollapsed ? "hidden" : "block"}`}