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

96.96% Statements 32/33
81.25% Branches 13/16
100% Functions 8/8
96.42% Lines 27/28

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 2243x   3x 3x 3x 3x 3x 3x     3x 3x 3x   3x 3x   3x     3x   175x       175x       175x             175x                   175x                                                                                 28x                 175x                 175x       175x                     175x   8x         8x     2x                                                                                                                                                                                        
import { Checkbox, FormControlLabel, styled, Typography } from "@mui/material";
import { UseMutateFunction } from "@tanstack/react-query";
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/utils/constants";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES, GLOBAL, PROFILE } 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 { Temporal } from "temporal-polyfill";
import { theme } from "theme";
import type { GeocodeResult } from "utils/hooks";
 
import EventTimeChanger from "./EventTimeChanger";
 
const StyledWrapper = styled("div")(() => ({
  marginBlockStart: theme.spacing(4),
}));
 
const StyledImageUploadHelperText = styled(Typography)(() => ({
  textAlign: "center",
}));
 
const StyledForm = styled("form")(() => ({
  display: "grid",
  gridTemplateColumns: "minmax(0, 1fr)",
  rowGap: theme.spacing(3),
  marginBlockEnd: theme.spacing(3),
}));
 
const StyledLocationContainer = styled("div")(() => ({
  display: "grid",
  gridTemplateColumns: "1fr",
  gap: theme.spacing(3, 2),
  [theme.breakpoints.up("md")]: {
    gridTemplateColumns: "1fr 1fr",
  },
  minHeight: theme.typography.pxToRem(66),
}));
 
const StyledEventDetailsContainer = styled("div")(() => ({
  display: "grid",
  gridTemplateColumns: "minmax(0, 1fr)",
  rowGap: theme.spacing(1),
}));
 
interface EventData {
  content: string;
  title: string;
  startDate: Temporal.PlainDate;
  endDate: Temporal.PlainDate;
  startTime: Temporal.PlainTime;
  endTime: Temporal.PlainTime;
  shouldNotify: boolean;
  eventImage?: string;
  parentCommunityId?: number;
  link?: string;
  location: GeocodeResult;
}
 
export type CreateEventData = EventData;
 
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;
  isEdit: boolean;
}
 
export default function EventForm({
  children,
  event,
  error,
  mutate,
  isMutationLoading,
  title,
  isEdit,
}: EventFormProps) {
  const { t } = useTranslation([GLOBAL, COMMUNITIES, PROFILE]);
 
  const {
    control,
    handleSubmit,
    getValues,
    register,
    setValue,
    formState: { dirtyFields, errors },
  } = useForm<CreateEventData>({
    mode: "onBlur",
  });
 
  const locationDefaultValue = useRef(
    event?.location
      ? {
          name: event.location.address,
          simplifiedName: event.location.address,
          location: new LngLat(event.location.lng, event.location.lat),
          bbox: [0, 0, 0, 0] as Coordinates,
        }
      : ("" as const),
  ).current;
 
  const onSubmit = handleSubmit(
    (data) => {
      const eventVariables = {
        ...data,
        dirtyFields,
      } as CreateEventVariables;
 
      mutate(eventVariables);
    },
    (errors) => {
      Iif (errors.eventImage) {
        window.scroll({ top: 0, behavior: "smooth" });
      }
    },
  );
 
  return (
    <StyledWrapper>
      <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%"}
      />
      <StyledImageUploadHelperText variant="body1">
        {t("communities:upload_helper_text")}
      </StyledImageUploadHelperText>
      <PageTitle>{title}</PageTitle>
      {(error || errors.eventImage) && (
        <Alert severity="error">
          {error?.message || errors.eventImage?.message || ""}
        </Alert>
      )}
      <StyledForm onSubmit={onSubmit}>
        <TextField
          id="title"
          {...register("title", { required: t("communities:title_required") })}
          defaultValue={event?.title}
          error={!!errors.title}
          fullWidth
          helperText={errors.title?.message || ""}
          label={t("communities:event_title_label")}
          variant="standard"
        />
        <EventTimeChanger
          control={control}
          errors={errors}
          event={isEdit ? event : undefined}
          getValues={getValues}
          register={register}
          setValue={setValue}
          dirtyFields={dirtyFields}
        />
        <StyledLocationContainer>
          <LocationAutocomplete
            control={control}
            name="location"
            defaultValue={locationDefaultValue}
            fieldError={errors.location?.message}
            fullWidth
            label={t("communities:location")}
            required={t("communities:location_required")}
            showFullDisplayName
            autocompleteContext="create-event-form"
          />
 
          {isEdit && (
            <FormControlLabel
              control={
                <Checkbox
                  {...register("shouldNotify")}
                  defaultChecked={false}
                  name="shouldNotify"
                />
              }
              label={t("communities:notify_attendees")}
            />
          )}
        </StyledLocationContainer>
        <StyledEventDetailsContainer>
          <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")}
          />
        </StyledEventDetailsContainer>
 
        {children({ isMutationLoading })}
      </StyledForm>
    </StyledWrapper>
  );
}