All files / src/util feedStack.ts

100% Statements 22/22
100% Branches 11/11
100% Functions 3/3
100% Lines 20/20

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                                                3x               204x 204x 204x   204x 912x 12x             900x   912x 912x     204x 742x 742x 742x 642x 642x   100x 100x   204x 204x    
/**
 * Folding runs of repetitive events in a feed into one stack, the way a
 * phone stacks a burst of notifications from the same app.
 *
 * Presentation only: the feed's filters, counts and search see every item;
 * this decides how the already-filtered list is drawn. An item's stack key
 * says what it is "the same as" — `null` means it always stands alone, which
 * is how a failure (or anything else that must never be folded away) opts out.
 */
 
export type FeedEntry<T> =
  | { kind: "item"; item: T }
  | {
      kind: "stack";
      /** Stable across refetches that add newer items above it: taken from
       *  the stack's oldest member, not its newest. */
      id: string;
      key: string;
      /** In feed order — `items[0]` is the one drawn on top. */
      items: T[];
    };
 
/** The smallest run worth stacking. Two rows folded into a header and a
 *  toggle save nothing, and cost a click. */
export const MIN_STACK_SIZE = 3;
 
export function stackConsecutive<T>(
  items: readonly T[],
  keyOf: (item: T) => string | null,
  idOf: (item: T) => string,
  minSize: number = MIN_STACK_SIZE,
): FeedEntry<T>[] {
  const out: FeedEntry<T>[] = [];
  let run: T[] = [];
  let runKey: string | null = null;
 
  const flush = () => {
    if (runKey !== null && run.length >= minSize) {
      out.push({
        kind: "stack",
        id: `stack:${runKey}:${idOf(run[run.length - 1])}`,
        key: runKey,
        items: run,
      });
    } else {
      run.forEach((item) => out.push({ kind: "item", item }));
    }
    run = [];
    runKey = null;
  };
 
  for (const item of items) {
    const key = keyOf(item);
    if (key === null || key !== runKey) flush();
    if (key === null) {
      out.push({ kind: "item", item });
      continue;
    }
    runKey = key;
    run.push(item);
  }
  flush();
  return out;
}