2021-11-03 10:47:52 +00:00
|
|
|
import type { IntegrationOAuthCallbackState } from "pages/api/integrations/types";
|
2021-10-20 15:42:40 +00:00
|
|
|
import { useState } from "react";
|
|
|
|
import { useMutation } from "react-query";
|
|
|
|
|
|
|
|
import { AddAppleIntegrationModal } from "@lib/integrations/Apple/components/AddAppleIntegration";
|
|
|
|
import { AddCalDavIntegrationModal } from "@lib/integrations/CalDav/components/AddCalDavIntegration";
|
|
|
|
|
|
|
|
import { ButtonBaseProps } from "@components/ui/Button";
|
|
|
|
|
|
|
|
export default function ConnectIntegration(props: {
|
|
|
|
type: string;
|
|
|
|
render: (renderProps: ButtonBaseProps) => JSX.Element;
|
2021-10-30 15:54:21 +00:00
|
|
|
onOpenChange: (isOpen: boolean) => unknown | Promise<unknown>;
|
2021-10-20 15:42:40 +00:00
|
|
|
}) {
|
|
|
|
const { type } = props;
|
|
|
|
const [isLoading, setIsLoading] = useState(false);
|
2021-11-03 10:47:52 +00:00
|
|
|
|
2021-10-20 15:42:40 +00:00
|
|
|
const mutation = useMutation(async () => {
|
2021-11-03 10:47:52 +00:00
|
|
|
const state: IntegrationOAuthCallbackState = {
|
|
|
|
returnTo: location.pathname + location.search,
|
|
|
|
};
|
|
|
|
const stateStr = encodeURIComponent(JSON.stringify(state));
|
|
|
|
const searchParams = `?state=${stateStr}`;
|
|
|
|
const res = await fetch("/api/integrations/" + type.replace("_", "") + "/add" + searchParams);
|
2021-10-20 15:42:40 +00:00
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error("Something went wrong");
|
|
|
|
}
|
|
|
|
const json = await res.json();
|
|
|
|
window.location.href = json.url;
|
|
|
|
setIsLoading(true);
|
|
|
|
});
|
|
|
|
const [isModalOpen, _setIsModalOpen] = useState(false);
|
|
|
|
|
|
|
|
const setIsModalOpen = (v: boolean) => {
|
|
|
|
_setIsModalOpen(v);
|
|
|
|
props.onOpenChange(v);
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
{props.render({
|
|
|
|
onClick() {
|
|
|
|
if (["caldav_calendar", "apple_calendar"].includes(type)) {
|
|
|
|
// special handlers
|
|
|
|
setIsModalOpen(true);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
mutation.mutate();
|
|
|
|
},
|
|
|
|
loading: mutation.isLoading || isLoading,
|
|
|
|
disabled: isModalOpen,
|
|
|
|
})}
|
|
|
|
{type === "caldav_calendar" && (
|
|
|
|
<AddCalDavIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />
|
|
|
|
)}
|
|
|
|
|
|
|
|
{type === "apple_calendar" && (
|
|
|
|
<AddAppleIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />
|
|
|
|
)}
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
}
|