Feature/new onboarding page (#3377)

* [WIP] New design and components for onboarding page

* saving work in progress

* new fonts

* [WIP] new onboarding page, initial page, components

* WIP calendar connect

* WIP availability new design

* WIP onboarding page

* WIP onboarding, working new availability form

* WIP AvailabilitySchedule componente v2

* WIP availability with defaultSchedule

* User profile view

* Relocate new onboarding/getting-started page components

* Steps test for onboarding v2

* Remove logs and unused code

* remove any as types

* Adding translations

* Fixes translation text and css for step 4

* Deprecation note for old-getting-started

* Added defaul events and refetch user query when finishing getting-started

* Fix button text translation

* Undo schedule v1 changes

* Fix calendar switches state

* Add cookie to save return-to when connecting calendar

* Change useTranslation for useLocale instead

* Change test to work with data-testid instead of hardcoded plain text due to translation

* Fix skeleton containers for calendars

* Style fixes

* fix styles to match v2

* Fix styles and props types to match v2 design

* Bugfix/router and console errors (#4206)

* The loading={boolean} parameter is required, so this must be <Button />

* Fixes duplicate key error

* Use zod and router.query.step directly to power state machine

* use ul>li & divide for borders

* Update apps/web/components/getting-started/steps-views/ConnectCalendars.tsx

Co-authored-by: alannnc <[email protected]>

* Linting

* Deprecation notices and type fixes

* Update CreateEventsOnCalendarSelect.tsx

* Type fixes

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: zomars <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-09-06 16:58:16 -06:00
1 parent 7f2db86a83
commit 13c2dc24dc
48 files changed
+1714 -470

No files matched your search

@@ -0,0 +1,85 @@
import { useRouter } from "next/router";
import { useForm } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc/react";
import { Dialog, DialogClose, DialogContent, DialogTrigger } from "@calcom/ui/Dialog";
import { Icon } from "@calcom/ui/Icon";
import { Form } from "@calcom/ui/form/fields";
import Button from "@calcom/ui/v2/core/Button";
import showToast from "@calcom/ui/v2/core/notifications";
export function NewScheduleButton({ name = "new-schedule" }: { name?: string }) {
const router = useRouter();
const { t } = useLocale();
const form = useForm<{
name: string;
}>();
const { register } = form;
const createMutation = trpc.useMutation("viewer.availability.schedule.create", {
onSuccess: async ({ schedule }) => {
await router.push("/availability/" + schedule.id);
showToast(t("schedule_created_successfully", { scheduleName: schedule.name }), "success");
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
if (err.data?.code === "UNAUTHORIZED") {
const message = `${err.data.code}: You are not able to create this event`;
showToast(message, "error");
}
},
});
return (
<Dialog name={name} clearQueryParamsOnClose={["copy-schedule-id"]}>
<DialogTrigger asChild>
<Button data-testid={name} StartIcon={Icon.FiPlus}>
{t("new")}
</Button>
</DialogTrigger>
<DialogContent>
<div className="mb-8">
<h3 className="text-lg font-bold leading-6 text-gray-900" id="modal-title">
{t("add_new_schedule")}
</h3>
</div>
<Form
form={form}
handleSubmit={(values) => {
createMutation.mutate(values);
}}>
<div className="mt-3 space-y-2">
<label htmlFor="label" className="block text-sm font-medium text-gray-700">
{t("name")}
</label>
<div className="mt-1">
<input
type="text"
id="name"
required
className="block w-full rounded-sm border-gray-300 text-sm"
placeholder={t("default_schedule_name")}
{...register("name")}
/>
</div>
</div>
<div className="mt-8 flex flex-row-reverse gap-x-2">
<Button type="submit" loading={createMutation.isLoading}>
{t("continue")}
</Button>
<DialogClose asChild>
<Button color="secondary">{t("cancel")}</Button>
</DialogClose>
</div>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,405 @@
import classNames from "classnames";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Controller,
useFieldArray,
UseFieldArrayAppend,
UseFieldArrayRemove,
useFormContext,
} from "react-hook-form";
import { GroupBase, Props } from "react-select";
import dayjs, { ConfigType, Dayjs } from "@calcom/dayjs";
import { defaultDayRange as DEFAULT_DAY_RANGE } from "@calcom/lib/availability";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { weekdayNames } from "@calcom/lib/weekday";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { TimeRange } from "@calcom/types/schedule";
import { Icon } from "@calcom/ui";
import Dropdown, { DropdownMenuContent, DropdownMenuTrigger } from "@calcom/ui/Dropdown";
import { Button, Select, Switch, Tooltip } from "@calcom/ui/v2";
const Schedule = () => {
const { i18n } = useLocale();
const form = useFormContext();
const initialValue = form.watch();
const copyAllPosition = (initialValue["schedule"] as Array<TimeRange[]>)?.findIndex(
(item: TimeRange[]) => item.length > 0
);
return (
<>
{/* First iterate for each day */}
{weekdayNames(i18n.language, 0, "long").map((weekday, num) => {
const name = `schedule.${num}`;
const copyAllShouldRender = copyAllPosition === num;
return (
<div className="mb-1 flex w-full flex-col py-1 sm:flex-row" key={weekday}>
{/* Label & switch container */}
<div className="flex justify-between">
<div>
<label className="flex flex-row items-center">
<Switch
defaultChecked={initialValue["schedule"][num].length > 0}
checked={!!initialValue["schedule"][num].length}
onCheckedChange={(isChecked) => {
form.setValue(name, isChecked ? [DEFAULT_DAY_RANGE] : []);
}}
className="relative mx-2 my-[6px] h-6 w-10 rounded-full bg-gray-200"
/>
<span className="inline-block min-w-[88px] text-sm capitalize">{weekday}</span>
</label>
</div>
<div className="inline sm:hidden">
<ActionButtons
name={name}
setValue={form.setValue}
watcher={form.watch(name, initialValue[name])}
copyAllShouldRender={copyAllShouldRender}
/>
</div>
</div>
<div className="w-full sm:ml-2">
<DayRanges name={name} copyAllShouldRender={copyAllShouldRender} />
</div>
<div className="my-2 h-[1px] w-full bg-gray-200 sm:hidden" />
</div>
);
})}
</>
);
};
const DayRanges = ({
name,
copyAllShouldRender,
}: {
name: string;
defaultValue?: TimeRange[];
copyAllShouldRender?: boolean;
}) => {
const form = useFormContext();
const fields = form.watch(`${name}` as `schedule.0`);
const { remove } = useFieldArray({
name,
});
return (
<>
{fields.map((field: { id: string }, index: number) => (
<div key={field.id} className="mb-2 flex rtl:space-x-reverse">
<TimeRangeField name={`${name}.${index}`} />
{index === 0 && (
<div className="hidden sm:inline">
<ActionButtons
name={name}
setValue={form.setValue}
watcher={form.watch(name)}
copyAllShouldRender={copyAllShouldRender}
/>
</div>
)}
{index !== 0 && <RemoveTimeButton index={index} remove={remove} />}
</div>
))}
</>
);
};
const RemoveTimeButton = ({
index,
remove,
className,
}: {
index: number | number[];
remove: UseFieldArrayRemove;
className?: string;
}) => {
return (
<Button
type="button"
size="icon"
color="minimal"
StartIcon={Icon.FiTrash}
onClick={() => remove(index)}
className={className}
/>
);
};
interface TimeRangeFieldProps {
name: string;
className?: string;
}
const TimeRangeField = ({ name, className }: TimeRangeFieldProps) => {
const { watch } = useFormContext();
const values = watch(name);
const minEnd = values["start"];
const maxStart = values["end"];
return (
<div className={classNames("mx-1 flex", className)}>
<Controller
name={`${name}.start`}
render={({ field: { onChange } }) => {
return (
<LazySelect
className="h-9 w-[100px]"
value={values["start"]}
max={maxStart}
onChange={(option) => {
onChange(new Date(option?.value as number));
}}
/>
);
}}
/>
<span className="mx-2 w-2 self-center"> - </span>
<Controller
name={`${name}.end`}
render={({ field: { onChange } }) => (
<LazySelect
className="w-[100px] rounded-md"
value={values["end"]}
min={minEnd}
onChange={(option) => {
onChange(new Date(option?.value as number));
}}
/>
)}
/>
</div>
);
};
const LazySelect = ({
value,
min,
max,
...props
}: Omit<Props<IOption, false, GroupBase<IOption>>, "value"> & {
value: ConfigType;
min?: ConfigType;
max?: ConfigType;
}) => {
// Lazy-loaded options, otherwise adding a field has a noticeable redraw delay.
const { options, filter } = useOptions();
useEffect(() => {
filter({ current: value });
}, [filter, value]);
return (
<Select
options={options}
onMenuOpen={() => {
if (min) filter({ offset: min });
if (max) filter({ limit: max });
}}
value={options.find((option) => option.value === dayjs(value).toDate().valueOf())}
onMenuClose={() => filter({ current: value })}
components={{ DropdownIndicator: () => null, IndicatorSeparator: () => null }}
{...props}
/>
);
};
interface IOption {
readonly label: string;
readonly value: number;
}
/**
* Creates an array of times on a 15 minute interval from
* 00:00:00 (Start of day) to
* 23:45:00 (End of day with enough time for 15 min booking)
*/
/** Begin Time Increments For Select */
const INCREMENT = 15;
const useOptions = () => {
// Get user so we can determine 12/24 hour format preferences
const query = useMeQuery();
const { timeFormat } = query.data || { timeFormat: null };
const [filteredOptions, setFilteredOptions] = useState<IOption[]>([]);
const options = useMemo(() => {
const end = dayjs().utc().endOf("day");
let t: Dayjs = dayjs().utc().startOf("day");
const options: IOption[] = [];
while (t.isBefore(end)) {
options.push({
value: t.toDate().valueOf(),
label: dayjs(t)
.utc()
.format(timeFormat === 12 ? "h:mma" : "HH:mm"),
});
t = t.add(INCREMENT, "minutes");
}
return options;
}, [timeFormat]);
const filter = useCallback(
({ offset, limit, current }: { offset?: ConfigType; limit?: ConfigType; current?: ConfigType }) => {
if (current) {
const currentOption = options.find((option) => option.value === dayjs(current).toDate().valueOf());
if (currentOption) setFilteredOptions([currentOption]);
} else
setFilteredOptions(
options.filter((option) => {
const time = dayjs(option.value);
return (!limit || time.isBefore(limit)) && (!offset || time.isAfter(offset));
})
);
},
[options]
);
return { options: filteredOptions, filter };
};
const ActionButtons = ({
name,
watcher,
setValue,
copyAllShouldRender,
}: {
name: string;
watcher: TimeRange[];
setValue: (key: string, value: TimeRange[]) => void;
copyAllShouldRender?: boolean;
}) => {
const { t } = useLocale();
const form = useFormContext();
const values = form.watch();
const { append } = useFieldArray({
name,
});
return (
<div className="flex items-center">
<Tooltip content={t("add_time_availability") as string}>
<Button
className="text-neutral-400"
type="button"
color="minimal"
size="icon"
StartIcon={Icon.FiPlus}
onClick={() => {
handleAppend({
fields: watcher,
/* Generics should help with this, but forgive us father as I have sinned */
append: append as unknown as UseFieldArrayAppend<TimeRange>,
});
}}
/>
</Tooltip>
<Dropdown>
<Tooltip content={t("duplicate") as string}>
<DropdownMenuTrigger asChild>
<Button type="button" color="minimal" size="icon" StartIcon={Icon.FiCopy} />
</DropdownMenuTrigger>
</Tooltip>
<DropdownMenuContent>
<CopyTimes
disabled={[parseInt(name.substring(name.lastIndexOf(".") + 1), 10)]}
onApply={(selected) =>
selected.forEach((day) => {
setValue(name.substring(0, name.lastIndexOf(".") + 1) + day, watcher);
})
}
/>
</DropdownMenuContent>
</Dropdown>
{/* This only displays on Desktop */}
{copyAllShouldRender && (
<Tooltip content={t("add_time_availability") as string}>
<Button
color="minimal"
className="whitespace-nowrap text-sm text-neutral-400"
type="button"
onClick={() => {
values["schedule"].forEach((item: TimeRange[], index: number) => {
if (item.length > 0) {
setValue(`schedule.${index}`, watcher);
}
});
}}
title={`${t("copy_all")}`}>
{t("copy_all")}
</Button>
</Tooltip>
)}
</div>
);
};
const handleAppend = ({
fields = [],
append,
}: {
fields: TimeRange[];
append: UseFieldArrayAppend<TimeRange>;
}) => {
if (fields.length === 0) {
return append(DEFAULT_DAY_RANGE);
}
const nextRangeStart = dayjs((fields[fields.length - 1] as unknown as TimeRange).end);
const nextRangeEnd = dayjs(nextRangeStart).add(1, "hour");
if (nextRangeEnd.isBefore(nextRangeStart.endOf("day"))) {
return append({
start: nextRangeStart.toDate(),
end: nextRangeEnd.toDate(),
});
}
};
const CopyTimes = ({ disabled, onApply }: { disabled: number[]; onApply: (selected: number[]) => void }) => {
const [selected, setSelected] = useState<number[]>([]);
const { i18n, t } = useLocale();
return (
<div className="m-4 space-y-2 py-4">
<p className="h6 text-xs font-medium uppercase text-neutral-400">Copy times to</p>
<ol className="space-y-2">
{weekdayNames(i18n.language).map((weekday, num) => (
<li key={weekday}>
<label className="flex w-full items-center justify-between">
<span className="px-1">{weekday}</span>
<input
value={num}
defaultChecked={disabled.includes(num)}
disabled={disabled.includes(num)}
onChange={(e) => {
if (e.target.checked && !selected.includes(num)) {
setSelected(selected.concat([num]));
} else if (!e.target.checked && selected.includes(num)) {
setSelected(selected.slice(selected.indexOf(num), 1));
}
}}
type="checkbox"
className="inline-block rounded-[4px] border-gray-300 text-neutral-900 focus:ring-neutral-500 disabled:text-neutral-400"
/>
</label>
</li>
))}
</ol>
<div className="pt-2">
<Button className="w-full justify-center" color="primary" onClick={() => onApply(selected)}>
{t("apply")}
</Button>
</div>
</div>
);
};
export default Schedule;
@@ -0,0 +1,89 @@
import Link from "next/link";
import { Fragment } from "react";
import { availabilityAsString } from "@calcom/lib/availability";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Availability } from "@calcom/prisma/client";
import { inferQueryOutput } from "@calcom/trpc/react";
import { Button } from "@calcom/ui";
import Dropdown, { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@calcom/ui/Dropdown";
import { Icon } from "@calcom/ui/Icon";
import Badge from "@calcom/ui/v2/core/Badge";
export function ScheduleListItem({
schedule,
deleteFunction,
isDeleting = false,
displayOptions,
}: {
schedule: inferQueryOutput<"viewer.availability.list">["schedules"][number];
deleteFunction: ({ scheduleId }: { scheduleId: number }) => void;
isDeleting: boolean;
displayOptions?: {
timeZone?: string;
hour12?: boolean;
};
}) {
const { t, i18n } = useLocale();
return (
<li key={schedule.id}>
<div className="flex items-center justify-between py-5 hover:bg-neutral-50 ltr:pl-4 rtl:pr-4 sm:ltr:pl-0 sm:rtl:pr-0">
<div className="group flex w-full items-center justify-between hover:bg-neutral-50 sm:px-6">
<Link href={"/availability/" + schedule.id}>
<a className="flex-grow truncate text-sm" title={schedule.name}>
<div className="space-x-2">
<span className="truncate font-medium text-neutral-900">{schedule.name}</span>
{schedule.isDefault && (
<Badge variant="success" className="text-xs">
{t("default")}
</Badge>
)}
</div>
<p className="mt-1 text-xs text-neutral-500">
{schedule.availability.map((availability: Availability) => (
<Fragment key={availability.id}>
{availabilityAsString(availability, {
locale: i18n.language,
hour12: displayOptions?.hour12,
})}
<br />
</Fragment>
))}
{schedule.timeZone && schedule.timeZone !== displayOptions?.timeZone && (
<p className="my-1 flex items-center first-letter:text-xs">
<Icon.FiGlobe />
&nbsp;{schedule.timeZone}
</p>
)}
</p>
</a>
</Link>
</div>
<Dropdown>
<DropdownMenuTrigger className="group mr-5 h-10 w-10 border border-transparent p-0 text-neutral-500 hover:border-gray-200">
<Icon.FiMoreHorizontal className="h-5 w-5 group-hover:text-gray-800" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<Button
disabled={isDeleting}
onClick={() => {
deleteFunction({
scheduleId: schedule.id,
});
}}
type="button"
color="warn"
className="w-full font-normal"
StartIcon={isDeleting ? undefined : Icon.FiTrash}
loading={isDeleting}>
{isDeleting ? t("deleting") : t("delete_schedule")}
</Button>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
</li>
);
}
@@ -0,0 +1,3 @@
export { NewScheduleButton } from "./NewScheduleButton";
export { default as Schedule } from "./Schedule";
export { ScheduleListItem } from "./ScheduleListItem";
+1
View File
@@ -0,0 +1 @@
export * from "./components";
@@ -20,7 +20,6 @@ function UserV2OptInBanner() {
.
</>
}
className="mb-2"
/>
);
@@ -36,7 +35,6 @@ function UserV2OptInBanner() {
.
</>
}
className="mb-2"
/>
);
}