Fixes Apple Calendar onboarding and type fixes (#988)

* Type fixes

* Type fixes

* Attemp to prevent unknown error in prod

* Type fixes

* Type fixes for onboarding

* Extracts ConnectIntegration

* Extracts IntegrationListItem

* Extracts CalendarsList

* Uses CalendarList on onboarding

* Removes deprecated Alert

* Extracts DisconnectIntegration

* Extracts CalendarSwitch

* Extracts ConnectedCalendarsList

* Extracted connectedCalendar logic for reuse

* Extracted SubHeadingTitleWithConnections

* Type fixes

* Fetched connected calendars in onboarding

* Refreshes data on when adding/removing calendars on onboarding

* Removed testing code

* Type fixes

* Feedback

* Moved integration helpers

* I was sleepy

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Omar Lópezandkodiakhq[bot] authored and GitHub committed 2021-10-20 15:42:40 +00:00
1 parent bd99a06765
commit 85d7122e43
27 files changed
+698 -614

No files matched your search

@@ -0,0 +1,75 @@
import { useMutation } from "react-query";
import showToast from "@lib/notification";
import { trpc } from "@lib/trpc";
import Switch from "@components/ui/Switch";
export default function CalendarSwitch(props: {
type: string;
externalId: string;
title: string;
defaultSelected: boolean;
}) {
const utils = trpc.useContext();
const mutation = useMutation<
unknown,
unknown,
{
isOn: boolean;
}
>(
async ({ isOn }) => {
const body = {
integration: props.type,
externalId: props.externalId,
};
if (isOn) {
const res = await fetch("/api/availability/calendar", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!res.ok) {
throw new Error("Something went wrong");
}
} else {
const res = await fetch("/api/availability/calendar", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!res.ok) {
throw new Error("Something went wrong");
}
}
},
{
async onSettled() {
await utils.invalidateQueries(["viewer.integrations"]);
},
onError() {
showToast(`Something went wrong when toggling "${props.title}""`, "error");
},
}
);
return (
<div className="py-1">
<Switch
key={props.externalId}
name="enabled"
label={props.title}
defaultChecked={props.defaultSelected}
onCheckedChange={(isOn: boolean) => {
mutation.mutate({ isOn });
}}
/>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import React, { ReactNode } from "react";
import { List } from "@components/List";
import Button from "@components/ui/Button";
import ConnectIntegration from "./ConnectIntegrations";
import IntegrationListItem from "./IntegrationListItem";
interface Props {
calendars: {
children?: ReactNode;
description: string;
imageSrc: string;
title: string;
type: string;
}[];
onChanged: () => void | Promise<void>;
}
const CalendarsList = (props: Props): JSX.Element => {
const { calendars, onChanged } = props;
return (
<List>
{calendars.map((item) => (
<IntegrationListItem
key={item.title}
{...item}
actions={
<ConnectIntegration
type={item.type}
render={(btnProps) => (
<Button color="secondary" {...btnProps}>
Connect
</Button>
)}
onOpenChange={onChanged}
/>
}
/>
))}
</List>
);
};
export default CalendarsList;
@@ -0,0 +1,56 @@
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;
onOpenChange: (isOpen: boolean) => void | Promise<void>;
}) {
const { type } = props;
const [isLoading, setIsLoading] = useState(false);
const mutation = useMutation(async () => {
const res = await fetch("/api/integrations/" + type.replace("_", "") + "/add");
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} />
)}
</>
);
}
@@ -0,0 +1,98 @@
import React, { Fragment, ReactNode } from "react";
import { List } from "@components/List";
import { Alert } from "@components/ui/Alert";
import Button from "@components/ui/Button";
import CalendarSwitch from "./CalendarSwitch";
import DisconnectIntegration from "./DisconnectIntegration";
import IntegrationListItem from "./IntegrationListItem";
type CalIntersection =
| {
calendars: {
externalId: string;
name: string;
isSelected: boolean;
}[];
error?: never;
}
| {
calendars?: never;
error: {
message: string;
};
};
type Props = {
onChanged: (isOpen: boolean) => void | Promise<void>;
connectedCalendars: (CalIntersection & {
credentialId: number;
integration: {
type: string;
imageSrc: string;
title: string;
children?: ReactNode;
};
primary?: { externalId: string } | undefined | null;
})[];
};
const ConnectedCalendarsList = (props: Props): JSX.Element => {
const { connectedCalendars, onChanged } = props;
return (
<List>
{connectedCalendars.map((item) => (
<Fragment key={item.credentialId}>
{item.calendars ? (
<IntegrationListItem
{...item.integration}
description={item.primary?.externalId || "No external Id"}
actions={
<DisconnectIntegration
id={item.credentialId}
render={(btnProps) => (
<Button {...btnProps} color="warn">
Disconnect
</Button>
)}
onOpenChange={onChanged}
/>
}>
<ul className="p-4 space-y-2">
{item.calendars.map((cal) => (
<CalendarSwitch
key={cal.externalId}
externalId={cal.externalId}
title={cal.name}
type={item.integration.type}
defaultSelected={cal.isSelected}
/>
))}
</ul>
</IntegrationListItem>
) : (
<Alert
severity="warning"
title="Something went wrong"
message={item.error?.message}
actions={
<DisconnectIntegration
id={item.credentialId}
render={(btnProps) => (
<Button {...btnProps} color="warn">
Disconnect
</Button>
)}
onOpenChange={onChanged}
/>
}
/>
)}
</Fragment>
))}
</List>
);
};
export default ConnectedCalendarsList;
@@ -0,0 +1,60 @@
import { useState } from "react";
import { useMutation } from "react-query";
import { Dialog } from "@components/Dialog";
import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
import { ButtonBaseProps } from "@components/ui/Button";
export default function DisconnectIntegration(props: {
/** Integration credential id */
id: number;
render: (renderProps: ButtonBaseProps) => JSX.Element;
onOpenChange: (isOpen: boolean) => void | Promise<void>;
}) {
const [modalOpen, setModalOpen] = useState(false);
const mutation = useMutation(
async () => {
const res = await fetch("/api/integrations", {
method: "DELETE",
body: JSON.stringify({ id: props.id }),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw new Error("Something went wrong");
}
},
{
async onSettled() {
props.onOpenChange(modalOpen);
},
onSuccess() {
setModalOpen(false);
},
}
);
return (
<>
<Dialog open={modalOpen} onOpenChange={setModalOpen}>
<ConfirmationDialogContent
variety="danger"
title="Disconnect Integration"
confirmBtnText="Yes, disconnect integration"
cancelBtnText="Cancel"
onConfirm={() => {
mutation.mutate();
}}>
Are you sure you want to disconnect this integration?
</ConfirmationDialogContent>
</Dialog>
{props.render({
onClick() {
setModalOpen(true);
},
disabled: modalOpen,
loading: mutation.isLoading,
})}
</>
);
}
@@ -0,0 +1,30 @@
import Image from "next/image";
import { ReactNode } from "react";
import classNames from "@lib/classNames";
import { ListItem, ListItemText, ListItemTitle } from "@components/List";
function IntegrationListItem(props: {
imageSrc: string;
title: string;
description: string;
actions?: ReactNode;
children?: ReactNode;
}): JSX.Element {
return (
<ListItem expanded={!!props.children} className={classNames("flex-col")}>
<div className={classNames("flex flex-1 space-x-2 w-full p-3 items-center")}>
<Image width={40} height={40} src={`/${props.imageSrc}`} alt={props.title} />
<div className="flex-grow pl-2 truncate">
<ListItemTitle component="h3">{props.title}</ListItemTitle>
<ListItemText component="p">{props.description}</ListItemText>
</div>
<div>{props.actions}</div>
</div>
{props.children && <div className="w-full border-t border-gray-200">{props.children}</div>}
</ListItem>
);
}
export default IntegrationListItem;
@@ -0,0 +1,29 @@
import { ReactNode } from "react";
import Badge from "@components/ui/Badge";
function pluralize(opts: { num: number; plural: string; singular: string }) {
if (opts.num === 0) {
return opts.singular;
}
return opts.singular;
}
export default function SubHeadingTitleWithConnections(props: { title: ReactNode; numConnections?: number }) {
const num = props.numConnections;
return (
<>
<span>{props.title}</span>
{num ? (
<Badge variant="success">
{num}{" "}
{pluralize({
num,
singular: "connection",
plural: "connections",
})}
</Badge>
) : null}
</>
);
}
+5 -1
View File
@@ -1,6 +1,10 @@
import React from "react";
const UsernameInput = React.forwardRef((props, ref) => (
interface UsernameInputProps extends React.ComponentPropsWithRef<"input"> {
label?: string;
}
const UsernameInput = React.forwardRef<HTMLInputElement, UsernameInputProps>((props, ref) => (
// todo, check if username is already taken here?
<div>
<label htmlFor="username" className="block text-sm font-medium text-gray-700">
+18 -8
View File
@@ -1,8 +1,13 @@
import React, { useEffect, useState } from "react";
export const WeekdaySelect = (props) => {
const [activeDays, setActiveDays] = useState(
[...Array(7).keys()].map((v, i) => (props.defaultValue || []).includes(i))
interface WeekdaySelectProps {
defaultValue: number[];
onSelect: (selected: number[]) => void;
}
export const WeekdaySelect = (props: WeekdaySelectProps) => {
const [activeDays, setActiveDays] = useState<boolean[]>(
Array.from(Array(7).keys()).map((v, i) => (props.defaultValue || []).includes(i))
);
const days = ["S", "M", "T", "W", "T", "F", "S"];
@@ -11,10 +16,9 @@ export const WeekdaySelect = (props) => {
props.onSelect(activeDays.map((v, idx) => (v ? idx : -1)).filter((v) => v !== -1));
}, [activeDays]);
const toggleDay = (e, idx: number) => {
e.preventDefault();
const toggleDay = (idx: number) => {
activeDays[idx] = !activeDays[idx];
setActiveDays([].concat(activeDays));
setActiveDays(([] as boolean[]).concat(activeDays));
};
return (
@@ -24,7 +28,10 @@ export const WeekdaySelect = (props) => {
activeDays[idx] ? (
<button
key={idx}
onClick={(e) => toggleDay(e, idx)}
onClick={(e) => {
e.preventDefault();
toggleDay(idx);
}}
className={`
w-10 h-10
bg-black text-white focus:outline-none px-3 py-1 rounded
@@ -38,7 +45,10 @@ export const WeekdaySelect = (props) => {
) : (
<button
key={idx}
onClick={(e) => toggleDay(e, idx)}
onClick={(e) => {
e.preventDefault();
toggleDay(idx);
}}
style={{ marginTop: "1px", marginBottom: "1px" }}
className={`w-10 h-10 bg-gray-50 focus:outline-none px-3 py-1 rounded-none ${
idx === 0 ? "rounded-l" : "border-l-0"
@@ -1,10 +1,10 @@
import React, { PropsWithChildren, useState } from "react";
import React, { ReactNode, useState } from "react";
import classNames from "@lib/classNames";
type RadioAreaProps = React.InputHTMLAttributes<HTMLInputElement> & {
onChange: (value: string) => void;
defaultChecked: boolean;
type RadioAreaProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange"> & {
onChange?: (value: string) => void;
defaultChecked?: boolean;
};
const RadioArea = (props: RadioAreaProps) => {
@@ -16,9 +16,13 @@ const RadioArea = (props: RadioAreaProps) => {
props.className
)}>
<input
onChange={(e) => props.onChange(e.target.value)}
onChange={(e) => {
if (typeof props.onChange === "function") {
props.onChange(e.target.value);
}
}}
checked={props.checked}
className="float-right text-neutral-900 focus:ring-neutral-500 ml-3"
className="float-right ml-3 text-neutral-900 focus:ring-neutral-500"
name={props.name}
value={props.value}
type="radio"
@@ -28,17 +32,17 @@ const RadioArea = (props: RadioAreaProps) => {
);
};
type RadioAreaGroupProps = {
name?: string;
onChange?: (value) => void;
type ChildrenProps = {
props: RadioAreaProps;
children?: ReactNode;
};
interface RadioAreaGroupProps extends Omit<React.ComponentPropsWithoutRef<"div">, "onChange"> {
children: ChildrenProps | ChildrenProps[];
name?: string;
onChange?: (value: string) => void;
}
const RadioAreaGroup = ({
children,
name,
onChange,
...passThroughProps
}: PropsWithChildren<RadioAreaGroupProps>) => {
const RadioAreaGroup = ({ children, name, onChange, ...passThroughProps }: RadioAreaGroupProps) => {
const [checkedIdx, setCheckedIdx] = useState<number | null>(null);
const changeHandler = (value: string, idx: number) => {
@@ -50,23 +54,21 @@ const RadioAreaGroup = ({
return (
<div {...passThroughProps}>
{(Array.isArray(children) ? children : [children]).map(
(child: React.ReactElement<RadioAreaProps>, idx: number) => {
if (checkedIdx === null && child.props.defaultChecked) {
setCheckedIdx(idx);
}
return (
<Item
{...child.props}
key={idx}
name={name}
checked={idx === checkedIdx}
onChange={(value: string) => changeHandler(value, idx)}>
{child.props.children}
</Item>
);
{(Array.isArray(children) ? children : [children]).map((child, idx: number) => {
if (checkedIdx === null && child.props.defaultChecked) {
setCheckedIdx(idx);
}
)}
return (
<Item
{...child.props}
key={idx}
name={name}
checked={idx === checkedIdx}
onChange={(value: string) => changeHandler(value, idx)}>
{child.props.children}
</Item>
);
})}
</div>
);
};