All files / src/hooks useFeedSource.ts

91.66% Statements 33/36
85.71% Branches 24/28
100% Functions 7/7
100% Lines 30/30

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                                                                                                                  1860x               358x     2771x 2763x 20x 20x         1860x 1860x 628x 628x 628x 316x 746x 746x 746x 746x     628x         1860x 628x 628x 746x 746x 746x   628x       1860x 1860x     1860x   1860x                 2x 2x          
import {
  InfiniteData,
  QueryKey,
  useInfiniteQuery,
} from "@tanstack/react-query";
import { useMemo } from "react";
 
import { SourceWindow } from "@/util/pagedFeed";
 
/** One page of rows from a source, and the server's total when it gives one. */
export interface FeedSourcePage<T> {
  rows: T[];
  total?: number;
  /** Anything else the response said about the source as a whole. */
  meta?: Record<string, unknown>;
}
 
export interface FeedSource<T> extends SourceWindow {
  /** Every row loaded so far, newest first, each once. */
  items: T[];
  /** The server's count, when the source reports one. */
  total: number | null;
  /** `meta` from the most recent page. */
  meta: Record<string, unknown> | null;
  isLoading: boolean;
  isFetchingMore: boolean;
  /** Load the next page. A no-op while one is in flight or none remains. */
  loadMore: () => void;
}
 
interface Options<T> {
  queryKey: QueryKey;
  fetchPage: (offset: number, limit: number) => Promise<FeedSourcePage<T>>;
  pageSize: number;
  idOf: (row: T) => string;
  /** The time the source orders by, in epoch ms. */
  sortTime: (row: T) => number;
  staleTime?: number;
}
 
/**
 * One source of a merged activity feed, read newest first a page at a time
 * by offset.
 *
 * Offset rather than a cursor because none of the sources offers one, and
 * the cost is bounded: a row arriving between two page reads pushes the
 * next page down by one, which shows up here as a duplicate — dropped by
 * id — never as a gap.
 */
export function useFeedSource<T>({
  queryKey,
  fetchPage,
  pageSize,
  idOf,
  sortTime,
  staleTime = 30_000,
}: Options<T>): FeedSource<T> {
  const query = useInfiniteQuery<
    FeedSourcePage<T>,
    Error,
    InfiniteData<FeedSourcePage<T>, number>,
    QueryKey,
    number
  >({
    queryKey,
    queryFn: ({ pageParam }) => fetchPage(pageParam, pageSize),
    initialPageParam: 0,
    getNextPageParam: (last, pages) => {
      const loaded = pages.reduce((n, p) => n + p.rows.length, 0);
      if (last.rows.length < pageSize) return undefined;
      Iif (last.total != null && loaded >= last.total) return undefined;
      return loaded;
    },
    staleTime,
  });
 
  const pages = query.data?.pages;
  const items = useMemo(() => {
    const seen = new Set<string>();
    const out: T[] = [];
    for (const page of pages ?? []) {
      for (const row of page.rows) {
        const id = idOf(row);
        Iif (seen.has(id)) continue;
        seen.add(id);
        out.push(row);
      }
    }
    return out;
    // idOf is a pure accessor supplied inline by the caller.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pages]);
 
  const oldest = useMemo(() => {
    let min: number | null = null;
    for (const row of items) {
      const t = sortTime(row);
      Iif (Number.isNaN(t)) continue;
      if (min === null || t < min) min = t;
    }
    return min;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [items]);
 
  const lastPage = pages?.[pages.length - 1];
  const loaded = pages !== undefined;
  // A failed read counts as exhausted: the feed shows what it has rather
  // than holding every other source behind a horizon that will never move.
  const exhausted = query.isError || (loaded && !query.hasNextPage);
 
  return {
    items,
    total: lastPage?.total ?? null,
    meta: lastPage?.meta ?? null,
    exhausted,
    oldest,
    isLoading: query.isLoading,
    isFetchingMore: query.isFetchingNextPage,
    loadMore: () => {
      Eif (query.hasNextPage && !query.isFetchingNextPage) {
        void query.fetchNextPage();
      }
    },
  };
}