All files / app/features/profile/view NewHostRequest.tsx

92.36% Statements 121/131
80.26% Branches 61/76
96.42% Functions 27/28
93.91% Lines 108/115

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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 3952x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x   2x                 387x 387x 387x                                             121x   121x 11x 11x 11x 11x 11x 11x   11x 113x 9x   11x 84x 8x 8x 8x     11x 190x                   11x 11x 11x 11x 11x   11x 11x 11x 11x 11x   11x 11x   11x 11x   11x                                   121x         121x           121x             242x       121x         121x       121x           2x                           23x 121x 121x 121x     121x                               121x                 121x   11x     189x 145x           121x   121x 121x 121x         121x           121x     11x 11x     121x   7x       5x 5x 5x 5x 5x       121x   121x   7x 7x     121x   121x 121x       121x 43x 43x 1x                                                       9x   9x                                                   9x   9x 9x                                                                                                                          
import { CardActions, Skeleton, styled, Typography } from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import Alert from "components/Alert";
import Button from "components/Button";
import Datepicker from "components/Datepicker";
import StyledLink from "components/StyledLink";
import TextField from "components/TextField";
import { createForegroundTracker } from "features/analytics/foregroundTracker";
import { useLogEvent } from "features/analytics/hooks";
import { readSearchReferrer, referrerToProperties } from "features/analytics/searchAttribution";
import { useAuthContext } from "features/auth/AuthProvider";
import { useProfileUser } from "features/profile/hooks/useProfileUser";
import { useLiteUser } from "features/userQueries/useLiteUsers";
import { Trans, useTranslation } from "i18n";
import { GLOBAL, PROFILE } from "i18n/namespaces";
import { useClearablePersistedState } from "platform/usePersistedState";
import React, { RefObject, useEffect, useRef } from "react";
import { useForm } from "react-hook-form";
import { howToWriteRequestGuideUrl } from "routes";
import { service } from "service";
import { CreateHostRequestWrapper } from "service/requests";
import { Temporal } from "temporal-polyfill";
import { theme } from "theme";
 
const TYPING_GAP_CAP_MS = 3000;
 
interface FormValuesSnapshot {
  text: string;
  fromDate: Temporal.PlainDate | null;
  toDate: Temporal.PlainDate | null;
}
 
function isFormField(target: EventTarget | null): boolean {
  Iif (!target || !(target instanceof HTMLElement)) return false;
  const tag = target.tagName;
  return tag === "INPUT" || tag === "TEXTAREA";
}
 
/**
 * Logs `host_request.form_closed` when the form unmounts (closed or submitted),
 * reporting engagement: time open and visible, time a field was focused, active
 * typing time and keystroke count, the final draft length and dates, whether it
 * was submitted, and any search referrer that led the user here.
 *
 * Runs once for the form's open/close lifecycle, so it reads the latest form
 * values and submitted flag from refs rather than re-subscribing on each change.
 */
function useHostRequestFormTracking({
  hostUserId,
  formRef,
  getSubmitted,
  getLatestValues,
}: {
  hostUserId: number;
  formRef: RefObject<HTMLFormElement | null>;
  getSubmitted: () => boolean;
  getLatestValues: () => FormValuesSnapshot;
}) {
  const logEvent = useLogEvent();
 
  useEffect(() => {
    const tracker = createForegroundTracker();
    let focusAccumMs = 0;
    let focusSince: number | null = null;
    let activeTypingMs = 0;
    let lastKeystroke: number | null = null;
    let keystrokeCount = 0;
 
    const onFocusIn = (e: FocusEvent) => {
      if (!isFormField(e.target)) return;
      Eif (focusSince === null) focusSince = performance.now();
    };
    const onFocusOut = (e: FocusEvent) => {
      if (!isFormField(e.target)) return;
      Eif (focusSince !== null) {
        focusAccumMs += performance.now() - focusSince;
        focusSince = null;
      }
    };
    const onKeyDown = (e: KeyboardEvent) => {
      Eif (!isFormField(e.target)) return;
      const now = performance.now();
      if (lastKeystroke !== null) {
        const gap = now - lastKeystroke;
        if (gap <= TYPING_GAP_CAP_MS) activeTypingMs += gap;
      }
      lastKeystroke = now;
      keystrokeCount += 1;
    };
 
    document.addEventListener("visibilitychange", tracker.onVisibilityChange);
    const formEl = formRef.current;
    formEl?.addEventListener("focusin", onFocusIn);
    formEl?.addEventListener("focusout", onFocusOut);
    formEl?.addEventListener("keydown", onKeyDown);
 
    return () => {
      document.removeEventListener("visibilitychange", tracker.onVisibilityChange);
      formEl?.removeEventListener("focusin", onFocusIn);
      formEl?.removeEventListener("focusout", onFocusOut);
      formEl?.removeEventListener("keydown", onKeyDown);
 
      if (focusSince !== null) focusAccumMs += performance.now() - focusSince;
      const { foregroundMs, totalMs } = tracker.finalize();
 
      const { text, fromDate, toDate } = getLatestValues();
      const referrerProps = referrerToProperties(readSearchReferrer(hostUserId));
 
      logEvent("host_request.form_closed", {
        host_user_id: hostUserId,
        submitted: getSubmitted(),
        form_open_ms: foregroundMs,
        form_open_total_ms: totalMs,
        focus_ms: Math.round(focusAccumMs),
        active_typing_ms: Math.round(activeTypingMs),
        keystroke_count: keystrokeCount,
        text_length: text.length,
        from_date: fromDate?.toString(),
        to_date: toDate?.toString(),
        ...referrerProps,
      });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}
 
const StyledTitle = styled(Typography)(() => ({
  marginTop: theme.spacing(1),
  marginBottom: theme.spacing(1),
}));
 
const StyledRequestRow = styled("div")(() => ({
  display: "flex",
  flexDirection: "row",
  alignItems: "center",
}));
 
const StyledDateRow = styled("div")(() => ({
  marginTop: theme.spacing(2),
  display: "flex",
  flexDirection: "column",
  width: "72%",
}));
 
const StyledDatepicker = styled(Datepicker)(() => ({
  marginBottom: theme.spacing(2),
}));
 
const StyledHelpText = styled(Typography)(() => ({
  marginTop: theme.spacing(2),
  marginBottom: theme.spacing(2),
}));
 
const StyledRequestField = styled(TextField)(() => ({
  marginTop: theme.spacing(2),
}));
 
const StyledSendActions = styled(CardActions)(() => ({
  display: "flex",
  justifyContent: "flex-end",
  marginTop: theme.spacing(2),
}));
 
const MIN_LENGTH = 250; // Must match backend
 
// Dates are stored as "yyyy-mm-dd" since Temporal objects don't survive JSON
interface HostRequestDraft {
  text: string;
  fromDate: string | null;
  toDate: string | null;
}
 
interface NewHostRequestProps {
  setIsRequestSuccess: (value: boolean) => void;
  setIsRequesting: (value: boolean) => void;
}
 
export default function NewHostRequest({ setIsRequestSuccess, setIsRequesting }: NewHostRequestProps) {
  const { t } = useTranslation([GLOBAL, PROFILE]);
  const user = useProfileUser();
  const currentUserId = useAuthContext().authState.userId;
 
  // Keep the draft across unmounts (e.g. the mobile profile sheet being swiped closed)
  const [draft, setDraft, clearDraft] = useClearablePersistedState<HostRequestDraft | null>(
    `hostRequestDraft.${currentUserId}.${user.userId}`,
    null,
    "sessionStorage",
  );
 
  const {
    control,
    getValues,
    handleSubmit,
    register,
    setValue,
    subscribe,
    watch,
    reset,
    formState: { errors },
  } = useForm<CreateHostRequestWrapper>({
    defaultValues: {
      hostUserId: user.userId,
      text: draft?.text ?? "",
      fromDate: draft?.fromDate ? Temporal.PlainDate.from(draft.fromDate) : undefined,
      toDate: draft?.toDate ? Temporal.PlainDate.from(draft.toDate) : undefined,
    },
  });
 
  useEffect(
    () =>
      subscribe({
        formState: { values: true },
        callback: ({ values: { text, fromDate, toDate } }) => {
          if (!text && !fromDate && !toDate) return clearDraft();
          setDraft({ text, fromDate: fromDate?.toString() ?? null, toDate: toDate?.toString() ?? null });
        },
      }),
    [subscribe, setDraft, clearDraft],
  );
 
  const textField = watch("text") ?? "";
 
  const formRef = useRef<HTMLFormElement | null>(null);
  const submittedRef = useRef(false);
  const latestValuesRef = useRef<FormValuesSnapshot>({
    text: "",
    fromDate: null,
    toDate: null,
  });
  latestValuesRef.current = {
    text: watch("text") ?? "",
    fromDate: watch("fromDate") ?? null,
    toDate: watch("toDate") ?? null,
  };
 
  useHostRequestFormTracking({
    hostUserId: user.userId,
    formRef,
    getSubmitted: () => submittedRef.current,
    getLatestValues: () => latestValuesRef.current,
  });
 
  const { error, isPending, mutate } = useMutation({
    mutationFn: (data: CreateHostRequestWrapper) => {
      return service.requests.createHostRequest(data);
    },
 
    onSuccess: () => {
      submittedRef.current = true;
      reset();
      clearDraft();
      setIsRequesting(false);
      setIsRequestSuccess(true);
    },
  });
 
  const { isLoading: hostLoading, error: hostError } = useLiteUser(user.userId);
 
  const onSubmit = handleSubmit((data) => {
    // The disabled button doesn't cover submitting with Enter from the date fields
    Iif (isPending) return;
    mutate(data);
  });
 
  const hostToday = Temporal.Now.plainDateISO(user.timezone || Temporal.Now.timeZoneId());
 
  const watchFromDate = watch("fromDate", undefined);
  const arrivalBeforeHostToday = !!watchFromDate && Temporal.PlainDate.compare(watchFromDate, hostToday) < 0;
 
  // Only react to the arrival date changing: adjusting on every render also fired while the
  // departure year was half-typed (e.g. year 0002), overwriting the departure being entered.
  const pushDepartureAfterArrival = (fromDate: Temporal.PlainDate | null) => {
    const toDate = getValues("toDate");
    if (fromDate && toDate && Temporal.PlainDate.compare(fromDate, toDate) >= 0) {
      setValue("toDate", fromDate.add({ days: 1 }));
    }
  };
 
  return (
    <>
      <StyledTitle variant="h1">
        {hostLoading ? <Skeleton width="100" /> : t("profile:request_form.send_request", { name: user.name })}
      </StyledTitle>
      {error && <Alert severity="error">{error.message}</Alert>}
      {hostError ? (
        <Alert severity={"error"}>{hostError?.message}</Alert>
      ) : (
        <form onSubmit={onSubmit} ref={formRef}>
          <StyledRequestRow>
            <StyledDateRow>
              <StyledDatepicker
                control={control}
                error={!!errors.fromDate}
                helperText={errors?.fromDate?.message}
                id="from-date"
                label={t("profile:request_form.arrival_date")}
                name="fromDate"
                minValue={hostToday}
                onPostChange={pushDepartureAfterArrival}
                rules={{
                  required: t("profile:request_form.arrival_date_empty"),
                  validate: {
                    notEmpty: (date) => !date || date !== "",
                    notBeforeHostToday: (date) =>
                      !date ||
                      Temporal.PlainDate.compare(Temporal.PlainDate.from(date), hostToday) >= 0 ||
                      t("profile:request_form.arrival_date_before_host_today", {
                        name: user.name,
                      }),
                  },
                }}
              />
              {arrivalBeforeHostToday && (
                <Alert severity="error">
                  {t("profile:request_form.arrival_date_before_host_today", {
                    name: user.name,
                  })}
                </Alert>
              )}
              <StyledDatepicker
                control={control}
                error={!!errors.toDate}
                helperText={errors?.toDate?.message}
                id="to-date"
                label={t("profile:request_form.departure_date")}
                minValue={watchFromDate ? watchFromDate.add({ days: 1 }) : Temporal.Now.plainDateISO()}
                name="toDate"
                rules={{
                  required: t("profile:request_form.departure_date_empty"),
                  validate: {
                    notEmpty: (stringDate) => stringDate !== "",
                    afterArrival: (date) => {
                      const fromDate = getValues("fromDate");
                      return (
                        !date ||
                        !fromDate ||
                        Temporal.PlainDate.compare(Temporal.PlainDate.from(date), fromDate) > 0 ||
                        t("profile:request_form.departure_date_not_after_arrival")
                      );
                    },
                  },
                }}
              />
            </StyledDateRow>
          </StyledRequestRow>
          <StyledHelpText variant="body1">
            <Trans
              i18nKey="profile:request_form.guide_link_help_text"
              components={{
                guideLink: <StyledLink variant="body1" href={howToWriteRequestGuideUrl} />,
              }}
            />
          </StyledHelpText>
 
          <StyledRequestField
            id="text"
            {...register("text", {
              required: t("profile:request_form.request_description_empty"),
              minLength: {
                value: MIN_LENGTH,
                message: t("profile:request_form.request_chars_remaining", {
                  count: MIN_LENGTH - textField.length,
                }),
              },
            })}
            label={t("profile:request_form.request")}
            minRows={6}
            multiline
            fullWidth
            placeholder={t("profile:request_form.request_description")}
            error={!!errors.text}
            helperText={
              errors.text?.message
                ? errors.text.message
                : MIN_LENGTH - textField.length > 0
                  ? t("profile:request_form.request_chars_remaining", {
                      count: MIN_LENGTH - textField.length,
                    })
                  : ""
            }
          />
          <StyledSendActions>
            <Button onClick={() => setIsRequesting(false)} variant="outlined">
              {t("global:cancel")}
            </Button>
            <Button type="submit" loading={isPending} onClick={onSubmit}>
              {t("global:send")}
            </Button>
          </StyledSendActions>
        </form>
      )}
    </>
  );
}