All files / pages ChatHistoryPage.jsx

100% Statements 135/135
100% Branches 33/33
100% Functions 5/5
100% Lines 135/135

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 1771x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x   1x 29x 29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x     29x 29x 28x 25x 25x 28x 1x   29x 5x 5x 5x 5x 5x 5x 5x 5x 5x   29x 29x 29x 29x 29x 29x 29x 29x 29x 23x 29x 29x 29x   29x 26x 20x 20x   6x 6x 3x 1x 1x 3x 6x 6x 6x     6x 6x   6x 6x 6x 29x   29x 23x 12x 2x 2x 10x 17x 17x 17x 10x 29x   29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x     29x 29x 29x   29x 29x   29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   29x 29x 29x       29x 29x       29x 29x       29x 29x   29x 29x 29x 29x   29x 4x 25x 4x 21x     29x 29x             29x   1x  
import React, { useEffect, useRef } from "react";
import { Button, Spinner } from "react-bootstrap";
import { useParams, useNavigate } from "react-router";
import { useInfiniteQuery } from "react-query";
import axios from "axios";
 
import BasicLayout from "main/layouts/BasicLayout/BasicLayout";
import ChatMessageDisplay from "main/components/Chat/ChatMessageDisplay";
import ChatMessageCreate from "main/components/Chat/ChatMessageCreate";
import { useBackend } from "main/utils/useBackend";
 
const PAGE_SIZE = 25;
const REFRESH_RATE = 2000;
 
const ChatHistoryPage = () => {
  const { commonsId } = useParams();
  const navigate = useNavigate();
  const loadMoreRef = useRef(null);
 
  const { data: userCommonsList } = useBackend(
    [`/api/usercommons/commons/all?commonsId=${commonsId}`],
    {
      method: "GET",
      url: "/api/usercommons/commons/all",
      params: {
        commonsId: commonsId,
      },
    },
    [],
    { refetchInterval: REFRESH_RATE, enabled: !!commonsId },
  );
 
  const hasValidUserCommons = Array.isArray(userCommonsList);
  const userIdToUsername = hasValidUserCommons
    ? userCommonsList.reduce((acc, user) => {
        acc[user.userId] = user.username || "";
        return acc;
      }, {})
    : {};
 
  const fetchChatPage = async ({ pageParam = 0 }) => {
    const response = await axios.get("/api/chat/get", {
      params: {
        commonsId: commonsId,
        page: pageParam,
        size: PAGE_SIZE,
      },
    });
    return response.data;
  };
 
  const {
    data,
    status,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
  } = useInfiniteQuery(["chatHistory", commonsId], fetchChatPage, {
    getNextPageParam: (lastPage, pages) =>
      lastPage?.last === false ? pages.length : undefined,
    refetchInterval: REFRESH_RATE,
    enabled: !!commonsId,
  });
 
  useEffect(() => {
    if (!hasNextPage) {
      return;
    }
 
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasNextPage && !isFetchingNextPage) {
          fetchNextPage();
        }
      },
      {
        threshold: 1.0,
      },
    );
 
    const currentRef = loadMoreRef.current;
    observer.observe(currentRef);
 
    return () => {
      observer.unobserve(currentRef);
    };
  }, [fetchNextPage, hasNextPage, isFetchingNextPage]);
 
  const messages = Array.isArray(data?.pages)
    ? data.pages.flatMap((page) => {
        if (!page || !Array.isArray(page.content)) {
          return [];
        }
        return page.content.map((message) => ({
          ...message,
          username: userIdToUsername[message.userId],
        }));
      })
    : [];
 
  const isInitialLoading = status === "loading";
  const showError = status === "error";
 
  return (
    <BasicLayout>
      <div className="pt-3" data-testid="ChatHistoryPage">
        <Button
          variant="secondary"
          className="mb-3"
          onClick={() => navigate(-1)}
          data-testid="ChatHistoryPage-back"
        >
          Back
        </Button>
        <div className="d-flex justify-content-between align-items-center mb-3">
          <h2 className="mb-0">Chat History</h2>
          <span className="text-muted">Commons #{commonsId}</span>
        </div>
        <div className="mb-4">
          <ChatMessageCreate commonsId={commonsId} />
        </div>
        <div
          style={{
            minHeight: "50vh",
            maxHeight: "70vh",
            overflowY: "auto",
            border: "1px solid #dee2e6",
            borderRadius: "0.5rem",
            padding: "1rem",
            backgroundColor: "white",
          }}
          data-testid="ChatHistoryPage-message-container"
        >
          {isInitialLoading && (
            <div className="text-center my-3">
              <Spinner animation="border" role="status" size="sm" /> Loading
              messages...
            </div>
          )}
          {showError && (
            <div className="text-center text-danger my-3">
              Unable to load chat messages.
            </div>
          )}
          {!isInitialLoading && messages.length === 0 && (
            <div className="text-center text-muted my-3">
              No messages available for this commons.
            </div>
          )}
          {messages.map((message) => (
            <ChatMessageDisplay key={message.id} message={message} />
          ))}
          <div
            ref={loadMoreRef}
            className="text-center text-muted mt-3"
            data-testid="ChatHistoryPage-status"
          >
            {isFetchingNextPage
              ? "Loading more messages..."
              : hasNextPage
                ? "Scroll to load more messages"
                : "[no more messages]"}
          </div>
        </div>
        {isFetching && !isFetchingNextPage && (
          <div className="text-center text-muted mt-2">
            Updating conversation...
          </div>
        )}
      </div>
    </BasicLayout>
  );
};
 
export default ChatHistoryPage;