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

+4 -3
View File
@@ -11,17 +11,18 @@ import { UpgradeToProDialog } from "@calcom/ui/UpgradeToProDialog";
import { InstallAppButtonMap } from "./apps.browser.generated";
import { InstallAppButtonProps } from "./types";
function InstallAppButtonWithoutPlanCheck(
export const InstallAppButtonWithoutPlanCheck = (
props: {
type: App["type"];
} & InstallAppButtonProps
) {
) => {
const key = deriveAppDictKeyFromType(props.type, InstallAppButtonMap);
const InstallAppButtonComponent = InstallAppButtonMap[key as keyof typeof InstallAppButtonMap];
if (!InstallAppButtonComponent) return <>{props.render({ useDefaultComponent: true })}</>;
return <InstallAppButtonComponent render={props.render} onChanged={props.onChanged} />;
}
};
export const InstallAppButton = (
props: {
isProOnly?: App["isProOnly"];
@@ -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,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"
/>
);
}
+2 -2
View File
@@ -600,8 +600,8 @@ const loggedInViewerRouter = createProtectedRouter()
input: z.object({
integration: z.string(),
externalId: z.string(),
eventTypeId: z.number().optional(),
bookingId: z.number().optional(),
eventTypeId: z.number().nullish(),
bookingId: z.number().nullish(),
}),
async resolve({ ctx, input }) {
const { user } = ctx;
@@ -1,8 +1,9 @@
import { Prisma } from "@prisma/client";
import { Availability as AvailabilityModel, Prisma, Schedule as ScheduleModel, User } from "@prisma/client";
import { z } from "zod";
import { getUserAvailability } from "@calcom/core/getUserAvailability";
import { getAvailabilityFromSchedule } from "@calcom/lib/availability";
import { PrismaClient } from "@calcom/prisma/client";
import { stringOrNumber } from "@calcom/prisma/zod-utils";
import { Schedule } from "@calcom/types/schedule";
@@ -66,34 +67,7 @@ export const availabilityRouter = createProtectedRouter()
code: "UNAUTHORIZED",
});
}
const availability = schedule.availability.reduce(
(schedule: Schedule, availability) => {
availability.days.forEach((day) => {
schedule[day].push({
start: new Date(
Date.UTC(
new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDate(),
availability.startTime.getUTCHours(),
availability.startTime.getUTCMinutes()
)
),
end: new Date(
Date.UTC(
new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDate(),
availability.endTime.getUTCHours(),
availability.endTime.getUTCMinutes()
)
),
});
});
return schedule;
},
Array.from([...Array(7)]).map(() => [])
);
const availability = convertScheduleToAvailability(schedule);
return {
schedule,
availability,
@@ -160,6 +134,12 @@ export const availabilityRouter = createProtectedRouter()
const schedule = await prisma.schedule.create({
data,
});
const hasDefaultScheduleId = await hasDefaultSchedule(user, prisma);
if (hasDefaultScheduleId) {
await setupDefaultSchedule(user.id, schedule.id, prisma);
}
return { schedule };
},
})
@@ -219,14 +199,7 @@ export const availabilityRouter = createProtectedRouter()
const availability = getAvailabilityFromSchedule(input.schedule);
if (input.isDefault) {
await prisma.user.update({
where: {
id: user.id,
},
data: {
defaultScheduleId: input.scheduleId,
},
});
setupDefaultSchedule(user.id, input.scheduleId, prisma);
}
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
@@ -277,3 +250,60 @@ export const availabilityRouter = createProtectedRouter()
};
},
});
export const convertScheduleToAvailability = (
schedule: Partial<ScheduleModel> & { availability: AvailabilityModel[] }
) => {
return schedule.availability.reduce(
(schedule: Schedule, availability) => {
availability.days.forEach((day) => {
schedule[day].push({
start: new Date(
Date.UTC(
new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDate(),
availability.startTime.getUTCHours(),
availability.startTime.getUTCMinutes()
)
),
end: new Date(
Date.UTC(
new Date().getUTCFullYear(),
new Date().getUTCMonth(),
new Date().getUTCDate(),
availability.endTime.getUTCHours(),
availability.endTime.getUTCMinutes()
)
),
});
});
return schedule;
},
Array.from([...Array(7)]).map(() => [])
);
};
const setupDefaultSchedule = async (userId: number, scheduleId: number, prisma: PrismaClient) => {
await prisma.user.update({
where: {
id: userId,
},
data: {
defaultScheduleId: scheduleId,
},
});
};
const isDefaultSchedule = (scheduleId: number, user: Partial<User>) => {
return !user.defaultScheduleId || user.defaultScheduleId === scheduleId;
};
const hasDefaultSchedule = async (user: Partial<User>, prisma: PrismaClient) => {
const defaultSchedule = await prisma.schedule.findFirst({
where: {
userId: user.id,
},
});
return !!user.defaultScheduleId || !!defaultSchedule;
};
+5 -2
View File
@@ -10,15 +10,18 @@ import BaseSelect, {
import { InputComponent } from "@calcom/ui/v2/core/form/Select";
function TimezoneSelect({ className, ...props }: SelectProps) {
// @TODO: remove borderRadius and haveRoundedClassName logic from theme so we use only new style
const haveRoundedClassName = !!(className && className.indexOf("rounded-") > -1);
const defaultBorderRadius = 2;
return (
<BaseSelect
theme={(theme) => ({
...theme,
borderRadius: 2,
...(haveRoundedClassName ? {} : { borderRadius: defaultBorderRadius }),
colors: {
...theme.colors,
primary: "var(--brand-color)",
primary50: "rgba(209 , 213, 219, var(--tw-bg-opacity))",
primary25: "rgba(244, 245, 246, var(--tw-bg-opacity))",
},
+5 -3
View File
@@ -17,11 +17,11 @@ const Switch = (
const id = useId();
return (
<div className="flex h-[20px] items-center">
<div className="flex h-auto w-auto flex-row items-center">
<PrimitiveSwitch.Root
className={classNames(
props.checked ? "bg-gray-900" : "bg-gray-200 hover:bg-gray-300",
"focus:ring-brand-800 h-[24px] w-[40px] rounded-full p-[3px] shadow-none",
"focus:ring-brand-800 h-6 w-10 rounded-full shadow-none",
props.className
)}
{...primitiveProps}>
@@ -30,7 +30,9 @@ const Switch = (
// Since we dont support global dark mode - we have to style dark mode components specifically on the instance for now
// TODO: Remove once we support global dark mode
className={classNames(
"block h-[18px] w-[18px] translate-x-0 rounded-full bg-white transition-transform",
"block h-[18px] w-[18px] rounded-full bg-white",
"translate-x-[4px] transition delay-100 will-change-transform",
"[&[data-state='checked']]:translate-x-[18px]",
props.checked && "shadow-inner",
props.thumbProps?.className
)}
+9
View File
@@ -49,6 +49,14 @@ function Select<
},
})}
styles={{
control: (base) => ({
...base,
// Brute force to remove focus outline of input
"& .react-select__input": {
borderWidth: 0,
boxShadow: "none",
},
}),
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? "var(--brand-color)" : state.isFocused ? "#F3F4F6" : "",
@@ -63,6 +71,7 @@ function Select<
...components,
IndicatorSeparator: () => null,
Input: InputComponent,
...props.components,
}}
{...props}
/>
@@ -1,333 +0,0 @@
import classNames from "classnames";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import { GroupBase, Props } from "react-select";
import dayjs, { Dayjs, ConfigType } from "@calcom/dayjs";
import { defaultDayRange } 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 Dropdown, { DropdownMenuContent } from "@calcom/ui/Dropdown";
import { Icon } from "@calcom/ui/Icon";
import Button from "@calcom/ui/v2/core/Button";
import Switch from "@calcom/ui/v2/core/Switch";
import Tooltip from "@calcom/ui/v2/core/Tooltip";
import Select from "@calcom/ui/v2/core/form/Select";
/** Begin Time Increments For Select */
const increment = 15;
type Option = {
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)
*/
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<Option[]>([]);
const options = useMemo(() => {
const end = dayjs().utc().endOf("day");
let t: Dayjs = dayjs().utc().startOf("day");
const options: Option[] = [];
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 };
};
type TimeRangeFieldProps = {
name: string;
className?: string;
};
const LazySelect = ({
value,
min,
max,
...props
}: Omit<Props<Option, false, GroupBase<Option>>, "value"> & {
value: ConfigType;
min?: ConfigType;
max?: ConfigType;
}) => {
// Lazy-loaded options, otherwise adding a field has a noticable 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 })}
{...props}
/>
);
};
const TimeRangeField = ({ name, className }: TimeRangeFieldProps) => {
const { watch } = useFormContext();
const minEnd = watch(`${name}.start`);
const maxStart = watch(`${name}.end`);
return (
<div className={classNames("flex flex-grow items-center space-x-3", className)}>
<Controller
name={`${name}.start`}
render={({ field: { onChange, value } }) => {
return (
<LazySelect
className="w-[120px]"
value={value}
max={maxStart}
onChange={(option) => {
onChange(new Date(option?.value as number));
}}
/>
);
}}
/>
<span>-</span>
<Controller
name={`${name}.end`}
render={({ field: { onChange, value } }) => (
<LazySelect
className="flex-grow sm:w-[120px]"
value={value}
min={minEnd}
onChange={(option) => {
onChange(new Date(option?.value as number));
}}
/>
)}
/>
</div>
);
};
type ScheduleBlockProps = {
day: number;
weekday: string;
name: string;
};
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>{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-sm 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 const DayRanges = ({
name,
defaultValue = [defaultDayRange],
}: {
name: string;
defaultValue?: TimeRange[];
}) => {
const { setValue, watch } = useFormContext();
// XXX: Hack to make copying times work; `fields` is out of date until save.
const watcher = watch(name);
const { t } = useLocale();
const { fields, replace, append, remove } = useFieldArray({
name,
});
useEffect(() => {
if (defaultValue.length && !fields.length) {
replace(defaultValue);
}
}, [replace, defaultValue, fields.length]);
const handleAppend = () => {
// FIXME: Fix type-inference, can't get this to work. @see https://github.com/react-hook-form/react-hook-form/issues/4499
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(),
});
}
};
return (
<div className="space-y-2">
{fields.map((field, index) => (
<div key={field.id} className="flex items-center rtl:space-x-reverse">
<div className="flex flex-grow space-x-1 sm:flex-grow-0">
<TimeRangeField name={`${name}.${index}`} />
<Button
type="button"
size="icon"
color="minimal"
StartIcon={Icon.FiTrash}
onClick={() => remove(index)}
/>
</div>
{index === 0 && (
<div className="absolute top-2 right-0 text-right sm:relative sm:top-0 sm:flex-grow">
<Tooltip content={t("add_time_availability") as string}>
<Button
className="text-neutral-400"
type="button"
color="minimal"
size="icon"
StartIcon={Icon.FiPlus}
onClick={handleAppend}
/>
</Tooltip>
<Dropdown>
<Tooltip content={t("duplicate") as string}>
<Button
type="button"
color="minimal"
size="icon"
StartIcon={Icon.FiCopy}
onClick={handleAppend}
/>
</Tooltip>
<DropdownMenuContent>
<CopyTimes
disabled={[parseInt(name.substring(name.lastIndexOf(".") + 1), 10)]}
onApply={(selected) =>
selected.forEach((day) => {
// TODO: Figure out why this is different?
// console.log(watcher, fields);
setValue(name.substring(0, name.lastIndexOf(".") + 1) + day, watcher);
})
}
/>
</DropdownMenuContent>
</Dropdown>
</div>
)}
</div>
))}
</div>
);
};
const ScheduleBlock = ({ name, day, weekday }: ScheduleBlockProps) => {
const { t } = useLocale();
const form = useFormContext();
const watchAvailable = form.watch(`${name}.${day}`, []);
return (
<fieldset className="relative flex flex-col justify-between space-y-2 py-5 sm:flex-row sm:space-y-0">
<label
className={classNames(
"flex space-x-2 rtl:space-x-reverse",
!watchAvailable.length ? "w-full" : "w-1/3"
)}>
<div className={classNames(!watchAvailable.length ? "w-1/3" : "w-full", "flex items-center")}>
<Switch
checked={watchAvailable.length}
onCheckedChange={(value) => {
form.setValue(`${name}.${day}`, value ? [defaultDayRange] : []);
}}
/>
<span className="ml-3 text-sm font-medium leading-4 text-gray-900">{weekday}</span>
</div>
{!watchAvailable.length && (
<div className="flex-grow text-right text-sm text-gray-500 sm:flex-shrink">
{t("no_availability")}
</div>
)}
</label>
{!!watchAvailable.length && (
<div className="flex-grow">
<DayRanges name={`${name}.${day}`} defaultValue={[]} />
</div>
)}
</fieldset>
);
};
const Schedule = ({ name }: { name: string }) => {
const { i18n } = useLocale();
return (
<fieldset className="divide-y divide-gray-200">
{weekdayNames(i18n.language).map((weekday, num) => (
<ScheduleBlock key={num} name={name} weekday={weekday} day={num} />
))}
</fieldset>
);
};
export default Schedule;
@@ -1,3 +0,0 @@
export * from "./NewScheduleButton";
export { default as Schedule } from "./Schedule";
export * from "./ScheduleListItem";
-1
View File
@@ -1,4 +1,3 @@
export * from "./auth";
export * from "./availability";
export * from "./booker";
export * from "./event-types";