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

96.55% Statements 28/29
84.21% Branches 16/19
100% Functions 4/4
96.29% Lines 26/27

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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 2734x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x   4x 4x       4x   4x   28x                                                                                                                                                                           4x               112x 112x                     112x   112x 112x                           112x   9x           3x           112x                                                                                                                                                                                                                                
import { Checkbox, FormControlLabel, Typography } from "@material-ui/core";
import classNames from "classnames";
import Alert from "components/Alert";
import ImageInput from "components/ImageInput";
import LocationAutocomplete from "components/LocationAutocomplete";
import MarkdownInput from "components/MarkdownInput";
import PageTitle from "components/PageTitle";
import TextField from "components/TextField";
import { Coordinates } from "features/search/constants";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL } from "i18n/namespaces";
import { LngLat } from "maplibre-gl";
import { Event } from "proto/events_pb";
import { useRef } from "react";
import { DeepMap, useForm } from "react-hook-form";
import { UseMutateFunction } from "react-query";
import { Dayjs } from "utils/dayjs";
import type { GeocodeResult } from "utils/hooks";
import makeStyles from "utils/makeStyles";
 
import EventTimeChanger from "./EventTimeChanger";
 
export const useEventFormStyles = makeStyles((theme) => ({
  root: {
    marginBlockStart: theme.spacing(4),
  },
  imageUploadhelperText: {
    textAlign: "center",
  },
  form: {
    display: "grid",
    gridTemplateColumns: "minmax(0, 1fr)",
    rowGap: theme.spacing(3),
    marginBlockEnd: theme.spacing(3),
  },
  duoContainer: {
    display: "grid",
    gridTemplateColumns: "1fr",
    gap: theme.spacing(3, 2),
    [theme.breakpoints.up("md")]: {
      gridTemplateColumns: "1fr 1fr",
    },
  },
  locationContainer: {
    minHeight: theme.typography.pxToRem(66),
  },
  endDateTimeButton: {
    justifySelf: "start",
  },
  isOnlineCheckbox: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
  },
  eventDetailsContainer: {
    display: "grid",
    gridTemplateColumns: "minmax(0, 1fr)",
    rowGap: theme.spacing(1),
  },
  submitButton: {
    justifySelf: "start",
  },
}));
 
interface BaseEventData {
  content: string;
  title: string;
  startDate: Dayjs;
  endDate: Dayjs;
  startTime: string;
  endTime: string;
  isOnline: boolean;
  eventImage?: string;
  parentCommunityId?: number;
  link?: string;
  location?: GeocodeResult;
}
interface OfflineEventData extends BaseEventData {
  isOnline: false;
  location: GeocodeResult;
}
 
interface OnlineEventData extends BaseEventData {
  isOnline: true;
  link: string;
  parentCommunityId: number;
}
 
export type CreateEventData = OfflineEventData | OnlineEventData;
 
export type CreateEventVariables = CreateEventData & {
  dirtyFields: DeepMap<CreateEventData, true>;
};
 
interface EventFormProps {
  children(data: { isMutationLoading: boolean }): React.ReactNode;
  event?: Event.AsObject;
  error: RpcError | null;
  mutate: UseMutateFunction<
    Event.AsObject,
    RpcError,
    CreateEventVariables,
    unknown
  >;
  isMutationLoading: boolean;
  title: string;
}
 
export default function EventForm({
  children,
  event,
  error,
  mutate,
  isMutationLoading,
  title,
}: EventFormProps) {
  const { t } = useTranslation([GLOBAL, COMMUNITIES]);
  const classes = useEventFormStyles();
 
  const {
    control,
    errors,
    handleSubmit,
    getValues,
    register,
    setValue,
    watch,
    formState: { dirtyFields },
  } = useForm<CreateEventData>();
 
  const isOnline = watch("isOnline", false);
  const locationDefaultValue = useRef(
    event?.offlineInformation
      ? {
          name: event.offlineInformation.address,
          simplifiedName: event.offlineInformation.address,
          location: new LngLat(
            event.offlineInformation.lng,
            event.offlineInformation.lat
          ),
          bbox: [0, 0, 0, 0] as Coordinates,
        }
      : ("" as const)
  ).current;
 
  const onSubmit = handleSubmit(
    (data) => {
      mutate({
        ...data,
        dirtyFields,
      });
    },
    (errors) => {
      Iif (errors.eventImage) {
        window.scroll({ top: 0, behavior: "smooth" });
      }
    }
  );
 
  return (
    <div className={classes.root}>
      <ImageInput
        alt={t("communities:event_image_input_alt")}
        control={control}
        id="event-image-input"
        initialPreviewSrc={event?.photoUrl || undefined}
        name="eventImage"
        type="rect"
        height={"200px"}
        width={"100%"}
      />
      <Typography className={classes.imageUploadhelperText} variant="body1">
        {t("communities:upload_helper_text")}
      </Typography>
      <PageTitle>{title}</PageTitle>
      {(error || errors.eventImage) && (
        <Alert severity="error">
          {error?.message || errors.eventImage?.message || ""}
        </Alert>
      )}
      <form className={classes.form} onSubmit={onSubmit}>
        <TextField
          defaultValue={event?.title}
          error={!!errors.title}
          fullWidth
          helperText={errors.title?.message || ""}
          id="title"
          inputRef={register({ required: t("communities:title_required") })}
          name="title"
          label={t("global:title")}
          variant="standard"
        />
        <EventTimeChanger
          control={control}
          errors={errors}
          event={event}
          getValues={getValues}
          register={register}
          setValue={setValue}
          dirtyFields={dirtyFields}
        />
        <div
          className={classNames(
            classes.duoContainer,
            classes.locationContainer
          )}
        >
          {isOnline ? (
            <TextField
              defaultValue={event?.onlineInformation?.link}
              error={!!errors.link?.message}
              helperText={errors.link?.message || ""}
              fullWidth
              id="link"
              name="link"
              inputRef={register({ required: t("communities:link_required") })}
              label={t("communities:virtual_event_link")}
              variant="standard"
            />
          ) : (
            <LocationAutocomplete
              control={control}
              name="location"
              defaultValue={locationDefaultValue}
              // @ts-expect-error
              fieldError={errors.location?.message}
              fullWidth
              label={t("communities:location")}
              required={t("communities:location_required")}
              showFullDisplayName
            />
          )}
          <div className={classes.isOnlineCheckbox}>
            <FormControlLabel
              control={
                <Checkbox
                  defaultChecked={!!event?.onlineInformation}
                  name="isOnline"
                  inputRef={register}
                />
              }
              label={t("communities:virtual_event")}
            />
            <Typography variant="body2">
              {t("communities:virtual_events_subtext")}
            </Typography>
          </div>
        </div>
        <div className={classes.eventDetailsContainer}>
          <Typography id="content-label" variant="h3" component="p">
            {t("communities:event_details")}
          </Typography>
          <MarkdownInput
            control={control}
            defaultValue={event?.content}
            id="content"
            name="content"
            labelId="content-label"
            required={t("communities:event_details_required")}
          />
          {errors.content && (
            <Typography color="error" variant="body2">
              {errors.content.message}
            </Typography>
          )}
        </div>
        {children({ isMutationLoading })}
      </form>
    </div>
  );
}