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

92.98% Statements 53/57
90.69% Branches 39/43
100% Functions 10/10
92.98% Lines 53/57

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 2404x 4x   4x 4x     4x 4x 4x   4x           856x 84x 84x         772x                         429x               428x 428x     428x   428x   428x 113x           428x 115x           428x 52x           428x 46x                                           124x 2x   122x                                         59x 2x     57x   57x       57x       57x       57x                                                 123x 1x     122x   122x 3x     119x                                           54x 1x     53x 53x 53x   53x       53x       53x       53x       53x 37x     16x                              
import Datepicker from "components/Datepicker";
import Timepicker from "components/Timepicker";
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 { UseFormReturn } from "react-hook-form";
import { isSameOrFutureDate, timestamp2Date } from "utils/date";
import dayjs, { Dayjs } from "utils/dayjs";
import { timePattern } from "utils/validation";
 
import { CreateEventData, useEventFormStyles } from "./EventForm";
 
function splitTimestampToDateAndTime(timestamp?: Timestamp.AsObject): {
  date?: Dayjs;
  time?: Dayjs;
} {
  if (timestamp) {
    const dayjsDate = dayjs(timestamp2Date(timestamp));
    return {
      date: dayjsDate.startOf("day"),
      time: dayjsDate,
    };
  }
  return {};
}
 
interface EventTimeChangerProps
  extends Pick<
    UseFormReturn<CreateEventData>,
    "control" | "getValues" | "setValue" | "register"
  > {
  dirtyFields: UseFormReturn<CreateEventData>["formState"]["dirtyFields"];
  event?: Event.AsObject;
  errors: UseFormReturn<CreateEventData>["formState"]["errors"];
}
 
export default function EventTimeChanger({
  control,
  dirtyFields,
  errors,
  event,
  getValues,
  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 handleStartDateChange = (newStartDate: Dayjs) => {
    setValue("startDate", newStartDate, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };
 
  const handleEndDateChange = (newEndDate: Dayjs) => {
    setValue("endDate", newEndDate, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };
 
  const handleStartTimeChange = (newStartTime: Dayjs) => {
    setValue("startTime", newStartTime, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };
 
  const handleEndTimeChange = (newEndTime: Dayjs) => {
    setValue("endTime", newEndTime, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };
 
  return (
    <>
      <div className={classes.duoContainer}>
        <Datepicker
          control={control}
          defaultValue={eventStartDate ?? null}
          error={!!errors.startDate?.message}
          helperText={errors.startDate?.message}
          id="startDate"
          label={t("communities:start_date")}
          name="startDate"
          onPostChange={handleStartDateChange}
          rules={{
            required: t("communities:date_required"),
            validate: (date: Dayjs) => {
              // 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"
        />
 
        <Timepicker
          control={control}
          name="startTime"
          onPostChange={handleStartTimeChange}
          defaultValue={eventStartTime || null}
          rules={{
            required: t("communities:time_required"),
            pattern: {
              message: t("communities:invalid_time"),
              value: timePattern,
            },
            validate: (time: Dayjs) => {
              if (event && !dirtyFields.startTime) {
                return true;
              }
 
              const startDate = getValues("startDate");
 
              Iif (!startDate) {
                return t("communities:date_required");
              }
 
              Iif (!time) {
                return t("communities:time_required");
              }
 
              const startDateTime = startDate
                .hour(time.hour())
                .minute(time.minute());
 
              return (
                startDateTime.isAfter(dayjs()) ||
                t("communities:past_time_error")
              );
            },
          }}
          id="startTime"
          label={t("communities:start_time")}
          error={!!errors.startTime?.message}
          helperText={errors.startTime?.message || ""}
          testId="startTime"
        />
      </div>
      <div className={classes.duoContainer}>
        <Datepicker
          control={control}
          defaultValue={eventEndDate ?? null}
          error={!!errors.endDate?.message}
          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;
              }
 
              const startDate = getValues("startDate");
 
              if (date.isBefore(startDate)) {
                return t("communities:end_date_error");
              }
 
              return (
                isSameOrFutureDate(date, dayjs()) ||
                t("communities:past_date_error")
              );
            },
          }}
          testId="endDate"
          onPostChange={handleEndDateChange}
        />
 
        <Timepicker
          control={control}
          name="endTime"
          onPostChange={handleEndTimeChange}
          defaultValue={eventEndTime || null}
          rules={{
            required: t("communities:time_required"),
            pattern: {
              message: t("communities:invalid_time"),
              value: timePattern,
            },
            validate: (time: Dayjs) => {
              if (event && !dirtyFields.endTime) {
                return true;
              }
 
              const startTime = getValues("startTime");
              const startDate = getValues("startDate");
              const endDate = getValues("endDate");
 
              Iif (!startTime || !time) {
                return t("communities:time_required");
              }
 
              Iif (!startDate || !endDate) {
                return t("communities:date_required");
              }
 
              const startDateTime = startDate
                .hour(startTime.hour())
                .minute(startTime.minute());
 
              const endDateTime = endDate
                .hour(time.hour())
                .minute(time.minute());
 
              if (!endDateTime.isAfter(startDateTime)) {
                return t("communities:end_time_error");
              }
 
              return (
                endDateTime.isAfter(dayjs()) || t("communities:past_time_error")
              );
            },
          }}
          id="endTime"
          label={t("communities:end_time")}
          error={!!errors.endTime?.message}
          helperText={errors.endTime?.message || ""}
          testId="endTime"
        />
      </div>
    </>
  );
}