import { useEffect, useState, useRef } from "react";
import { useRouter } from "next/router";
import { useForm } from "react-hook-form";
import { PlusIcon } from "lucide-react";
import { observer } from "mobx-react-lite";
// store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
import useKeypress from "hooks/use-keypress";
import useOutsideClickDetector from "hooks/use-outside-click-detector";
// helpers
import { createIssuePayload } from "helpers/issue.helper";
// types
import { IIssue, IProject } from "types";
const Inputs = (props: any) => {
const { register, setFocus, projectDetail } = props;
useEffect(() => {
setFocus("name");
}, [setFocus]);
return (
{projectDetail?.identifier ?? "..."}
);
};
interface IKanBanQuickAddIssueForm {
formKey: keyof IIssue;
groupId?: string;
subGroupId?: string | null;
prePopulatedData?: Partial;
quickAddCallback?: (
workspaceSlug: string,
projectId: string,
data: IIssue,
viewId?: string
) => Promise;
viewId?: string;
}
const defaultValues: Partial = {
name: "",
};
export const KanBanQuickAddIssueForm: React.FC = observer((props) => {
const { formKey, groupId, prePopulatedData, quickAddCallback, viewId } = props;
// router
const router = useRouter();
const { workspaceSlug, projectId } = router.query as { workspaceSlug: string; projectId: string };
const { workspace: workspaceStore, project: projectStore } = useMobxStore();
const workspaceDetail = (workspaceSlug && workspaceStore.getWorkspaceBySlug(workspaceSlug)) || null;
const projectDetail: IProject | null =
(workspaceSlug && projectId && projectStore.getProjectById(workspaceSlug, projectId)) || null;
const ref = useRef(null);
const [isOpen, setIsOpen] = useState(false);
const handleClose = () => setIsOpen(false);
useKeypress("Escape", handleClose);
useOutsideClickDetector(ref, handleClose);
const { setToastAlert } = useToast();
const {
reset,
handleSubmit,
setFocus,
register,
formState: { isSubmitting },
} = useForm({ defaultValues });
useEffect(() => {
if (!isOpen) reset({ ...defaultValues });
}, [isOpen, reset]);
const onSubmitHandler = async (formData: IIssue) => {
if (isSubmitting || !groupId || !workspaceDetail || !projectDetail) return;
reset({ ...defaultValues });
const payload = createIssuePayload(workspaceDetail, projectDetail, {
...(prePopulatedData ?? {}),
...formData,
});
try {
quickAddCallback &&
(await quickAddCallback(
workspaceSlug,
projectId,
{
...payload,
},
viewId
));
setToastAlert({
type: "success",
title: "Success!",
message: "Issue created successfully.",
});
} catch (err: any) {
console.error(err);
setToastAlert({
type: "error",
title: "Error!",
message: err?.message || "Some error occurred. Please try again.",
});
}
};
return (
{isOpen ? (
{`Press 'Enter' to add another issue`}
) : (
setIsOpen(true)}
>
New Issue
)}
{/* {isOpen && (
)}
{isOpen && (
Press {"'"}Enter{"'"} to add another issue
)}
{!isOpen && (
)} */}
);
});