All files / app/features/communities/events EventTimeChanger.tsx

100% Statements 62/62
100% Branches 47/47
100% Functions 11/11
100% Lines 62/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 2514x 4x   4x 4x   4x 4x 4x 4x 4x   4x           308x 86x 86x         222x                       4x                 154x 154x     154x   154x   154x 154x   154x 154x         154x 37x 37x     37x 37x       154x 154x   27x           154x         154x 40x 40x       40x 34x       154x                           5x               19x 4x   15x                                           18x 4x     14x 14x       14x                 13x 13x 5x                                                     19x 2x     17x                                       18x 3x     15x 15x       15x 15x         15x 2x     13x                              
import Datepicker from "components/Datepicker";
import TextField from "components/TextField";
import { Timestamp } from "google-protobuf/google/protobuf/timestamp_pb";
import { useTranslation } from "i18n";
import { COMMUNITIES } from "i18n/namespaces";
import { Event } from "proto/events_pb";
import { useEffect, useMemo, useRef } from "react";
import { UseFormMethods, useWatch } from "react-hook-form";
import { isSameOrFutureDate, timestamp2Date } from "utils/date";
import dayjs, { Dayjs, TIME_FORMAT } from "utils/dayjs";
import { timePattern } from "utils/validation";
 
import { CreateEventData, useEventFormStyles } from "./EventForm";
 
function splitTimestampToDateAndTime(timestamp?: Timestamp.AsObject): {
  date?: Dayjs;
  time?: string;
} {
  if (timestamp) {
    const dayjsDate = dayjs(timestamp2Date(timestamp));
    return {
      date: dayjsDate.startOf("day"),
      time: dayjsDate.format(TIME_FORMAT),
    };
  }
  return {};
}
 
interface EventTimeChangerProps
  extends Pick<
    UseFormMethods<CreateEventData>,
    "control" | "errors" | "getValues" | "setValue" | "register"
  > {
  dirtyFields: UseFormMethods<CreateEventData>["formState"]["dirtyFields"];
  event?: Event.AsObject;
}
 
export default function EventTimeChanger({
  control,
  dirtyFields,
  errors,
  event,
  getValues,
  register,
  setValue,
}: EventTimeChangerProps) {
  const { t } = useTranslation([COMMUNITIES]);
  const classes = useEventFormStyles();
 
  const { date: eventStartDate, time: eventStartTime } =
    splitTimestampToDateAndTime(event?.startTime);
  const { date: eventEndDate, time: eventEndTime } =
    splitTimestampToDateAndTime(event?.endTime);
 
  const now = dayjs();
  const defaultDate = now.get("hour") === 23 ? now.add(1, "day") : now;
 
  const dateDelta = useRef(0);
  const endDate = useWatch({
    control,
    name: "endDate",
    defaultValue: eventEndDate || defaultDate,
  });
  useEffect(() => {
    const startDate = getValues("startDate");
    const newDelta = endDate
      .startOf("day")
      .diff(startDate.startOf("day"), "days");
    if (!isNaN(newDelta)) {
      dateDelta.current = newDelta;
    }
  }, [getValues, endDate]);
 
  const timeDelta = useRef(60);
  const defaultEndTime = useMemo(
    () =>
      dayjs()
        .add(1, "hour")
        .add(timeDelta.current, "minutes")
        .format("HH:[00]"),
    []
  );
  const endTime = useWatch({
    control,
    name: "endTime",
    defaultValue: eventEndTime || defaultEndTime,
  });
  useEffect(() => {
    const startTime = getValues("startTime");
    const newDelta = dayjs(endTime, TIME_FORMAT).diff(
      dayjs(startTime, TIME_FORMAT),
      "minutes"
    );
    if (!isNaN(newDelta)) {
      timeDelta.current = newDelta;
    }
  }, [getValues, endTime]);
 
  return (
    <>
      <div className={classes.duoContainer}>
        <Datepicker
          control={control}
          defaultValue={eventStartDate ?? defaultDate}
          // @ts-expect-error - react-hook-form incorrect types the message property for input fields with object values
          error={!!errors.startDate?.message}
          // @ts-expect-error
          helperText={errors.startDate?.message || ""}
          id="startDate"
          label={t("communities:start_date")}
          name="startDate"
          onPostChange={(date) => {
            setValue("endDate", date.add(dateDelta.current, "days"), {
              shouldDirty: true,
            });
          }}
          rules={{
            required: t("communities:date_required"),
            validate: (date) => {
              // Only disable validation temporarily if `event` exists/in the edit event context
              if (event && !dirtyFields.startDate) {
                return true;
              }
              return (
                isSameOrFutureDate(date, dayjs()) ||
                t("communities:past_date_error")
              );
            },
          }}
          testId="startDate"
        />
        <TextField
          defaultValue={
            eventStartTime || dayjs().add(1, "hour").format("HH:[00]")
          }
          error={!!errors.startTime?.message}
          fullWidth
          helperText={errors.startTime?.message || ""}
          id="startTime"
          inputRef={register({
            pattern: {
              message: t("communities:invalid_time"),
              value: timePattern,
            },
            validate: (time) => {
              if (event && !dirtyFields.startTime) {
                return true;
              }
 
              const startTime = dayjs(time, TIME_FORMAT);
              const startDate = getValues("startDate")
                .startOf("day")
                .add(startTime.get("hour"), "hour")
                .add(startTime.get("minute"), "minute");
              return (
                startDate.isAfter(dayjs()) || t("communities:past_time_error")
              );
            },
          })}
          InputLabelProps={{ shrink: true }}
          label={t("communities:start_time")}
          name="startTime"
          onChange={(e) => {
            const newStartTime = dayjs(e.target.value, TIME_FORMAT);
            if (newStartTime.isValid()) {
              setValue(
                "endTime",
                dayjs(e.target.value, TIME_FORMAT)
                  .add(timeDelta.current, "minutes")
                  .format(TIME_FORMAT),
                { shouldDirty: true }
              );
            }
          }}
          type="time"
          variant="standard"
        />
      </div>
      <div className={classes.duoContainer}>
        <Datepicker
          control={control}
          defaultValue={eventEndDate ?? defaultDate}
          // @ts-expect-error
          error={!!errors.endDate?.message}
          // @ts-expect-error
          helperText={errors.endDate?.message || ""}
          id="endDate"
          label={t("communities:end_date")}
          name="endDate"
          rules={{
            required: t("communities:date_required"),
            validate: (date) => {
              if (event && !dirtyFields.endDate) {
                return true;
              }
 
              return (
                isSameOrFutureDate(date, dayjs()) ||
                t("communities:past_date_error")
              );
            },
          }}
          testId="endDate"
        />
        <TextField
          defaultValue={eventEndTime || defaultEndTime}
          error={!!errors.endTime?.message}
          fullWidth
          helperText={errors.endTime?.message || ""}
          id="endTime"
          inputRef={register({
            pattern: {
              message: t("communities:invalid_time"),
              value: timePattern,
            },
            validate: (time) => {
              if (event && !dirtyFields.endTime) {
                return true;
              }
 
              const startTime = dayjs(getValues("startTime"), TIME_FORMAT);
              const startDate = getValues("startDate")
                .startOf("day")
                .add(startTime.get("hour"), "hour")
                .add(startTime.get("minute"), "minute");
              const endTime = dayjs(time, TIME_FORMAT);
              const endDate = getValues("endDate")
                .startOf("day")
                .add(endTime.get("hour"), "hour")
                .add(endTime.get("minute"), "minute");
 
              if (!endDate.isAfter(startDate)) {
                return t("communities:end_time_error");
              }
 
              return (
                endDate.isAfter(dayjs()) || t("communities:past_time_error")
              );
            },
          })}
          InputLabelProps={{ shrink: true }}
          label={t("communities:end_time")}
          name="endTime"
          type="time"
          variant="standard"
        />
      </div>
    </>
  );
}