Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Enhance UserLocationMap and UserSidebar components: update geocoding function to include country parameter and improve region name handling in UserSidebar. This ensures more accurate location queries and better user experience.

Bill Yangc90370634fa0
diff --git a/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx b/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx
new file mode 100644
index 000000000..1fef9a154
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/components/UserLocationMap.test.tsx
@@ -0,0 +1,136 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { UserInfo } from "@/api/analytics/endpoints";
+import { UserLocationMap } from "./UserLocationMap";
+import { UserSidebar } from "./UserSidebar";
+
+const mocks = vi.hoisted(() => ({
+ fetch: vi.fn<typeof fetch>(),
+ map: vi.fn(function () {
+ return { remove: vi.fn() };
+ }),
+ setLngLat: vi.fn().mockReturnThis(),
+}));
+
+vi.mock("mapbox-gl", () => ({
+ default: {
+ Map: mocks.map,
+ Marker: vi.fn(function () {
+ return { setLngLat: mocks.setLngLat, addTo: vi.fn().mockReturnThis(), remove: vi.fn() };
+ }),
+ },
+}));
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
+vi.mock("@/lib/configs", () => ({ useConfigs: () => ({ configs: { mapboxToken: "test-token" } }) }));
+vi.mock("@/lib/userStore", () => ({ userStore: () => ({ user: null }) }));
+vi.mock("@/components/EditTraitsDialog", () => ({ EditTraitsDialog: () => null }));
+vi.mock("./Calendar", () => ({ VisitCalendar: () => null }));
+
+const regionNames: Record<string, string> = {
+ "ES-MD": "Madrid, Comunidad de",
+ "AU-WA": "Western Australia",
+};
+const getRegionName = (region: string) => regionNames[region] ?? "";
+
+let client: QueryClient;
+
+beforeEach(() => {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ vi.stubGlobal("fetch", mocks.fetch);
+ mocks.fetch.mockResolvedValue(new Response(JSON.stringify({ features: [{ center: [-3.701219, 40.421345] }] })));
+});
+
+afterEach(() => {
+ cleanup();
+ client.clear();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function showSidebar(location: Pick<UserInfo, "country" | "region" | "city">, resolveRegion = getRegionName) {
+ return render(
+ <QueryClientProvider client={client}>
+ <UserSidebar
+ data={location as UserInfo}
+ isLoading={false}
+ sessionCount={[]}
+ isLoadingCalendar={false}
+ getRegionName={resolveRegion}
+ />
+ </QueryClientProvider>
+ );
+}
+
+async function geocodingRequest() {
+ await waitFor(() => expect(mocks.fetch).toHaveBeenCalledOnce());
+ const url = new URL(String(mocks.fetch.mock.calls[0][0]));
+ const query = decodeURIComponent(
+ url.pathname
+ .split("/")
+ .at(-1)!
+ .replace(/\.json$/, "")
+ );
+ return { url, query };
+}
+
+describe("user location geocoding", () => {
+ it.each([
+ {
+ country: "ES",
+ region: "ES-MD",
+ city: "Madrid",
+ query: "Madrid, Madrid, Comunidad de, Spain",
+ },
+ {
+ country: "AU",
+ region: "AU-WA",
+ city: "Perth",
+ query: "Perth, Western Australia, Australia",
+ },
+ ])("resolves region names and restricts $city to its country", async ({ country, region, city, query }) => {
+ showSidebar({ country, region, city });
+
+ const request = await geocodingRequest();
+ expect(request.query).toBe(query);
+ expect(request.url.searchParams.get("country")).toBe(country.toLowerCase());
+ });
+
+ it.each(["", "ES-UNKNOWN", "ES-MD"])("omits an unavailable region name (%s)", async region => {
+ showSidebar({ country: "ES", region, city: "Madrid" }, () => "");
+
+ const { url, query } = await geocodingRequest();
+ expect(query).toBe("Madrid, Spain");
+ expect(url.searchParams.get("country")).toBe("es");
+ });
+
+ it("can locate a user when only the country is known", async () => {
+ showSidebar({ country: "ES", region: "", city: "" });
+
+ const { url, query } = await geocodingRequest();
+ expect(query).toBe("Spain");
+ expect(url.searchParams.get("country")).toBe("es");
+ });
+
+ it("positions the map and marker at the geocoded coordinates", async () => {
+ showSidebar({ country: "ES", region: "ES-MD", city: "Madrid" });
+
+ await waitFor(() => expect(mocks.setLngLat).toHaveBeenCalledWith([-3.701219, 40.421345]));
+ expect(mocks.map).toHaveBeenCalledWith(expect.objectContaining({ center: [-3.701219, 40.421345] }));
+ });
+
+ it("leaves the map hidden when there is no match in the country", async () => {
+ mocks.fetch.mockResolvedValue(new Response(JSON.stringify({ features: [] })));
+ const { container } = render(
+ <QueryClientProvider client={client}>
+ <UserLocationMap country="ES" region="" city="Unknown city" />
+ </QueryClientProvider>
+ );
+
+ const { url } = await geocodingRequest();
+ expect(url.searchParams.get("country")).toBe("es");
+ await waitFor(() => expect(container.innerHTML).toBe(""));
+ expect(mocks.map).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx b/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
index 193162739..bc5a08c49 100644
--- a/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
@@ -5,7 +5,7 @@ import "mapbox-gl/dist/mapbox-gl.css";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { useTheme } from "next-themes";
-import { cn } from "../../../../../lib/utils";
+import { cn, getCountryName } from "../../../../../lib/utils";
import { Skeleton } from "../../../../../components/ui/skeleton";
import { useConfigs } from "../../../../../lib/configs";
@@ -23,13 +23,13 @@ export function UserLocationMap({ country, region, city, className }: UserLocati
const { configs } = useConfigs();
const { resolvedTheme } = useTheme();
- const query = [city, region, country].filter(Boolean).join(", ");
+ const query = [city, region, getCountryName(country)].filter(Boolean).join(", ");
const style = resolvedTheme === "dark" ? "mapbox://styles/mapbox/dark-v11" : "mapbox://styles/mapbox/light-v11";
const { data: coordinates, isLoading } = useQuery({
- queryKey: ["user-location-geocode", configs?.mapboxToken, query],
- queryFn: () => geocodeUserLocation(configs!.mapboxToken, query),
+ queryKey: ["user-location-geocode", configs?.mapboxToken, query, country],
+ queryFn: () => geocodeUserLocation(configs!.mapboxToken, query, country),
enabled: Boolean(configs?.mapboxToken && query),
staleTime: 24 * 60 * 60 * 1000,
retry: false,
@@ -99,13 +99,15 @@ interface MapboxGeocodingResponse {
}>;
}
-async function geocodeUserLocation(token: string, query: string): Promise<[number, number] | null> {
+async function geocodeUserLocation(token: string, query: string, country: string): Promise<[number, number] | null> {
try {
const params = new URLSearchParams({
access_token: token,
limit: "1",
});
+ if (country) params.set("country", country.toLowerCase());
+
const response = await fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(query)}.json?${params}`
);
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index 79b91194e..3a77f08f3 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -125,7 +125,7 @@ export function UserSidebar({ data, isLoading, sessionCount, isLoadingCalendar,
{showMap && data && !isLoading && (
<UserLocationMap
country={data.country}
- region={data.region}
+ region={getRegionName(data.region)}
city={data.city}
className="mb-3 h-[132px]"
/>