All files / app/features/dashboard ReminderCarousel.tsx

88.6% Statements 70/79
66.66% Branches 24/36
80% Functions 12/15
88% Lines 66/75

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  1x 1x 1x 1x 1x   1x 1x   1x 1x   1x 1x 1x 1x   1x 1x 1x   1x               20x 8x   12x     12x 10x   2x     2x 2x                       3x 3x 1x       3x       20x 20x 20x 6x     6x             1x                 1x                       8x 23x   23x   8x     23x         23x 23x   23x 23x   23x   23x 20x 20x 16x   20x     23x 3x 3x 3x     23x 16x 16x 6x 6x     23x 16x     23x               22x                                                   16x 3x                                
import { ChevronLeft as ChevronLeftIcon, ChevronRight as ChevronRightIcon } from "@mui/icons-material";
import { Box, styled, useMediaQuery } from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import Alert from "components/Alert";
import FadingScrollTrack from "components/FadingScrollTrack";
import IconButton from "components/IconButton";
import { RpcError } from "grpc-web";
import { useTranslation } from "next-i18next";
import { usePersistedState } from "platform/usePersistedState";
import { GetRemindersRes, Reminder } from "proto/account_pb";
import { useEffect, useRef, useState } from "react";
import { service } from "service";
 
import { DASHBOARD } from "../../i18n/namespaces";
import { theme } from "../../theme";
import { remindersKey } from "../queryKeys";
import ReminderItem from "./ReminderItem";
 
const CARD_WIDTH_DESKTOP = 280;
const CARD_WIDTH_MOBILE = 200;
const CARD_GAP = 16;
 
const ONE_WEEK_MS = 7 * 24 * 60 * 60 * 1000;
 
interface ReminderWithId {
  id: string;
  reminder: Reminder.AsObject;
}
 
function getReminderId(reminder: Reminder.AsObject): string | null {
  if (reminder.respondToHostRequestReminder?.hostRequestId != null) {
    return `respond_host_request:${reminder.respondToHostRequestReminder.hostRequestId}`;
  }
  Iif (reminder.writeReferenceReminder?.hostRequestId != null) {
    return `write_reference:${reminder.writeReferenceReminder.hostRequestId}`;
  }
  if (reminder.completeProfileReminder) {
    return "complete_profile";
  }
  Iif (reminder.completeMyHomeReminder) {
    return "complete_my_home";
  }
  Eif (reminder.completeVerificationReminder) {
    return "complete_verification";
  }
  if (reminder.confirmHostRequestReminder?.hostRequestId != null) {
    return `confirm_host_request:${reminder.confirmHostRequestReminder.hostRequestId}`;
  }
  return null;
}
 
function pruneStaleEntries(
  dismissedReminders: Record<string, number>,
  currentDismissalTime: number,
): Record<string, number> {
  const out: Record<string, number> = {};
  for (const [reminderId, dismissalTime] of Object.entries(dismissedReminders)) {
    Iif (currentDismissalTime - dismissalTime < ONE_WEEK_MS) {
      out[reminderId] = dismissalTime;
    }
  }
  return out;
}
 
function isStillDismissed(dismissedReminders: Record<string, number>, key: string): boolean {
  const now = Date.now();
  const ts = dismissedReminders[key];
  if (ts === undefined) return false;
  return now - ts < ONE_WEEK_MS;
}
 
const StyledContainer = styled(Box)(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  gap: theme.spacing(1),
  width: "100%",
}));
 
const StyledCardSlot = styled(Box)({
  flex: `0 0 ${CARD_WIDTH_DESKTOP}px`,
  scrollSnapAlign: "start",
 
  [theme.breakpoints.down("md")]: {
    flex: `0 0 ${CARD_WIDTH_MOBILE}px`,
  },
});
 
const StyledArrow = styled(IconButton)({
  backgroundColor: "var(--mui-palette-primary-main)",
  color: "var(--mui-palette-primary-contrastText)",
  "&:hover": {
    backgroundColor: "var(--mui-palette-primary-dark)",
  },
  "&.Mui-disabled": {
    backgroundColor: "var(--mui-palette-grey-300)",
    color: "var(--mui-palette-grey-500)",
  },
});
 
export default function ReminderCarousel() {
  const { t } = useTranslation(DASHBOARD);
 
  const { data, error } = useQuery<GetRemindersRes.AsObject, RpcError>({
    queryKey: [remindersKey],
    queryFn: () => service.account.getReminders(),
  });
 
  const [dismissedReminders, setDismissedReminders] = usePersistedState<Record<string, number>>(
    "dismissedReminders",
    {},
  );
 
  const scrollerRef = useRef<HTMLDivElement>(null);
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
 
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);
 
  const reminders = data?.remindersList ?? [];
 
  const visibleReminders = reminders.reduce<ReminderWithId[]>((acc, r) => {
    const id = getReminderId(r);
    if (id && !isStillDismissed(dismissedReminders, id)) {
      acc.push({ id, reminder: r });
    }
    return acc;
  }, []);
 
  const handleDismiss = (id: string) => {
    const dismissTime = Date.now();
    const pruned = pruneStaleEntries(dismissedReminders, dismissTime);
    setDismissedReminders({ ...pruned, [id]: dismissTime });
  };
 
  const updateScrollState = () => {
    const el = scrollerRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 0);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);
  };
 
  useEffect(() => {
    updateScrollState();
  }, [visibleReminders.length]);
 
  const scrollByCard = (direction: 1 | -1) => {
    scrollerRef.current?.scrollBy({
      left: direction * (isMobile ? CARD_WIDTH_MOBILE + CARD_GAP : CARD_WIDTH_DESKTOP + CARD_GAP),
      behavior: "smooth",
    });
  };
 
  if (error) return <Alert severity="error">{error.message}</Alert>;
  if (!visibleReminders.length) return null;
 
  return (
    <StyledContainer>
      <StyledArrow
        aria-label={t("dashboard:carousel_scroller.left_arrow_a11y")}
        size={isMobile ? "small" : "medium"}
        onClick={() => scrollByCard(-1)}
        disabled={!canScrollLeft}
      >
        <ChevronLeftIcon />
      </StyledArrow>
 
      <FadingScrollTrack
        ref={scrollerRef}
        onScroll={updateScrollState}
        $gap={CARD_GAP}
        $canScrollLeft={canScrollLeft}
        $canScrollRight={canScrollRight}
        sx={{
          flex: 1,
          minWidth: 0,
          ...(isMobile && visibleReminders.length === 1 ? { justifyContent: "center" } : {}),
        }}
      >
        {visibleReminders.map(({ id, reminder }) => (
          <StyledCardSlot key={id}>
            <ReminderItem reminder={reminder} onDismiss={() => handleDismiss(id)} />
          </StyledCardSlot>
        ))}
      </FadingScrollTrack>
 
      <StyledArrow
        aria-label={t("dashboard:carousel_scroller.right_arrow_a11y")}
        size={isMobile ? "small" : "medium"}
        onClick={() => scrollByCard(1)}
        disabled={!canScrollRight}
      >
        <ChevronRightIcon />
      </StyledArrow>
    </StyledContainer>
  );
}