All files / app/features/publicTrips OfferToHostDialog.tsx

89.65% Statements 52/58
69.23% Branches 9/13
54.54% Functions 6/11
94.23% Lines 49/52

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 273 274 275 276 277 2786x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x   6x                                   6x                         6x                 6x           6x                   6x           6x           6x               157x                 157x 157x 157x   157x     157x                 157x                 157x 157x 157x             157x   1x                       1x 1x 1x 1x 1x       157x           157x   157x 157x 157x                                                                                                                                                           157x                                                      
import { styled, SwipeableDrawer } from "@mui/material";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import Alert from "components/Alert";
import Button from "components/Button";
import Datepicker from "components/Datepicker";
import { Dialog, DialogActions, DialogContent, DialogTitle } from "components/Dialog";
import TextField from "components/TextField";
import { publicTripsBaseKey, publicTripsByUserBaseKey } from "features/queryKeys";
import { useTranslation } from "i18n";
import { GLOBAL, PUBLIC_TRIPS } from "i18n/namespaces";
import { useRouter } from "next/router";
import { useForm } from "react-hook-form";
import { routeToHostRequest } from "routes";
import { service } from "service";
import { Temporal } from "temporal-polyfill";
import { theme } from "theme";
import useIsScreenSizeOrSmaller from "utils/useIsScreenSizeOrSmaller";
 
// Must match the backend PUBLIC_TRIP_OFFER_MIN_LENGTH_UTF16.
const MESSAGE_MIN_LENGTH = 100;
 
const DATE_FIELD_ID = "offer-to-host-dates";
 
interface FormValues {
  fromDate: Temporal.PlainDate | null;
  toDate: Temporal.PlainDate | null;
  text: string;
}
 
interface OfferToHostDialogProps {
  open: boolean;
  onClose: () => void;
  tripId: number;
  hostUserId: number;
  hostName: string;
  tripFromDate: Temporal.PlainDate;
  tripToDate: Temporal.PlainDate;
}
 
const StyledSheet = styled(SwipeableDrawer)(({ theme }) => ({
  "& .MuiDrawer-paper": {
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    maxHeight: "90vh",
    display: "flex",
    flexDirection: "column",
    overflow: "hidden",
    backgroundColor: "var(--mui-palette-background-paper)",
    padding: theme.spacing(0, 2),
  },
}));
 
const Puller = styled("div")({
  width: 30,
  height: 6,
  backgroundColor: "var(--mui-palette-grey-300)",
  borderRadius: 3,
  margin: "8px auto",
  flexShrink: 0,
});
 
const SheetScrollContent = styled("div")({
  overflowY: "auto",
  flexGrow: 1,
  WebkitOverflowScrolling: "touch",
});
 
const SheetActionBar = styled("div")(({ theme }) => ({
  display: "flex",
  gap: theme.spacing(1),
  padding: theme.spacing(1.5, 0),
  paddingBottom: `calc(${theme.spacing(2)} + env(safe-area-inset-bottom, 0px))`,
  borderTop: `1px solid ${theme.palette.divider}`,
  flexShrink: 0,
  "& > *": { flex: 1 },
}));
 
const SheetTitle = styled("h2")(({ theme }) => ({
  ...theme.typography.h2,
  margin: theme.spacing(1, 0, 2),
  flexShrink: 0,
}));
 
const FieldStack = styled("div")(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  gap: theme.spacing(2),
}));
 
const DateRow = styled("div")(({ theme }) => ({
  display: "flex",
  gap: theme.spacing(2),
  [theme.breakpoints.down("sm")]: {
    flexDirection: "column",
  },
}));
 
export default function OfferToHostDialog({
  open,
  onClose,
  tripId,
  hostUserId,
  hostName,
  tripFromDate,
  tripToDate,
}: OfferToHostDialogProps) {
  const { t } = useTranslation([PUBLIC_TRIPS, GLOBAL]);
  const router = useRouter();
  const queryClient = useQueryClient();
 
  const today = Temporal.Now.plainDateISO();
  // The host can offer within the trip's window (shorten, not extend), and
  // never in the past. The backend enforces these too.
  const earliest = Temporal.PlainDate.compare(tripFromDate, today) > 0 ? tripFromDate : today;
 
  const {
    control,
    handleSubmit,
    register,
    reset,
    watch,
    formState: { errors },
  } = useForm<FormValues>({
    mode: "onBlur",
    defaultValues: {
      fromDate: tripFromDate,
      toDate: tripToDate,
      text: "",
    },
  });
 
  const watchFromDate = watch("fromDate");
  const text = watch("text") ?? "";
  const charsRemaining = MESSAGE_MIN_LENGTH - text.length;
 
  const {
    mutate,
    isPending,
    error,
    reset: resetMutation,
  } = useMutation({
    mutationFn: ({ fromDate, toDate, text }: FormValues) =>
      service.requests.createHostRequest({
        hostUserId,
        // Both are required by the form, so non-null at submit time.
        fromDate: fromDate!,
        toDate: toDate!,
        text: text.trim(),
        publicTripId: tripId,
        stayType: 0,
      }),
    onSuccess: (hostRequestId) => {
      // Refetch trips so the card's viewerHostRequestId updates (the button
      // flips to "Already offered") next time the list is shown.
      queryClient.invalidateQueries({ queryKey: [publicTripsBaseKey] });
      queryClient.invalidateQueries({ queryKey: [publicTripsByUserBaseKey] });
      reset();
      onClose();
      router.push(routeToHostRequest(hostRequestId));
    },
  });
 
  const handleClose = () => {
    reset();
    resetMutation();
    onClose();
  };
 
  const onSubmit = handleSubmit((data) => mutate(data));
 
  const isMobile = useIsScreenSizeOrSmaller("mobile");
  const titleId = "offer-to-host-dialog-title";
  const formId = "offer-to-host-form";
 
  const formBody = (
    <>
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error.message}
        </Alert>
      )}
      <form id={formId} onSubmit={onSubmit} noValidate>
        <FieldStack>
          <DateRow>
            <Datepicker
              control={control}
              error={!!errors.fromDate}
              helperText={errors.fromDate?.message}
              id={`${DATE_FIELD_ID}-from`}
              label={t("publicTrips:create_edit_dialog.from_date.label")}
              name="fromDate"
              minValue={earliest}
              maxValue={tripToDate}
              rules={{ required: t("publicTrips:create_edit_dialog.from_date.required_error") }}
            />
            <Datepicker
              control={control}
              error={!!errors.toDate}
              helperText={errors.toDate?.message}
              id={`${DATE_FIELD_ID}-to`}
              label={t("publicTrips:create_edit_dialog.to_date.label")}
              name="toDate"
              minValue={watchFromDate ?? earliest}
              maxValue={tripToDate}
              rules={{ required: t("publicTrips:create_edit_dialog.to_date.required_error") }}
            />
          </DateRow>
          <TextField
            id="offer-to-host-message"
            {...register("text", {
              required: t("publicTrips:offer_to_host_dialog.message.required_error"),
              minLength: {
                value: MESSAGE_MIN_LENGTH,
                message: t("publicTrips:offer_to_host_dialog.message.chars_remaining", {
                  count: charsRemaining,
                }),
              },
            })}
            label={t("publicTrips:offer_to_host_dialog.message.label")}
            placeholder={t("publicTrips:offer_to_host_dialog.message.placeholder")}
            minRows={6}
            multiline
            fullWidth
            error={!!errors.text}
            helperText={
              errors.text?.message
                ? errors.text.message
                : charsRemaining > 0
                  ? t("publicTrips:offer_to_host_dialog.message.chars_remaining", {
                      count: charsRemaining,
                    })
                  : ""
            }
          />
        </FieldStack>
      </form>
    </>
  );
 
  const cancelButton = (
    <Button variant="outlined" onClick={handleClose}>
      {t("global:cancel")}
    </Button>
  );
  const submitButton = (
    <Button type="submit" form={formId} loading={isPending}>
      {t("publicTrips:offer_to_host_dialog.submit_button")}
    </Button>
  );
 
  Iif (isMobile) {
    return (
      <StyledSheet anchor="bottom" open={open} onClose={handleClose} onOpen={() => {}} disableSwipeToOpen>
        <Puller />
        <SheetTitle id={titleId}>{t("publicTrips:offer_to_host_dialog.title", { name: hostName })}</SheetTitle>
        <SheetScrollContent>{formBody}</SheetScrollContent>
        <SheetActionBar>
          {cancelButton}
          {submitButton}
        </SheetActionBar>
      </StyledSheet>
    );
  }
 
  return (
    <Dialog aria-labelledby={titleId} open={open} onClose={handleClose}>
      <DialogTitle id={titleId} onClose={handleClose}>
        {t("publicTrips:offer_to_host_dialog.title", { name: hostName })}
      </DialogTitle>
      <DialogContent>{formBody}</DialogContent>
      <DialogActions sx={{ padding: theme.spacing(0, 3, 2) }}>
        {cancelButton}
        {submitButton}
      </DialogActions>
    </Dialog>
  );
}