Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

feat(Mobile): Pull to refresh

erwanMarmelabadc700d91345
diff --git a/src/components/atomic-crm/layout/MobileLayout.tsx b/src/components/atomic-crm/layout/MobileLayout.tsx
index 334ae0e8..6be718a7 100644
--- a/src/components/atomic-crm/layout/MobileLayout.tsx
+++ b/src/components/atomic-crm/layout/MobileLayout.tsx
@@ -6,11 +6,13 @@ import { ErrorBoundary } from "react-error-boundary";
import { useConfigurationLoader } from "../root/useConfigurationLoader";
import { MobileNavigation } from "./MobileNavigation";
+import { PullToRefresh } from "./PullToRefresh";
export const MobileLayout = ({ children }: { children: ReactNode }) => {
useConfigurationLoader();
return (
<>
+ <PullToRefresh />
<ErrorBoundary FallbackComponent={Error}>
<Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
{children}
diff --git a/src/components/atomic-crm/layout/PullToRefresh.test.tsx b/src/components/atomic-crm/layout/PullToRefresh.test.tsx
new file mode 100644
index 00000000..1e7d4ad1
--- /dev/null
+++ b/src/components/atomic-crm/layout/PullToRefresh.test.tsx
@@ -0,0 +1,125 @@
+import {
+ QueryClient,
+ QueryClientProvider,
+ useQuery,
+} from "@tanstack/react-query";
+import { I18nContextProvider } from "ra-core";
+import { render } from "vitest-browser-react";
+
+import { testI18nProvider } from "../providers/commons/i18nProvider";
+import { PullToRefresh } from "./PullToRefresh";
+
+const touchEvent = (type: string, target: Element, clientY: number) => {
+ const touch = new Touch({ identifier: 0, target, clientX: 0, clientY });
+ return new TouchEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ touches: type === "touchend" ? [] : [touch],
+ changedTouches: [touch],
+ });
+};
+
+const pull = (target: Element, toY: number) => {
+ target.dispatchEvent(touchEvent("touchstart", target, 0));
+ target.dispatchEvent(touchEvent("touchmove", target, toY));
+};
+
+const release = (target: Element, atY: number) => {
+ target.dispatchEvent(touchEvent("touchend", target, atY));
+};
+
+/** Displays how many times the query has been fetched from the server. */
+const FetchCounter = () => {
+ const { data } = useQuery({
+ queryKey: ["fetch-count"],
+ queryFn: () => ++fetchCount,
+ staleTime: Infinity,
+ });
+ return <p>fetches: {data}</p>;
+};
+
+let fetchCount = 0;
+
+const Fixture = () => (
+ <QueryClientProvider client={new QueryClient()}>
+ <I18nContextProvider value={testI18nProvider}>
+ <FetchCounter />
+ <PullToRefresh />
+ </I18nContextProvider>
+ </QueryClientProvider>
+);
+
+describe("PullToRefresh", () => {
+ beforeEach(() => {
+ fetchCount = 0;
+ });
+
+ it("shows a refresh button while the user pulls down from the top of the page", async () => {
+ const screen = await render(<Fixture />);
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+
+ pull(document.body, 200);
+
+ await expect
+ .element(screen.getByRole("button", { name: "Refresh" }))
+ .toBeInTheDocument();
+ });
+
+ it("hides the refresh button again when the pull is released short of the trigger distance", async () => {
+ const screen = await render(<Fixture />);
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+
+ pull(document.body, 20);
+ release(document.body, 20);
+
+ await expect
+ .element(screen.getByRole("button", { name: "Refresh" }))
+ .not.toBeInTheDocument();
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+ });
+
+ it("refetches the data when the pull is released past the trigger distance", async () => {
+ const screen = await render(<Fixture />);
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+
+ pull(document.body, 200);
+ release(document.body, 200);
+
+ await expect.element(screen.getByText("fetches: 2")).toBeInTheDocument();
+ });
+
+ it("refetches the data when the revealed refresh button is tapped", async () => {
+ const screen = await render(<Fixture />);
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+
+ pull(document.body, 200);
+ await screen.getByRole("button", { name: "Refresh" }).click();
+
+ await expect.element(screen.getByText("fetches: 2")).toBeInTheDocument();
+ });
+
+ it("scrolls instead of refreshing when the pull starts inside an already scrolled area", async () => {
+ const screen = await render(
+ <>
+ <Fixture />
+ <div
+ data-testid="scroller"
+ style={{ height: "50px", overflowY: "auto" }}
+ >
+ <div style={{ height: "500px" }}>tall content</div>
+ </div>
+ </>,
+ );
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+ const scroller = screen.getByTestId("scroller").element();
+ scroller.scrollTop = 100;
+
+ pull(scroller.firstElementChild!, 200);
+ release(scroller.firstElementChild!, 200);
+
+ await expect
+ .element(screen.getByRole("button", { name: "Refresh" }))
+ .not.toBeInTheDocument();
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+ });
+});
diff --git a/src/components/atomic-crm/layout/PullToRefresh.tsx b/src/components/atomic-crm/layout/PullToRefresh.tsx
new file mode 100644
index 00000000..8e307ea1
--- /dev/null
+++ b/src/components/atomic-crm/layout/PullToRefresh.tsx
@@ -0,0 +1,166 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { LoaderCircle, RotateCw } from "lucide-react";
+import { useTranslate } from "ra-core";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+/** Finger travel below which we cannot tell a pull from a tap, so we stay passive. */
+const GESTURE_SLOP = 8;
+/** Finger travel is damped by this factor, which is what makes the pull feel elastic. */
+const DRAG_RESISTANCE = 0.5;
+/** How far the control must travel before releasing triggers a refresh. */
+const TRIGGER_DISTANCE = 64;
+/** The control never travels further than this, however hard the user pulls. */
+const MAX_DISTANCE = 96;
+/** Keep the spinner up at least this long, so a cache-warm refresh is not a flash. */
+const MIN_SPINNER_MS = 400;
+
+/**
+ * True when a pull starting on `target` should scroll the page rather than refresh it:
+ * some ancestor is already scrolled down, or the touch is inside a dialog/sheet, which
+ * owns its own scrolling.
+ */
+const isScrollGesture = (target: EventTarget | null) => {
+ let node = target instanceof Element ? target : null;
+ if (node?.closest('[role="dialog"], [data-vaul-drawer]')) {
+ return true;
+ }
+ while (node) {
+ if (node.scrollTop > 0) {
+ return true;
+ }
+ node = node.parentElement;
+ }
+ return false;
+};
+
+/**
+ * Mobile pull-to-refresh: pulling down from the top of the page reveals a refresh
+ * button that follows the finger, and releasing it past the trigger distance refetches
+ * every active query — the mobile equivalent of the desktop <RefreshButton>, which is
+ * hidden on small screens. Tapping the button while it is visible refreshes too.
+ *
+ * Mounted once by <MobileLayout>: it listens on the document, so it covers every mobile
+ * page without each of them having to opt in.
+ */
+export const PullToRefresh = () => {
+ const queryClient = useQueryClient();
+ const translate = useTranslate();
+ const [distance, setDistance] = useState(0);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ // The gesture runs on raw DOM events, so its inputs are read from refs rather than
+ // from state, which would be a render behind.
+ const distanceRef = useRef(0);
+ const isRefreshingRef = useRef(false);
+ const startYRef = useRef<number | null>(null);
+
+ const moveTo = useCallback((value: number) => {
+ distanceRef.current = value;
+ setDistance(value);
+ }, []);
+
+ const refresh = useCallback(async () => {
+ if (isRefreshingRef.current) {
+ return;
+ }
+ isRefreshingRef.current = true;
+ setIsRefreshing(true);
+ moveTo(TRIGGER_DISTANCE);
+ try {
+ // Same effect as ra-core's useRefresh, but awaitable so the spinner can stop
+ // when the data has actually come back.
+ await Promise.all([
+ queryClient.invalidateQueries(),
+ new Promise((resolve) => setTimeout(resolve, MIN_SPINNER_MS)),
+ ]);
+ } finally {
+ isRefreshingRef.current = false;
+ setIsRefreshing(false);
+ moveTo(0);
+ }
+ }, [moveTo, queryClient]);
+
+ useEffect(() => {
+ const onTouchStart = (event: TouchEvent) => {
+ startYRef.current =
+ event.touches.length === 1 &&
+ !isRefreshingRef.current &&
+ !isScrollGesture(event.target)
+ ? event.touches[0].clientY
+ : null;
+ };
+
+ const onTouchMove = (event: TouchEvent) => {
+ if (startYRef.current === null) {
+ return;
+ }
+ const delta = event.touches[0].clientY - startYRef.current;
+ if (delta <= GESTURE_SLOP) {
+ moveTo(0);
+ return;
+ }
+ // We own the gesture from here: suppress the native overscroll, which on Chrome
+ // for Android is its own pull-to-refresh reloading the whole page.
+ event.preventDefault();
+ moveTo(Math.min(MAX_DISTANCE, (delta - GESTURE_SLOP) * DRAG_RESISTANCE));
+ };
+
+ const onTouchEnd = () => {
+ if (startYRef.current === null) {
+ return;
+ }
+ startYRef.current = null;
+ if (distanceRef.current >= TRIGGER_DISTANCE) {
+ void refresh();
+ } else {
+ moveTo(0);
+ }
+ };
+
+ const onTouchCancel = () => {
+ startYRef.current = null;
+ moveTo(0);
+ };
+
+ document.addEventListener("touchstart", onTouchStart, { passive: true });
+ document.addEventListener("touchmove", onTouchMove, { passive: false });
+ document.addEventListener("touchend", onTouchEnd);
+ document.addEventListener("touchcancel", onTouchCancel);
+ return () => {
+ document.removeEventListener("touchstart", onTouchStart);
+ document.removeEventListener("touchmove", onTouchMove);
+ document.removeEventListener("touchend", onTouchEnd);
+ document.removeEventListener("touchcancel", onTouchCancel);
+ };
+ }, [moveTo, refresh]);
+
+ if (distance === 0 && !isRefreshing) {
+ return null;
+ }
+
+ const progress = Math.min(1, distance / TRIGGER_DISTANCE);
+
+ return (
+ <div className="fixed inset-x-0 top-0 z-50 flex justify-center pointer-events-none">
+ <button
+ type="button"
+ aria-label={translate("ra.action.refresh")}
+ disabled={isRefreshing}
+ onClick={() => void refresh()}
+ className="-mt-12 flex size-10 items-center justify-center rounded-full bg-secondary text-secondary-foreground shadow-md pointer-events-auto"
+ style={{
+ transform: `translateY(${distance}px)`,
+ opacity: isRefreshing ? 1 : progress,
+ }}
+ >
+ {isRefreshing ? (
+ <LoaderCircle className="size-5 animate-spin" />
+ ) : (
+ <RotateCw
+ className="size-5"
+ style={{ transform: `rotate(${progress * 270}deg)` }}
+ />
+ )}
+ </button>
+ </div>
+ );
+};
diff --git a/src/index.css b/src/index.css
index e3d464a3..d4908727 100644
--- a/src/index.css
+++ b/src/index.css
@@ -186,3 +186,12 @@ input[type="time"] {
body {
font-family: "Inter Variable", ui-sans-serif, system-ui, sans-serif;
}
+
+/* The mobile pull-to-refresh (see layout/PullToRefresh.tsx) owns the overscroll
+ gesture: without this, Chrome for Android runs its own pull-to-refresh — a full
+ page reload — on top of ours. 767px is the mobile breakpoint of useIsMobile(). */
+@media (max-width: 767px) {
+ html {
+ overscroll-behavior-y: contain;
+ }
+}