All files / app/components PullToRefresh.tsx

93.9% Statements 77/82
91.42% Branches 32/35
100% Functions 11/11
95.89% Lines 70/73

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 14712x 12x 12x 12x 12x 12x   12x   12x 12x   12x 12x                 7x 7x 6x 12x   6x                 340x 351x 351x 351x 351x 351x 351x 351x 351x   351x 351x   351x 94x   9x 12x   12x 12x 12x     9x 7x   7x       7x     9x 8x 7x 7x 7x   7x         7x     9x 5x 5x 5x 5x   3x 3x 3x   3x 5x 3x     1x 1x       9x 9x 9x 9x 9x 9x 9x 9x 9x       351x   12x                 12x                                      
import { CircularProgress, Paper } from "@mui/material";
import { QueryKey, useQueryClient } from "@tanstack/react-query";
import { GLOBAL } from "i18n/namespaces";
import { useTranslation } from "next-i18next";
import { useEffect, useRef, useState } from "react";
import { sendNativeHapticImpact, useIsNativeEmbed } from "utils/nativeLink";
 
const PULL_THRESHOLD_PX = 70;
// a fast refetch would only flash the spinner, so it doesn't look like anything happened
const MIN_REFRESH_MS = 600;
const MAX_PULL_PX = 100;
// the indicator moves at half the finger's speed, so it feels like it resists
const PULL_RESISTANCE = 0.5;
const INDICATOR_SIZE_PX = 40;
 
interface PullToRefreshProps {
  // refetched by prefix, so ["event", 1] also covers ["event", 1, "summary"]
  queryKeys: QueryKey[];
}
 
// Pulling on these should scroll or pan them, not refresh the page
function startsInsideScrollable(target: EventTarget | null) {
  Iif (!(target instanceof Element)) return false;
  if (target.closest(".maplibregl-map, [role='dialog']")) return true;
  for (let el: Element | null = target; el; el = el.parentElement) {
    Iif (el.scrollTop > 0) return true;
  }
  return false;
}
 
/**
 * Pull down at the top of the page to refetch its data. Only in the mobile app:
 * mobile browsers have their own pull to refresh, and desktop has no pull gesture.
 * Render it on screens with live content (messages, discussions), not on forms or settings.
 * Only refetches the screen's own queryKeys, not app-wide ones like ping or the current user.
 */
export default function PullToRefresh({ queryKeys }: PullToRefreshProps) {
  const { t } = useTranslation(GLOBAL);
  const isNativeEmbed = useIsNativeEmbed();
  const queryClient = useQueryClient();
  const [pull, setPull] = useState(0);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const startRef = useRef<{ x: number; y: number } | null>(null);
  const fullyPulledRef = useRef(false);
  const isRefreshingRef = useRef(false);
  // a ref so a new array each render doesn't re-attach the touch listeners
  const queryKeysRef = useRef(queryKeys);
  queryKeysRef.current = queryKeys;
 
  useEffect(() => {
    if (!isNativeEmbed) return;
 
    const updatePull = (value: number) => {
      const fullyPulled = value >= PULL_THRESHOLD_PX;
      // a tap on reaching the threshold, so the user feels the pull "take"
      if (fullyPulled && !fullyPulledRef.current) sendNativeHapticImpact();
      fullyPulledRef.current = fullyPulled;
      setPull(value);
    };
 
    const handleTouchStart = (event: TouchEvent) => {
      const touch = event.touches[0];
      const canPull =
        !isRefreshingRef.current &&
        event.touches.length === 1 &&
        window.scrollY <= 0 &&
        !startsInsideScrollable(event.target);
      startRef.current = canPull ? { x: touch.clientX, y: touch.clientY } : null;
    };
 
    const handleTouchMove = (event: TouchEvent) => {
      if (!startRef.current) return;
      const touch = event.touches[0];
      const dy = touch.clientY - startRef.current.y;
      const dx = Math.abs(touch.clientX - startRef.current.x);
      // a sideways swipe isn't a pull
      Iif (dx > dy) {
        startRef.current = null;
        updatePull(0);
        return;
      }
      updatePull(Math.min(Math.max(dy * PULL_RESISTANCE, 0), MAX_PULL_PX));
    };
 
    const handleTouchEnd = async () => {
      const shouldRefresh = startRef.current !== null && fullyPulledRef.current;
      startRef.current = null;
      updatePull(0);
      if (!shouldRefresh) return;
 
      isRefreshingRef.current = true;
      setIsRefreshing(true);
      try {
        // "active" skips cached variants nothing on screen uses; awaiting keeps the spinner until data is back
        await Promise.all([
          ...queryKeysRef.current.map((queryKey) => queryClient.refetchQueries({ queryKey, type: "active" })),
          new Promise((resolve) => setTimeout(resolve, MIN_REFRESH_MS)),
        ]);
      } finally {
        isRefreshingRef.current = false;
        setIsRefreshing(false);
      }
    };
 
    window.addEventListener("touchstart", handleTouchStart, { passive: true });
    window.addEventListener("touchmove", handleTouchMove, { passive: true });
    window.addEventListener("touchend", handleTouchEnd);
    window.addEventListener("touchcancel", handleTouchEnd);
    return () => {
      window.removeEventListener("touchstart", handleTouchStart);
      window.removeEventListener("touchmove", handleTouchMove);
      window.removeEventListener("touchend", handleTouchEnd);
      window.removeEventListener("touchcancel", handleTouchEnd);
    };
  }, [isNativeEmbed, queryClient]);
 
  if (!isNativeEmbed || (pull === 0 && !isRefreshing)) return null;
 
  const offset = isRefreshing ? PULL_THRESHOLD_PX : pull;
 
  return (
    <Paper
      elevation={3}
      sx={{
        position: "fixed",
        top: 0,
        left: "50%",
        zIndex: (theme) => theme.zIndex.appBar + 1,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        width: INDICATOR_SIZE_PX,
        height: INDICATOR_SIZE_PX,
        borderRadius: "50%",
        transform: `translate(-50%, ${offset - INDICATOR_SIZE_PX}px)`,
      }}
    >
      <CircularProgress
        size={24}
        aria-label={t("pull_to_refresh_progress_a11y")}
        variant={isRefreshing ? "indeterminate" : "determinate"}
        value={Math.min((pull / PULL_THRESHOLD_PX) * 100, 100)}
      />
    </Paper>
  );
}