refactor: webhooks (#2896)

* refactor: webhooks workflow

* chore: update delete modal content
This commit is contained in:
Aaryan Khandelwal 2023-11-27 17:15:48 +05:30 committed by sriram veeraghanta
parent 6e940399cb
commit 726f4668e0
29 changed files with 812 additions and 835 deletions

View file

@ -1,30 +1,31 @@
import React, { FC, useState } from "react";
import { useRouter } from "next/router";
import { Dialog, Transition } from "@headlessui/react";
// icons
import { AlertTriangle } from "lucide-react";
// ui
import { Button } from "@plane/ui";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { Button } from "@plane/ui";
interface IDeleteWebhook {
isOpen: boolean;
webhook_url: string;
onClose: () => void;
}
export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
const { isOpen, onClose } = props;
// states
const [isDeleting, setIsDeleting] = useState(false);
// router
const router = useRouter();
const { webhook: webhookStore } = useMobxStore();
// toast
const { setToastAlert } = useToast();
const [deleting, setDelete] = useState(false);
// mobx store
const {
webhook: { removeWebhook },
} = useMobxStore();
const { workspaceSlug, webhookId } = router.query;
@ -33,29 +34,27 @@ export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
};
const handleDelete = async () => {
setDelete(true);
if (!workspaceSlug || !webhookId) return;
webhookStore
.remove(workspaceSlug.toString(), webhookId.toString())
setIsDeleting(true);
removeWebhook(workspaceSlug.toString(), webhookId.toString())
.then(() => {
setToastAlert({
title: "Success",
type: "success",
message: "Successfully deleted",
title: "Success!",
message: "Webhook deleted successfully.",
});
router.replace(`/${workspaceSlug}/settings/webhooks/`);
})
.catch((error) => {
console.log(error);
.catch((error) =>
setToastAlert({
title: "Oops!",
type: "error",
message: error?.error,
});
})
.finally(() => {
setDelete(false);
});
title: "Error!",
message: error?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsDeleting(false));
};
return (
@ -90,23 +89,21 @@ export const DeleteWebhookModal: FC<IDeleteWebhook> = (props) => {
<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 Webhook</h3>
<h3 className="text-xl font-medium 2xl:text-2xl">Delete webhook</h3>
</span>
</div>
<span>
<p className="text-sm leading-7 text-custom-text-200">
Are you sure you want to delete workspace <span className="break-words font-semibold" />? All of the
data related to the workspace will be permanently removed. This action cannot be undone.
</p>
</span>
<p className="text-sm text-custom-text-200 mt-4">
Are you sure you want to delete this webhook? Future events will not be delivered to this webhook.
This action cannot be undone.
</p>
<div className="flex justify-end gap-2">
<Button variant="neutral-primary" onClick={onClose}>
Cancel
</Button>
<Button variant="danger" type="submit" onClick={handleDelete}>
{deleting ? "Deleting..." : "Delete Webhook"}
<Button variant="danger" onClick={handleDelete} loading={isDeleting}>
{isDeleting ? "Deleting..." : "Delete webhook"}
</Button>
</div>
</Dialog.Panel>

View file

@ -0,0 +1,28 @@
// next
import { useRouter } from "next/router";
import Image from "next/image";
// ui
import { Button } from "@plane/ui";
// assets
import EmptyWebhook from "public/empty-state/web-hook.svg";
export const WebhooksEmptyState = () => {
const router = useRouter();
return (
<div
className={`flex items-center justify-center mx-auto rounded-sm border border-custom-border-200 bg-custom-background-90 py-10 px-16 w-full`}
>
<div className="text-center flex flex-col items-center w-full">
<Image src={EmptyWebhook} className="w-52 sm:w-60" alt="empty" />
<h6 className="text-xl font-semibold mt-6 sm:mt-8 mb-3">No webhooks</h6>
<p className="text-custom-text-300 mb-7 sm:mb-8">
Create webhooks to receive real-time updates and automate actions
</p>
<Button className="flex items-center gap-1.5" onClick={() => router.push(`${router.asPath}/create/`)}>
Add webhook
</Button>
</div>
</div>
);
};

View file

@ -1,33 +0,0 @@
// next
import { useRouter } from "next/router";
import Image from "next/image";
// ui
import { Button } from "@plane/ui";
// assets
import EmptyWebhook from "public/empty-state/web-hook.svg";
export const EmptyWebhooks = () => {
const router = useRouter();
return (
<div className={`flex items-center justify-center mx-auto rounded-sm border border-custom-border-200 bg-custom-background-90 py-10 px-16 w-full`}>
<div className="text-center flex flex-col items-center w-full">
<Image src={EmptyWebhook} className="w-52 sm:w-60" alt="empty" />
<h6 className="text-xl font-semibold mt-6 sm:mt-8 mb-3">No Webhooks</h6>
{
<p className="text-custom-text-300 mb-7 sm:mb-8">
Create webhooks to receive real-time updates and automate actions
</p>
}
<Button
className="flex items-center gap-1.5"
onClick={() => {
router.push(`${router.asPath}/create/`);
}}
>
Add Webhook
</Button>
</div>
</div>
);
};

View file

@ -0,0 +1,48 @@
import { Disclosure, Transition } from "@headlessui/react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@plane/ui";
type Props = {
openDeleteModal: () => void;
};
export const WebhookDeleteSection: React.FC<Props> = (props) => {
const { openDeleteModal } = props;
return (
<Disclosure as="div" className="border-t border-custom-border-200">
{({ open }) => (
<div className="w-full">
<Disclosure.Button as="button" type="button" className="flex items-center justify-between w-full py-4">
<span className="text-lg tracking-tight">Danger zone</span>
{open ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
</Disclosure.Button>
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0"
enterTo="transform opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform opacity-100"
leaveTo="transform opacity-0"
>
<Disclosure.Panel>
<div className="flex flex-col gap-8">
<span className="text-sm tracking-tight">
Once a webhook is deleted, it cannot be restored. Future events will no longer be delivered to this
webhook.
</span>
<div>
<Button variant="danger" onClick={openDeleteModal}>
Delete webhook
</Button>
</div>
</div>
</Disclosure.Panel>
</Transition>
</div>
)}
</Disclosure>
);
};

View file

@ -1,50 +0,0 @@
import { Disclosure, Transition } from "@headlessui/react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@plane/ui";
interface IWebHookEditForm {
setOpenDeleteModal: React.Dispatch<React.SetStateAction<boolean>>;
}
export const WebHookEditForm = ({ setOpenDeleteModal }: IWebHookEditForm) => (
<Disclosure as="div" className="border-t border-custom-border-200">
{({ open }) => (
<div className="w-full">
<Disclosure.Button as="button" type="button" className="flex items-center justify-between w-full py-4">
<span className="text-lg tracking-tight">Danger Zone</span>
{open ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
</Disclosure.Button>
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0"
enterTo="transform opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform opacity-100"
leaveTo="transform opacity-0"
>
<Disclosure.Panel>
<div className="flex flex-col gap-8">
<span className="text-sm tracking-tight">
The danger zone of the workspace delete page is a critical area that requires careful consideration and
attention. When deleting a workspace, all of the data and resources within that workspace will be
permanently removed and cannot be recovered.
</span>
<div>
<Button
variant="danger"
onClick={() => {
setOpenDeleteModal(true);
}}
>
Delete Webhook
</Button>
</div>
</div>
</Disclosure.Panel>
</Transition>
</div>
)}
</Disclosure>
);

View file

@ -0,0 +1,44 @@
// types
import { TWebhookEventTypes } from "types";
type Props = {
value: string;
onChange: (value: TWebhookEventTypes) => void;
};
const WEBHOOK_EVENT_TYPES: { key: TWebhookEventTypes; label: string }[] = [
{
key: "all",
label: "Send me everything",
},
{
key: "individual",
label: "Select individual events",
},
];
export const WebhookOptions: React.FC<Props> = (props) => {
const { value, onChange } = props;
return (
<>
<h6 className="text-sm font-medium">Which events would you like to trigger this webhook?</h6>
<div className="space-y-3">
{WEBHOOK_EVENT_TYPES.map((option) => (
<div key={option.key} className="flex items-center gap-2">
<input
id={option.key}
type="radio"
value={option.key}
checked={value == option.key}
onChange={() => onChange(option.key)}
/>
<label className="text-sm" htmlFor={option.key}>
{option.label}
</label>
</div>
))}
</div>
</>
);
};

View file

@ -0,0 +1,167 @@
import React, { FC, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
// components
import {
WebhookIndividualEventOptions,
WebhookInput,
WebhookOptions,
WebhookSecretKey,
WebhookToggle,
getCurrentHookAsCSV,
} from "components/web-hooks";
// ui
import { Button } from "@plane/ui";
// helpers
import { csvDownload } from "helpers/download.helper";
// types
import { IWebhook, TWebhookEventTypes } from "types";
type Props = {
data?: Partial<IWebhook>;
};
const initialWebhookPayload: Partial<IWebhook> = {
cycle: true,
issue: true,
issue_comment: true,
module: true,
project: true,
url: "",
};
export const WebhookForm: FC<Props> = observer((props) => {
const { data } = props;
// states
const [webhookEventType, setWebhookEventType] = useState<TWebhookEventTypes>("all");
// router
const router = useRouter();
const { workspaceSlug } = router.query;
// toast
const { setToastAlert } = useToast();
// mobx store
const {
webhook: { createWebhook, updateWebhook },
workspace: { currentWorkspace },
} = useMobxStore();
// use form
const {
handleSubmit,
control,
formState: { isSubmitting, errors },
} = useForm<IWebhook>({
defaultValues: { ...initialWebhookPayload, ...data },
});
const handleCreateWebhook = async (formData: IWebhook) => {
if (!workspaceSlug) return;
let payload: Partial<IWebhook> = {
url: formData.url,
};
if (webhookEventType === "all")
payload = {
...payload,
project: true,
cycle: true,
module: true,
issue: true,
issue_comment: true,
};
else
payload = {
...payload,
project: formData.project ?? false,
cycle: formData.cycle ?? false,
module: formData.module ?? false,
issue: formData.issue ?? false,
issue_comment: formData.issue_comment ?? false,
};
await createWebhook(workspaceSlug.toString(), payload)
.then(({ webHook, secretKey }) => {
setToastAlert({
type: "success",
title: "Success!",
message: "Webhook created successfully.",
});
const csvData = getCurrentHookAsCSV(currentWorkspace, webHook, secretKey);
csvDownload(csvData, `webhook-secret-key-${Date.now()}`);
if (webHook && webHook.id)
router.push({ pathname: `/${workspaceSlug}/settings/webhooks/${webHook.id}`, query: { isCreated: true } });
})
.catch((error) => {
setToastAlert({
type: "error",
title: "Error!",
message: error?.error ?? "Something went wrong. Please try again.",
});
});
};
const handleUpdateWebhook = async (formData: IWebhook) => {
if (!workspaceSlug || !data || !data.id) return;
const payload = {
url: formData?.url,
is_active: formData?.is_active,
project: formData?.project,
cycle: formData?.cycle,
module: formData?.module,
issue: formData?.issue,
issue_comment: formData?.issue_comment,
};
return await updateWebhook(workspaceSlug.toString(), data.id, payload);
};
const handleFormSubmit = async (formData: IWebhook) => {
if (data) await handleUpdateWebhook(formData);
else await handleCreateWebhook(formData);
};
useEffect(() => {
if (!data) return;
if (data.project && data.cycle && data.module && data.issue && data.issue_comment) setWebhookEventType("all");
else setWebhookEventType("individual");
}, [data]);
return (
<div className="space-y-6">
<div className="text-xl font-medium">{data ? "Webhook details" : "Create webhook"}</div>
<form className="space-y-8" onSubmit={handleSubmit(handleFormSubmit)}>
<div>
<Controller
control={control}
name="url"
rules={{
required: "URL is required",
}}
render={({ field: { onChange, value } }) => (
<WebhookInput value={value} onChange={onChange} hasError={Boolean(errors.url)} />
)}
/>
{errors.url && <div className="text-xs text-red-500">{errors.url.message}</div>}
</div>
{data && <WebhookToggle control={control} />}
<div className="space-y-3">
<WebhookOptions value={webhookEventType} onChange={(val) => setWebhookEventType(val)} />
</div>
{webhookEventType === "individual" && <WebhookIndividualEventOptions control={control} />}
{data && <WebhookSecretKey data={data} />}
<Button type="submit" loading={isSubmitting}>
{data ? (isSubmitting ? "Updating..." : "Update") : isSubmitting ? "Creating..." : "Create"}
</Button>
</form>
</div>
);
});

View file

@ -1,139 +0,0 @@
import { useState, FC } from "react";
import { useRouter } from "next/router";
import { Button } from "@plane/ui";
import { Copy, Eye, EyeOff, RefreshCw } from "lucide-react";
import { observer } from "mobx-react-lite";
// hooks
import useToast from "hooks/use-toast";
// store
import { RootStore } from "store/root";
import { useMobxStore } from "lib/mobx/store-provider";
// helpers
import { copyTextToClipboard } from "helpers/string.helper";
import { csvDownload } from "helpers/download.helper";
// utils
import { getCurrentHookAsCSV } from "../utils";
// enum
import { WebHookFormTypes } from "./index";
interface IGenerateKey {
type: WebHookFormTypes.CREATE | WebHookFormTypes.EDIT;
}
export const GenerateKey: FC<IGenerateKey> = observer((props) => {
const { type } = props;
// states
const [regenerating, setRegenerate] = useState(false);
const [shouldShowKey, setShouldShowKey] = useState(false);
// router
const router = useRouter();
const { workspaceSlug, webhookId } = router.query as { workspaceSlug: string; webhookId: string };
// store
const { webhook: webhookStore, workspace: workspaceStore }: RootStore = useMobxStore();
// hooks
const { setToastAlert } = useToast();
const handleCopySecret = () => {
if (webhookStore?.webhookSecretKey) {
copyTextToClipboard(webhookStore.webhookSecretKey);
setToastAlert({
title: "Success",
type: "success",
message: "Secret key copied",
});
} else {
setToastAlert({
title: "Oops",
type: "error",
message: "Error occurred while copying secret key",
});
}
};
function handleRegenerate() {
setRegenerate(true);
webhookStore
.regenerate(workspaceSlug, webhookId)
.then(() => {
setToastAlert({
title: "Success",
type: "success",
message: "Successfully regenerated",
});
const csvData = getCurrentHookAsCSV(
workspaceStore.currentWorkspace,
webhookStore.currentWebhook,
webhookStore.webhookSecretKey
);
csvDownload(csvData, `Secret-key-${Date.now()}`);
})
.catch((err) => {
setToastAlert({
title: "Oops!",
type: "error",
message: err?.error,
});
})
.finally(() => {
setRegenerate(false);
});
}
const toggleShowKey = () => {
setShouldShowKey((prevState) => !prevState);
};
const icons = [
{ Component: Copy, onClick: handleCopySecret, key: "copy" },
{ Component: shouldShowKey ? EyeOff : Eye, onClick: toggleShowKey, key: "eye" },
];
return (
<>
{(type === WebHookFormTypes.EDIT || (type === WebHookFormTypes.CREATE && webhookStore?.webhookSecretKey)) && (
<div className="space-y-2">
<div className="text-sm font-medium">Secret Key</div>
<div className="text-sm text-neutral-400">Genarate a token to sign-in the webhook payload</div>
<div className="flex gap-5 items-center">
<div className="relative flex items-center p-2 rounded w-full border border-custom-border-200">
<div className="flex w-full overflow-hidden h-7 px-2 font-medium select-none">
{webhookStore?.webhookSecretKey && shouldShowKey ? (
<div>{webhookStore?.webhookSecretKey}</div>
) : (
<div className="flex items-center gap-1.5">
{[...Array(41)].map((_, index) => (
<div key={index} className="w-[4px] h-[4px] bg-gray-300 rounded-full" />
))}
</div>
)}
</div>
{webhookStore?.webhookSecretKey && (
<>
{icons.map(({ Component, onClick, key }) => (
<div
className="w-7 h-7 flex-shrink-0 flex justify-center items-center cursor-pointer hover:bg-custom-background-80 rounded"
onClick={onClick}
key={key}
>
<Component className="text-custom-text-400 w-4 h-4" />
</div>
))}
</>
)}
</div>
<div>
{type != WebHookFormTypes.CREATE && (
<Button disabled={regenerating} onClick={handleRegenerate} variant="accent-primary" className="">
<RefreshCw className={`h-3 w-3`} />
{regenerating ? "Re-generating..." : "Re-genarate Key"}
</Button>
)}
</div>
</div>
</div>
)}
</>
);
});

View file

@ -0,0 +1,7 @@
export * from "./delete-section";
export * from "./event-types";
export * from "./form";
export * from "./individual-event-options";
export * from "./input";
export * from "./secret-key";
export * from "./toggle";

View file

@ -1,102 +0,0 @@
import React, { FC, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { IWebhook, IExtendedWebhook } from "types";
import { GenerateKey } from "./generate-key";
import { observer } from "mobx-react-lite";
// components
import { DeleteWebhookModal } from "../delete-webhook-modal";
import { WebHookInput } from "./input";
import { WebHookToggle } from "./toggle";
import { WEBHOOK_EVENTS, WebHookOptions, WebhookTypes } from "./options";
import { WebHookIndividualOptions, individualWebhookOptions } from "./option";
import { WebHookSubmitButton } from "./submit";
import { WebHookEditForm } from "./edit-form";
export enum WebHookFormTypes {
EDIT = "edit",
CREATE = "create",
}
interface IWebHookForm {
type: WebHookFormTypes;
initialData: IWebhook;
onSubmit: (val: IExtendedWebhook) => void;
}
export const WebHookForm: FC<IWebHookForm> = observer((props) => {
const { type, initialData, onSubmit } = props;
// states
const [openDeleteModal, setOpenDeleteModal] = useState(false);
// use form
const {
reset,
watch,
handleSubmit,
control,
getValues,
formState: { isSubmitting, errors },
} = useForm<IExtendedWebhook>();
const checkWebhookEvent = (initialData: IWebhook) => {
const { project, module, cycle, issue, issue_comment } = initialData;
if (!project || !cycle || !module || !issue || !issue_comment) {
return WebhookTypes.INDIVIDUAL;
}
return WebhookTypes.ALL;
};
useEffect(() => {
if (initialData && reset) reset({ ...initialData, webhook_events: checkWebhookEvent(initialData) });
}, [initialData, reset]);
useEffect(() => {
if (!watch(WEBHOOK_EVENTS)) return;
const allWebhookOptions: { [key: string]: boolean } = {};
/**For Webhooks to return all the types */
if (watch(WEBHOOK_EVENTS) === WebhookTypes.ALL) {
individualWebhookOptions.forEach(({ name }) => {
allWebhookOptions[name] = true;
});
} /**For Webhooks to return selected individual types, retain the saved individual types */ else if (
watch(WEBHOOK_EVENTS) === WebhookTypes.INDIVIDUAL
) {
individualWebhookOptions.forEach(({ name }) => {
if (initialData[name] !== undefined) {
allWebhookOptions[name] = initialData[name]!;
} else {
allWebhookOptions[name] = true;
}
});
}
reset({ ...getValues(), ...allWebhookOptions });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [watch && watch(WEBHOOK_EVENTS)]);
return (
<>
<DeleteWebhookModal
isOpen={openDeleteModal}
webhook_url=""
onClose={() => {
setOpenDeleteModal(false);
}}
/>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="space-y-8 py-5">
<WebHookInput control={control} errors={errors} />
<WebHookToggle control={control} />
<div className="space-y-3">
<WebHookOptions control={control} />
{watch(WEBHOOK_EVENTS) === WebhookTypes.INDIVIDUAL && <WebHookIndividualOptions control={control} />}
</div>
<GenerateKey type={type} />
<WebHookSubmitButton isSubmitting={isSubmitting} type={type} />
{type === WebHookFormTypes.EDIT && <WebHookEditForm setOpenDeleteModal={setOpenDeleteModal} />}
</div>
</form>
</>
);
});

View file

@ -0,0 +1,69 @@
import { Control, Controller } from "react-hook-form";
import { IWebhook } from "types/webhook";
export const individualWebhookOptions: {
key: keyof IWebhook;
label: string;
description: string;
}[] = [
{
key: "project",
label: "Projects",
description: "Project created, updated or deleted.",
},
{
key: "cycle",
label: "Cycles",
description: "Cycle created, updated or deleted.",
},
{
key: "issue",
label: "Issues",
description: "Issue created, updated, deleted, added to a cycle or module.",
},
{
key: "module",
label: "Modules",
description: "Module created, updated or deleted.",
},
{
key: "issue_comment",
label: "Issue comments",
description: "Comment posted, updated or deleted.",
},
];
type Props = {
control: Control<IWebhook, any>;
};
export const WebhookIndividualEventOptions = ({ control }: Props) => (
<>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-4 gap-y-8 px-6 mt-5">
{individualWebhookOptions.map((option) => (
<Controller
key={option.key}
control={control}
name={option.key}
render={({ field: { onChange, value } }) => (
<div>
<div className="flex items-center gap-2">
<input
id={option.key}
onChange={() => onChange(!value)}
type="checkbox"
name="selectIndividualEvents"
checked={value === true}
/>
<label className="text-sm" htmlFor={option.key}>
{option.label}
</label>
</div>
<p className="text-xs text-custom-text-300 ml-6 mt-0.5">{option.description}</p>
</div>
)}
/>
))}
</div>
</>
);

View file

@ -1,33 +1,26 @@
import { Control, Controller, FieldErrors } from "react-hook-form";
import { Input } from "@plane/ui";
import { IExtendedWebhook } from "types/webhook";
interface IWebHookInput {
control: Control<IExtendedWebhook, any>;
errors: FieldErrors<IExtendedWebhook>;
}
type Props = {
value: string;
onChange: (value: string) => void;
hasError: boolean;
};
export const WebhookInput: React.FC<Props> = (props) => {
const { value, onChange, hasError } = props;
export const WebHookInput = ({ control, errors }: IWebHookInput) => (
<div>
<div className="font-medium text-sm">URL</div>
<Controller
control={control}
name="url"
rules={{
required: "URL is Required",
validate: (value) => (/^(ftp|http|https):\/\/[^ "]+$/.test(value) ? true : "Enter a valid URL"),
}}
render={({ field: { onChange, value } }) => (
<Input
className="w-full h-11"
onChange={onChange}
value={value}
id="url"
autoComplete="off"
placeholder="Enter URL"
/>
)}
/>
{errors.url && <p className="py-2 text-sm text-red-500">{errors.url.message}</p>}
</div>
);
return (
<>
<h6 className="font-medium text-sm">Payload URL</h6>
<Input
type="url"
className="w-full h-11"
onChange={(e) => onChange(e.target.value)}
value={value}
autoComplete="off"
hasError={hasError}
placeholder="https://example.com/post"
autoFocus
/>
</>
);
};

View file

@ -1,70 +0,0 @@
import { Control, Controller } from "react-hook-form";
import { IWebhookIndividualOptions, IExtendedWebhook } from "types/webhook";
export enum IndividualWebhookTypes {
PROJECTS = "Projects",
MODULES = "Modules",
CYCLES = "Cycles",
ISSUES = "Issues",
ISSUE_COMMENTS = "Issue Comments",
}
export const individualWebhookOptions: IWebhookIndividualOptions[] = [
{
key: "project_toggle",
label: IndividualWebhookTypes.PROJECTS,
name: "project",
},
{
key: "cycle-toggle",
label: IndividualWebhookTypes.CYCLES,
name: "cycle",
},
{
key: "issue_toggle",
label: IndividualWebhookTypes.ISSUES,
name: "issue",
},
{
key: "module_toggle",
label: IndividualWebhookTypes.MODULES,
name: "module",
},
{
key: "issue_comment_toggle",
label: IndividualWebhookTypes.ISSUE_COMMENTS,
name: "issue_comment",
},
];
interface IWebHookIndividualOptions {
control: Control<IExtendedWebhook, any>;
}
export const WebHookIndividualOptions = ({ control }: IWebHookIndividualOptions) => (
<>
<div className="grid grid-cols-2 md:grid-cols-3 grid-flow-row gap-4 px-8 py-6 bg-custom-background-90">
{individualWebhookOptions.map(({ key, label, name }: IWebhookIndividualOptions) => (
<Controller
control={control}
name={name}
key={key}
render={({ field: { onChange, value } }) => (
<div className="relative flex items-center gap-2">
<input
id={key}
onChange={() => onChange(!value)}
type="checkbox"
name="selectIndividualEvents"
checked={value == true}
/>
<label className="text-sm" htmlFor={key}>
{label}
</label>
</div>
)}
/>
))}
</div>
</>
);

View file

@ -1,54 +0,0 @@
import { Control, Controller } from "react-hook-form";
import { IExtendedWebhook, IWebhookOptions } from "types/webhook";
export enum WebhookTypes {
ALL = "all",
INDIVIDUAL = "individual",
}
interface IWebHookOptionsProps {
control: Control<IExtendedWebhook, any>;
}
export const WEBHOOK_EVENTS = "webhook_events";
const webhookOptions: IWebhookOptions[] = [
{
key: WebhookTypes.ALL,
label: "Send everything",
name: WEBHOOK_EVENTS,
},
{
key: WebhookTypes.INDIVIDUAL,
label: "Select Individual events",
name: WEBHOOK_EVENTS,
},
];
export const WebHookOptions = ({ control }: IWebHookOptionsProps) => (
<>
<div className="text-sm font-medium">Which events do you like to trigger this webhook</div>
{webhookOptions.map(({ key, label, name }: IWebhookOptions) => (
<div className="flex items-center gap-2">
<Controller
control={control}
name={name}
key={key}
render={({ field: { onChange, value } }) => (
<input
id={key}
type="radio"
name={name}
value={key}
checked={value == key}
onChange={() => onChange(key)}
/>
)}
/>
<label className="text-sm" htmlFor={key}>
{label}
</label>
</div>
))}
</>
);

View file

@ -0,0 +1,135 @@
import { useState, FC } from "react";
import { useRouter } from "next/router";
import { Button, Tooltip } from "@plane/ui";
import { Copy, Eye, EyeOff, RefreshCw } from "lucide-react";
import { observer } from "mobx-react-lite";
// hooks
import useToast from "hooks/use-toast";
// store
import { useMobxStore } from "lib/mobx/store-provider";
// helpers
import { copyTextToClipboard } from "helpers/string.helper";
import { csvDownload } from "helpers/download.helper";
// utils
import { getCurrentHookAsCSV } from "../utils";
// types
import { IWebhook } from "types";
type Props = {
data: Partial<IWebhook>;
};
export const WebhookSecretKey: FC<Props> = observer((props) => {
const { data } = props;
// states
const [isRegenerating, setIsRegenerating] = useState(false);
const [shouldShowKey, setShouldShowKey] = useState(false);
// router
const router = useRouter();
const { workspaceSlug, webhookId } = router.query;
// store
const {
webhook: { currentWebhook, regenerateSecretKey, webhookSecretKey },
workspace: { currentWorkspace },
} = useMobxStore();
// hooks
const { setToastAlert } = useToast();
const handleCopySecretKey = () => {
if (!webhookSecretKey) return;
copyTextToClipboard(webhookSecretKey)
.then(() =>
setToastAlert({
type: "success",
title: "Success!",
message: "Secret key copied to clipboard.",
})
)
.catch(() =>
setToastAlert({
type: "error",
title: "Error!",
message: "Error occurred while copying secret key.",
})
);
};
const handleRegenerateSecretKey = () => {
if (!workspaceSlug || !webhookId) return;
setIsRegenerating(true);
regenerateSecretKey(workspaceSlug.toString(), webhookId.toString())
.then(() => {
setToastAlert({
type: "success",
title: "Success!",
message: "New key regenerated successfully.",
});
const csvData = getCurrentHookAsCSV(currentWorkspace, currentWebhook, webhookSecretKey);
csvDownload(csvData, `webhook-secret-key-${Date.now()}`);
})
.catch((err) =>
setToastAlert({
type: "error",
title: "Error!",
message: err?.error ?? "Something went wrong. Please try again.",
})
)
.finally(() => setIsRegenerating(false));
};
const toggleShowKey = () => setShouldShowKey((prevState) => !prevState);
const SECRET_KEY_OPTIONS = [
{ label: "View secret key", Icon: shouldShowKey ? EyeOff : Eye, onClick: toggleShowKey, key: "eye" },
{ label: "Copy secret key", Icon: Copy, onClick: handleCopySecretKey, key: "copy" },
];
return (
<>
{(data || webhookSecretKey) && (
<div className="space-y-2">
<div className="text-sm font-medium">Secret key</div>
<div className="text-xs text-custom-text-400">Generate a token to sign-in to the webhook payload</div>
<div className="flex items-center gap-4">
<div className="self-stretch flex items-center justify-between py-1.5 px-2 rounded min-w-[30rem] max-w-lg border border-custom-border-200">
<div className="overflow-hidden font-medium select-none">
{shouldShowKey ? (
<p className="text-xs">{webhookSecretKey}</p>
) : (
<div className="flex items-center gap-1.5">
{[...Array(30)].map((_, index) => (
<div key={index} className="w-1 h-1 bg-custom-text-400 rounded-full" />
))}
</div>
)}
</div>
{webhookSecretKey && (
<div className="flex items-center gap-2">
{SECRET_KEY_OPTIONS.map((option) => (
<Tooltip key={option.key} tooltipContent={option.label}>
<button type="button" className="flex-shrink-0 grid place-items-center" onClick={option.onClick}>
<option.Icon className="text-custom-text-400 h-3 w-3" />
</button>
</Tooltip>
))}
</div>
)}
</div>
{data && (
<div>
<Button onClick={handleRegenerateSecretKey} variant="accent-primary" loading={isRegenerating}>
<RefreshCw className="h-3 w-3" />
{isRegenerating ? "Re-generating..." : "Re-generate key"}
</Button>
</div>
)}
</div>
</div>
)}
</>
);
});

View file

@ -1,13 +0,0 @@
import { Button } from "@plane/ui";
import { WebHookFormTypes } from "./index";
interface IWebHookSubmitButton {
isSubmitting: boolean;
type: WebHookFormTypes;
}
export const WebHookSubmitButton = ({ isSubmitting, type }: IWebHookSubmitButton) => (
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "processing..." : type === "create" ? "Create webhook" : "Save webhook"}
</Button>
);

View file

@ -1,14 +1,16 @@
import { Control, Controller } from "react-hook-form";
import { IExtendedWebhook } from "types/webhook";
// ui
import { ToggleSwitch } from "@plane/ui";
// types
import { IWebhook } from "types/webhook";
interface IWebHookToggle {
control: Control<IExtendedWebhook, any>;
control: Control<IWebhook, any>;
}
export const WebHookToggle = ({ control }: IWebHookToggle) => (
export const WebhookToggle = ({ control }: IWebHookToggle) => (
<div className="flex gap-6">
<div className="text-sm"> Enable webhook </div>
<div className="text-sm font-medium">Enable webhook</div>
<Controller
control={control}
name="is_active"

View file

@ -1,4 +1,6 @@
export * from "./empty-webhooks";
export * from "./webhooks-list";
export * from "./webhooks-list-item";
export * from "./form";
export * from "./delete-webhook-modal";
export * from "./empty-state";
export * from "./utils";
export * from "./webhooks-list-item";
export * from "./webhooks-list";

View file

@ -1,41 +1,40 @@
import { FC } from "react";
import { ToggleSwitch } from "@plane/ui";
import Link from "next/link";
import { RootStore } from "store/root";
import { useRouter } from "next/router";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { ToggleSwitch } from "@plane/ui";
// types
import { IWebhook } from "types";
interface IWebhookListItem {
workspaceSlug: string;
webhook: IWebhook;
}
export const WebhooksListItem: FC<IWebhookListItem> = (props) => {
const { workspaceSlug, webhook } = props;
const { webhook } = props;
// router
const router = useRouter();
const { workspaceSlug } = router.query;
const { webhook: webhookStore }: RootStore = useMobxStore();
const {
webhook: { updateWebhook },
} = useMobxStore();
const handleToggle = () => {
if (webhook.id) {
webhookStore.update(workspaceSlug, webhook.id, { ...webhook, is_active: !webhook.is_active }).catch(() => {});
}
if (!workspaceSlug || !webhook.id) return;
updateWebhook(workspaceSlug.toString(), webhook.id, { is_active: !webhook.is_active });
};
return (
<div>
<div className="border-b border-custom-border-200">
<Link href={`/${workspaceSlug}/settings/webhooks/${webhook?.id}`}>
<div className="flex cursor-pointer justify-between px-3.5 py-[18px]">
<div>
<div className="text-base font-medium">{webhook?.url || "Webhook URL"}</div>
{/* <div className="text-base text-neutral-700">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
</div> */}
</div>
<div className="flex gap-4 items-center">
<ToggleSwitch value={webhook.is_active} onChange={handleToggle} />
</div>
</div>
<a className="flex items-center justify-between gap-4 px-3.5 py-[18px]">
<h5 className="text-base font-medium truncate">{webhook.url}</h5>
<ToggleSwitch value={webhook.is_active} onChange={handleToggle} />
</a>
</Link>
</div>
);

View file

@ -1,38 +1,19 @@
import { FC } from "react";
import Link from "next/link";
import { Button } from "@plane/ui";
import { useMobxStore } from "lib/mobx/store-provider";
import { RootStore } from "store/root";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// components
import { WebhooksListItem } from "./webhooks-list-item";
interface IWebHookLists {
workspaceSlug: string;
}
export const WebhookLists: FC<IWebHookLists> = observer((props) => {
const { workspaceSlug } = props;
export const WebhooksList = observer(() => {
const {
webhook: { webhooks },
}: RootStore = useMobxStore();
} = useMobxStore();
return (
<>
<div className="flex items-center justify-between gap-4 py-3.5 border-b border-custom-border-200">
<div className="text-xl font-medium">Webhooks</div>
<Link href={`/${workspaceSlug}/settings/webhooks/create`}>
<Button variant="primary" size="sm">
Add webhook
</Button>
</Link>
</div>
<div className="divide-y divide-custom-border-200 overflow-y-scroll">
{Object.values(webhooks).map((item) => (
<WebhooksListItem workspaceSlug={workspaceSlug} webhook={item} key={item.id} />
))}
</div>
</>
<div className="h-full w-full overflow-y-auto">
{Object.values(webhooks ?? {}).map((webhook) => (
<WebhooksListItem key={webhook.id} webhook={webhook} />
))}
</div>
);
});