Feature/availability page revamp (#1032)

* Refactored Schedule component

* Merge branch 'main' into feature/availability-page-revamp

* wip

* Turned value into number, many other TS tweaks

* NodeJS 16x works 100% on my local, but out of scope for this already massive PR

* Fixed TS errors in viewer.tsx and schedule/index.ts

* Reverted next.config.js

* Fixed minor remnant from moving types to @lib/types

* schema comment

* some changes to form handling

* add comments

* Turned ConfigType into number; which seems to be the value preferred by tRPC

* Fixed localized time display during onboarding

* Update components/ui/form/Schedule.tsx

Co-authored-by: Alex Johansson <[email protected]>

* Added showToast to indicate save success

* Converted number to Date, and also always establish time based on current date

* prevent height flickering of availability

by removing mb-2 of input field

* availabilty: re-added mb-2 but added min-height

* Quite a few bugs discovered, but this seems functional

Co-authored-by: KATT <[email protected]>
Co-authored-by: Bailey Pumfleet <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2021-11-10 11:16:32 +00:00
1 parent 559ccb8ca7
commit 8664d217c9
23 files changed
+2550 -2028

No files matched your search

-337
View File
@@ -1,337 +0,0 @@
import { PlusIcon, TrashIcon } from "@heroicons/react/outline";
import classnames from "classnames";
import dayjs, { Dayjs } from "dayjs";
import React from "react";
import { useLocale } from "@lib/hooks/useLocale";
import Text from "@components/ui/Text";
export const SCHEDULE_FORM_ID = "SCHEDULE_FORM_ID";
export const toCalendsoAvailabilityFormat = (schedule: Schedule) => {
return schedule;
};
export const _24_HOUR_TIME_FORMAT = `HH:mm:ss`;
const DEFAULT_START_TIME = "09:00:00";
const DEFAULT_END_TIME = "17:00:00";
/** Begin Time Increments For Select */
const increment = 15;
/**
* 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 TIMES = (() => {
const starting_time = dayjs().startOf("day");
const ending_time = dayjs().endOf("day");
const times = [];
let t: Dayjs = starting_time;
while (t.isBefore(ending_time)) {
times.push(t);
t = t.add(increment, "minutes");
}
return times;
})();
/** End Time Increments For Select */
const DEFAULT_SCHEDULE: Schedule = {
monday: [{ start: "09:00:00", end: "17:00:00" }],
tuesday: [{ start: "09:00:00", end: "17:00:00" }],
wednesday: [{ start: "09:00:00", end: "17:00:00" }],
thursday: [{ start: "09:00:00", end: "17:00:00" }],
friday: [{ start: "09:00:00", end: "17:00:00" }],
saturday: null,
sunday: null,
};
type DayOfWeek = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
export type TimeRange = {
start: string;
end: string;
};
export type FreeBusyTime = TimeRange[];
export type Schedule = {
monday?: FreeBusyTime | null;
tuesday?: FreeBusyTime | null;
wednesday?: FreeBusyTime | null;
thursday?: FreeBusyTime | null;
friday?: FreeBusyTime | null;
saturday?: FreeBusyTime | null;
sunday?: FreeBusyTime | null;
};
type ScheduleBlockProps = {
day: DayOfWeek;
ranges?: FreeBusyTime | null;
selected?: boolean;
};
type Props = {
schedule?: Schedule;
onChange?: (data: Schedule) => void;
onSubmit: (data: Schedule) => void;
};
const SchedulerForm = ({ schedule = DEFAULT_SCHEDULE, onSubmit }: Props) => {
const { t } = useLocale();
const ref = React.useRef<HTMLFormElement>(null);
const transformElementsToSchedule = (elements: HTMLFormControlsCollection): Schedule => {
const schedule: Schedule = {};
const formElements = Array.from(elements)
.map((element) => {
return element.id;
})
.filter((value) => value);
/**
* elementId either {day} or {day.N.start} or {day.N.end}
* If elementId in DAYS_ARRAY add elementId to scheduleObj
* then element is the checkbox and can be ignored
*
* If elementId starts with a day in DAYS_ARRAY
* the elementId should be split by "." resulting in array length 3
* [day, rangeIndex, "start" | "end"]
*/
formElements.forEach((elementId) => {
const [day, rangeIndex, rangeId] = elementId.split(".");
if (rangeIndex && rangeId) {
if (!schedule[day]) {
schedule[day] = [];
}
if (!schedule[day][parseInt(rangeIndex)]) {
schedule[day][parseInt(rangeIndex)] = {};
}
schedule[day][parseInt(rangeIndex)][rangeId] = elements[elementId].value;
}
});
return schedule;
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const elements = ref.current?.elements;
if (elements) {
const schedule = transformElementsToSchedule(elements);
onSubmit && typeof onSubmit === "function" && onSubmit(schedule);
}
};
const ScheduleBlock = ({ day, ranges: defaultRanges, selected: defaultSelected }: ScheduleBlockProps) => {
const [ranges, setRanges] = React.useState(defaultRanges);
const [selected, setSelected] = React.useState(defaultSelected);
React.useEffect(() => {
if (!ranges || ranges.length === 0) {
setSelected(false);
} else {
setSelected(true);
}
}, [ranges]);
const handleSelectedChange = () => {
if (!selected && (!ranges || ranges.length === 0)) {
setRanges([
{
start: "09:00:00",
end: "17:00:00",
},
]);
}
setSelected(!selected);
};
const handleAddRange = () => {
let rangeToAdd;
if (!ranges || ranges?.length === 0) {
rangeToAdd = {
start: DEFAULT_START_TIME,
end: DEFAULT_END_TIME,
};
setRanges([rangeToAdd]);
} else {
const lastRange = ranges[ranges.length - 1];
const [hour, minute, second] = lastRange.end.split(":");
const date = dayjs()
.set("hour", parseInt(hour))
.set("minute", parseInt(minute))
.set("second", parseInt(second));
const nextStartTime = date.add(1, "hour");
const nextEndTime = date.add(2, "hour");
/**
* If next range goes over into "tomorrow"
* i.e. time greater that last value in Times
* return
*/
if (nextStartTime.isAfter(date.endOf("day"))) {
return;
}
rangeToAdd = {
start: nextStartTime.format(_24_HOUR_TIME_FORMAT),
end: nextEndTime.format(_24_HOUR_TIME_FORMAT),
};
setRanges([...ranges, rangeToAdd]);
}
};
const handleDeleteRange = (range: TimeRange) => {
if (ranges && ranges.length > 0) {
setRanges(
ranges.filter((r: TimeRange) => {
return r.start != range.start;
})
);
}
};
/**
* Should update ranges values
*/
const handleSelectRangeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const [day, rangeIndex, rangeId] = event.currentTarget.name.split(".");
if (day && ranges) {
const newRanges = ranges.map((range, index) => {
const newRange = {
...range,
[rangeId]: event.currentTarget.value,
};
return index === parseInt(rangeIndex) ? newRange : range;
});
setRanges(newRanges);
}
};
const TimeRangeField = ({ range, day, index }: { range: TimeRange; day: DayOfWeek; index: number }) => {
const timeOptions = (type: "start" | "end") =>
TIMES.map((time) => (
<option
key={`${day}.${index}.${type}.${time.format(_24_HOUR_TIME_FORMAT)}`}
value={time.format(_24_HOUR_TIME_FORMAT)}>
{time.toDate().toLocaleTimeString(undefined, { minute: "numeric", hour: "numeric" })}
</option>
));
return (
<div key={`${day}-range-${index}`} className="flex items-center space-x-2">
<div className="flex items-center space-x-2">
<select
id={`${day}.${index}.start`}
name={`${day}.${index}.start`}
defaultValue={range?.start || DEFAULT_START_TIME}
onChange={handleSelectRangeChange}
className="block px-4 pr-8 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-sm">
{timeOptions("start")}
</select>
<Text>-</Text>
<select
id={`${day}.${index}.end`}
name={`${day}.${index}.end`}
defaultValue={range?.end || DEFAULT_END_TIME}
onChange={handleSelectRangeChange}
className=" block px-4 pr-8 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-sm">
{timeOptions("end")}
</select>
</div>
<div>
<DeleteAction range={range} />
</div>
</div>
);
};
const Actions = () => {
return (
<div className="flex items-center">
<button className="btn-icon" type="button" onClick={() => handleAddRange()}>
<PlusIcon className="h-5 w-5" />
</button>
</div>
);
};
const DeleteAction = ({ range }: { range: TimeRange }) => {
return (
<button className="btn-icon" type="button" onClick={() => handleDeleteRange(range)}>
<TrashIcon className="h-5 w-5" />
</button>
);
};
return (
<fieldset className=" py-6">
<section
className={classnames(
"flex flex-col space-y-6 sm:space-y-0 sm:flex-row sm:justify-between",
ranges && ranges?.length > 1 ? "sm:items-start" : "sm:items-center"
)}>
<div style={{ minWidth: "33%" }} className="flex items-center justify-between">
<div className="flex items-center space-x-2 ">
<input
id={day}
name={day}
checked={selected}
onChange={handleSelectedChange}
type="checkbox"
className="focus:ring-neutral-500 h-4 w-4 text-neutral-900 border-gray-300 rounded-sm"
/>
<Text variant="overline">{day}</Text>
</div>
<div className="sm:hidden justify-self-end self-end">
<Actions />
</div>
</div>
<div className="space-y-2 w-full">
{selected && ranges && ranges.length != 0 ? (
ranges.map((range, index) => (
<TimeRangeField key={`${day}-range-${index}`} range={range} index={index} day={day} />
))
) : (
<Text key={`${day}`} variant="caption">
{t("unavailable")}
</Text>
)}
</div>
<div className="hidden sm:block px-2">
<Actions />
</div>
</section>
</fieldset>
);
};
return (
<>
<form id={SCHEDULE_FORM_ID} onSubmit={handleSubmit} ref={ref} className="divide-y divide-gray-200">
{Object.keys(schedule).map((day) => {
const selected = schedule[day as DayOfWeek] != null;
return (
<ScheduleBlock
key={`${day}`}
day={day as DayOfWeek}
ranges={schedule[day as DayOfWeek]}
selected={selected}
/>
);
})}
</form>
</>
);
};
export default SchedulerForm;
+51 -50
View File
@@ -4,9 +4,10 @@ import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import React, { useEffect, useState } from "react";
import TimezoneSelect from "react-timezone-select";
import TimezoneSelect, { ITimezoneOption } from "react-timezone-select";
import { useLocale } from "@lib/hooks/useLocale";
import { OpeningHours, DateOverride } from "@lib/types/event-type";
import { WeekdaySelect } from "./WeekdaySelect";
import SetTimesModal from "./modal/SetTimesModal";
@@ -17,44 +18,30 @@ dayjs.extend(timezone);
type Props = {
timeZone: string;
availability: Availability[];
setTimeZone: unknown;
setTimeZone: (timeZone: string) => void;
setAvailability: (schedule: { openingHours: OpeningHours[]; dateOverrides: DateOverride[] }) => void;
};
export const Scheduler = ({
availability,
setAvailability,
timeZone: selectedTimeZone,
setTimeZone,
}: Props) => {
const { t } = useLocale();
/**
* @deprecated
*/
export const Scheduler = ({ availability, setAvailability, timeZone, setTimeZone }: Props) => {
const { t, i18n } = useLocale();
const [editSchedule, setEditSchedule] = useState(-1);
const [dateOverrides, setDateOverrides] = useState([]);
const [openingHours, setOpeningHours] = useState([]);
const [openingHours, setOpeningHours] = useState<Availability[]>([]);
useEffect(() => {
setOpeningHours(
availability
.filter((item: Availability) => item.days.length !== 0)
.map((item) => {
item.startDate = dayjs().utc().startOf("day").add(item.startTime, "minutes");
item.endDate = dayjs().utc().startOf("day").add(item.endTime, "minutes");
return item;
})
);
setDateOverrides(availability.filter((item: Availability) => item.date));
setOpeningHours(availability.filter((item: Availability) => item.days.length !== 0));
}, []);
// updates availability to how it should be formatted outside this component.
useEffect(() => {
setAvailability({
dateOverrides: dateOverrides,
openingHours: openingHours,
});
}, [dateOverrides, openingHours]);
setAvailability({ openingHours, dateOverrides: [] });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openingHours]);
const addNewSchedule = () => setEditSchedule(openingHours.length);
const applyEditSchedule = (changed) => {
const applyEditSchedule = (changed: Availability) => {
// new entry
if (!changed.days) {
changed.days = [1, 2, 3, 4, 5]; // Mon - Fri
@@ -63,39 +50,33 @@ export const Scheduler = ({
// update
const replaceWith = { ...openingHours[editSchedule], ...changed };
openingHours.splice(editSchedule, 1, replaceWith);
setOpeningHours([].concat(openingHours));
setOpeningHours([...openingHours]);
}
};
const removeScheduleAt = (toRemove: number) => {
openingHours.splice(toRemove, 1);
setOpeningHours([].concat(openingHours));
setOpeningHours([...openingHours]);
};
const OpeningHours = ({ idx, item }) => (
<li className="py-2 flex justify-between border-b">
const OpeningHours = ({ idx, item }: { idx: number; item: Availability }) => (
<li className="flex justify-between py-2 border-b">
<div className="flex flex-col space-y-4 lg:inline-flex">
<WeekdaySelect defaultValue={item.days} onSelect={(selected: number[]) => (item.days = selected)} />
<button
className="text-sm bg-neutral-100 rounded-sm py-2 px-3"
className="px-3 py-2 text-sm rounded-sm bg-neutral-100"
type="button"
onClick={() => setEditSchedule(idx)}>
{dayjs()
.startOf("day")
.add(item.startTime, "minutes")
.format(item.startTime % 60 === 0 ? "ha" : "h:mma")}
{item.startTime.toLocaleTimeString(i18n.language, { hour: "numeric", minute: "2-digit" })}
&nbsp;{t("until")}&nbsp;
{dayjs()
.startOf("day")
.add(item.endTime, "minutes")
.format(item.endTime % 60 === 0 ? "ha" : "h:mma")}
{item.endTime.toLocaleTimeString(i18n.language, { hour: "numeric", minute: "2-digit" })}
</button>
</div>
<button
type="button"
onClick={() => removeScheduleAt(idx)}
className="btn-sm bg-transparent px-2 py-1 ml-1">
<TrashIcon className="h-5 w-5 inline text-gray-400 -mt-1" />
className="px-2 py-1 ml-1 bg-transparent btn-sm">
<TrashIcon className="inline w-5 h-5 -mt-1 text-gray-400" />
</button>
</li>
);
@@ -111,9 +92,9 @@ export const Scheduler = ({
<div className="mt-1">
<TimezoneSelect
id="timeZone"
value={{ value: selectedTimeZone }}
onChange={(tz) => setTimeZone(tz.value)}
className="shadow-sm focus:ring-black focus:border-brand mt-1 block w-full sm:text-sm border-gray-300 rounded-md"
value={timeZone}
onChange={(tz: ITimezoneOption) => setTimeZone(tz.value)}
className="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-black focus:border-brand sm:text-sm"
/>
</div>
</div>
@@ -122,16 +103,36 @@ export const Scheduler = ({
<OpeningHours key={idx} idx={idx} item={item} />
))}
</ul>
<button type="button" onClick={addNewSchedule} className="btn-white btn-sm mt-2">
<button type="button" onClick={addNewSchedule} className="mt-2 btn-white btn-sm">
{t("add_another")}
</button>
</div>
</div>
{editSchedule >= 0 && (
<SetTimesModal
startTime={openingHours[editSchedule] ? openingHours[editSchedule].startTime : 540}
endTime={openingHours[editSchedule] ? openingHours[editSchedule].endTime : 1020}
onChange={(times) => applyEditSchedule({ ...(openingHours[editSchedule] || {}), ...times })}
startTime={
openingHours[editSchedule]
? new Date(openingHours[editSchedule].startTime).getHours() * 60 +
new Date(openingHours[editSchedule].startTime).getMinutes()
: 540
}
endTime={
openingHours[editSchedule]
? new Date(openingHours[editSchedule].endTime).getHours() * 60 +
new Date(openingHours[editSchedule].endTime).getMinutes()
: 1020
}
onChange={(times: { startTime: number; endTime: number }) =>
applyEditSchedule({
...(openingHours[editSchedule] || {}),
startTime: new Date(
new Date().setHours(Math.floor(times.startTime / 60), times.startTime % 60, 0, 0)
),
endTime: new Date(
new Date().setHours(Math.floor(times.endTime / 60), times.endTime % 60, 0, 0)
),
})
}
onExit={() => setEditSchedule(-1)}
/>
)}
+187
View File
@@ -0,0 +1,187 @@
import { PlusIcon, TrashIcon } from "@heroicons/react/outline";
import dayjs, { Dayjs } from "dayjs";
import React, { useCallback, useState } from "react";
import { Controller, useFieldArray } from "react-hook-form";
import { weekdayNames } from "@lib/core/i18n/weekday";
import { useLocale } from "@lib/hooks/useLocale";
import { TimeRange, Schedule as ScheduleType } from "@lib/types/schedule";
import Button from "@components/ui/Button";
import Select from "@components/ui/form/Select";
/** Begin Time Increments For Select */
const increment = 15;
/**
* 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 TIMES = (() => {
const end = dayjs().endOf("day");
let t: Dayjs = dayjs().startOf("day");
const times = [];
while (t.isBefore(end)) {
times.push(t);
t = t.add(increment, "minutes");
}
return times;
})();
/** End Time Increments For Select */
// sets the desired time in current date, needs to be current date for proper DST translation
const defaultDayRange: TimeRange = {
start: new Date(new Date().setHours(9, 0, 0, 0)),
end: new Date(new Date().setHours(17, 0, 0, 0)),
};
export const DEFAULT_SCHEDULE: ScheduleType = [
[],
[defaultDayRange],
[defaultDayRange],
[defaultDayRange],
[defaultDayRange],
[defaultDayRange],
[],
];
type Option = {
readonly label: string;
readonly value: number;
};
type TimeRangeFieldProps = {
name: string;
};
const TimeRangeField = ({ name }: TimeRangeFieldProps) => {
// Lazy-loaded options, otherwise adding a field has a noticable redraw delay.
const [options, setOptions] = useState<Option[]>([]);
const getOption = (time: Date) => ({
value: time.valueOf(),
label: time.toLocaleTimeString("nl-NL", { minute: "numeric", hour: "numeric" }),
});
const timeOptions = useCallback((offsetOrLimit: { offset?: number; limit?: number } = {}) => {
const { limit, offset } = offsetOrLimit;
return TIMES.filter((time) => (!limit || time.isBefore(limit)) && (!offset || time.isAfter(offset))).map(
(t) => getOption(t.toDate())
);
}, []);
return (
<>
<Controller
name={`${name}.start`}
render={({ field: { onChange, value } }) => (
<Select
className="w-[6rem]"
options={options}
onFocus={() => setOptions(timeOptions())}
onBlur={() => setOptions([])}
defaultValue={getOption(value)}
onChange={(option) => onChange(new Date(option?.value as number))}
/>
)}
/>
<span>-</span>
<Controller
name={`${name}.end`}
render={({ field: { onChange, value } }) => (
<Select
className="w-[6rem]"
options={options}
onFocus={() => setOptions(timeOptions())}
onBlur={() => setOptions([])}
defaultValue={getOption(value)}
onChange={(option) => onChange(new Date(option?.value as number))}
/>
)}
/>
</>
);
};
type ScheduleBlockProps = {
day: number;
weekday: string;
name: string;
};
const ScheduleBlock = ({ name, day, weekday }: ScheduleBlockProps) => {
const { t } = useLocale();
const { fields, append, remove, replace } = useFieldArray({
name: `${name}.${day}`,
});
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 (
<fieldset className="flex justify-between py-5 min-h-[86px]">
<div className="w-1/3">
<label className="flex items-center space-x-2">
<input
type="checkbox"
checked={fields.length > 0}
onChange={(e) => (e.target.checked ? replace([defaultDayRange]) : replace([]))}
className="inline-block border-gray-300 rounded-sm focus:ring-neutral-500 text-neutral-900"
/>
<span className="inline-block capitalize">{weekday}</span>
</label>
</div>
<div className="flex-grow">
{fields.map((field, index) => (
<div key={field.id} className="flex justify-between mb-2">
<div className="flex items-center space-x-2">
<TimeRangeField name={`${name}.${day}.${index}`} />
</div>
<Button
size="icon"
color="minimal"
StartIcon={TrashIcon}
type="button"
onClick={() => remove(index)}
/>
</div>
))}
{!fields.length && t("no_availability")}
</div>
<div>
<Button
type="button"
color="minimal"
size="icon"
className={fields.length > 0 ? "visible" : "invisible"}
StartIcon={PlusIcon}
onClick={handleAppend}
/>
</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;
+29 -25
View File
@@ -1,29 +1,33 @@
import React, { PropsWithChildren } from "react";
import Select, { components, NamedProps } from "react-select";
import React from "react";
import ReactSelect, { components, GroupBase, Props } from "react-select";
import classNames from "@lib/classNames";
export const SelectComp = (props: PropsWithChildren<NamedProps>) => (
<Select
theme={(theme) => ({
...theme,
borderRadius: 2,
colors: {
...theme.colors,
primary: "rgba(17, 17, 17, var(--tw-bg-opacity))",
primary50: "rgba(17, 17, 17, var(--tw-bg-opacity))",
primary25: "rgba(244, 245, 246, var(--tw-bg-opacity))",
},
})}
components={{
...components,
IndicatorSeparator: () => null,
}}
className={classNames("text-sm shadow-sm focus:border-primary-500", props.className)}
{...props}
/>
);
function Select<
Option,
IsMulti extends boolean = false,
Group extends GroupBase<Option> = GroupBase<Option>
>({ className, ...props }: Props<Option, IsMulti, Group>) {
return (
<ReactSelect
theme={(theme) => ({
...theme,
borderRadius: 2,
colors: {
...theme.colors,
primary: "rgba(17, 17, 17, var(--tw-bg-opacity))",
primary50: "rgba(17, 17, 17, var(--tw-bg-opacity))",
primary25: "rgba(244, 245, 246, var(--tw-bg-opacity))",
},
})}
components={{
...components,
IndicatorSeparator: () => null,
}}
className={classNames("text-sm shadow-sm focus:border-primary-500", className)}
{...props}
/>
);
}
SelectComp.displayName = "Select";
export default SelectComp;
export default Select;