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

93.22% Statements 55/59
90.69% Branches 39/43
100% Functions 11/11
93.1% Lines 54/58

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 2504x 4x 4x   4x 4x     4x 4x 4x 4x       922x                         922x 94x 94x         828x                         462x               461x     461x   461x   461x 113x           461x 115x           461x 52x           461x 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 { styled } from "@mui/material";
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 { theme } from "theme";
import { isSameOrFutureDate, timestamp2Date } from "utils/date";
import dayjs, { Dayjs } from "utils/dayjs";
import { timePattern } from "utils/validation";
 
import { CreateEventData } from "./EventForm";
 
const StyledContainer = styled("div")(() => ({
  display: "grid",
  gridTemplateColumns: "1fr",
  gap: theme.spacing(3, 2),
  [theme.breakpoints.up("md")]: {
    gridTemplateColumns: "1fr 1fr",
  },
}));
 
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 { 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 (
    <>
      <StyledContainer>
        <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"
        />
      </StyledContainer>
      <StyledContainer>
        <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"
        />
      </StyledContainer>
    </>
  );
}