All files / client/src/views/all-program-items/components AllProgramItemsList.tsx

97.05% Statements 132/136
77.35% Branches 41/53
100% Functions 39/39
97.67% Lines 126/129

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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478                                                                                                                    520x 520x       520x                 520x   520x                     2302x   2302x 3125x   2302x 2302x 2302x 2302x 3125x 3125x 3125x 2302x 3125x 3125x 2302x   2302x 3125x               2302x   5238x         2302x 366x 366x 441x       217x     366x     2302x   433x                         2302x 565x   59552x 38094x   565x   5527x     565x 565x 565x     580x 580x 580x 5527x     565x         2302x 2302x 2302x 364x 364x 84x       280x   753x 753x 752x     280x 280x 280x 280x 280x 87x 87x                     2302x 2302x     364x 222x   364x     364x 138x       2302x         372x 368x 368x   4x 4x 4x             27938x                     44139x 44139x             1762x         7210x     2302x                                       2302x 364x   144x   144x                     2302x 2302x 564x 284x   280x   280x 276x     4x               4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x 4x         2302x 364x 3x       2302x   2302x   2302x                                                             6852x   6852x   6852x                                                                                                 1x         1x                         5345x         1x         1x 345x 345x     1x      
import {
  VirtualItem,
  defaultRangeExtractor,
  useWindowVirtualizer,
} from "@tanstack/react-virtual";
import {
  ReactElement,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { groupBy, sortBy } from "remeda";
import styled from "styled-components";
import { config } from "shared/config";
import {
  ProgramItem,
  ProgramItemSignupStrategy,
  UserSignup,
} from "shared/types/models/programItem";
import { SignupQuestion } from "shared/types/models/settings";
import { RaisedCard } from "client/components/RaisedCard";
import { getLotterySignups } from "client/utils/getUpcomingProgramItems";
import { useAppSelector } from "client/utils/hooks";
import { registerScrollToTopOverride } from "client/utils/scrollToTop";
import { useTimeNow } from "client/utils/useTimeNow";
import { selectProgramTypeForTexts } from "client/views/admin/adminSlice";
import { ProgramItemListTitle } from "client/views/all-program-items/components/ProgramItemListTitle";
import { getActiveStickyHeaderIndex } from "client/views/all-program-items/programListUtils";
import { selectGroupMembers } from "client/views/group/groupSlice";
import { getIsInGroup } from "client/views/group/groupUtils";
import {
  selectDirectSignups,
  selectLotterySignups,
} from "client/views/my-program-items/myProgramItemsSlice";
import { ProgramItemEntry } from "client/views/program-item/ProgramItemEntry";
 
interface Props {
  programItems: readonly ProgramItem[];
  // Program item to briefly highlight (and scroll to) — the one the user just
  // came back from, or null
  highlightedProgramItemId: string | null;
}
 
// The grouped list is flattened into a single sequence of rows (a start-time
// header followed by its program items) so it can be window-virtualized
type VirtualRow =
  | { kind: "header"; startTime: string }
  | { kind: "item"; programItem: ProgramItem };
 
// Initial row-height guesses; the virtualizer measures the real heights on
// mount. Keep these close to the real median row heights: every estimated-vs-
// actual mismatch on a row's first measurement is compensated with a scroll
// correction, and large corrections show up as visible jumps when scrolling
// through rows that were skipped past unmeasured (e.g. after a fast fling)
const HEADER_ESTIMATED_HEIGHT = 92;
const ITEM_ESTIMATED_HEIGHT = 350;
 
// One shared value for every program item nobody has signed up to, so those
// rows keep getting the same reference and the memoized row can bail out
const NO_SIGNUPS: UserSignup[] = [];
 
// The window scroll offset and measured row sizes when the list unmounts, so
// returning to it (e.g. via the browser back button after viewing a program
// item) restores the exact scroll position — the clicked card comes back where
// it was. Module-scoped so it survives navigation within the SPA session
let savedScrollState: {
  offset: number;
  measurementsCache: VirtualItem[];
} | null = null;
 
export const AllProgramItemsList = ({
  programItems,
  highlightedProgramItemId,
}: Props): ReactElement => {
  // Opted out of the React Compiler: the virtualizer hook returns one instance
  // that stays referentially stable while its measurements mutate inside it, so
  // the row offsets and total size read from it during render are external
  // mutable state the compiler cannot see change. Memoized, rows keep the
  // offsets they were first rendered with and end up overlapping each other
  "use no memo";
 
  const { t, i18n } = useTranslation();
 
  const signups = useAppSelector(
    (state) => state.allProgramItems.directSignups,
  );
  const lotterySignups = useAppSelector(selectLotterySignups);
  const directSignups = useAppSelector(selectDirectSignups);
  const programTypeForTexts = useAppSelector(selectProgramTypeForTexts);
  const groupMembers = useAppSelector(selectGroupMembers);
  const isGroupCreator = useAppSelector((state) => state.group.isGroupCreator);
  const groupCode = useAppSelector((state) => state.group.groupCode);
  const username = useAppSelector((state) => state.login.username);
  const timeNow = useTimeNow();
  const loggedIn = useAppSelector((state) => state.login.loggedIn);
  const userGroup = useAppSelector((state) => state.login.userGroup);
  const isInGroup = getIsInGroup(groupCode);
 
  const signupQuestions = useAppSelector(
    (state) => state.admin.signupQuestions,
  );
 
  // Index sign-ups by program item id so each row is an O(1) lookup instead of
  // scanning the full sign-ups array (which made the list render O(n^2)).
  // Memoized by hand because the opt-out above also stops the compiler from
  // memoizing anything else here, and this component re-renders on every clock
  // tick and every scroll-driven virtualizer update
  const signupsByProgramItemId = useMemo(
    () =>
      new Map(signups.map((signup) => [signup.programItemId, signup.users])),
    [signups],
  );
 
  // Index the first public sign-up question per program item id
  const publicSignupQuestionByProgramItemId = useMemo(() => {
    const byProgramItemId = new Map<string, SignupQuestion>();
    for (const signupQuestion of signupQuestions) {
      if (
        !signupQuestion.private &&
        !byProgramItemId.has(signupQuestion.programItemId)
      ) {
        byProgramItemId.set(signupQuestion.programItemId, signupQuestion);
      }
    }
    return byProgramItemId;
  }, [signupQuestions]);
 
  const ownOrGroupCreatorLotterySignups = useMemo(
    () =>
      getLotterySignups({
        lotterySignups,
        isGroupCreator,
        groupMembers,
        isInGroup,
        showAllProgramItems: true,
        timeNow,
      }),
    [lotterySignups, isGroupCreator, groupMembers, isInGroup, timeNow],
  );
 
  // Flatten the grouped list once per program-item set (stable across scroll and
  // language changes so it stays out of the scroll render path)
  const { rows, stickyHeaderIndexes } = useMemo(() => {
    const sortedProgramItems = sortBy(
      programItems,
      (programItem) => programItem.startTime,
      (programItem) => programItem.title.toLowerCase(),
    );
    const programItemsByStartTime = groupBy(
      sortedProgramItems,
      (programItem) => programItem.startTime,
    );
 
    const nextRows: VirtualRow[] = [];
    const nextStickyHeaderIndexes: number[] = [];
    for (const [startTime, programItemsForStartTime] of Object.entries(
      programItemsByStartTime,
    )) {
      nextStickyHeaderIndexes.push(nextRows.length);
      nextRows.push({ kind: "header", startTime });
      for (const programItem of programItemsForStartTime) {
        nextRows.push({ kind: "item", programItem });
      }
    }
    return { rows: nextRows, stickyHeaderIndexes: nextStickyHeaderIndexes };
  }, [programItems]);
 
  // The page itself scrolls (no inner scroll container), so virtualize against
  // the window. scrollMargin is the list's offset from the top of the document
  const listRef = useRef<HTMLDivElement>(null);
  const [scrollMargin, setScrollMargin] = useState(0);
  useLayoutEffect(() => {
    const element = listRef.current;
    if (!element) {
      return;
    }
    // Keep the list's document offset current: content above it (the filter
    // card) can change height, which would otherwise misalign every row
    const updateScrollMargin = (): void => {
      const nextScrollMargin =
        element.getBoundingClientRect().top + window.scrollY;
      setScrollMargin((previous) =>
        previous === nextScrollMargin ? previous : nextScrollMargin,
      );
    };
    updateScrollMargin();
    const resizeObserver = new ResizeObserver(updateScrollMargin);
    resizeObserver.observe(document.body);
    window.addEventListener("resize", updateScrollMargin);
    return () => {
      resizeObserver.disconnect();
      window.removeEventListener("resize", updateScrollMargin);
    };
  }, []);
 
  // When a row's measured height differs from its estimate, the virtualizer
  // corrects the scroll position so on-screen content doesn't shift. It issues
  // the correction as an absolute scrollTo based on its cached scroll offset,
  // which lags the live position by up to a frame while the user is scrolling —
  // an absolute target would yank the page back by that lag (a visible jump).
  // Apply only the not-yet-applied part of the correction as a relative
  // scrollBy instead, which is immune to the stale base offset
  const appliedAdjustmentsRef = useRef(0);
  useEffect(() => {
    // The virtualizer zeroes its cumulative adjustments on every scroll event;
    // mirror that so the applied tally stays in sync with it
    const resetAppliedAdjustments = (): void => {
      appliedAdjustmentsRef.current = 0;
    };
    window.addEventListener("scroll", resetAppliedAdjustments, {
      passive: true,
    });
    return () => {
      window.removeEventListener("scroll", resetAppliedAdjustments);
    };
  }, []);
 
  const virtualizer = useWindowVirtualizer({
    count: rows.length,
    scrollToFn: (offset, { adjustments, behavior }) => {
      // No adjustments: a navigation scroll (scrollToOffset/scrollToIndex)
      // where the absolute target is the intent — pass it through
      if (adjustments === undefined) {
        window.scrollTo({ top: offset, behavior });
        return;
      }
      const delta = adjustments - appliedAdjustmentsRef.current;
      appliedAdjustmentsRef.current = adjustments;
      window.scrollBy({ top: delta, behavior });
    },
    // Seeding the virtualizer with the previous visit's measured row sizes
    // lets the saved pixel offset land on the same rows instead of drifting on
    // height estimates. Only read when the virtualizer instance is created
    initialMeasurementsCache: savedScrollState?.measurementsCache,
    estimateSize: (index) =>
      rows[index].kind === "header"
        ? HEADER_ESTIMATED_HEIGHT
        : ITEM_ESTIMATED_HEIGHT,
    // Rows are measured when they mount, and a mismatch against the estimate
    // is fixed with a scroll correction — visible as a jump if the row is
    // already on screen. Overscan is the buffer that lets rows mount and
    // measure while still off-screen, so it needs to cover a realistic
    // per-frame wheel/fling scroll distance
    overscan: 10,
    scrollMargin,
    getItemKey: (index) => {
      const row = rows[index];
      return row.kind === "header"
        ? `header-${row.startTime}`
        : row.programItem.programItemId;
    },
    // Always render the active sticky header, even when it's scrolled out of the
    // measured range, so it can stay pinned to the top
    rangeExtractor: (range) =>
      [
        ...new Set([
          getActiveStickyHeaderIndex(stickyHeaderIndexes, range.startIndex),
          ...defaultRangeExtractor(range),
        ]),
      ].sort((a, b) => a - b),
  });
 
  const activeStickyHeaderIndex = getActiveStickyHeaderIndex(
    stickyHeaderIndexes,
    virtualizer.range?.startIndex ?? 0,
  );
 
  // Remember the scroll offset and row measurements on unmount so the exact
  // position can be restored on return (e.g. via the back button). Runs as a
  // layout-effect cleanup to capture the position before the next route
  // resets the window scroll. Neither direct offset source is reliable here
  // on WebKit: window.scrollY has already been pulled down by scroll
  // anchoring when the commit removed content above the list (and may be
  // clamped against the shrinking document), and the virtualizer's last
  // observed offset misses its own row-measurement compensation scroll while
  // the scroll event for it is still undelivered (WebKit dispatches scroll
  // events for programmatic scrolls asynchronously — under load only after
  // the navigation). The virtualizer tracks that undelivered compensation in
  // scrollAdjustments (cleared once the event arrives), so its intended
  // offset is scrollOffset + scrollAdjustments. The field is private, so
  // read it defensively — if it disappears in an upgrade, only the
  // undelivered-event case regresses
  useLayoutEffect(() => {
    return () => {
      const pendingAdjustments =
        (virtualizer as unknown as { scrollAdjustments?: number })
          .scrollAdjustments ?? 0;
      savedScrollState = {
        offset:
          (virtualizer.scrollOffset ?? window.scrollY) + pendingAdjustments,
        measurementsCache: virtualizer.takeSnapshot(),
      };
    };
  }, [virtualizer]);
 
  // On mount, restore the previous scroll position (e.g. returning via the back
  // button). The just-viewed item comes back exactly where it was and is
  // highlighted there. Guarded to run only once, when the list first has rows
  const hasRestoredScrollRef = useRef(false);
  useEffect(() => {
    if (hasRestoredScrollRef.current || rows.length === 0) {
      return;
    }
    hasRestoredScrollRef.current = true;
 
    if (!savedScrollState || savedScrollState.offset <= 0) {
      return;
    }
 
    const targetOffset = savedScrollState.offset;
    // The document keeps growing for a few frames after mount as rows are
    // measured and the scroll margin settles, so a single scrollTo can clamp
    // short (the document isn't tall enough yet) and stick there. Re-apply
    // across frames until the offset holds — WebKit most often lands short on
    // the first frame. Stop once the document stops growing (scrollY no longer
    // climbs) so an unreachable target doesn't keep yanking the user for the
    // full frame budget, e.g. when the list is now shorter than the saved offset
    const MAX_RESTORE_FRAMES = 30;
    const MAX_STALLED_FRAMES = 3;
    let attempts = 0;
    let stalledFrames = 0;
    let previousScrollY = -1;
    let rafId = 0;
    const restore = (): void => {
      window.scrollTo(0, targetOffset);
      attempts += 1;
      const scrollY = Math.round(window.scrollY);
      stalledFrames = scrollY > previousScrollY ? 0 : stalledFrames + 1;
      previousScrollY = scrollY;
      Iif (
        scrollY < Math.round(targetOffset) &&
        stalledFrames < MAX_STALLED_FRAMES &&
        attempts < MAX_RESTORE_FRAMES
      ) {
        rafId = requestAnimationFrame(restore);
      }
    };
    rafId = requestAnimationFrame(restore);
    return () => cancelAnimationFrame(rafId);
  }, [rows]);
 
  // Make scroll-to-top go through the virtualizer so the smooth scroll isn't
  // cancelled by row-measurement adjustments (see client/src/utils/scrollToTop.ts)
  useEffect(() => {
    return registerScrollToTopOverride(() => {
      virtualizer.scrollToOffset(0, { behavior: "smooth" });
    });
  }, [virtualizer]);
 
  const { programGuideUrlFi, programGuideUrlEn } = config.event();
  const programGuideUrl =
    i18n.language === "fi" ? programGuideUrlFi : programGuideUrlEn;
 
  if (rows.length === 0) {
    return (
      <RaisedCard>
        <Container>
          <NoProgramItemsText>
            {t("noProgramItemsAvailable", {
              PROGRAM_TYPE: t(
                `programTypePartitivePlural.${programTypeForTexts}`,
              ),
            })}
          </NoProgramItemsText>
          <SecondNoProgramItemsText>
            {t("checkProgramGuide")}{" "}
            {programGuideUrl ? (
              <Link to={programGuideUrl} target="_blank">
                {t("programGuide")}
              </Link>
            ) : (
              t("programGuide")
            )}
            .
          </SecondNoProgramItemsText>
        </Container>
      </RaisedCard>
    );
  }
 
  return (
    <div ref={listRef}>
      <VirtualContainer style={{ height: virtualizer.getTotalSize() }}>
        {virtualizer.getVirtualItems().map((virtualItem) => {
          const row = rows[virtualItem.index];
          const isActiveStickyHeader =
            row.kind === "header" &&
            virtualItem.index === activeStickyHeaderIndex;
          return (
            <VirtualRowWrapper
              key={virtualItem.key}
              data-index={virtualItem.index}
              ref={virtualizer.measureElement}
              $sticky={isActiveStickyHeader}
              style={
                isActiveStickyHeader
                  ? undefined
                  : {
                      transform: `translateY(${virtualItem.start - scrollMargin}px)`,
                    }
              }
            >
              {row.kind === "header" ? (
                <ProgramItemListTitle startTime={row.startTime} />
              ) : (
                <ProgramItemEntry
                  isAlwaysExpanded={false}
                  isRecentlyViewed={
                    row.programItem.programItemId === highlightedProgramItemId
                  }
                  programItem={row.programItem}
                  signups={
                    signupsByProgramItemId.get(row.programItem.programItemId) ??
                    NO_SIGNUPS
                  }
                  signupStrategy={
                    row.programItem.signupStrategy ??
                    ProgramItemSignupStrategy.DIRECT
                  }
                  lotterySignups={ownOrGroupCreatorLotterySignups}
                  directSignups={directSignups}
                  username={username}
                  loggedIn={loggedIn}
                  userGroup={userGroup}
                  publicSignupQuestion={publicSignupQuestionByProgramItemId.get(
                    row.programItem.programItemId,
                  )}
                />
              )}
            </VirtualRowWrapper>
          );
        })}
      </VirtualContainer>
    </div>
  );
};
 
const VirtualContainer = styled.div`
  position: relative;
  width: 100%;
`;
 
const VirtualRowWrapper = styled.div<{ $sticky: boolean }>`
  left: 0;
  width: 100%;
 
  /* Contain the child card's vertical margins so the virtualizer measures the
     row's real footprint (margins are otherwise excluded from measurement) */
  display: flow-root;
 
  /* The active group header is pinned to the top of the viewport; all other
     rows are absolutely positioned by the virtualizer via an inline transform.
     The header's own 20px top margin is contained by flow-root, so the pin is
     lifted by that amount to keep the header flush with the viewport top */
  ${(props) =>
    props.$sticky
      ? `position: sticky; top: -20px; z-index: 2;`
      : `position: absolute; top: 0;`}
`;
 
const Container = styled.div`
  display: flex;
  flex-direction: column;
`;
 
const NoProgramItemsText = styled.span`
  color: ${(props) => props.theme.textSecondary};
  font-size: ${(props) => props.theme.fontSizeLarge};
`;
 
const SecondNoProgramItemsText = styled(NoProgramItemsText)`
  padding-top: 8px;
`;