All files / app/features/messages/messagelist InfiniteMessageLoader.tsx

72.54% Statements 37/51
47.61% Branches 10/21
70% Functions 7/10
79.54% Lines 35/44

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 1463x 3x 3x 3x   3x 3x 3x   42x                                                       3x                                                 3x                   42x   42x 42x 42x   42x               42x   42x 22x 22x 22x       42x 22x 22x       42x 22x                       22x 22x       42x 42x 25x 25x 25x 25x 3x 3x                                      
import { styled } from "@mui/material";
import CircularProgress from "components/CircularProgress";
import { useAuthContext } from "features/auth/AuthProvider";
import { messageElementId } from "features/messages/messagelist/MessageView";
import { Message } from "proto/messages_pb";
import { ReactNode, useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { theme } from "theme";
import useOnVisibleEffect from "utils/useOnVisibleEffect";
 
const StyledWrapper = styled("div")(() => ({
  position: "relative",
  flex: 1,
  minHeight: 0,
 
  "&::-webkit-scrollbar": {
    background: "rgba(0,0,0,0)",
    height: "0.5rem",
    width: "0.5rem",
  },
  "&::-webkit-scrollbar:hover": {
    background: "rgba(0,0,0,0.1)",
    width: "0.5rem",
  },
  "&::-webkit-scrollbar-thumb": {
    background: "rgba(0,0,0,0.2)",
    borderRadius: "20px",
  },
  "&::-webkit-scrollbar-thumb:hover": {
    background: "rgba(0,0,0,0.3)",
  },
  overflowY: "auto",
  overflowX: "hidden",
  paddingInlineEnd: `0.5rem`,
  scrollbarHeight: "thin",
  scrollbarWidth: "thin",
}));
 
const StyledLoader = styled("div")(() => ({
  loader: {
    "& > *": {
      display: "block",
      marginInlineEnd: "auto",
      marginInlineStart: "auto",
    },
    paddingTop: theme.spacing(1),
    position: "absolute",
    top: 0,
    width: "100%",
  },
}));
 
interface InfiniteMessageLoaderProps {
  earliestMessageId?: number;
  latestMessage?: Message.AsObject;
  fetchNextPage: () => void;
  isFetchingNextPage: boolean;
  hasNextPage: boolean;
  isError: boolean;
  className?: string;
  children: ReactNode;
}
 
export default function InfiniteMessageLoader({
  earliestMessageId,
  latestMessage,
  fetchNextPage,
  isFetchingNextPage,
  hasNextPage,
  isError,
  className,
  children,
}: InfiniteMessageLoaderProps) {
  const { authState } = useAuthContext();
 
  const scrollRef = useRef<HTMLDivElement>(null);
  const prevScrollHeight = useRef<number | undefined>(undefined);
  const prevTopMessageId = useRef<number | null>(null);
 
  const handleLoadMoreVisible = useCallback(() => {
    prevScrollHeight.current = scrollRef.current?.scrollHeight;
    if (earliestMessageId) {
      prevTopMessageId.current = earliestMessageId;
    }
    fetchNextPage();
  }, [earliestMessageId, fetchNextPage]);
 
  const { ref: loadMoreRef } = useOnVisibleEffect(handleLoadMoreVisible);
 
  useLayoutEffect(() => {
    Iif (isFetchingNextPage) return;
    const messageEl = document.getElementById(messageElementId(prevTopMessageId.current ?? 0));
    messageEl?.scrollIntoView();
  }, [isFetchingNextPage]);
 
  // Scroll to bottom on load
  useLayoutEffect(() => {
    Iif (!scrollRef.current) return;
    scrollRef.current.scroll(0, scrollRef.current.scrollHeight);
  }, []);
 
  //**  Keep at bottom on window resize only if user was already near the bottom **//
  useEffect(() => {
    const updateMessagePosition = () => {
      if (!scrollRef.current) return;
 
      // Only auto-scroll if user was already near the bottom
      // This prevents fighting with mobile keyboard focus behavior
      const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
 
      if (isNearBottom) {
        scrollRef.current.scroll(0, scrollRef.current.scrollHeight);
      }
    };
    window.addEventListener("resize", updateMessagePosition);
    return () => window.removeEventListener("resize", updateMessagePosition);
  }, []);
 
  //** Scroll to the bottom after sending own new message  **//
  const savedMessageId = useRef(latestMessage?.messageId);
  useLayoutEffect(() => {
    Iif (!scrollRef.current) return;
    const isUserMessage = latestMessage?.authorUserId === authState.userId;
    const isNewMessage = latestMessage?.messageId !== savedMessageId.current;
    if (isUserMessage && isNewMessage) {
      scrollRef.current.scroll(0, scrollRef.current.scrollHeight);
      savedMessageId.current = latestMessage?.messageId;
    }
  }, [latestMessage?.messageId, latestMessage?.authorUserId, authState.userId]);
 
  return (
    <StyledWrapper className={className} ref={scrollRef}>
      {hasNextPage && !isError && (
        <StyledLoader>
          {isFetchingNextPage ? (
            <CircularProgress />
          ) : (
            <CircularProgress variant="determinate" value={0} ref={loadMoreRef} />
          )}
        </StyledLoader>
      )}
      {children}
    </StyledWrapper>
  );
}