Skip to content

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

Apply review

erwanMarmelabe6f28bf9414c
diff --git a/doc/src/content/docs/users/mobile-app.mdx b/doc/src/content/docs/users/mobile-app.mdx
index 0b2a7fd7..fe0915a1 100644
--- a/doc/src/content/docs/users/mobile-app.mdx
+++ b/doc/src/content/docs/users/mobile-app.mdx
@@ -33,6 +33,8 @@ You can view and manage your contacts, tasks, and notes from the app. When addin
| -- | -- | -- |
| ![Mobile App Tasks](../../images/mobile-tasks.png) | ![Mobile App Create Note](../../images/mobile-create-note.png) | ![Mobile App Edit Contact](../../images/mobile-contact-edit.png) |
+To get the latest data on the page you are looking at — a note just forwarded by email, a task a colleague completed — tap the refresh button in the top bar. You can also pull the page down from the top and release it, as in most mobile apps.
+
## Offline Mode
The mobile app also supports offline mode, allowing you to access your data even when you don't have an internet connection.
diff --git a/registry.json b/registry.json
index 266cf58a..760af163 100644
--- a/registry.json
+++ b/registry.json
@@ -509,6 +509,10 @@
"path": "src/components/atomic-crm/login/ConfirmationRequired.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/layout/useRefreshData.ts",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/layout/TopToolbar.tsx",
"type": "registry:component"
@@ -517,6 +521,10 @@
"path": "src/components/atomic-crm/layout/PullToRefresh.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/layout/MobileRefreshButton.tsx",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/layout/MobileNavigation.tsx",
"type": "registry:component"
diff --git a/src/components/atomic-crm/layout/MobileHeader.tsx b/src/components/atomic-crm/layout/MobileHeader.tsx
index e300584f..1b57b541 100644
--- a/src/components/atomic-crm/layout/MobileHeader.tsx
+++ b/src/components/atomic-crm/layout/MobileHeader.tsx
@@ -1,7 +1,10 @@
+import { MobileRefreshButton } from "./MobileRefreshButton";
+
const MobileHeader = ({ children }: { children: React.ReactNode }) => {
return (
<header className="fixed top-0 left-0 right-0 z-10 bg-secondary h-14 px-4 w-full flex justify-between items-center">
{children}
+ <MobileRefreshButton />
</header>
);
};
diff --git a/src/components/atomic-crm/layout/MobileRefreshButton.test.tsx b/src/components/atomic-crm/layout/MobileRefreshButton.test.tsx
new file mode 100644
index 00000000..3e2c46d0
--- /dev/null
+++ b/src/components/atomic-crm/layout/MobileRefreshButton.test.tsx
@@ -0,0 +1,46 @@
+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 { MobileRefreshButton } from "./MobileRefreshButton";
+
+/** 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 />
+ <MobileRefreshButton />
+ </I18nContextProvider>
+ </QueryClientProvider>
+);
+
+describe("MobileRefreshButton", () => {
+ beforeEach(() => {
+ fetchCount = 0;
+ });
+
+ it("refetches the data when tapped", async () => {
+ const screen = await render(<Fixture />);
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+
+ await screen.getByRole("button", { name: "Refresh" }).click();
+
+ await expect.element(screen.getByText("fetches: 2")).toBeInTheDocument();
+ });
+});
diff --git a/src/components/atomic-crm/layout/MobileRefreshButton.tsx b/src/components/atomic-crm/layout/MobileRefreshButton.tsx
new file mode 100644
index 00000000..7ae0ded4
--- /dev/null
+++ b/src/components/atomic-crm/layout/MobileRefreshButton.tsx
@@ -0,0 +1,34 @@
+import { Button } from "@/components/ui/button";
+import { LoaderCircle, RotateCw } from "lucide-react";
+import { useTranslate } from "ra-core";
+
+import { useRefreshData } from "./useRefreshData";
+
+/**
+ * Refreshes the data of the current page. Rendered by <MobileHeader>, so every mobile
+ * page has a discoverable, tappable way to refresh — the desktop <RefreshButton> is
+ * hidden on small screens, and the <PullToRefresh> gesture is neither visible nor
+ * available to everyone.
+ */
+export const MobileRefreshButton = () => {
+ const translate = useTranslate();
+ const { refresh, isRefreshing } = useRefreshData();
+
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="rounded-full"
+ aria-label={translate("ra.action.refresh")}
+ disabled={isRefreshing}
+ onClick={() => void refresh()}
+ >
+ {isRefreshing ? (
+ <LoaderCircle className="size-5 animate-spin" />
+ ) : (
+ <RotateCw className="size-5" />
+ )}
+ </Button>
+ );
+};
diff --git a/src/components/atomic-crm/layout/PullToRefresh.test.tsx b/src/components/atomic-crm/layout/PullToRefresh.test.tsx
index 1e7d4ad1..7afc8a8b 100644
--- a/src/components/atomic-crm/layout/PullToRefresh.test.tsx
+++ b/src/components/atomic-crm/layout/PullToRefresh.test.tsx
@@ -3,29 +3,30 @@ import {
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 });
+const touchEvent = (type: string, target: Element, clientYs: number[]) => {
+ const touches = clientYs.map(
+ (clientY, identifier) =>
+ new Touch({ identifier, target, clientX: 0, clientY }),
+ );
return new TouchEvent(type, {
bubbles: true,
cancelable: true,
- touches: type === "touchend" ? [] : [touch],
- changedTouches: [touch],
+ touches: type === "touchend" ? [] : touches,
+ changedTouches: touches,
});
};
const pull = (target: Element, toY: number) => {
- target.dispatchEvent(touchEvent("touchstart", target, 0));
- target.dispatchEvent(touchEvent("touchmove", target, toY));
+ target.dispatchEvent(touchEvent("touchstart", target, [0]));
+ target.dispatchEvent(touchEvent("touchmove", target, [toY]));
};
const release = (target: Element, atY: number) => {
- target.dispatchEvent(touchEvent("touchend", target, atY));
+ target.dispatchEvent(touchEvent("touchend", target, [atY]));
};
/** Displays how many times the query has been fetched from the server. */
@@ -40,12 +41,11 @@ const FetchCounter = () => {
let fetchCount = 0;
-const Fixture = () => (
+const Fixture = ({ children }: { children?: React.ReactNode }) => (
<QueryClientProvider client={new QueryClient()}>
- <I18nContextProvider value={testI18nProvider}>
- <FetchCounter />
- <PullToRefresh />
- </I18nContextProvider>
+ <FetchCounter />
+ <PullToRefresh />
+ {children}
</QueryClientProvider>
);
@@ -54,18 +54,18 @@ describe("PullToRefresh", () => {
fetchCount = 0;
});
- it("shows a refresh button while the user pulls down from the top of the page", async () => {
+ it("shows the refresh indicator 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" }))
+ .element(screen.getByTestId("pull-to-refresh"))
.toBeInTheDocument();
});
- it("hides the refresh button again when the pull is released short of the trigger distance", async () => {
+ it("hides the refresh indicator 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();
@@ -73,7 +73,7 @@ describe("PullToRefresh", () => {
release(document.body, 20);
await expect
- .element(screen.getByRole("button", { name: "Refresh" }))
+ .element(screen.getByTestId("pull-to-refresh"))
.not.toBeInTheDocument();
await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
});
@@ -88,27 +88,33 @@ describe("PullToRefresh", () => {
await expect.element(screen.getByText("fetches: 2")).toBeInTheDocument();
});
- it("refetches the data when the revealed refresh button is tapped", async () => {
+ it("hides the refresh indicator and disarms the gesture when a second finger joins the pull", 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();
+ // A second finger lands: the gesture is no longer a pull-to-refresh.
+ document.body.dispatchEvent(
+ touchEvent("touchstart", document.body, [200, 200]),
+ );
+ release(document.body, 200);
- await expect.element(screen.getByText("fetches: 2")).toBeInTheDocument();
+ await expect
+ .element(screen.getByTestId("pull-to-refresh"))
+ .not.toBeInTheDocument();
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
});
it("scrolls instead of refreshing when the pull starts inside an already scrolled area", async () => {
const screen = await render(
- <>
- <Fixture />
+ <Fixture>
<div
data-testid="scroller"
style={{ height: "50px", overflowY: "auto" }}
>
<div style={{ height: "500px" }}>tall content</div>
</div>
- </>,
+ </Fixture>,
);
await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
const scroller = screen.getByTestId("scroller").element();
@@ -118,7 +124,30 @@ describe("PullToRefresh", () => {
release(scroller.firstElementChild!, 200);
await expect
- .element(screen.getByRole("button", { name: "Refresh" }))
+ .element(screen.getByTestId("pull-to-refresh"))
+ .not.toBeInTheDocument();
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+ });
+
+ it("ignores a pull started inside an overlay portalled out of the page", async () => {
+ const screen = await render(
+ <Fixture>
+ {/* Shape of a Radix dropdown menu / select: portalled popper, own scrolling. */}
+ <div data-radix-popper-content-wrapper="">
+ <div role="menu" data-testid="menu">
+ <div role="menuitem">Archive</div>
+ </div>
+ </div>
+ </Fixture>,
+ );
+ await expect.element(screen.getByText("fetches: 1")).toBeInTheDocument();
+ const menu = screen.getByTestId("menu").element();
+
+ pull(menu, 200);
+ release(menu, 200);
+
+ await expect
+ .element(screen.getByTestId("pull-to-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
index 8e307ea1..3c113da1 100644
--- a/src/components/atomic-crm/layout/PullToRefresh.tsx
+++ b/src/components/atomic-crm/layout/PullToRefresh.tsx
@@ -1,8 +1,8 @@
-import { useQueryClient } from "@tanstack/react-query";
import { LoaderCircle, RotateCw } from "lucide-react";
-import { useTranslate } from "ra-core";
import { useCallback, useEffect, useRef, useState } from "react";
+import { useRefreshData } from "./useRefreshData";
+
/** 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. */
@@ -11,21 +11,31 @@ const DRAG_RESISTANCE = 0.5;
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 the element scrolls on its own and has somewhere to scroll to. */
+const isScroller = (node: Element) => {
+ const { overflowY } = getComputedStyle(node);
+ return (
+ (overflowY === "auto" || overflowY === "scroll") &&
+ node.scrollHeight > node.clientHeight
+ );
+};
/**
- * 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.
+ * True when a pull starting on `target` belongs to something else than the page: an
+ * ancestor scrolls on its own or is already scrolled down, or the touch is inside an
+ * overlay. Overlays are matched on their two portal roots — Radix's popper wrapper
+ * (select, dropdown menu, popover, command) and the dialog role (dialog and, since
+ * vaul renders one too, sheet) — rather than on the role of the panel itself, which
+ * varies (dialog, listbox, menu, …) and is portalled out of its own sheet anyway.
*/
const isScrollGesture = (target: EventTarget | null) => {
let node = target instanceof Element ? target : null;
- if (node?.closest('[role="dialog"], [data-vaul-drawer]')) {
+ if (node?.closest('[role="dialog"], [data-radix-popper-content-wrapper]')) {
return true;
}
while (node) {
- if (node.scrollTop > 0) {
+ if (node.scrollTop > 0 || isScroller(node)) {
return true;
}
node = node.parentElement;
@@ -34,59 +44,61 @@ const isScrollGesture = (target: EventTarget | null) => {
};
/**
- * 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.
+ * Mobile pull-to-refresh: pulling down from the top of the page reveals an indicator
+ * that follows the finger, and releasing it past the trigger distance refetches every
+ * active query. The indicator is decorative — the gesture's accessible counterpart is
+ * the <MobileRefreshButton> in the header.
*
* Mounted once by <MobileLayout>: it listens on the document, so it covers every mobile
- * page without each of them having to opt in.
+ * page without each of them having to opt in. Native overscroll (Chrome for Android's
+ * own pull-to-refresh, the iOS rubber-band) is suppressed in CSS, by the
+ * `overscroll-behavior-y: none` in index.css, so all our listeners stay passive.
*/
export const PullToRefresh = () => {
- const queryClient = useQueryClient();
- const translate = useTranslate();
+ const { refresh, isRefreshing } = useRefreshData();
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);
+ useEffect(() => {
+ isRefreshingRef.current = isRefreshing;
+ }, [isRefreshing]);
+
const moveTo = useCallback((value: number) => {
distanceRef.current = value;
setDistance(value);
}, []);
- const refresh = useCallback(async () => {
- if (isRefreshingRef.current) {
- return;
- }
+ // Holds the indicator at the trigger distance for as long as the refresh runs.
+ const pullRefresh = useCallback(async () => {
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)),
- ]);
+ await refresh();
} finally {
- isRefreshingRef.current = false;
- setIsRefreshing(false);
moveTo(0);
}
- }, [moveTo, queryClient]);
+ }, [moveTo, refresh]);
useEffect(() => {
const onTouchStart = (event: TouchEvent) => {
- startYRef.current =
- event.touches.length === 1 &&
- !isRefreshingRef.current &&
- !isScrollGesture(event.target)
- ? event.touches[0].clientY
- : null;
+ if (
+ event.touches.length !== 1 ||
+ isRefreshingRef.current ||
+ isScrollGesture(event.target)
+ ) {
+ // Not our gesture. A second finger landing mid-pull ends up here, so drop the
+ // indicator too, or it would stay on screen and stay armed.
+ startYRef.current = null;
+ if (!isRefreshingRef.current) {
+ moveTo(0);
+ }
+ return;
+ }
+ startYRef.current = event.touches[0].clientY;
};
const onTouchMove = (event: TouchEvent) => {
@@ -98,20 +110,19 @@ export const PullToRefresh = () => {
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) {
+ const startY = startYRef.current;
+ startYRef.current = null;
+ if (isRefreshingRef.current) {
return;
}
- startYRef.current = null;
- if (distanceRef.current >= TRIGGER_DISTANCE) {
- void refresh();
+ if (startY !== null && distanceRef.current >= TRIGGER_DISTANCE) {
+ void pullRefresh();
} else {
+ // Also covers the abandoned pull of a gesture we gave up on mid-way.
moveTo(0);
}
};
@@ -122,16 +133,16 @@ export const PullToRefresh = () => {
};
document.addEventListener("touchstart", onTouchStart, { passive: true });
- document.addEventListener("touchmove", onTouchMove, { passive: false });
- document.addEventListener("touchend", onTouchEnd);
- document.addEventListener("touchcancel", onTouchCancel);
+ document.addEventListener("touchmove", onTouchMove, { passive: true });
+ document.addEventListener("touchend", onTouchEnd, { passive: true });
+ document.addEventListener("touchcancel", onTouchCancel, { passive: true });
return () => {
document.removeEventListener("touchstart", onTouchStart);
document.removeEventListener("touchmove", onTouchMove);
document.removeEventListener("touchend", onTouchEnd);
document.removeEventListener("touchcancel", onTouchCancel);
};
- }, [moveTo, refresh]);
+ }, [moveTo, pullRefresh]);
if (distance === 0 && !isRefreshing) {
return null;
@@ -140,13 +151,13 @@ export const PullToRefresh = () => {
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"
+ <div
+ aria-hidden="true"
+ data-testid="pull-to-refresh"
+ className="fixed inset-x-0 top-0 z-50 flex justify-center pointer-events-none"
+ >
+ <div
+ className="-mt-12 flex size-10 items-center justify-center rounded-full bg-secondary text-secondary-foreground shadow-md"
style={{
transform: `translateY(${distance}px)`,
opacity: isRefreshing ? 1 : progress,
@@ -160,7 +171,7 @@ export const PullToRefresh = () => {
style={{ transform: `rotate(${progress * 270}deg)` }}
/>
)}
- </button>
+ </div>
</div>
);
};
diff --git a/src/components/atomic-crm/layout/useRefreshData.ts b/src/components/atomic-crm/layout/useRefreshData.ts
new file mode 100644
index 00000000..41c0bcdf
--- /dev/null
+++ b/src/components/atomic-crm/layout/useRefreshData.ts
@@ -0,0 +1,39 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { useCallback, useRef, useState } from "react";
+
+/** Keep the spinner up at least this long, so a cache-warm refresh is not a flash. */
+const MIN_SPINNER_MS = 400;
+
+/**
+ * Refetches every active query, and reports whether that is in flight — shared by the
+ * two mobile refresh affordances, <MobileRefreshButton> and <PullToRefresh>.
+ *
+ * Same effect as ra-core's useRefresh, but awaitable, so a spinner can stop when the
+ * data has actually come back rather than after a guessed delay.
+ */
+export const useRefreshData = () => {
+ const queryClient = useQueryClient();
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ // Guards re-entrancy synchronously: state is a render behind, and refresh() is called
+ // from raw DOM handlers.
+ const isRefreshingRef = useRef(false);
+
+ const refresh = useCallback(async () => {
+ if (isRefreshingRef.current) {
+ return;
+ }
+ isRefreshingRef.current = true;
+ setIsRefreshing(true);
+ try {
+ await Promise.all([
+ queryClient.invalidateQueries(),
+ new Promise((resolve) => setTimeout(resolve, MIN_SPINNER_MS)),
+ ]);
+ } finally {
+ isRefreshingRef.current = false;
+ setIsRefreshing(false);
+ }
+ }, [queryClient]);
+
+ return { refresh, isRefreshing };
+};
diff --git a/src/index.css b/src/index.css
index d4908727..ee7971a3 100644
--- a/src/index.css
+++ b/src/index.css
@@ -189,9 +189,11 @@ body {
/* 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(). */
+ page reload — on top of ours, and iOS rubber-bands the page under the indicator.
+ Suppressing both here is what lets our touch listeners stay passive.
+ 767px is the mobile breakpoint of useIsMobile(). */
@media (max-width: 767px) {
html {
- overscroll-behavior-y: contain;
+ overscroll-behavior-y: none;
}
}