feat: gpt integration for page block description (#539)

This commit is contained in:
Aaryan Khandelwal 2023-03-26 11:36:10 +05:30 committed by GitHub
parent 52d4828e1d
commit 5dd5fe2d09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 316 additions and 102 deletions

View File

@ -0,0 +1,154 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
// react-hook-form
import { useForm } from "react-hook-form";
// services
import aiService from "services/ai.service";
// hooks
import useToast from "hooks/use-toast";
// ui
import { Input, PrimaryButton, SecondaryButton } from "components/ui";
type Props = {
isOpen: boolean;
handleClose: () => void;
inset?: string;
content: string;
onResponse: (response: string) => void;
};
type FormData = {
prompt: string;
task: string;
};
export const GptAssistantModal: React.FC<Props> = ({
isOpen,
handleClose,
inset = "top-0 left-0",
content,
onResponse,
}) => {
const [response, setResponse] = useState("");
const [invalidResponse, setInvalidResponse] = useState(false);
const router = useRouter();
const { workspaceSlug, projectId } = router.query;
const { setToastAlert } = useToast();
const {
handleSubmit,
register,
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 (!content || content === "") {
setToastAlert({
type: "error",
title: "Error!",
message: "Please enter some description to get AI assistance.",
});
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,
task: formData.task,
})
.then((res) => {
setResponse(res.response);
setFocus("task");
if (res.response === "") setInvalidResponse(true);
else setInvalidResponse(false);
});
};
useEffect(() => {
if (isOpen) setFocus("task");
}, [isOpen, setFocus]);
return (
<div
className={`absolute ${inset} z-20 w-full rounded-[10px] border bg-white p-4 shadow ${
isOpen ? "block" : "hidden"
}`}
>
<form onSubmit={handleSubmit(handleResponse)} className="space-y-4">
<div className="text-sm">
Content: <p className="text-gray-500">{content}</p>
</div>
{response !== "" && (
<div className="text-sm">
Response: <p className="text-gray-500">{response}</p>
</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>
)}
<Input
type="text"
name="task"
register={register}
placeholder="Tell OpenAI what action to perform on this content..."
autoComplete="off"
/>
<div className={`flex gap-2 ${response === "" ? "justify-end" : "justify-between"}`}>
{response !== "" && (
<PrimaryButton
onClick={() => {
onResponse(response);
onClose();
}}
>
Use this response
</PrimaryButton>
)}
<div className="flex items-center gap-2">
<SecondaryButton onClick={onClose}>Close</SecondaryButton>
<PrimaryButton type="submit" loading={isSubmitting}>
{isSubmitting
? "Generating response..."
: response === ""
? "Generate response"
: "Generate again"}
</PrimaryButton>
</div>
</div>
</form>
</div>
);
};

View File

@ -3,6 +3,7 @@ export * from "./list-view";
export * from "./sidebar";
export * from "./bulk-delete-issues-modal";
export * from "./existing-issues-list-modal";
export * from "./gpt-assistant-modal";
export * from "./image-upload-modal";
export * from "./issues-view-filter";
export * from "./issues-view";

View File

@ -9,8 +9,12 @@ import { mutate } from "swr";
import { Controller, useForm } from "react-hook-form";
// services
import pagesService from "services/pages.service";
import aiService from "services/ai.service";
// hooks
import useToast from "hooks/use-toast";
// components
import { CreateUpdateIssueModal } from "components/issues";
import { GptAssistantModal } from "components/core";
// ui
import { CustomMenu, Loader, TextArea } from "components/ui";
// icons
@ -18,13 +22,13 @@ import { WaterDropIcon } from "components/icons";
// helpers
import { copyTextToClipboard } from "helpers/string.helper";
// types
import { IPageBlock } from "types";
import { IPageBlock, IProject } from "types";
// fetch-keys
import { PAGE_BLOCKS_LIST } from "constants/fetch-keys";
import { CreateUpdateIssueModal } from "components/issues";
type Props = {
block: IPageBlock;
projectDetails: IProject | undefined;
};
const RemirrorRichTextEditor = dynamic(() => import("components/rich-text-editor"), {
@ -36,9 +40,11 @@ const RemirrorRichTextEditor = dynamic(() => import("components/rich-text-editor
),
});
export const SinglePageBlock: React.FC<Props> = ({ block }) => {
export const SinglePageBlock: React.FC<Props> = ({ block, projectDetails }) => {
const [createUpdateIssueModal, setCreateUpdateIssueModal] = useState(false);
const [gptAssistantModal, setGptAssistantModal] = useState(false);
const router = useRouter();
const { workspaceSlug, projectId, pageId } = router.query;
@ -68,17 +74,15 @@ export const SinglePageBlock: React.FC<Props> = ({ block }) => {
false
);
await pagesService.patchPageBlock(
workspaceSlug as string,
projectId as string,
pageId as string,
block.id,
{
await pagesService
.patchPageBlock(workspaceSlug as string, projectId as string, pageId as string, block.id, {
name: formData.name,
description: formData.description,
description_html: formData.description_html,
}
);
})
.then(() => {
mutate(PAGE_BLOCKS_LIST(pageId as string));
});
};
const pushBlockIntoIssues = async () => {
@ -142,6 +146,28 @@ export const SinglePageBlock: React.FC<Props> = ({ block }) => {
});
};
const handleAiAssistance = async (response: string) => {
if (!workspaceSlug || !projectId) return;
setValue("description", {});
setValue("description_html", `<p>${response}</p>`);
handleSubmit(updatePageBlock)()
.then(() => {
setToastAlert({
type: "success",
title: "Success!",
message: "Block description updated successfully.",
});
})
.catch(() => {
setToastAlert({
type: "error",
title: "Error!",
message: "Block description could not be updated. Please try again.",
});
});
};
const handleCopyText = () => {
const originURL =
typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
@ -187,23 +213,32 @@ export const SinglePageBlock: React.FC<Props> = ({ block }) => {
role="textbox"
disabled={block.issue ? true : false}
/>
<CustomMenu label={<WaterDropIcon width={14} height={15} />} noBorder noChevron>
{block.issue ? (
<CustomMenu.MenuItem onClick={handleCopyText}>Copy issue link</CustomMenu.MenuItem>
) : (
<>
<CustomMenu.MenuItem onClick={pushBlockIntoIssues}>
Push into issues
</CustomMenu.MenuItem>
<CustomMenu.MenuItem onClick={editAndPushBlockIntoIssues}>
Edit and push into issues
</CustomMenu.MenuItem>
</>
)}
<CustomMenu.MenuItem onClick={deletePageBlock}>Delete block</CustomMenu.MenuItem>
</CustomMenu>
<div className="flex items-center">
<button
type="button"
className="rounded px-1.5 py-1 text-xs hover:bg-gray-100"
onClick={() => setGptAssistantModal((prevData) => !prevData)}
>
AI
</button>
<CustomMenu label={<WaterDropIcon width={14} height={15} />} noBorder noChevron>
{block.issue ? (
<CustomMenu.MenuItem onClick={handleCopyText}>Copy issue link</CustomMenu.MenuItem>
) : (
<>
<CustomMenu.MenuItem onClick={pushBlockIntoIssues}>
Push into issues
</CustomMenu.MenuItem>
<CustomMenu.MenuItem onClick={editAndPushBlockIntoIssues}>
Edit and push into issues
</CustomMenu.MenuItem>
</>
)}
<CustomMenu.MenuItem onClick={deletePageBlock}>Delete block</CustomMenu.MenuItem>
</CustomMenu>
</div>
</div>
<div className="page-block-section -mx-3 -mt-5">
<div className="page-block-section relative -mx-3 -mt-5">
<Controller
name="description"
control={control}
@ -220,10 +255,18 @@ export const SinglePageBlock: React.FC<Props> = ({ block }) => {
placeholder="Description..."
editable={block.issue ? false : true}
customClassName="text-gray-500"
// gptOption
noBorder
/>
)}
/>
<GptAssistantModal
isOpen={gptAssistantModal}
handleClose={() => setGptAssistantModal(false)}
inset="top-2 left-0"
content={block.description_stripped}
onResponse={handleAiAssistance}
/>
</div>
</div>
);

View File

@ -12,6 +12,7 @@ import { truncateText } from "helpers/string.helper";
import { renderShortDate, renderShortTime } from "helpers/date-time.helper";
// types
import { IPage } from "types";
import { PencilScribbleIcon } from "components/icons";
type TSingleStatProps = {
page: IPage;
@ -36,6 +37,7 @@ export const SinglePageListItem: React.FC<TSingleStatProps> = ({
<div className="relative rounded p-4 hover:bg-gray-100">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<PencilScribbleIcon />
<Link href={`/${workspaceSlug}/projects/${projectId}/pages/${page.id}`}>
<a>
<p className="mr-2 truncate text-sm font-medium">{truncateText(page.name, 75)}</p>

View File

@ -48,6 +48,7 @@ export interface IRemirrorRichTextEditor {
showToolbar?: boolean;
editable?: boolean;
customClassName?: string;
gptOption?: boolean;
noBorder?: boolean;
}
@ -66,6 +67,7 @@ const RemirrorRichTextEditor: FC<IRemirrorRichTextEditor> = (props) => {
showToolbar = true,
editable = true,
customClassName,
gptOption = false,
noBorder = false,
} = props;
@ -215,7 +217,7 @@ const RemirrorRichTextEditor: FC<IRemirrorRichTextEditor> = (props) => {
renderOutsideEditor
>
<FloatingToolbar className="z-[9999] overflow-hidden rounded">
<CustomFloatingToolbar />
<CustomFloatingToolbar gptOption={gptOption} editorState={state} />
</FloatingToolbar>
</FloatingWrapper>
)}

View File

@ -8,39 +8,61 @@ import {
ToggleBulletListButton,
ToggleCodeButton,
ToggleHeadingButton,
useActive,
} from "@remirror/react";
import { EditorState } from "remirror";
export const CustomFloatingToolbar: React.FC = () => (
<div className="z-[99999] flex items-center gap-y-2 divide-x rounded border bg-white p-1 px-0.5 shadow-md">
<div className="flex items-center gap-x-1 px-2">
<ToggleHeadingButton
attrs={{
level: 1,
}}
/>
<ToggleHeadingButton
attrs={{
level: 2,
}}
/>
<ToggleHeadingButton
attrs={{
level: 3,
}}
/>
type Props = {
gptOption?: boolean;
editorState: Readonly<EditorState>;
};
export const CustomFloatingToolbar: React.FC<Props> = ({ gptOption, editorState }) => {
const active = useActive();
return (
<div className="z-[99999] flex items-center gap-y-2 divide-x rounded border bg-white p-1 px-0.5 shadow-md">
<div className="flex items-center gap-x-1 px-2">
<ToggleHeadingButton
attrs={{
level: 1,
}}
/>
<ToggleHeadingButton
attrs={{
level: 2,
}}
/>
<ToggleHeadingButton
attrs={{
level: 3,
}}
/>
</div>
<div className="flex items-center gap-x-1 px-2">
<ToggleBoldButton />
<ToggleItalicButton />
<ToggleUnderlineButton />
<ToggleStrikeButton />
</div>
<div className="flex items-center gap-x-1 px-2">
<ToggleOrderedListButton />
<ToggleBulletListButton />
</div>
{gptOption && (
<div className="flex items-center gap-x-1 px-2">
<button
type="button"
className="rounded py-1 px-1.5 text-xs hover:bg-gray-100"
onClick={() => console.log(editorState.selection.$anchor.nodeBefore)}
>
AI
</button>
</div>
)}
<div className="flex items-center gap-x-1 px-2">
<ToggleCodeButton />
</div>
</div>
<div className="flex items-center gap-x-1 px-2">
<ToggleBoldButton />
<ToggleItalicButton />
<ToggleUnderlineButton />
<ToggleStrikeButton />
</div>
<div className="flex items-center gap-x-1 px-2">
<ToggleOrderedListButton />
<ToggleBulletListButton />
</div>
<div className="flex items-center gap-x-1 px-2">
<ToggleCodeButton />
</div>
</div>
);
);
};

View File

@ -1,4 +1,3 @@
export * from "./danger-button";
export * from "./no-border-button";
export * from "./primary-button";
export * from "./secondary-button";

View File

@ -1,36 +0,0 @@
// types
import { ButtonProps } from "./type";
export const NoBorderButton: React.FC<ButtonProps> = ({
children,
className = "",
onClick,
type = "button",
disabled = false,
loading = false,
size = "sm",
outline = false,
}) => (
<button
type={type}
className={`${className} border border-red-500 font-medium duration-300 ${
size === "sm"
? "rounded px-3 py-2 text-xs"
: size === "md"
? "rounded-md px-3.5 py-2 text-sm"
: "rounded-lg px-4 py-2 text-base"
} ${
disabled
? "cursor-not-allowed border-gray-300 bg-gray-300 text-black hover:border-gray-300 hover:border-opacity-100 hover:bg-gray-300 hover:bg-opacity-100 hover:text-black"
: ""
} ${
outline
? "bg-transparent hover:bg-red-500 hover:text-white"
: "bg-red-500 text-white hover:border-opacity-90 hover:bg-opacity-90"
} ${loading ? "cursor-wait" : ""}`}
onClick={onClick}
disabled={disabled || loading}
>
{children}
</button>
);

View File

@ -323,9 +323,6 @@ const SinglePage: NextPage = () => {
<ShareIcon className="h-4 w-4" />
Share
</PrimaryButton>
<button type="button" className="text-sm">
AI
</button>
<div className="flex-shrink-0">
<Popover className="relative grid place-items-center">
{({ open }) => (
@ -407,7 +404,11 @@ const SinglePage: NextPage = () => {
<>
<div className="space-y-4">
{pageBlocks.map((block) => (
<SinglePageBlock key={block.id} block={block} />
<SinglePageBlock
key={block.id}
block={block}
projectDetails={projectDetails}
/>
))}
</div>
<div className="">

View File

@ -0,0 +1,24 @@
// services
import APIService from "services/api.service";
const { NEXT_PUBLIC_API_BASE_URL } = process.env;
class AiServices extends APIService {
constructor() {
super(NEXT_PUBLIC_API_BASE_URL || "http://localhost:8000");
}
async createGptTask(
workspaceSlug: string,
projectId: string,
data: { prompt: string; task: string }
): Promise<any> {
return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/ai-assistant/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
}
export default new AiServices();

View File

@ -75,6 +75,7 @@ export interface IIssue {
cycle_detail: ICycle | null;
description: any;
description_html: any;
description_stripped: any;
id: string;
issue_cycle: IIssueCycle | null;
issue_link: {

View File

@ -33,6 +33,7 @@ export interface IPageBlock {
created_by: string;
description: any;
description_html: any;
description_stripped: any;
id: string;
issue: string | null;
issue_detail: string | null;