Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

6.1 KB
Raw Blame
"use client";

import { useExtracted } from "next-intl";
import { useGetErrorNamesPaginated } from "@/api/analytics/hooks/errors/useGetErrorNames";
import { ErrorNameItem } from "@/api/analytics/endpoints";
import { Pagination } from "@/components/pagination";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { useStore, useTimezone } from "@/lib/store";
import { cn } from "@/lib/utils";
import { useEffect, useState } from "react";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { ErrorListItem } from "./components/ErrorListItem";
import { ErrorListSkeleton } from "./components/ErrorListSkeleton";
import { EnableErrorTracking } from "./components/EnableErrorTracking";
import { NothingFound } from "../../../components/NothingFound";

// Number of items per page
const PAGE_SIZE = 10;

export default function Errors() {
  const t = useExtracted();
  const { site, time, filters } = useStore();
  const timeZone = useTimezone();

  // Anything that changes which errors are listed sends the pager back to page one, and keeps it there:
  // returning to an earlier scope starts on page one too, not on the page it was left at.
  const scope = JSON.stringify([site, time, filters, timeZone]);
  const [pageState, setPageState] = useState({ scope, pageIndex: 0 });
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  if (pageState.scope !== scope) {
    setPageState({ scope, pageIndex: 0 });
  }
  const pagination = { pageIndex: pageState.scope === scope ? pageState.pageIndex : 0, pageSize };
  const setPagination = (next: { pageIndex: number; pageSize: number }) => {
    setPageState({ scope, pageIndex: next.pageIndex });
    setPageSize(next.pageSize);
  };
  const [totalPages, setTotalPages] = useState(0);

  useSetPageTitle("Errors");

  // Get page number (1-based) from pageIndex (0-based)
  const pageNumber = pagination.pageIndex + 1;

  const {
    data: apiResponse,
    isLoading: isLoadingErrors,
    isError: isErrorErrors,
    error: errorsError,
    isPlaceholderData,
    isFetching,
  } = useGetErrorNamesPaginated({
    limit: pagination.pageSize,
    page: pageNumber,
  });

  const errorsDataArray: ErrorNameItem[] | undefined = apiResponse?.data;
  const totalCount: number | undefined = apiResponse?.totalCount;

  // Create a minimal table object with the required pagination methods
  const table = {
    getState: () => ({
      pagination: {
        pageIndex: pagination.pageIndex,
        pageSize: pagination.pageSize,
      },
    }),
    getCanPreviousPage: () => pagination.pageIndex > 0,
    getCanNextPage: () => {
      if (totalCount === undefined) return true;
      return (pagination.pageIndex + 1) * pagination.pageSize < totalCount;
    },
    getPageCount: () => totalPages,
    setPageIndex: (index: number) => setPagination({ ...pagination, pageIndex: index }),
    previousPage: () => setPagination({ ...pagination, pageIndex: pagination.pageIndex - 1 }),
    nextPage: () => setPagination({ ...pagination, pageIndex: pagination.pageIndex + 1 }),
  };

  useEffect(() => {
    if (!isLoadingErrors && !isPlaceholderData && !isFetching) {
      if (totalCount !== undefined) {
        const pageCount = Math.ceil(totalCount / pagination.pageSize);
        setTotalPages(pageCount);
        // The list can shrink under the current page (a refetch, a rolling window): step back to the last
        // page that has rows instead of showing an empty one.
        if (pagination.pageIndex > 0 && pagination.pageIndex >= pageCount) {
          setPageState({ scope, pageIndex: Math.max(pageCount - 1, 0) });
        }
      } else if (errorsDataArray && errorsDataArray.length === 0 && pagination.pageIndex === 0) {
        // Fallback if totalCount is somehow undefined but we have an empty array on page 1
        setTotalPages(0);
      } else if (errorsDataArray && errorsDataArray.length < pagination.pageSize) {
        // Fallback: if less than a full page is returned, assume it's the last
        setTotalPages(pagination.pageIndex + 1);
      }
    } else if (pagination.pageIndex === 0 && isLoadingErrors && !errorsDataArray) {
      // Initial load, no data yet
      setTotalPages(0);
    }
  }, [
    apiResponse,
    totalCount,
    errorsDataArray,
    isLoadingErrors,
    isPlaceholderData,
    isFetching,
    pagination.pageIndex,
    pagination.pageSize,
    scope,
  ]);

  if (!site) {
    return null;
  }

  return (
    <DisabledOverlay message="errors" featurePath="errors">
      <div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3">
        <SubHeader />
        <EnableErrorTracking />

        {/* Skeleton on the first load only. A new page, filter or time range keeps the previous list
            on screen (placeholder data), dimmed until the answer arrives. */}
        {isLoadingErrors ? (
          <ErrorListSkeleton count={pagination.pageSize} />
        ) : isErrorErrors ? (
          <div className="text-center p-8 text-destructive">
            <p>{t("Error loading errors data")}</p>
            <p className="text-sm">{errorsError?.toString()}</p>
          </div>
        ) : errorsDataArray && errorsDataArray.length > 0 ? (
          <>
            <div aria-busy={isFetching} className={cn("transition-opacity", isPlaceholderData && "opacity-60")}>
              {errorsDataArray.map((errorItem: ErrorNameItem, index: number) => (
                <ErrorListItem key={`${errorItem.value}-${index}-${pagination.pageIndex}`} errorData={errorItem} />
              ))}
            </div>
            {totalPages > 0 && (
              <Pagination
                table={table}
                data={{ items: errorsDataArray || [], total: totalCount || 0 }}
                pagination={pagination}
                setPagination={setPagination}
                isLoading={isPlaceholderData}
                itemName={t("errors")}
              />
            )}
          </>
        ) : (
          <NothingFound
            title={t("No error events found")}
            description={t("Errors will appear here once error tracking is enabled and errors occur on your site.")}
          />
        )}
      </div>
    </DisabledOverlay>
  );
}