chore: gpt modal refactor (#3276)

* chore: gpt modal refactor

* chore: refactored gpt assistant modal to popover component
This commit is contained in:
Anmol Singh Bhatia 2024-01-02 13:07:12 +05:30 committed by GitHub
parent 6e702d6cc7
commit d9ee692ce9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 372 additions and 679 deletions

View File

@ -1,202 +0,0 @@
import React, { useEffect, useState, useRef } from "react";
import { useRouter } from "next/router";
// react-hook-form
import { Controller, useForm } from "react-hook-form";
// services
import { AIService } from "services/ai.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Button, Input } from "@plane/ui";
// components
import { RichReadOnlyEditorWithRef } from "@plane/rich-text-editor";
// types
import { IIssue, IPageBlock } from "types";
type Props = {
isOpen: boolean;
handleClose: () => void;
inset?: string;
content: string;
htmlContent?: string;
onResponse: (response: string) => void;
projectId: string;
block?: IPageBlock;
issue?: IIssue;
};
type FormData = {
prompt: string;
task: string;
};
// services
const aiService = new AIService();
export const GptAssistantModal: React.FC<Props> = (props) => {
const { isOpen, handleClose, inset = "top-0 left-0", content, htmlContent, onResponse, projectId } = props;
const [response, setResponse] = useState("");
const [invalidResponse, setInvalidResponse] = useState(false);
const router = useRouter();
const { workspaceSlug } = router.query;
const editorRef = useRef<any>(null);
const responseRef = useRef<any>(null);
const { setToastAlert } = useToast();
const {
handleSubmit,
control,
reset,
setFocus,
formState: { isSubmitting },
} = useForm({
defaultValues: {
prompt: content,
task: "",
},
});
const onClose = () => {
handleClose();
setResponse("");
setInvalidResponse(false);
reset();
};
const handleResponse = async (formData: FormData) => {
if (!workspaceSlug || !projectId) return;
if (formData.task === "") {
setToastAlert({
type: "error",
title: "Error!",
message: "Please enter some task to get AI assistance.",
});
return;
}
await aiService
.createGptTask(workspaceSlug as string, projectId as string, {
prompt: content && content !== "" ? content : htmlContent ?? "",
task: formData.task,
})
.then((res) => {
setResponse(res.response_html);
setFocus("task");
if (res.response === "") setInvalidResponse(true);
else setInvalidResponse(false);
})
.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.",
});
});
};
useEffect(() => {
if (isOpen) setFocus("task");
}, [isOpen, setFocus]);
useEffect(() => {
editorRef.current?.setEditorValue(htmlContent ?? `<p>${content}</p>`);
}, [htmlContent, editorRef, content]);
useEffect(() => {
responseRef.current?.setEditorValue(`<p>${response}</p>`);
}, [response, responseRef]);
return (
<div
className={`absolute ${inset} z-20 flex w-full flex-col space-y-4 overflow-hidden rounded-[10px] border border-custom-border-200 bg-custom-background-100 p-4 shadow ${
isOpen ? "block" : "hidden"
}`}
>
<div className="vertical-scroll-enable max-h-72 space-y-4 overflow-y-auto">
{((content && content !== "") || (htmlContent && htmlContent !== "<p></p>")) && (
<div className="text-sm">
Content:
<RichReadOnlyEditorWithRef
value={htmlContent ?? `<p>${content}</p>`}
customClassName="-m-3"
noBorder
borderOnFocus={false}
ref={editorRef}
/>
</div>
)}
{response !== "" && (
<div className="page-block-section text-sm">
Response:
<RichReadOnlyEditorWithRef
value={`<p>${response}</p>`}
customClassName="-mx-3 -my-3"
noBorder
borderOnFocus={false}
ref={responseRef}
/>
</div>
)}
{invalidResponse && (
<div className="text-sm text-red-500">
No response could be generated. This may be due to insufficient content or task information. Please try
again.
</div>
)}
</div>
<Controller
control={control}
name="task"
render={({ field: { value, onChange, ref } }) => (
<Input
id="task"
name="task"
type="text"
value={value}
onChange={onChange}
ref={ref}
placeholder={`${
content && content !== "" ? "Tell AI what action to perform on this content..." : "Ask AI anything..."
}`}
className="w-full"
/>
)}
/>
<div className={`flex gap-2 ${response === "" ? "justify-end" : "justify-between"}`}>
{response !== "" && (
<Button
variant="primary"
onClick={() => {
onResponse(response);
onClose();
}}
>
Use this response
</Button>
)}
<div className="flex items-center gap-2">
<Button variant="neutral-primary" size="sm" onClick={onClose}>
Close
</Button>
<Button variant="primary" size="sm" onClick={handleSubmit(handleResponse)} loading={isSubmitting}>
{isSubmitting ? "Generating response..." : response === "" ? "Generate response" : "Generate again"}
</Button>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,267 @@
import React, { useEffect, useState, useRef, Fragment } from "react";
import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form"; // services
import { AIService } from "services/ai.service";
// hooks
import useToast from "hooks/use-toast";
import { usePopper } from "react-popper";
// ui
import { Button, Input } from "@plane/ui";
// components
import { RichReadOnlyEditorWithRef } from "@plane/rich-text-editor";
import { Popover, Transition } from "@headlessui/react";
// types
import { Placement } from "@popperjs/core";
type Props = {
isOpen: boolean;
projectId: string;
handleClose: () => void;
onResponse: (response: any) => void;
onError?: (error: any) => void;
placement?: Placement;
prompt?: string;
button: JSX.Element;
className?: string;
};
type FormData = {
prompt: string;
task: string;
};
const aiService = new AIService();
export const GptAssistantPopover: React.FC<Props> = (props) => {
const { isOpen, projectId, handleClose, onResponse, onError, placement, prompt, button, className = "" } = props;
// states
const [response, setResponse] = useState("");
const [invalidResponse, setInvalidResponse] = useState(false);
const [referenceElement, setReferenceElement] = useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(null);
const editorRef = useRef<any>(null);
const responseRef = useRef<any>(null);
// router
const router = useRouter();
const { workspaceSlug } = router.query;
// toast alert
const { setToastAlert } = useToast();
// popper
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: placement ?? "auto",
});
// form
const {
handleSubmit,
control,
reset,
setFocus,
formState: { isSubmitting },
} = useForm<FormData>({
defaultValues: {
prompt: prompt || "",
task: "",
},
});
const onClose = () => {
handleClose();
setResponse("");
setInvalidResponse(false);
reset();
};
const handleServiceError = (err: any) => {
const error = err?.data?.error;
const errorMessage =
err?.status === 429
? error || "You have reached the maximum number of requests of 50 requests per month per user."
: error || "Some error occurred. Please try again.";
setToastAlert({
type: "error",
title: "Error!",
message: errorMessage,
});
if (onError) onError(err);
};
const callAIService = async (formData: FormData) => {
try {
const res = await aiService.createGptTask(workspaceSlug as string, projectId, {
prompt: prompt || "",
task: formData.task,
});
setResponse(res.response_html);
setFocus("task");
setInvalidResponse(res.response === "");
} catch (err) {
handleServiceError(err);
}
};
const handleInvalidTask = () => {
setToastAlert({
type: "error",
title: "Error!",
message: "Please enter some task to get AI assistance.",
});
};
const handleAIResponse = async (formData: FormData) => {
if (!workspaceSlug || !projectId) return;
if (formData.task === "") {
handleInvalidTask();
return;
}
await callAIService(formData);
};
useEffect(() => {
if (isOpen) setFocus("task");
}, [isOpen, setFocus]);
useEffect(() => {
editorRef.current?.setEditorValue(prompt || "");
}, [editorRef, prompt]);
useEffect(() => {
responseRef.current?.setEditorValue(`<p>${response}</p>`);
}, [response, responseRef]);
useEffect(() => {
const handleEnterKeyPress = (event: KeyboardEvent) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
handleSubmit(handleAIResponse)();
}
};
const handleEscapeKeyPress = (event: KeyboardEvent) => {
if (event.key === "Escape") {
onClose();
}
};
if (isOpen) {
window.addEventListener("keydown", handleEnterKeyPress);
window.addEventListener("keydown", handleEscapeKeyPress);
}
return () => {
window.removeEventListener("keydown", handleEnterKeyPress);
window.removeEventListener("keydown", handleEscapeKeyPress);
};
}, [isOpen, handleSubmit, onClose]);
const responseActionButton = response !== "" && (
<Button
variant="primary"
onClick={() => {
onResponse(response);
onClose();
}}
>
Use this response
</Button>
);
const generateResponseButtonText = isSubmitting
? "Generating response..."
: response === ""
? "Generate response"
: "Generate again";
return (
<Popover as="div" className={`relative w-min text-left`}>
<Popover.Button as={Fragment}>
<button ref={setReferenceElement}>{button}</button>
</Popover.Button>
<Transition
show={isOpen}
as={React.Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Popover.Panel
as="div"
className={`fixed z-10 flex flex-col w-full max-w-full min-w-[50rem] space-y-4 overflow-hidden rounded-[10px] border border-custom-border-200 bg-custom-background-100 p-4 shadow ${className}`}
ref={setPopperElement}
style={styles.popper}
{...attributes.popper}
>
<div className="vertical-scroll-enable max-h-72 space-y-4 overflow-y-auto">
{prompt && (
<div className="text-sm">
Content:
<RichReadOnlyEditorWithRef
value={prompt}
customClassName="-m-3"
noBorder
borderOnFocus={false}
ref={editorRef}
/>
</div>
)}
{response !== "" && (
<div className="page-block-section text-sm max-h-[8rem]">
Response:
<RichReadOnlyEditorWithRef
value={`<p>${response}</p>`}
customClassName={response ? "-mx-3 -my-3" : ""}
noBorder
borderOnFocus={false}
ref={responseRef}
/>
</div>
)}
{invalidResponse && (
<div className="text-sm text-red-500">
No response could be generated. This may be due to insufficient content or task information. Please try
again.
</div>
)}
</div>
<Controller
control={control}
name="task"
render={({ field: { value, onChange, ref } }) => (
<Input
id="task"
name="task"
type="text"
value={value}
onChange={onChange}
ref={ref}
placeholder={`${
prompt && prompt !== "" ? "Tell AI what action to perform on this content..." : "Ask AI anything..."
}`}
className="w-full"
/>
)}
/>
<div className={`flex gap-2 ${response === "" ? "justify-end" : "justify-between"}`}>
{responseActionButton}
<div className="flex items-center gap-2">
<Button variant="neutral-primary" size="sm" onClick={onClose}>
Close
</Button>
<Button variant="primary" size="sm" onClick={handleSubmit(handleAIResponse)} loading={isSubmitting}>
{generateResponseButtonText}
</Button>
</div>
</div>
</Popover.Panel>
</Transition>
</Popover>
);
};

View File

@ -1,6 +1,6 @@
export * from "./bulk-delete-issues-modal";
export * from "./existing-issues-list-modal";
export * from "./gpt-assistant-modal";
export * from "./gpt-assistant-popover";
export * from "./link-modal";
export * from "./user-image-upload-modal";
export * from "./workspace-image-upload-modal";

View File

@ -16,7 +16,7 @@ import { Button, Input, ToggleSwitch } from "@plane/ui";
// types
import { IIssue } from "types";
import useEditorSuggestions from "hooks/use-editor-suggestions";
import { GptAssistantModal } from "components/core";
import { GptAssistantPopover } from "components/core";
import { Sparkle } from "lucide-react";
import useToast from "hooks/use-toast";
import { AIService } from "services/ai.service";
@ -227,7 +227,7 @@ export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
/>
</div>
<div className="relative">
<div className="flex justify-end">
<div className="border-0.5 absolute bottom-3.5 right-3.5 z-10 flex rounded bg-custom-background-80">
{issueName && issueName !== "" && (
<button
type="button"
@ -246,14 +246,33 @@ export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
)}
</button>
)}
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</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 hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
}
className="!min-w-[38rem]"
placement="top-end"
/>
)}
</div>
<Controller
name="description_html"
@ -276,23 +295,6 @@ export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
/>
)}
/>
{envConfig?.has_openai_configured && (
<GptAssistantModal
isOpen={gptAssistantModal}
handleClose={() => {
setGptAssistantModal(false);
// this is done so that the title do not reset after gpt popover closed
reset(getValues());
}}
inset="top-2 left-0"
content=""
htmlContent={watch("description_html")}
onResponse={(response) => {
handleAiAssistance(response);
}}
projectId={projectId}
/>
)}
</div>
<div className="flex flex-wrap items-center gap-2">

View File

@ -8,7 +8,7 @@ import { FileService } from "services/file.service";
import useToast from "hooks/use-toast";
import useLocalStorage from "hooks/use-local-storage";
// components
import { GptAssistantModal } from "components/core";
import { GptAssistantPopover } from "components/core";
import { ParentIssuesListModal } from "components/issues";
import {
IssueAssigneeSelect,
@ -389,7 +389,7 @@ export const DraftIssueForm: FC<IssueFormProps> = observer((props) => {
)}
{(fieldsToShow.includes("all") || fieldsToShow.includes("description")) && (
<div className="relative">
<div className="flex justify-end">
<div className="border-0.5 absolute bottom-3.5 right-3.5 z-10 flex rounded bg-custom-background-80">
{issueName && issueName !== "" && (
<button
type="button"
@ -408,14 +408,32 @@ export const DraftIssueForm: FC<IssueFormProps> = observer((props) => {
)}
</button>
)}
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</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 hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
}
className=" !min-w-[38rem]"
placement="top-end"
/>
)}
</div>
<Controller
name="description_html"
@ -443,23 +461,6 @@ export const DraftIssueForm: FC<IssueFormProps> = observer((props) => {
/>
)}
/>
{envConfig?.has_openai_configured && (
<GptAssistantModal
isOpen={gptAssistantModal}
handleClose={() => {
setGptAssistantModal(false);
// this is done so that the title do not reset after gpt popover closed
reset(getValues());
}}
inset="top-2 left-0"
content=""
htmlContent={watch("description_html")}
onResponse={(response) => {
handleAiAssistance(response);
}}
projectId={projectId}
/>
)}
</div>
)}
<div className="flex flex-wrap items-center gap-2">

View File

@ -10,7 +10,7 @@ import { FileService } from "services/file.service";
// hooks
import useToast from "hooks/use-toast";
// components
import { GptAssistantModal } from "components/core";
import { GptAssistantPopover } from "components/core";
import { ParentIssuesListModal } from "components/issues";
import {
IssueAssigneeSelect,
@ -363,14 +363,31 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
)}
</button>
)}
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</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);
}}
placement="top-end"
button={
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
}
/>
)}
</div>
<Controller
name="description_html"
@ -398,23 +415,6 @@ export const IssueForm: FC<IssueFormProps> = observer((props) => {
/>
)}
/>
{envConfig?.has_openai_configured && (
<GptAssistantModal
isOpen={gptAssistantModal}
handleClose={() => {
setGptAssistantModal(false);
// this is done so that the title do not reset after gpt popover closed
reset(getValues());
}}
inset="top-2 left-0"
content=""
htmlContent={watch("description_html")}
onResponse={(response) => {
handleAiAssistance(response);
}}
projectId={projectId}
/>
)}
</div>
)}
<div className="flex flex-wrap items-center gap-2">

View File

@ -1,378 +0,0 @@
import { useCallback, useEffect, useState, FC, Dispatch, SetStateAction, useRef } from "react";
import { useRouter } from "next/router";
import { mutate } from "swr";
import { Sparkle } from "lucide-react";
import { Controller, useForm } from "react-hook-form";
// services
import { PageService } from "services/page.service";
import { IssueService } from "services/issue/issue.service";
import { AIService } from "services/ai.service";
import { FileService } from "services/file.service";
// hooks
import useToast from "hooks/use-toast";
// components
import { GptAssistantModal } from "components/core";
import { Button, TextArea } from "@plane/ui";
import { RichTextEditorWithRef } from "@plane/rich-text-editor";
// types
import { IUser, IPageBlock } from "types";
// fetch-keys
import { PAGE_BLOCKS_LIST } from "constants/fetch-keys";
import useEditorSuggestions from "hooks/use-editor-suggestions";
import { useMobxStore } from "lib/mobx/store-provider";
type Props = {
handleClose: () => void;
data?: IPageBlock;
handleAiAssistance?: (response: string) => void;
setIsSyncing?: Dispatch<SetStateAction<boolean>>;
focus?: keyof IPageBlock;
user: IUser | undefined;
};
const defaultValues = {
name: "",
description: null,
description_html: null,
};
const aiService = new AIService();
const pagesService = new PageService();
const issueService = new IssueService();
const fileService = new FileService();
export const CreateUpdateBlockInline: FC<Props> = (props) => {
const { handleClose, data, handleAiAssistance, setIsSyncing, focus } = props;
// states
const [iAmFeelingLucky, setIAmFeelingLucky] = useState(false);
const [gptAssistantModal, setGptAssistantModal] = useState(false);
// store
const {
appConfig: { envConfig },
} = useMobxStore();
// refs
const editorRef = useRef<any>(null);
// router
const router = useRouter();
const { workspaceSlug, projectId, pageId } = router.query;
// hooks
const editorSuggestion = useEditorSuggestions();
const { setToastAlert } = useToast();
// form info
const {
handleSubmit,
control,
watch,
setValue,
setFocus,
reset,
formState: { errors, isSubmitting },
} = useForm<IPageBlock>({
defaultValues,
});
const onClose = useCallback(() => {
if (data) handleClose();
reset();
}, [handleClose, reset, data]);
const createPageBlock = useCallback(
async (formData: Partial<IPageBlock>) => {
if (!workspaceSlug || !projectId || !pageId) return;
await pagesService
.createPageBlock(workspaceSlug as string, projectId as string, pageId as string, {
name: formData.name,
description: formData.description ?? "",
description_html: formData.description_html ?? "<p></p>",
})
.then((res) => {
mutate<IPageBlock[]>(
PAGE_BLOCKS_LIST(pageId as string),
(prevData) => [...(prevData as IPageBlock[]), res],
false
);
editorRef.current?.clearEditor();
})
.catch(() => {
setToastAlert({
type: "error",
title: "Error!",
message: "Page could not be created. Please try again.",
});
})
.finally(() => onClose());
},
[workspaceSlug, projectId, pageId, onClose, setToastAlert]
);
const updatePageBlock = useCallback(
async (formData: Partial<IPageBlock>) => {
if (!workspaceSlug || !projectId || !pageId || !data) return;
if (data.issue && data.sync && setIsSyncing) setIsSyncing(true);
mutate<IPageBlock[]>(
PAGE_BLOCKS_LIST(pageId as string),
(prevData) =>
prevData?.map((p) => {
if (p.id === data.id) return { ...p, ...formData };
return p;
}),
false
);
await pagesService
.patchPageBlock(workspaceSlug as string, projectId as string, pageId as string, data.id, {
name: formData.name,
description: formData.description,
description_html: formData.description_html,
})
.then((res) => {
mutate(PAGE_BLOCKS_LIST(pageId as string));
editorRef.current?.setEditorValue(res.description_html);
if (data.issue && data.sync)
issueService
.patchIssue(workspaceSlug as string, projectId as string, data.issue, {
name: res.name,
description: res.description,
description_html: res.description_html,
})
.finally(() => {
if (setIsSyncing) setIsSyncing(false);
});
})
.finally(() => onClose());
},
[workspaceSlug, projectId, pageId, data, onClose, setIsSyncing]
);
const handleAutoGenerateDescription = async () => {
if (!workspaceSlug || !projectId) return;
setIAmFeelingLucky(true);
aiService
.createGptTask(workspaceSlug as string, projectId as string, {
prompt: watch("name"),
task: "Generate a proper description for this issue.",
})
.then((res) => {
if (res.response === "")
setToastAlert({
type: "error",
title: "Error!",
message:
"Block title isn't informative enough to generate the description. Please try with a different title.",
});
else {
setValue("description", {});
setValue("description_html", `${watch("description_html") ?? ""}<p>${res.response}</p>`);
editorRef.current?.setEditorValue(watch("description_html") ?? "");
}
})
.catch((err) => {
if (err.status === 429)
setToastAlert({
type: "error",
title: "Error!",
message: "You have reached the maximum number of requests of 50 requests per month per user.",
});
else
setToastAlert({
type: "error",
title: "Error!",
message: "Some error occurred. Please try again.",
});
})
.finally(() => setIAmFeelingLucky(false));
};
useEffect(() => {
if (focus) setFocus(focus);
if (!data) return;
reset({
...defaultValues,
name: data.name,
description:
!data.description || data.description === ""
? {
type: "doc",
content: [{ type: "paragraph" }],
}
: data.description,
description_html: data.description_html ?? "<p></p>",
});
}, [reset, data, focus, setFocus]);
useEffect(() => {
window.addEventListener("keydown", (e: KeyboardEvent) => {
if (e.key === "Escape") handleClose();
});
return () => {
window.removeEventListener("keydown", (e: KeyboardEvent) => {
if (e.key === "Escape") handleClose();
});
};
}, [handleClose]);
useEffect(() => {
const submitForm = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
if (data) handleSubmit(updatePageBlock)();
else handleSubmit(createPageBlock)();
}
};
window.addEventListener("keydown", submitForm);
return () => {
window.removeEventListener("keydown", submitForm);
};
}, [createPageBlock, updatePageBlock, data, handleSubmit]);
return (
<div className="relative">
<form
className="divide-y divide-custom-border-200 rounded border border-custom-border-200 shadow"
onSubmit={data ? handleSubmit(updatePageBlock) : handleSubmit(createPageBlock)}
>
<div className="pt-2">
<div className="flex justify-between">
<Controller
name="name"
control={control}
render={({ field: { value, onChange } }) => (
<TextArea
id="name"
name="name"
value={value}
placeholder="Title"
onChange={onChange}
className="min-h-10 font medium block w-full resize-none overflow-hidden border-none bg-transparent py-1 text-base"
autoComplete="off"
maxLength={255}
hasError={Boolean(errors?.name)}
/>
)}
/>
</div>
<div className="page-block-section relative -mt-2 text-custom-text-200">
<Controller
name="description_html"
control={control}
render={({ field: { value, onChange } }) => {
if (!data)
return (
<RichTextEditorWithRef
cancelUploadImage={fileService.cancelUpload}
uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
deleteFile={fileService.deleteImage}
restoreFile={fileService.restoreImage}
ref={editorRef}
value={"<p></p>"}
debouncedUpdatesEnabled={false}
customClassName="text-sm"
noBorder
borderOnFocus={false}
onChange={(description: Object, description_html: string) => {
onChange(description_html);
setValue("description", description);
}}
mentionHighlights={editorSuggestion.mentionHighlights}
mentionSuggestions={editorSuggestion.mentionSuggestions}
/>
);
else if (!value || !watch("description_html"))
return <div className="flex h-32 w-full items-center justify-center text-sm text-custom-text-200" />;
return (
<RichTextEditorWithRef
cancelUploadImage={fileService.cancelUpload}
uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
deleteFile={fileService.deleteImage}
restoreFile={fileService.restoreImage}
ref={editorRef}
value={
value && value !== "" && Object.keys(value).length > 0
? value
: { type: "doc", content: [{ type: "paragraph" }] }
}
debouncedUpdatesEnabled={false}
customClassName="text-sm"
noBorder
borderOnFocus={false}
onChange={(description: Object, description_html: string) => {
onChange(description_html);
setValue("description", description);
}}
/>
);
}}
/>
<div className="m-2 mt-6 flex">
<button
type="button"
className={`flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-80 ${
iAmFeelingLucky ? "cursor-wait bg-custom-background-90" : ""
}`}
onClick={handleAutoGenerateDescription}
disabled={iAmFeelingLucky}
>
{iAmFeelingLucky ? (
"Generating response..."
) : (
<>
<Sparkle className="h-4 w-4" />I{"'"}m feeling lucky
</>
)}
</button>
<button
type="button"
className="ml-2 flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-80"
onClick={() => setGptAssistantModal(true)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
</div>
</div>
</div>
<div className="flex items-center justify-end gap-2 p-4">
<Button variant="neutral-primary" onClick={handleClose}>
Cancel
</Button>
<Button variant="primary" type="submit" disabled={watch("name") === ""} loading={isSubmitting}>
{data ? (isSubmitting ? "Updating..." : "Update block") : isSubmitting ? "Adding..." : "Add block"}
</Button>
</div>
</form>
{envConfig?.has_openai_configured && (
<GptAssistantModal
block={data ? data : undefined}
isOpen={gptAssistantModal}
handleClose={() => setGptAssistantModal(false)}
inset="top-8 left-0"
content={watch("description_html")}
htmlContent={watch("description_html")}
onResponse={(response) => {
if (data && handleAiAssistance) {
handleAiAssistance(response);
editorRef.current?.setEditorValue(`${watch("description_html")}<p>${response}</p>` ?? "");
} else {
setValue("description", {});
setValue("description_html", `${watch("description_html")}<p>${response}</p>`);
editorRef.current?.setEditorValue(watch("description_html") ?? "");
}
}}
projectId={projectId?.toString() ?? ""}
/>
)}
</div>
);
};

View File

@ -1,6 +1,5 @@
export * from "./pages-list";
export * from "./create-block";
export * from "./create-update-block-inline";
export * from "./create-update-page-modal";
export * from "./delete-page-modal";
export * from "./page-form";

View File

@ -31,7 +31,7 @@ import { IssueService } from "services/issue";
import useToast from "hooks/use-toast";
import useReloadConfirmations from "hooks/use-reload-confirmation";
import { EUserWorkspaceRoles } from "constants/workspace";
import { GptAssistantModal } from "components/core";
import { GptAssistantPopover } from "components/core";
import { Sparkle } from "lucide-react";
import { observer } from "mobx-react-lite";
@ -59,7 +59,7 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
const { user } = useUser();
const { handleSubmit, setValue, watch, getValues, control } = useForm<IPage>({
const { handleSubmit, setValue, watch, getValues, control, reset } = useForm<IPage>({
defaultValues: { name: "", description_html: "" },
});
@ -487,28 +487,32 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
)}
/>
{projectId && envConfig?.has_openai_configured && (
<>
<button
type="button"
className="absolute right-[68px] top-2.5 flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
<GptAssistantModal
<div className="absolute right-[68px] top-2.5">
<GptAssistantPopover
isOpen={gptModalOpen}
projectId={projectId.toString()}
handleClose={() => {
setGptModal(false);
setGptModal((prevData) => !prevData);
// this is done so that the title do not reset after gpt popover closed
reset(getValues());
}}
inset="top-9 right-[68px] !w-1/2 !max-h-[50%]"
content=""
onResponse={(response) => {
handleAiAssistance(response);
}}
projectId={projectId.toString()}
placement="top-end"
button={
<button
type="button"
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
onClick={() => setGptModal((prevData) => !prevData)}
>
<Sparkle className="h-4 w-4" />
AI
</button>
}
className="!min-w-[38rem]"
/>
</>
</div>
)}
</div>
)}