Skip to content

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

Alternate maps (#629)

Bill Yange24e71e1a5f7
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 1321a4496..8bc639f8a 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -1,51 +1,13 @@
{
"permissions": {
"allow": [
- "Bash(mkdir:*)",
- "Bash(grep:*)",
- "Bash(npm install)",
- "Bash(npm install:*)",
- "Bash(npm run build:analytics:*)",
- "Bash(ls:*)",
- "Bash(npm test:*)",
- "Bash(node:*)",
- "Bash(rm:*)",
- "Bash(tsc --noEmit)",
- "Bash(npx tsc:*)",
- "Bash(npm run build:*)",
- "Bash(npm run:*)",
- "Bash(mv:*)",
- "Bash(chmod:*)",
- "Bash(rg:*)",
- "Bash(sed:*)",
- "Bash(cat:*)",
- "Bash(find:*)",
- "Bash(clickhouse-client:*)",
- "Bash(curl:*)",
- "Bash(npm uninstall:*)",
- "Bash(pkill:*)",
- "Bash(psql:*)",
- "Bash(source .env)",
- "Bash(POSTGRES_PASSWORD=carbink node src/test-pgboss.js)",
- "Bash(tsc)",
- "Bash(touch:*)",
- "Bash(npm init:*)",
- "Bash(cp:*)",
- "Bash(-print)",
- "Bash(python3:*)",
- "WebFetch(domain:github.com)",
- "WebFetch(domain:plausible.io)",
- "WebFetch(domain:www.simpleanalytics.com)",
- "WebFetch(domain:usefathom.com)",
- "WebSearch",
- "WebFetch(domain:umami.is)",
- "WebFetch(domain:posthog.com)",
- "WebFetch(domain:rybbit.io)",
- "WebFetch(domain:docs.mapbox.com)",
- "WebFetch(domain:www.onyx.app)",
- "WebFetch(domain:docs.onyx.app)",
- "Bash(awk:*)"
- ]
+ "Bash(do sed -i '' 's|from \"\"../../../../../|from \"\"../../../../../../|g' \"$file\")",
+ "Bash(do sed -i '' 's|from \"\"../../utils/|from \"\"../../../utils/|g' \"$file\")",
+ "Bash([ -d hooks ])",
+ "WebFetch(domain:carto.com)"
+ ],
+ "deny": [],
+ "ask": []
},
"enableAllProjectMcpServers": false
}
diff --git a/client/package-lock.json b/client/package-lock.json
index e2cb968f6..a25e7355c 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -53,19 +53,18 @@
"ip-address": "^10.0.1",
"jotai": "2.12.4",
"ldrs": "1.1.7",
- "leaflet": "1.9.4",
"lodash": "4.17.21",
"lucide-react": "0.510.0",
"luxon": "3.6.1",
"mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
+ "ol": "^10.6.1",
"react": "19.1.0",
"react-day-picker": "^8.10.1",
"react-dom": "19.1.0",
"react-globe.gl": "2.33.2",
"react-hook-form": "7.56.3",
- "react-leaflet": "5.0.0",
"react-scan": "^0.3.4",
"react-select": "5.10.1",
"rrweb": "^2.0.0-alpha.11",
@@ -81,7 +80,6 @@
"devDependencies": {
"@types/d3": "7.4.3",
"@types/geojson": "7946.0.16",
- "@types/leaflet": "1.9.17",
"@types/lodash": "4.17.16",
"@types/luxon": "3.6.2",
"@types/mapbox-gl": "^3.4.1",
@@ -2714,6 +2712,12 @@
"tslib": "^2.8.1"
}
},
+ "node_modules/@petamoriken/float16": {
+ "version": "3.9.3",
+ "resolved": "https://registry.npmjs.org/@petamoriken/float16/-/float16-3.9.3.tgz",
+ "integrity": "sha512-8awtpHXCx/bNpFt4mt2xdkgtgVvKqty8VbjHI/WWWQuEw+KLzFot3f4+LkQY9YmOtq7A5GdOnqoIC8Pdygjk2g==",
+ "license": "MIT"
+ },
"node_modules/@pivanov/utils": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/@pivanov/utils/-/utils-0.0.2.tgz",
@@ -5956,17 +5960,6 @@
}
}
},
- "node_modules/@react-leaflet/core": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz",
- "integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==",
- "license": "Hippocratic-2.1",
- "peerDependencies": {
- "leaflet": "^1.9.0",
- "react": "^19.0.0",
- "react-dom": "^19.0.0"
- }
- },
"node_modules/@react-spring/rafz": {
"version": "9.7.5",
"resolved": "https://registry.npmjs.org/@react-spring/rafz/-/rafz-9.7.5.tgz",
@@ -6560,16 +6553,6 @@
"@types/geojson": "*"
}
},
- "node_modules/@types/leaflet": {
- "version": "1.9.17",
- "resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.17.tgz",
- "integrity": "sha512-IJ4K6t7I3Fh5qXbQ1uwL3CFVbCi6haW9+53oLWgdKlLP7EaS21byWFJxxqOx9y8I0AP0actXSJLVMbyvxhkUTA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/geojson": "*"
- }
- },
"node_modules/@types/lodash": {
"version": "4.17.16",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.16.tgz",
@@ -6621,6 +6604,12 @@
"integrity": "sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA==",
"license": "MIT"
},
+ "node_modules/@types/rbush": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@types/rbush/-/rbush-4.0.0.tgz",
+ "integrity": "sha512-+N+2H39P8X+Hy1I5mC6awlTX54k3FhiUmvt7HWzGJZvF+syUAAxP/stwppS8JE84YHqFgRMv6fCy31202CMFxQ==",
+ "license": "MIT"
+ },
"node_modules/@types/react": {
"version": "19.1.4",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.4.tgz",
@@ -8230,6 +8219,25 @@
"integrity": "sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A==",
"license": "ISC"
},
+ "node_modules/geotiff": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/geotiff/-/geotiff-2.1.3.tgz",
+ "integrity": "sha512-PT6uoF5a1+kbC3tHmZSUsLHBp2QJlHasxxxxPW47QIY1VBKpFB+FcDvX+MxER6UzgLQZ0xDzJ9s48B9JbOCTqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@petamoriken/float16": "^3.4.7",
+ "lerc": "^3.0.0",
+ "pako": "^2.0.4",
+ "parse-headers": "^2.0.2",
+ "quick-lru": "^6.1.1",
+ "web-worker": "^1.2.0",
+ "xml-utils": "^1.0.2",
+ "zstddec": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10.19"
+ }
+ },
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -8764,11 +8772,11 @@
"integrity": "sha512-rZnfveeY1SeS3F3ifUVd9AVGTFHmQ0qzp5fuszAirnrVkjqJBLrm99vtr/Mxbby4XgadUYv+DsFqyk2p4FV40Q==",
"license": "MIT"
},
- "node_modules/leaflet": {
- "version": "1.9.4",
- "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
- "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
- "license": "BSD-2-Clause"
+ "node_modules/lerc": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/lerc/-/lerc-3.0.0.tgz",
+ "integrity": "sha512-Rm4J/WaHhRa93nCN2mwWDZFoRVF18G1f47C+kvQWyHGEZxFpTUi73p7lMVSAndyxGt6lJ2/CFbOcf9ra5p8aww==",
+ "license": "Apache-2.0"
},
"node_modules/lilconfig": {
"version": "2.1.0",
@@ -9200,6 +9208,23 @@
"node": ">= 6"
}
},
+ "node_modules/ol": {
+ "version": "10.6.1",
+ "resolved": "https://registry.npmjs.org/ol/-/ol-10.6.1.tgz",
+ "integrity": "sha512-xp174YOwPeLj7c7/8TCIEHQ4d41tgTDDhdv6SqNdySsql5/MaFJEJkjlsYcvOPt7xA6vrum/QG4UdJ0iCGT1cg==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@types/rbush": "4.0.0",
+ "earcut": "^3.0.0",
+ "geotiff": "^2.1.3",
+ "pbf": "4.0.1",
+ "rbush": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/openlayers"
+ }
+ },
"node_modules/oxc-resolver": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/oxc-resolver/-/oxc-resolver-11.2.0.tgz",
@@ -9231,6 +9256,12 @@
"dev": true,
"license": "BlueOak-1.0.0"
},
+ "node_modules/pako": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
+ "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -9243,6 +9274,12 @@
"node": ">=6"
}
},
+ "node_modules/parse-headers": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.6.tgz",
+ "integrity": "sha512-Tz11t3uKztEW5FEVZnj1ox8GKblWn+PvHY9TmJV5Mll2uHEwRdR/5Li1OlXoECjLYkApdhWy44ocONwXLiKO5A==",
+ "license": "MIT"
+ },
"node_modules/parse-json": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
@@ -9622,6 +9659,18 @@
],
"license": "MIT"
},
+ "node_modules/quick-lru": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-6.1.2.tgz",
+ "integrity": "sha512-AAFUA5O1d83pIHEhJwWCq/RQcRukCkn/NSm2QsTEMle5f2hP0ChI2+3Xb051PZCkLryI/Ir1MVKviT2FIloaTQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/quickselect": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
@@ -10354,6 +10403,15 @@
}
}
},
+ "node_modules/rbush": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/rbush/-/rbush-4.0.1.tgz",
+ "integrity": "sha512-IP0UpfeWQujYC8Jg162rMNc01Rf0gWMMAb2Uxus/Q0qOFw4lCcq6ZnQEZwUoJqWyUGJ9th7JjwI4yIWo+uvoAQ==",
+ "license": "MIT",
+ "dependencies": {
+ "quickselect": "^3.0.0"
+ }
+ },
"node_modules/react": {
"version": "19.1.0",
"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz",
@@ -10448,20 +10506,6 @@
"react": ">=16.13.1"
}
},
- "node_modules/react-leaflet": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
- "integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==",
- "license": "Hippocratic-2.1",
- "dependencies": {
- "@react-leaflet/core": "^3.0.0"
- },
- "peerDependencies": {
- "leaflet": "^1.9.0",
- "react": "^19.0.0",
- "react-dom": "^19.0.0"
- }
- },
"node_modules/react-remove-scroll": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.6.3.tgz",
@@ -11660,6 +11704,12 @@
"node": "20 || >=22"
}
},
+ "node_modules/web-worker": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz",
+ "integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",
+ "license": "Apache-2.0"
+ },
"node_modules/webpack-virtual-modules": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
@@ -11786,6 +11836,12 @@
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
+ "node_modules/xml-utils": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/xml-utils/-/xml-utils-1.10.2.tgz",
+ "integrity": "sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==",
+ "license": "CC0-1.0"
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
@@ -11821,6 +11877,12 @@
"zod": "^3.24.4"
}
},
+ "node_modules/zstddec": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/zstddec/-/zstddec-0.1.0.tgz",
+ "integrity": "sha512-w2NTI8+3l3eeltKAdK8QpiLo/flRAr2p8AGeakfMZOXBxOg9HIu4LVDxBi81sYgVhFhdJjv1OrB5ssI8uFPoLg==",
+ "license": "MIT AND BSD-3-Clause"
+ },
"node_modules/zustand": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.4.tgz",
diff --git a/client/package.json b/client/package.json
index b64b31207..b737d9826 100644
--- a/client/package.json
+++ b/client/package.json
@@ -57,19 +57,18 @@
"ip-address": "^10.0.1",
"jotai": "2.12.4",
"ldrs": "1.1.7",
- "leaflet": "1.9.4",
"lodash": "4.17.21",
"lucide-react": "0.510.0",
"luxon": "3.6.1",
"mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
+ "ol": "^10.6.1",
"react": "19.1.0",
"react-day-picker": "^8.10.1",
"react-dom": "19.1.0",
"react-globe.gl": "2.33.2",
"react-hook-form": "7.56.3",
- "react-leaflet": "5.0.0",
"react-scan": "^0.3.4",
"react-select": "5.10.1",
"rrweb": "^2.0.0-alpha.11",
@@ -85,7 +84,6 @@
"devDependencies": {
"@types/d3": "7.4.3",
"@types/geojson": "7946.0.16",
- "@types/leaflet": "1.9.17",
"@types/lodash": "4.17.16",
"@types/luxon": "3.6.2",
"@types/mapbox-gl": "^3.4.1",
diff --git a/client/src/app/[site]/components/shared/Map.tsx b/client/src/app/[site]/components/shared/Map.tsx
deleted file mode 100644
index 559dd8c3c..000000000
--- a/client/src/app/[site]/components/shared/Map.tsx
+++ /dev/null
@@ -1,320 +0,0 @@
-"use client";
-
-import { FilterParameter } from "@rybbit/shared";
-import { useSingleCol } from "@/api/analytics/useSingleCol";
-import { useMeasure } from "@uidotdev/usehooks";
-import { scalePow } from "d3-scale";
-import { Feature, GeoJsonObject } from "geojson";
-import { Layer } from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { round } from "lodash";
-import { useEffect, useMemo, useState } from "react";
-import { GeoJSON, MapContainer, useMapEvent } from "react-leaflet";
-import { getCountryPopulation } from "../../../../lib/countryPopulation";
-import { useCountries, useSubdivisions } from "../../../../lib/geo";
-import { addFilter } from "../../../../lib/store";
-import { CountryFlag } from "./icons/CountryFlag";
-
-interface TooltipContent {
- name: string;
- code: string;
- count: number;
- percentage: number;
- perCapita?: number; // Visits per million people
-}
-
-interface TooltipPosition {
- x: number;
- y: number;
-}
-
-export function MapComponent({
- height,
- mode = "total",
- mapView: controlledMapView,
-}: {
- height: string;
- mode?: "total" | "perCapita";
- mapView?: "countries" | "subdivisions";
-}) {
- const {
- data: countryData,
- isLoading: isCountryLoading,
- isFetching: isCountryFetching,
- } = useSingleCol({
- parameter: "country",
- });
- const {
- data: subdivisionData,
- isLoading: isSubdivisionLoading,
- isFetching: isSubdivisionFetching,
- } = useSingleCol({
- parameter: "region",
- limit: 10000,
- });
-
- const [dataVersion, setDataVersion] = useState<number>(0);
-
- useEffect(() => {
- if (countryData || subdivisionData) {
- setDataVersion(prev => prev + 1);
- }
- }, [countryData, subdivisionData]);
-
- const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(null);
- const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({
- x: 0,
- y: 0,
- });
- const [internalMapView, setInternalMapView] = useState<"countries" | "subdivisions">("countries");
-
- // Use controlled value if provided, otherwise use internal state
- const mapView = controlledMapView ?? internalMapView;
-
- // Track which feature is currently hovered to control opacity without conflicts
- const [hoveredId, setHoveredId] = useState<string | null>(null);
-
- // Process data to include per capita metrics
- const processedCountryData = useMemo(() => {
- if (!countryData?.data) return null;
-
- return countryData.data.map((item: any) => {
- const population = getCountryPopulation(item.value);
- const perCapitaValue = population > 0 ? item.count / population : 0;
- return {
- ...item,
- perCapita: perCapitaValue,
- };
- });
- }, [countryData?.data]);
-
- const processedSubdivisionData = useMemo(() => {
- if (!subdivisionData?.data) return null;
-
- return subdivisionData.data.map((item: any) => {
- // For subdivisions, we'll use the country code from the beginning of the iso_3166_2 code
- const countryCode = item.value?.split("-")[0];
- const population = getCountryPopulation(countryCode);
- // For subdivisions, we divide by 10x the population since regions are smaller
- const perCapitaValue = population > 0 ? item.count / (population / 10) : 0;
- return {
- ...item,
- perCapita: perCapitaValue,
- };
- });
- }, [subdivisionData?.data]);
-
- const colorScale = useMemo(() => {
- if (mapView === "countries" && !processedCountryData) return () => "#eee";
- if (mapView === "subdivisions" && !processedSubdivisionData) return () => "#eee";
-
- const dataToUse = mapView === "countries" ? processedCountryData : processedSubdivisionData;
-
- // Get computed values from CSS variables
- const getComputedColor = (cssVar: string) => {
- // Get the HSL values from CSS
- const hslValues = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
- return `hsl(${hslValues})`;
- };
-
- // Get only the accent-500 color
- const accentColor = getComputedColor("--accent-400");
-
- // Parse the HSL values to extract h, s, l components
- const hslMatch = accentColor.match(/hsl\(([^)]+)\)/);
- const hslValues = hslMatch ? hslMatch[1].split(" ") : ["0", "0%", "50%"];
- const [h, s, l] = hslValues;
-
- // Get the range of values
- const metricToUse = mode === "perCapita" ? "perCapita" : "count";
- const values = dataToUse?.map((d: any) => d[metricToUse]) || [0];
- const maxValue = Math.max(...values);
-
- // Use a power scale with exponent 0.4 (between linear=1.0 and logarithmic)
- // This makes it somewhat logarithmic but not as extreme
- return scalePow<string>()
- .exponent(0.4) // Adjust this value between 0.1-0.5 to control logarithmic effect
- .domain([0, maxValue])
- .range([`hsla(${h}, ${s}, ${l}, 0.05)`, `hsla(${h}, ${s}, ${l}, 0.8)`]);
- }, [processedCountryData, processedSubdivisionData, mapView, mode]);
-
- const { data: subdivisionsGeoData } = useSubdivisions();
- const { data: countriesGeoData } = useCountries();
-
- const handleStyle = (feature: Feature | undefined) => {
- const borderColors = ["#377eb8", "#ff7f00", "#4daf4a", "#1abc9c", "#984ea3"];
- const isCountryView = mapView === "countries";
- const dataKey = isCountryView ? feature?.properties?.["ISO_A2"] : feature?.properties?.["iso_3166_2"];
- const borderKey = isCountryView ? feature?.properties?.["BORDER"] : feature?.properties?.["border"];
-
- // Use the processed data that includes per capita metrics
- const dataToUse = isCountryView ? processedCountryData : processedSubdivisionData;
-
- const foundData = dataToUse?.find(({ value }: any) => value === dataKey);
-
- // Use count or per capita value based on mode
- const metricValue = mode === "perCapita" ? foundData?.perCapita || 0 : foundData?.count || 0;
-
- const color = metricValue > 0 ? colorScale(metricValue) : "rgba(140, 140, 140, 0.5)";
-
- return {
- color: color,
- weight: 1,
- fill: true,
- fillColor: color,
- // Increase opacity if this feature is currently hovered
- fillOpacity: hoveredId === dataKey?.toString() ? 0.8 : 0.5,
- };
- };
-
- const handleEachFeature = (feature: Feature, layer: Layer) => {
- layer.on({
- mouseover: () => {
- const isCountryView = mapView === "countries";
- const code = isCountryView ? feature.properties?.["ISO_A2"] : feature.properties?.["iso_3166_2"];
-
- // Mark this feature as hovered so handleStyle increases opacity
- setHoveredId(code);
-
- const name = isCountryView ? feature.properties?.["ADMIN"] : feature.properties?.["name"];
-
- // Use the processed data that includes per capita metrics
- const dataToUse = isCountryView ? processedCountryData : processedSubdivisionData;
-
- const foundData = dataToUse?.find(({ value }: any) => value === code);
- const count = foundData?.count || 0;
- const percentage = foundData?.percentage || 0;
- const perCapita = foundData?.perCapita || 0;
-
- setTooltipContent({
- name,
- code,
- count,
- percentage,
- perCapita,
- });
- },
- mouseout: () => {
- // Clear hover state
- setHoveredId(null);
- setTooltipContent(null);
- },
- click: () => {
- const isCountryView = mapView === "countries";
- const code = isCountryView ? feature.properties?.["ISO_A2"] : feature.properties?.["iso_3166_2"];
-
- // Set filter based on the current map view
- const filterParameter: FilterParameter = isCountryView ? "country" : "region";
-
- addFilter({
- parameter: filterParameter,
- value: [code],
- type: "equals",
- });
- },
- });
- };
-
- const MapEventHandler = () => {
- const map = useMapEvent("zoomend", () => {
- const newMapView = map.getZoom() >= 5 ? "subdivisions" : "countries";
- if (newMapView !== mapView) {
- setInternalMapView(newMapView);
- setTooltipContent(null);
- }
- });
- return null;
- };
-
- const isLoading = isCountryLoading || isSubdivisionLoading || isCountryFetching || isSubdivisionFetching;
-
- const [ref, { height: resolvedHeight }] = useMeasure();
-
- const zoom = resolvedHeight ? Math.log2(resolvedHeight / 400) + 1 : 1;
-
- return (
- <div
- onMouseMove={e => {
- if (tooltipContent) {
- setTooltipPosition({
- x: e.clientX,
- y: e.clientY,
- });
- }
- }}
- style={{
- height: height,
- }}
- ref={ref}
- >
- {isLoading && (
- <div className="absolute inset-0 bg-neutral-900/30 backdrop-blur-sm z-10 flex items-center justify-center">
- <div className="flex flex-col items-center gap-2">
- <div className="h-8 w-8 rounded-full border-2 border-accent-400 border-t-transparent animate-spin"></div>
- <span className="text-sm text-neutral-300">Loading map data...</span>
- </div>
- </div>
- )}
- {(countriesGeoData || subdivisionsGeoData) && (
- <MapContainer
- preferCanvas={true}
- attributionControl={false}
- zoomControl={false}
- center={[40, 3]}
- zoom={zoom}
- style={{
- // height: height,
- height: "100%",
- background: "none",
- cursor: "default",
- outline: "none",
- zIndex: "1",
- }}
- >
- <MapEventHandler />
- {mapView === "subdivisions" && subdivisionsGeoData && (
- <GeoJSON
- key={`subdivisions-${dataVersion}-${mode}`}
- data={subdivisionsGeoData as GeoJsonObject}
- style={handleStyle}
- onEachFeature={handleEachFeature}
- />
- )}
- {mapView === "countries" && countriesGeoData && (
- <GeoJSON
- key={`countries-${dataVersion}-${mode}`}
- data={countriesGeoData as GeoJsonObject}
- style={handleStyle}
- onEachFeature={handleEachFeature}
- />
- )}
- </MapContainer>
- )}
- {tooltipContent && (
- <div
- className="fixed z-50 bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
- style={{
- left: tooltipPosition.x,
- top: tooltipPosition.y - 10,
- transform: "translate(-50%, -100%)",
- }}
- >
- <div className="font-sm flex items-center gap-1">
- {tooltipContent.code && <CountryFlag country={tooltipContent.code.slice(0, 2)} />}
- {tooltipContent.name}
- </div>
- <div>
- <span className="font-bold text-accent-400">{tooltipContent.count.toLocaleString()}</span>{" "}
- <span className="text-neutral-300">({tooltipContent.percentage.toFixed(1)}%) sessions</span>
- </div>
- {mode === "perCapita" && mapView === "countries" && (
- <div className="text-sm text-neutral-300">
- <span className="font-bold text-accent-400">{round(tooltipContent.perCapita ?? 0, 2)}</span> per million
- people
- </div>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/app/[site]/components/shared/Map/MapComponent.tsx b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
new file mode 100644
index 000000000..1b1984b84
--- /dev/null
+++ b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
@@ -0,0 +1,129 @@
+"use client";
+
+import { useMeasure } from "@uidotdev/usehooks";
+import "ol/ol.css";
+import { useEffect, useState } from "react";
+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";
+import { useCountries, useSubdivisions } from "../../../../../lib/geo";
+import { CountryFlag } from "../icons/CountryFlag";
+import { useMapInstance } from "./hooks/useMapInstance";
+import { useMapLayers } from "./hooks/useMapLayers";
+import { useMapStyles } from "./hooks/useMapStyles";
+import type { MapComponentProps, TooltipContent, TooltipPosition } from "./types";
+
+export function MapComponent({ height, mapView: controlledMapView }: MapComponentProps) {
+ const {
+ data: countryData,
+ isLoading: isCountryLoading,
+ isFetching: isCountryFetching,
+ } = useSingleCol({
+ parameter: "country",
+ });
+
+ const {
+ data: subdivisionData,
+ isLoading: isSubdivisionLoading,
+ isFetching: isSubdivisionFetching,
+ } = useSingleCol({
+ parameter: "region",
+ limit: 10000,
+ });
+
+ const [dataVersion, setDataVersion] = useState<number>(0);
+
+ useEffect(() => {
+ if (countryData || subdivisionData) {
+ setDataVersion(prev => prev + 1);
+ }
+ }, [countryData, subdivisionData]);
+
+ const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(null);
+ const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({
+ x: 0,
+ y: 0,
+ });
+ const [internalMapView, setInternalMapView] = useState<"countries" | "subdivisions">("countries");
+
+ const mapView = controlledMapView ?? internalMapView;
+ const [hoveredId, setHoveredId] = useState<string | null>(null);
+
+ const { colorScale } = useMapStyles(mapView, countryData?.data ?? null, subdivisionData?.data ?? null);
+
+ const { data: subdivisionsGeoData } = useSubdivisions();
+ const { data: countriesGeoData } = useCountries();
+
+ const [ref, { height: resolvedHeight }] = useMeasure();
+ const zoom = resolvedHeight ? Math.log2(resolvedHeight / 400) + 1 : 1;
+
+ const { mapRef, mapInstanceRef, mapViewRef } = useMapInstance({
+ mapView,
+ zoom,
+ countryData: countryData?.data ?? null,
+ subdivisionData: subdivisionData?.data ?? null,
+ setInternalMapView,
+ setTooltipContent,
+ setTooltipPosition,
+ setHoveredId,
+ });
+
+ useMapLayers({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ countriesGeoData,
+ subdivisionsGeoData,
+ countryData: countryData?.data ?? null,
+ subdivisionData: subdivisionData?.data ?? null,
+ dataVersion,
+ colorScale,
+ hoveredId,
+ });
+
+ return (
+ <div
+ style={{
+ height: height,
+ }}
+ ref={ref}
+ >
+ {isCountryLoading ||
+ (isSubdivisionLoading && (
+ <div className="absolute inset-0 bg-neutral-900/30 backdrop-blur-sm z-10 flex items-center justify-center">
+ <div className="flex flex-col items-center gap-2">
+ <div className="h-8 w-8 rounded-full border-2 border-accent-400 border-t-transparent animate-spin"></div>
+ <span className="text-sm text-neutral-300">Loading map data...</span>
+ </div>
+ </div>
+ ))}
+ <div
+ ref={mapRef}
+ style={{
+ height: "100%",
+ width: "100%",
+ background: "none",
+ cursor: "default",
+ outline: "none",
+ }}
+ />
+ {tooltipContent && (
+ <div
+ className="fixed z-50 bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
+ style={{
+ left: tooltipPosition.x,
+ top: tooltipPosition.y - 10,
+ transform: "translate(-50%, -100%)",
+ }}
+ >
+ <div className="font-sm flex items-center gap-1">
+ {tooltipContent.code && <CountryFlag country={tooltipContent.code.slice(0, 2)} />}
+ {tooltipContent.name}
+ </div>
+ <div>
+ <span className="font-bold text-accent-400">{tooltipContent.count.toLocaleString()}</span>{" "}
+ <span className="text-neutral-300">({tooltipContent.percentage.toFixed(1)}%) sessions</span>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/components/shared/Map/hooks/useMapInstance.ts b/client/src/app/[site]/components/shared/Map/hooks/useMapInstance.ts
new file mode 100644
index 000000000..8700bb967
--- /dev/null
+++ b/client/src/app/[site]/components/shared/Map/hooks/useMapInstance.ts
@@ -0,0 +1,139 @@
+import { FilterParameter } from "@rybbit/shared";
+import Map from "ol/Map";
+import View from "ol/View";
+import { fromLonLat } from "ol/proj";
+import { useEffect, useRef } from "react";
+import { addFilter } from "../../../../../../lib/store";
+import type { ProcessedData, TooltipContent } from "../types";
+
+interface UseMapInstanceParams {
+ mapView: "countries" | "subdivisions";
+ zoom: number;
+ countryData: ProcessedData[] | null;
+ subdivisionData: ProcessedData[] | null;
+ setInternalMapView: (view: "countries" | "subdivisions") => void;
+ setTooltipContent: (content: TooltipContent | null) => void;
+ setTooltipPosition: (pos: { x: number; y: number }) => void;
+ setHoveredId: (id: string | null) => void;
+}
+
+export function useMapInstance({
+ mapView,
+ zoom,
+ countryData,
+ subdivisionData,
+ setInternalMapView,
+ setTooltipContent,
+ setTooltipPosition,
+ setHoveredId,
+}: UseMapInstanceParams) {
+ const mapRef = useRef<HTMLDivElement>(null);
+ const mapInstanceRef = useRef<Map | null>(null);
+ const mapViewRef = useRef<"countries" | "subdivisions">(mapView);
+
+ // Update mapView ref when it changes
+ useEffect(() => {
+ mapViewRef.current = mapView;
+ }, [mapView]);
+
+ // Initialize map
+ useEffect(() => {
+ if (!mapRef.current) return;
+
+ const map = new Map({
+ target: mapRef.current,
+ view: new View({
+ center: fromLonLat([3, 40]),
+ zoom: zoom,
+ }),
+ controls: [],
+ });
+
+ mapInstanceRef.current = map;
+
+ // Handle zoom changes
+ map.getView().on("change:resolution", () => {
+ const currentZoom = map.getView().getZoom() || 1;
+ const newMapView = currentZoom >= 5 ? "subdivisions" : "countries";
+ if (newMapView !== mapViewRef.current) {
+ setInternalMapView(newMapView);
+ setTooltipContent(null);
+ }
+ });
+
+ // Handle pointer move for hover effects
+ map.on("pointermove", evt => {
+ if (evt.dragging) {
+ return;
+ }
+
+ const pixel = map.getEventPixel(evt.originalEvent);
+ const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
+
+ if (feature) {
+ const isCountryView = mapViewRef.current === "countries";
+ const code = isCountryView ? feature.get("ISO_A2") : feature.get("iso_3166_2");
+ const name = isCountryView ? feature.get("ADMIN") : feature.get("name");
+
+ setHoveredId(code);
+
+ const dataToUse = isCountryView ? countryData : subdivisionData;
+ const foundData = dataToUse?.find(({ value }) => value === code);
+ const count = foundData?.count || 0;
+ const percentage = foundData?.percentage || 0;
+
+ setTooltipContent({
+ name,
+ code,
+ count,
+ percentage,
+ });
+
+ // Update tooltip position
+ const [x, y] = evt.pixel;
+ const rect = mapRef.current?.getBoundingClientRect();
+ if (rect) {
+ setTooltipPosition({
+ x: rect.left + x,
+ y: rect.top + y,
+ });
+ }
+ } else {
+ setHoveredId(null);
+ setTooltipContent(null);
+ }
+ });
+
+ // Handle click for filtering
+ map.on("click", evt => {
+ const pixel = map.getEventPixel(evt.originalEvent);
+ const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
+
+ if (feature) {
+ const isCountryView = mapViewRef.current === "countries";
+ const code = isCountryView ? feature.get("ISO_A2") : feature.get("iso_3166_2");
+
+ const filterParameter: FilterParameter = isCountryView ? "country" : "region";
+
+ addFilter({
+ parameter: filterParameter,
+ value: [code],
+ type: "equals",
+ });
+ }
+ });
+
+ return () => {
+ map.setTarget(undefined);
+ };
+ }, []);
+
+ // Update zoom when height changes
+ useEffect(() => {
+ if (mapInstanceRef.current && zoom) {
+ mapInstanceRef.current.getView().setZoom(zoom);
+ }
+ }, [zoom]);
+
+ return { mapRef, mapInstanceRef, mapViewRef };
+}
diff --git a/client/src/app/[site]/components/shared/Map/hooks/useMapLayers.ts b/client/src/app/[site]/components/shared/Map/hooks/useMapLayers.ts
new file mode 100644
index 000000000..529b7d83a
--- /dev/null
+++ b/client/src/app/[site]/components/shared/Map/hooks/useMapLayers.ts
@@ -0,0 +1,115 @@
+import { useEffect, useRef, MutableRefObject } from "react";
+import Map from "ol/Map";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import GeoJSON from "ol/format/GeoJSON";
+import { Style, Fill, Stroke } from "ol/style";
+import type { ProcessedData } from "../types";
+
+interface UseMapLayersParams {
+ mapInstanceRef: MutableRefObject<Map | null>;
+ mapViewRef: MutableRefObject<"countries" | "subdivisions">;
+ mapView: "countries" | "subdivisions";
+ countriesGeoData: any;
+ subdivisionsGeoData: any;
+ countryData: ProcessedData[] | null;
+ subdivisionData: ProcessedData[] | null;
+ dataVersion: number;
+ colorScale: (value: number) => string;
+ hoveredId: string | null;
+}
+
+export function useMapLayers({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ countriesGeoData,
+ subdivisionsGeoData,
+ countryData,
+ subdivisionData,
+ dataVersion,
+ colorScale,
+ hoveredId,
+}: UseMapLayersParams) {
+ const vectorLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
+
+ // Update vector layer when geo data or map view changes
+ useEffect(() => {
+ if (!mapInstanceRef.current) return;
+
+ const geoData = mapView === "countries" ? countriesGeoData : subdivisionsGeoData;
+ if (!geoData) return;
+
+ // Wait for data to be available
+ const dataToCheck = mapView === "countries" ? countryData : subdivisionData;
+ if (!dataToCheck) return;
+
+ // Remove existing layer
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ }
+
+ // Create new vector source with GeoJSON data
+ const vectorSource = new VectorSource({
+ features: new GeoJSON().readFeatures(geoData, {
+ featureProjection: "EPSG:3857",
+ }),
+ });
+
+ // Create new vector layer with a style function
+ const vectorLayer = new VectorLayer({
+ source: vectorSource,
+ style: feature => {
+ const isCountryView = mapViewRef.current === "countries";
+ const dataKey = isCountryView ? feature.get("ISO_A2") : feature.get("iso_3166_2");
+
+ const dataToUse = isCountryView ? countryData : subdivisionData;
+ const foundData = dataToUse?.find(({ value }) => value === dataKey);
+
+ const metricValue = foundData?.count || 0;
+
+ let fillColor: string;
+ let strokeColor: string;
+
+ if (metricValue > 0) {
+ const baseColor = colorScale(metricValue);
+
+ if (hoveredId === dataKey?.toString()) {
+ fillColor = baseColor.replace(/,\s*([\d.]+)\)$/, (match, opacity) => {
+ const newOpacity = Math.min(parseFloat(opacity) + 0.2, 1);
+ return `, ${newOpacity})`;
+ });
+ } else {
+ fillColor = baseColor;
+ }
+ strokeColor = baseColor;
+ } else {
+ fillColor = "rgba(140, 140, 140, 0.3)";
+ strokeColor = "rgba(140, 140, 140, 0.5)";
+ }
+
+ return new Style({
+ fill: new Fill({
+ color: fillColor,
+ }),
+ stroke: new Stroke({
+ color: strokeColor,
+ width: 1,
+ }),
+ });
+ },
+ });
+
+ vectorLayerRef.current = vectorLayer;
+ mapInstanceRef.current.addLayer(vectorLayer);
+ }, [mapView, countriesGeoData, subdivisionsGeoData, dataVersion, colorScale, countryData, subdivisionData]);
+
+ // Update styles when hoveredId changes (without recreating the layer)
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.changed();
+ }
+ }, [hoveredId]);
+
+ return { vectorLayerRef };
+}
diff --git a/client/src/app/[site]/components/shared/Map/hooks/useMapStyles.ts b/client/src/app/[site]/components/shared/Map/hooks/useMapStyles.ts
new file mode 100644
index 000000000..eb33fda24
--- /dev/null
+++ b/client/src/app/[site]/components/shared/Map/hooks/useMapStyles.ts
@@ -0,0 +1,37 @@
+import { useMemo } from "react";
+import { scalePow } from "d3-scale";
+import type { ProcessedData } from "../types";
+
+export function useMapStyles(
+ mapView: "countries" | "subdivisions",
+ countryData: ProcessedData[] | null,
+ subdivisionData: ProcessedData[] | null
+) {
+ const colorScale = useMemo(() => {
+ if (mapView === "countries" && !countryData) return () => "#eee";
+ if (mapView === "subdivisions" && !subdivisionData) return () => "#eee";
+
+ const dataToUse = mapView === "countries" ? countryData : subdivisionData;
+
+ const getComputedColor = (cssVar: string) => {
+ const hslValues = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
+ return `hsl(${hslValues})`;
+ };
+
+ const accentColor = getComputedColor("--accent-400");
+
+ const hslMatch = accentColor.match(/hsl\(([^)]+)\)/);
+ const hslValues = hslMatch ? hslMatch[1].split(" ") : ["0", "0%", "50%"];
+ const [h, s, l] = hslValues;
+
+ const values = dataToUse?.map((d: any) => d.count) || [0];
+ const maxValue = Math.max(...values);
+
+ return scalePow<string>()
+ .exponent(0.4)
+ .domain([0, maxValue])
+ .range([`hsla(${h}, ${s}, ${l}, 0.05)`, `hsla(${h}, ${s}, ${l}, 0.8)`]);
+ }, [countryData, subdivisionData, mapView]);
+
+ return { colorScale };
+}
diff --git a/client/src/app/[site]/components/shared/Map/types.ts b/client/src/app/[site]/components/shared/Map/types.ts
new file mode 100644
index 000000000..ada1f5300
--- /dev/null
+++ b/client/src/app/[site]/components/shared/Map/types.ts
@@ -0,0 +1,22 @@
+export interface TooltipContent {
+ name: string;
+ code: string;
+ count: number;
+ percentage: number;
+}
+
+export interface TooltipPosition {
+ x: number;
+ y: number;
+}
+
+export interface MapComponentProps {
+ height: string;
+ mapView?: "countries" | "subdivisions";
+}
+
+export interface ProcessedData {
+ value: string;
+ count: number;
+ percentage: number;
+}
diff --git a/client/src/app/[site]/globe/2d/components/OpenLayersMap.tsx b/client/src/app/[site]/globe/2d/components/OpenLayersMap.tsx
new file mode 100644
index 000000000..6d688ada8
--- /dev/null
+++ b/client/src/app/[site]/globe/2d/components/OpenLayersMap.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import { useRef, useEffect } from "react";
+import Map from "ol/Map";
+import View from "ol/View";
+import TileLayer from "ol/layer/Tile";
+import XYZ from "ol/source/XYZ";
+import { fromLonLat } from "ol/proj";
+import "ol/ol.css";
+import { useOpenLayersCountriesLayer } from "../hooks/useOpenLayersCountriesLayer";
+import { useOpenLayersSubdivisionsLayer } from "../hooks/useOpenLayersSubdivisionsLayer";
+import { useOpenLayersCoordinatesLayer } from "../hooks/useOpenLayersCoordinatesLayer";
+import { useOpenLayersTimelineLayer } from "../hooks/useOpenLayersTimelineLayer";
+
+interface OpenLayersMapProps {
+ mapView: "countries" | "subdivisions" | "coordinates" | "timeline";
+ onSessionSelect?: (session: any) => void;
+}
+
+export function OpenLayersMap({ mapView, onSessionSelect }: OpenLayersMapProps) {
+ const mapRef = useRef<HTMLDivElement>(null);
+ const mapInstanceRef = useRef<Map | null>(null);
+ const mapViewRef = useRef<typeof mapView>(mapView);
+
+ // Update mapView ref when it changes
+ useEffect(() => {
+ mapViewRef.current = mapView;
+ }, [mapView]);
+
+ // Initialize map
+ useEffect(() => {
+ if (!mapRef.current || mapInstanceRef.current) return;
+
+ // Create base tile layer with CartoDB Dark Matter (no labels)
+ const baseLayer = new TileLayer({
+ source: new XYZ({
+ url: "https://{a-d}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
+ attributions:
+ '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
+ }),
+ });
+
+ const map = new Map({
+ target: mapRef.current,
+ layers: [baseLayer],
+ view: new View({
+ center: fromLonLat([0, 20]),
+ zoom: 2,
+ minZoom: 1,
+ maxZoom: 18,
+ }),
+ controls: [],
+ });
+
+ mapInstanceRef.current = map;
+
+ return () => {
+ map.setTarget(undefined);
+ mapInstanceRef.current = null;
+ };
+ }, []);
+
+ // Use layer hooks
+ useOpenLayersCountriesLayer({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ });
+
+ useOpenLayersSubdivisionsLayer({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ });
+
+ useOpenLayersCoordinatesLayer({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ });
+
+ const { selectedSession, setSelectedSession } = useOpenLayersTimelineLayer({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+ });
+
+ // Pass selected session to parent
+ useEffect(() => {
+ if (selectedSession && onSessionSelect) {
+ onSessionSelect(selectedSession);
+ setSelectedSession(null);
+ }
+ }, [selectedSession, onSessionSelect, setSelectedSession]);
+
+ return <div ref={mapRef} className="w-full h-full" />;
+}
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
new file mode 100644
index 000000000..ad7a12f1d
--- /dev/null
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
@@ -0,0 +1,280 @@
+import { FilterParameter } from "@rybbit/shared/dist/filters";
+import { round } from "lodash";
+import { useEffect, useRef } from "react";
+import Map from "ol/Map";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import Feature, { FeatureLike } from "ol/Feature";
+import Point from "ol/geom/Point";
+import { Circle, Fill, Stroke, Style } from "ol/style";
+import { fromLonLat } from "ol/proj";
+import { useGetSessionLocations } from "../../../../../api/analytics/useGetSessionLocations";
+import { addFilter, removeFilter, useStore } from "../../../../../lib/store";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
+
+const getSizeMultiplier = (total: number) => {
+ if (total <= 50) return 3; // Large dots
+ if (total <= 200) return 2; // Medium dots
+ if (total <= 500) return 1.5; // Small-medium dots
+ return 1; // Small dots
+};
+
+interface CoordinatesLayerProps {
+ mapInstanceRef: React.RefObject<Map | null>;
+ mapViewRef: React.RefObject<string>;
+ mapView: string;
+}
+
+export function useOpenLayersCoordinatesLayer({ mapInstanceRef, mapViewRef, mapView }: CoordinatesLayerProps) {
+ const { data: liveSessionLocations } = useGetSessionLocations();
+ const vectorLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
+ const filters = useStore(state => state.filters);
+
+ useEffect(() => {
+ const map = mapInstanceRef.current;
+ if (!map || !liveSessionLocations) return;
+
+ const maxCount = liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;
+ const topSize = Math.pow(maxCount, 0.5);
+ const totalLocations = liveSessionLocations.length;
+ const sizeMultiplier = getSizeMultiplier(totalLocations);
+
+ // Get filtered lat/lon from filters
+ const latFilter = filters.find(f => f.parameter === "lat");
+ const lonFilter = filters.find(f => f.parameter === "lon");
+ const filteredLat = latFilter?.value[0];
+ const filteredLon = lonFilter?.value[0];
+
+ // Create features from locations
+ const features = liveSessionLocations.map(location => {
+ const roundedLat = round(location.lat, 4);
+ const roundedLon = round(location.lon, 4);
+
+ const isFiltered =
+ filteredLat !== undefined &&
+ filteredLon !== undefined &&
+ Math.abs(roundedLat - Number(filteredLat)) < 0.00001 &&
+ Math.abs(roundedLon - Number(filteredLon)) < 0.00001;
+
+ const feature = new Feature({
+ geometry: new Point(fromLonLat([roundedLon, roundedLat])),
+ });
+
+ feature.setProperties({
+ count: location.count,
+ city: location.city,
+ country: location.country,
+ isFiltered,
+ lat: roundedLat,
+ lon: roundedLon,
+ });
+
+ return feature;
+ });
+
+ // Create or update vector source
+ const vectorSource = new VectorSource({
+ features,
+ });
+
+ // Calculate radius based on zoom level and count - continuous scale
+ const getRadius = (count: number, zoom: number): number => {
+ // Ensure count is at least 1
+ const safeCount = Math.max(count, 1);
+ const sqrt = Math.sqrt(safeCount);
+
+ // Guard against division by zero when topSize <= 1
+ const denominator = Math.max(topSize - 1, 1);
+ const normalizedCount = Math.max(0, Math.min(1, (sqrt - 1) / denominator)); // Clamp to [0, 1]
+
+ // Exponential zoom scaling: radius grows exponentially with zoom
+ // At zoom 0: min 1, max 4
+ // At zoom 4: min 2, max 8
+ // At zoom 8: min 4, max 16
+ // At zoom 12: min 8, max 32
+ const zoomFactor = Math.pow(2, zoom / 4); // Doubles every 4 zoom levels
+
+ const minRadius = 1 * zoomFactor * sizeMultiplier;
+ const maxRadius = 4 * zoomFactor * sizeMultiplier;
+
+ return minRadius + normalizedCount * (maxRadius - minRadius);
+ };
+
+ // Style function
+ const styleFunction = (feature: FeatureLike) => {
+ const isFiltered = feature.get("isFiltered");
+ const count = feature.get("count");
+ const zoom = map.getView().getZoom() || 2;
+ const radius = getRadius(count, zoom);
+
+ return new Style({
+ image: new Circle({
+ radius,
+ fill: new Fill({
+ color: isFiltered ? "rgba(59, 130, 246, 0.9)" : "rgba(255, 244, 214, 0.5)",
+ }),
+ stroke: new Stroke({
+ color: isFiltered ? "rgba(96, 165, 250, 1)" : "rgba(255, 255, 255, 0.3)",
+ width: isFiltered ? 2 : 1,
+ }),
+ }),
+ });
+ };
+
+ // Create or update vector layer
+ if (!vectorLayerRef.current) {
+ const vectorLayer = new VectorLayer({
+ source: vectorSource,
+ style: styleFunction,
+ });
+
+ vectorLayer.set("id", "coordinates-layer");
+ vectorLayer.setVisible(mapView === "coordinates");
+ map.addLayer(vectorLayer);
+ vectorLayerRef.current = vectorLayer;
+ } else {
+ vectorLayerRef.current.setSource(vectorSource);
+ vectorLayerRef.current.setStyle(styleFunction);
+ }
+
+ // Update visibility based on mapView
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.setVisible(mapView === "coordinates");
+ }
+
+ // Handle zoom changes to update circle sizes
+ const handleZoomChange = () => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.changed();
+ }
+ };
+
+ map.on("moveend", handleZoomChange);
+
+ // Cleanup
+ return () => {
+ map.un("moveend", handleZoomChange);
+
+ // Remove layer on cleanup
+ if (vectorLayerRef.current) {
+ map.removeLayer(vectorLayerRef.current);
+ vectorLayerRef.current = null;
+ }
+ };
+ }, [liveSessionLocations, mapView, mapInstanceRef, filters, mapViewRef]);
+
+ // Handle hover and click events
+ useEffect(() => {
+ const map = mapInstanceRef.current;
+ if (!map) return;
+
+ let tooltip: HTMLDivElement | null = null;
+
+ const handlePointerMove = (event: any) => {
+ const isCoordinatesView = mapViewRef.current === "coordinates";
+ if (!isCoordinatesView) return;
+
+ const pixel = map.getEventPixel(event.originalEvent);
+ const features = map.getFeaturesAtPixel(pixel, {
+ layerFilter: layer => layer.get("id") === "coordinates-layer",
+ });
+
+ if (features.length > 0) {
+ map.getTargetElement().style.cursor = "pointer";
+
+ const feature = features[0] as Feature;
+ const city = feature.get("city") || "Unknown";
+ const count = feature.get("count") || 0;
+ const countryCode = feature.get("country")?.length === 2 ? feature.get("country") : "";
+ const flagSVG = renderCountryFlag(countryCode);
+
+ // Create tooltip if it doesn't exist
+ if (!tooltip) {
+ tooltip = document.createElement("div");
+ tooltip.id = "ol-coordinates-tooltip";
+ tooltip.style.position = "absolute";
+ tooltip.style.pointerEvents = "none";
+ tooltip.style.zIndex = "10000";
+ document.body.appendChild(tooltip);
+ }
+
+ tooltip.innerHTML = `
+ <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2 shadow-lg">
+ <div class="flex items-center gap-2 mb-1">
+ ${flagSVG}
+ <span class="text-sm font-medium text-white">${city}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${count.toLocaleString()}</span>
+ <span class="text-neutral-300"> sessions</span>
+ </div>
+ </div>
+ `;
+
+ tooltip.style.left = event.originalEvent.pageX + 10 + "px";
+ tooltip.style.top = event.originalEvent.pageY + 10 + "px";
+ tooltip.style.display = "block";
+ } else {
+ map.getTargetElement().style.cursor = "";
+ if (tooltip) {
+ tooltip.style.display = "none";
+ }
+ }
+ };
+
+ const handleClick = (event: any) => {
+ const isCoordinatesView = mapViewRef.current === "coordinates";
+ if (!isCoordinatesView) return;
+
+ const pixel = map.getEventPixel(event.originalEvent);
+ const features = map.getFeaturesAtPixel(pixel, {
+ layerFilter: layer => layer.get("id") === "coordinates-layer",
+ });
+
+ if (features.length > 0) {
+ const feature = features[0] as Feature;
+ const isCurrentlyFiltered = feature.get("isFiltered");
+ const lat = feature.get("lat");
+ const lon = feature.get("lon");
+
+ if (lat === undefined || lon === undefined) return;
+
+ // If this location is already filtered, remove the filters
+ if (isCurrentlyFiltered) {
+ const { filters } = useStore.getState();
+ const latFilter = filters.find(f => f.parameter === "lat");
+ const lonFilter = filters.find(f => f.parameter === "lon");
+
+ if (latFilter) removeFilter(latFilter);
+ if (lonFilter) removeFilter(lonFilter);
+ } else {
+ // Otherwise, add the filters
+ addFilter({
+ parameter: "lat" as FilterParameter,
+ value: [lat],
+ type: "equals",
+ });
+
+ addFilter({
+ parameter: "lon" as FilterParameter,
+ value: [lon],
+ type: "equals",
+ });
+ }
+ }
+ };
+
+ map.on("pointermove", handlePointerMove);
+ map.on("click", handleClick);
+
+ return () => {
+ map.un("pointermove", handlePointerMove);
+ map.un("click", handleClick);
+
+ // Remove tooltip from DOM
+ if (tooltip && tooltip.parentNode) {
+ tooltip.parentNode.removeChild(tooltip);
+ }
+ };
+ }, [mapInstanceRef, mapViewRef]);
+}
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
new file mode 100644
index 000000000..07139af33
--- /dev/null
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
@@ -0,0 +1,233 @@
+import { FilterParameter } from "@rybbit/shared";
+import Map from "ol/Map";
+import GeoJSON from "ol/format/GeoJSON";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import { Fill, Stroke, Style } from "ol/style";
+import { MutableRefObject, useEffect, useMemo, useRef, useState } from "react";
+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";
+import { useCountries } from "../../../../../lib/geo";
+import { addFilter } from "../../../../../lib/store";
+import { createColorScale } from "../../utils/colorScale";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
+
+interface UseOpenLayersCountriesLayerProps {
+ mapInstanceRef: MutableRefObject<Map | null>;
+ mapViewRef: MutableRefObject<"countries" | "subdivisions" | "coordinates" | "timeline">;
+ mapView: "countries" | "subdivisions" | "coordinates" | "timeline";
+}
+
+interface TooltipData {
+ name: string;
+ code: string;
+ count: number;
+ percentage: number;
+ x: number;
+ y: number;
+}
+
+export function useOpenLayersCountriesLayer({ mapInstanceRef, mapViewRef, mapView }: UseOpenLayersCountriesLayerProps) {
+ const { data: countryData } = useSingleCol({ parameter: "country" });
+ const { data: countriesGeoData } = useCountries();
+ const colorScale = useMemo(() => createColorScale(countryData?.data), [countryData?.data]);
+
+ const vectorLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
+ const [hoveredId, setHoveredId] = useState<string | null>(null);
+ const [tooltipData, setTooltipData] = useState<TooltipData | null>(null);
+
+ // Add/update countries layer
+ useEffect(() => {
+ if (!mapInstanceRef.current || !countriesGeoData || !countryData?.data) return;
+
+ // Remove existing layer
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ }
+
+ // Create new vector source with GeoJSON data
+ const vectorSource = new VectorSource({
+ features: new GeoJSON().readFeatures(countriesGeoData, {
+ featureProjection: "EPSG:3857",
+ }),
+ });
+
+ // Create new vector layer with styling
+ const vectorLayer = new VectorLayer({
+ source: vectorSource,
+ style: feature => {
+ const code = feature.get("ISO_A2");
+ const foundData = countryData?.data?.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+
+ let fillColor: string;
+ let strokeColor: string;
+
+ if (count > 0) {
+ const baseColor = colorScale(count);
+ if (hoveredId === code) {
+ fillColor = baseColor.replace(/,\s*([\d.]+)\)$/, (match, opacity) => {
+ const newOpacity = Math.min(parseFloat(opacity) + 0.2, 1);
+ return `, ${newOpacity})`;
+ });
+ } else {
+ fillColor = baseColor;
+ }
+ strokeColor = "rgba(110, 231, 183, 0.25)";
+ } else {
+ fillColor = "rgba(0, 0, 0, 0)";
+ strokeColor = "rgba(0, 0, 0, 0)";
+ }
+
+ return new Style({
+ fill: new Fill({
+ color: fillColor,
+ }),
+ stroke: new Stroke({
+ color: strokeColor,
+ width: 0.5,
+ }),
+ });
+ },
+ visible: mapView === "countries",
+ });
+
+ vectorLayerRef.current = vectorLayer;
+ mapInstanceRef.current.addLayer(vectorLayer);
+
+ // Handle pointer move for tooltips
+ const handlePointerMove = (evt: any) => {
+ if (!mapInstanceRef.current) return;
+
+ const pixel = mapInstanceRef.current.getEventPixel(evt.originalEvent);
+ const feature = mapInstanceRef.current.forEachFeatureAtPixel(pixel, f => f, {
+ layerFilter: layer => layer === vectorLayerRef.current,
+ });
+
+ if (feature && mapViewRef.current === "countries") {
+ const code = feature.get("ISO_A2");
+ const name = feature.get("ADMIN");
+ setHoveredId(code);
+
+ const foundData = countryData?.data?.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+ const percentage = foundData?.percentage || 0;
+
+ const rect = mapInstanceRef.current.getTargetElement().getBoundingClientRect();
+ const [x, y] = evt.pixel;
+
+ setTooltipData({
+ name,
+ code,
+ count,
+ percentage,
+ x: rect.left + x,
+ y: rect.top + y,
+ });
+
+ mapInstanceRef.current.getTargetElement().style.cursor = "pointer";
+ } else {
+ setHoveredId(null);
+ setTooltipData(null);
+ if (mapInstanceRef.current) {
+ mapInstanceRef.current.getTargetElement().style.cursor = "";
+ }
+ }
+ };
+
+ // Handle click for filtering
+ const handleClick = (evt: any) => {
+ if (!mapInstanceRef.current) return;
+
+ const pixel = mapInstanceRef.current.getEventPixel(evt.originalEvent);
+ const feature = mapInstanceRef.current.forEachFeatureAtPixel(pixel, f => f, {
+ layerFilter: layer => layer === vectorLayerRef.current,
+ });
+
+ if (feature && mapViewRef.current === "countries") {
+ const code = feature.get("ISO_A2");
+ addFilter({
+ parameter: "country" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
+ }
+ };
+
+ mapInstanceRef.current.on("pointermove", handlePointerMove);
+ mapInstanceRef.current.on("click", handleClick);
+
+ return () => {
+ if (mapInstanceRef.current) {
+ mapInstanceRef.current.un("pointermove", handlePointerMove);
+ mapInstanceRef.current.un("click", handleClick);
+
+ // Remove layer on cleanup
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ vectorLayerRef.current = null;
+ }
+ }
+ };
+ }, [countriesGeoData, countryData?.data, colorScale, mapView]);
+
+ // Update layer visibility
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.setVisible(mapView === "countries");
+ }
+ }, [mapView]);
+
+ // Update styles when hovered
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.changed();
+ }
+ }, [hoveredId]);
+
+ // Render tooltip
+ useEffect(() => {
+ if (!tooltipData) {
+ const existingTooltip = document.getElementById("ol-countries-tooltip");
+ if (existingTooltip) {
+ existingTooltip.remove();
+ }
+ return;
+ }
+
+ let tooltip = document.getElementById("ol-countries-tooltip") as HTMLDivElement;
+ if (!tooltip) {
+ tooltip = document.createElement("div");
+ tooltip.id = "ol-countries-tooltip";
+ tooltip.style.position = "fixed";
+ tooltip.style.pointerEvents = "none";
+ tooltip.style.zIndex = "9999";
+ document.body.appendChild(tooltip);
+ }
+
+ const flagSVG = renderCountryFlag(tooltipData.code);
+
+ tooltip.innerHTML = `
+ <div class="bg-neutral-850 border border-neutral-700 rounded-lg p-2 shadow-lg">
+ <div class="flex items-center gap-2 mb-1">
+ ${flagSVG}
+ <span class="text-sm font-medium text-white">${tooltipData.name}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${tooltipData.count.toLocaleString()}</span>
+ <span class="text-neutral-300"> (${tooltipData.percentage.toFixed(1)}%) sessions</span>
+ </div>
+ </div>
+ `;
+
+ tooltip.style.left = `${tooltipData.x}px`;
+ tooltip.style.top = `${tooltipData.y - 10}px`;
+ tooltip.style.transform = "translate(-50%, -100%)";
+
+ return () => {
+ const existingTooltip = document.getElementById("ol-countries-tooltip");
+ if (existingTooltip) {
+ existingTooltip.remove();
+ }
+ };
+ }, [tooltipData]);
+}
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
new file mode 100644
index 000000000..28a053f8f
--- /dev/null
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
@@ -0,0 +1,239 @@
+import { FilterParameter } from "@rybbit/shared";
+import Map from "ol/Map";
+import GeoJSON from "ol/format/GeoJSON";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import { Fill, Stroke, Style } from "ol/style";
+import { MutableRefObject, useEffect, useMemo, useRef, useState } from "react";
+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";
+import { useSubdivisions } from "../../../../../lib/geo";
+import { addFilter } from "../../../../../lib/store";
+import { createColorScale } from "../../utils/colorScale";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
+
+interface UseOpenLayersSubdivisionsLayerProps {
+ mapInstanceRef: MutableRefObject<Map | null>;
+ mapViewRef: MutableRefObject<"countries" | "subdivisions" | "coordinates" | "timeline">;
+ mapView: "countries" | "subdivisions" | "coordinates" | "timeline";
+}
+
+interface TooltipData {
+ name: string;
+ code: string;
+ count: number;
+ percentage: number;
+ x: number;
+ y: number;
+}
+
+export function useOpenLayersSubdivisionsLayer({
+ mapInstanceRef,
+ mapViewRef,
+ mapView,
+}: UseOpenLayersSubdivisionsLayerProps) {
+ const { data: subdivisionData } = useSingleCol({ parameter: "region", limit: 10000 });
+ const { data: subdivisionsGeoData } = useSubdivisions();
+ const colorScale = useMemo(() => createColorScale(subdivisionData?.data), [subdivisionData?.data]);
+
+ const vectorLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
+ const [hoveredId, setHoveredId] = useState<string | null>(null);
+ const [tooltipData, setTooltipData] = useState<TooltipData | null>(null);
+
+ // Add/update subdivisions layer
+ useEffect(() => {
+ if (!mapInstanceRef.current || !subdivisionsGeoData || !subdivisionData?.data) return;
+
+ // Remove existing layer
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ }
+
+ // Create new vector source with GeoJSON data
+ const vectorSource = new VectorSource({
+ features: new GeoJSON().readFeatures(subdivisionsGeoData, {
+ featureProjection: "EPSG:3857",
+ }),
+ });
+
+ // Create new vector layer with styling
+ const vectorLayer = new VectorLayer({
+ source: vectorSource,
+ style: feature => {
+ const code = feature.get("iso_3166_2");
+ const foundData = subdivisionData?.data?.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+
+ let fillColor: string;
+ let strokeColor: string;
+
+ if (count > 0) {
+ const baseColor = colorScale(count);
+ if (hoveredId === code) {
+ fillColor = baseColor.replace(/,\s*([\d.]+)\)$/, (match, opacity) => {
+ const newOpacity = Math.min(parseFloat(opacity) + 0.2, 1);
+ return `, ${newOpacity})`;
+ });
+ } else {
+ fillColor = baseColor;
+ }
+ strokeColor = "rgba(110, 231, 183, 0.25)";
+ } else {
+ fillColor = "rgba(0, 0, 0, 0)";
+ strokeColor = "rgba(0, 0, 0, 0)";
+ }
+
+ return new Style({
+ fill: new Fill({
+ color: fillColor,
+ }),
+ stroke: new Stroke({
+ color: strokeColor,
+ width: 0.5,
+ }),
+ });
+ },
+ visible: mapView === "subdivisions",
+ });
+
+ vectorLayerRef.current = vectorLayer;
+ mapInstanceRef.current.addLayer(vectorLayer);
+
+ // Handle pointer move for tooltips
+ const handlePointerMove = (evt: any) => {
+ if (!mapInstanceRef.current) return;
+
+ const pixel = mapInstanceRef.current.getEventPixel(evt.originalEvent);
+ const feature = mapInstanceRef.current.forEachFeatureAtPixel(pixel, f => f, {
+ layerFilter: layer => layer === vectorLayerRef.current,
+ });
+
+ if (feature && mapViewRef.current === "subdivisions") {
+ const code = feature.get("iso_3166_2");
+ const name = feature.get("name");
+ setHoveredId(code);
+
+ const foundData = subdivisionData?.data?.find((d: any) => d.value === code);
+ const count = foundData?.count || 0;
+ const percentage = foundData?.percentage || 0;
+
+ const rect = mapInstanceRef.current.getTargetElement().getBoundingClientRect();
+ const [x, y] = evt.pixel;
+
+ setTooltipData({
+ name,
+ code,
+ count,
+ percentage,
+ x: rect.left + x,
+ y: rect.top + y,
+ });
+
+ mapInstanceRef.current.getTargetElement().style.cursor = "pointer";
+ } else {
+ setHoveredId(null);
+ setTooltipData(null);
+ if (mapInstanceRef.current) {
+ mapInstanceRef.current.getTargetElement().style.cursor = "";
+ }
+ }
+ };
+
+ // Handle click for filtering
+ const handleClick = (evt: any) => {
+ if (!mapInstanceRef.current) return;
+
+ const pixel = mapInstanceRef.current.getEventPixel(evt.originalEvent);
+ const feature = mapInstanceRef.current.forEachFeatureAtPixel(pixel, f => f, {
+ layerFilter: layer => layer === vectorLayerRef.current,
+ });
+
+ if (feature && mapViewRef.current === "subdivisions") {
+ const code = feature.get("iso_3166_2");
+ addFilter({
+ parameter: "region" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
+ }
+ };
+
+ mapInstanceRef.current.on("pointermove", handlePointerMove);
+ mapInstanceRef.current.on("click", handleClick);
+
+ return () => {
+ if (mapInstanceRef.current) {
+ mapInstanceRef.current.un("pointermove", handlePointerMove);
+ mapInstanceRef.current.un("click", handleClick);
+
+ // Remove layer on cleanup
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ vectorLayerRef.current = null;
+ }
+ }
+ };
+ }, [subdivisionsGeoData, subdivisionData?.data, colorScale, mapView]);
+
+ // Update layer visibility
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.setVisible(mapView === "subdivisions");
+ }
+ }, [mapView]);
+
+ // Update styles when hovered
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.changed();
+ }
+ }, [hoveredId]);
+
+ // Render tooltip
+ useEffect(() => {
+ if (!tooltipData) {
+ const existingTooltip = document.getElementById("ol-subdivisions-tooltip");
+ if (existingTooltip) {
+ existingTooltip.remove();
+ }
+ return;
+ }
+
+ let tooltip = document.getElementById("ol-subdivisions-tooltip") as HTMLDivElement;
+ if (!tooltip) {
+ tooltip = document.createElement("div");
+ tooltip.id = "ol-subdivisions-tooltip";
+ tooltip.style.position = "fixed";
+ tooltip.style.pointerEvents = "none";
+ tooltip.style.zIndex = "9999";
+ document.body.appendChild(tooltip);
+ }
+
+ // Extract country code from iso_3166_2 (e.g., "US-CA" -> "US")
+ const countryCode = tooltipData.code?.split("-")[0] || "";
+ const flagSVG = renderCountryFlag(countryCode);
+
+ tooltip.innerHTML = `
+ <div class="bg-neutral-850 border border-neutral-700 rounded-lg p-2 shadow-lg">
+ <div class="flex items-center gap-2 mb-1">
+ ${flagSVG}
+ <span class="text-sm font-medium text-white">${tooltipData.name}</span>
+ </div>
+ <div class="text-sm">
+ <span class="font-bold text-accent-400">${tooltipData.count.toLocaleString()}</span>
+ <span class="text-neutral-300"> (${tooltipData.percentage.toFixed(1)}%) sessions</span>
+ </div>
+ </div>
+ `;
+
+ tooltip.style.left = `${tooltipData.x}px`;
+ tooltip.style.top = `${tooltipData.y - 10}px`;
+ tooltip.style.transform = "translate(-50%, -100%)";
+
+ return () => {
+ const existingTooltip = document.getElementById("ol-subdivisions-tooltip");
+ if (existingTooltip) {
+ existingTooltip.remove();
+ }
+ };
+ }, [tooltipData]);
+}
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
new file mode 100644
index 000000000..d648e80ad
--- /dev/null
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
@@ -0,0 +1,557 @@
+import { useEffect, useRef, useState } from "react";
+import OLMap from "ol/Map";
+import Overlay from "ol/Overlay";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import Cluster from "ol/source/Cluster";
+import Feature, { FeatureLike } from "ol/Feature";
+import Point from "ol/geom/Point";
+import { Circle, Fill, Stroke, Style, Text } from "ol/style";
+import { fromLonLat } from "ol/proj";
+import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import { useTimelineStore, useActiveSessions } from "../../timelineStore";
+import { generateAvatarSVG } from "../../3d/hooks/timelineLayer/timelineMarkerHelpers";
+import { buildTooltipHTML } from "../../utils/timelineTooltipBuilder";
+import { CLUSTER_MAX_ZOOM, MIN_CLUSTER_SIZE, CLUSTERING_THRESHOLD } from "../../utils/clusteringConstants";
+
+// OpenLayers-specific clustering constants
+const CLUSTER_RADIUS = 50; // pixels (OpenLayers specific)
+
+interface TimelineLayerProps {
+ mapInstanceRef: React.RefObject<OLMap | null>;
+ mapViewRef: React.RefObject<string>;
+ mapView: string;
+}
+
+type OverlayData = {
+ overlay: Overlay;
+ element: HTMLDivElement;
+ session: GetSessionsResponse[number];
+ cleanup: () => void;
+};
+
+export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView }: TimelineLayerProps) {
+ const activeSessions = useActiveSessions();
+ const { currentTime } = useTimelineStore();
+ const overlaysMapRef = useRef<Map<string, OverlayData>>(new Map());
+ const clusterLayerRef = useRef<VectorLayer<Cluster> | null>(null);
+ const tooltipOverlayRef = useRef<Overlay | null>(null);
+ const [openTooltipSessionId, setOpenTooltipSessionId] = useState<string | null>(null);
+ const [selectedSession, setSelectedSession] = useState<GetSessionsResponse[number] | null>(null);
+ const currentZoomRef = useRef<number>(2);
+
+ // Close tooltip when timeline time changes
+ useEffect(() => {
+ if (tooltipOverlayRef.current && openTooltipSessionId) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ }
+ }, [currentTime]);
+
+ // Track zoom level changes
+ useEffect(() => {
+ const map = mapInstanceRef.current;
+ if (!map) return;
+
+ const handleZoomChange = () => {
+ const zoom = map.getView().getZoom() || 2;
+ currentZoomRef.current = zoom;
+ };
+
+ // Set initial zoom
+ handleZoomChange();
+
+ map.on("moveend", handleZoomChange);
+
+ return () => {
+ map.un("moveend", handleZoomChange);
+ };
+ }, [mapInstanceRef]);
+
+ // Initialize tooltip overlay
+ useEffect(() => {
+ const map = mapInstanceRef.current;
+ if (!map) return;
+
+ if (!tooltipOverlayRef.current) {
+ const tooltipElement = document.createElement("div");
+ tooltipElement.className = "ol-timeline-tooltip";
+ tooltipElement.style.position = "absolute";
+ tooltipElement.style.zIndex = "1000";
+
+ const tooltip = new Overlay({
+ element: tooltipElement,
+ positioning: "top-left",
+ offset: [-46, -46], // Offset to align tooltip avatar center with marker center (12px padding + 18px half-avatar)
+ stopEvent: true,
+ });
+
+ map.addOverlay(tooltip);
+ tooltipOverlayRef.current = tooltip;
+ }
+
+ return () => {
+ if (tooltipOverlayRef.current) {
+ map.removeOverlay(tooltipOverlayRef.current);
+ tooltipOverlayRef.current = null;
+ }
+ };
+ }, [mapInstanceRef]);
+
+ // Update clusters/overlays when active sessions change
+ useEffect(() => {
+ const map = mapInstanceRef.current;
+ if (!map) return;
+
+ const overlaysMap = overlaysMapRef.current;
+
+ // Hide everything if not in timeline view
+ if (mapView !== "timeline") {
+ // Clear overlays
+ overlaysMap.forEach(({ overlay, cleanup }) => {
+ cleanup();
+ map.removeOverlay(overlay);
+ });
+ overlaysMap.clear();
+
+ // Clear cluster layer
+ if (clusterLayerRef.current) {
+ map.removeLayer(clusterLayerRef.current);
+ clusterLayerRef.current = null;
+ }
+ return;
+ }
+
+ // Determine if we should use clustering
+ const shouldCluster = activeSessions.length > CLUSTERING_THRESHOLD && currentZoomRef.current < CLUSTER_MAX_ZOOM;
+
+ if (shouldCluster) {
+ // Create features for clustering
+ const features = activeSessions.map(session => {
+ if (!session.lat || !session.lon) return null;
+
+ const feature = new Feature({
+ geometry: new Point(fromLonLat([session.lon, session.lat])),
+ });
+
+ feature.setProperties({
+ session_id: session.session_id,
+ session,
+ });
+
+ return feature;
+ }).filter(Boolean) as Feature[];
+
+ // Create vector source
+ const vectorSource = new VectorSource({
+ features,
+ });
+
+ // Create cluster source
+ const clusterSource = new Cluster({
+ distance: CLUSTER_RADIUS,
+ source: vectorSource,
+ });
+
+ // Style function for clusters (matching Mapbox styling)
+ const styleFunction = (feature: FeatureLike) => {
+ const clusterFeatures = feature.get("features");
+ const size = clusterFeatures ? clusterFeatures.length : 1;
+
+ if (size >= MIN_CLUSTER_SIZE) {
+ // Determine color based on cluster size (matching Mapbox steps)
+ let color: string;
+ if (size >= 100) {
+ color = "#34d399"; // green-400
+ } else if (size >= 30) {
+ color = "#10b981"; // green-500
+ } else {
+ color = "#059669"; // green-600
+ }
+
+ // Determine radius based on cluster size (matching Mapbox steps)
+ let radius: number;
+ if (size >= 30) {
+ radius = 25;
+ } else if (size >= 10) {
+ radius = 20;
+ } else {
+ radius = 15;
+ }
+
+ return new Style({
+ image: new Circle({
+ radius,
+ fill: new Fill({
+ color,
+ }),
+ }),
+ text: new Text({
+ text: size.toString(),
+ fill: new Fill({
+ color: "#ffffff",
+ }),
+ font: "bold 14px sans-serif",
+ }),
+ });
+ } else {
+ // Small cluster - invisible (we'll use overlays for these)
+ return new Style({});
+ }
+ };
+
+ // Function to update unclustered overlays
+ const updateUnclusteredOverlays = () => {
+ // Get unclustered features (clusters with size < MIN_CLUSTER_SIZE) and create overlays for them
+ const extent = map.getView().calculateExtent(map.getSize());
+ const clusterFeatures = clusterSource.getFeaturesInExtent(extent);
+ const unclusteredSessions: GetSessionsResponse = [];
+
+ clusterFeatures.forEach(clusterFeature => {
+ const features = clusterFeature.get("features");
+ if (features && features.length < MIN_CLUSTER_SIZE) {
+ // Extract all sessions from small clusters
+ features.forEach((feature: Feature) => {
+ const session = feature.get("session");
+ if (session) {
+ unclusteredSessions.push(session);
+ }
+ });
+ }
+ });
+
+ // Update overlays for unclustered sessions
+ const currentSessionIds = new Set(unclusteredSessions.map(s => s.session_id));
+
+ // Remove overlays that are no longer unclustered
+ const toRemove: string[] = [];
+ overlaysMap.forEach(({ overlay, cleanup }, sessionId) => {
+ if (!currentSessionIds.has(sessionId)) {
+ cleanup();
+ map.removeOverlay(overlay);
+ toRemove.push(sessionId);
+ }
+ });
+ toRemove.forEach(id => overlaysMap.delete(id));
+
+ // Create or update overlays for unclustered sessions
+ unclusteredSessions.forEach(session => {
+ if (!session?.session_id || !session.lat || !session.lon) return;
+
+ const existing = overlaysMap.get(session.session_id);
+
+ if (existing) {
+ // Update position if needed
+ const currentPos = existing.overlay.getPosition();
+ const newPos = fromLonLat([session.lon, session.lat]);
+ if (!currentPos || currentPos[0] !== newPos[0] || currentPos[1] !== newPos[1]) {
+ existing.overlay.setPosition(newPos);
+ }
+ } else {
+ // Create new overlay (same code as non-clustering case)
+ const avatarContainer = document.createElement("div");
+ avatarContainer.className = "timeline-avatar-marker";
+ avatarContainer.style.cursor = "pointer";
+ avatarContainer.style.borderRadius = "50%";
+ avatarContainer.style.overflow = "hidden";
+ avatarContainer.style.width = "32px";
+ avatarContainer.style.height = "32px";
+ avatarContainer.style.boxShadow = "0 2px 8px rgba(0,0,0,0.3)";
+ avatarContainer.style.transform = "translate(-50%, -50%)";
+
+ const avatarSVG = generateAvatarSVG(session.user_id, 32);
+ avatarContainer.innerHTML = avatarSVG;
+
+ // Track cleanup resources
+ let timeoutId: number | null = null;
+ let buttonHandler: ((e: Event) => void) | null = null;
+ let buttonElement: Element | null = null;
+
+ const handleAvatarClick = (e: MouseEvent) => {
+ e.stopPropagation();
+
+ if (openTooltipSessionId === session.session_id && tooltipOverlayRef.current) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ return;
+ }
+
+ if (tooltipOverlayRef.current) {
+ const html = buildTooltipHTML(session, session.lon, session.lat);
+ tooltipOverlayRef.current.getElement()!.innerHTML = html;
+ tooltipOverlayRef.current.setPosition(fromLonLat([session.lon, session.lat]));
+ setOpenTooltipSessionId(session.session_id);
+
+ timeoutId = window.setTimeout(() => {
+ const button = document.querySelector(`[data-session-id="${session.session_id}"]`);
+ if (button) {
+ buttonHandler = (e: Event) => {
+ e.stopPropagation();
+ setSelectedSession(session);
+ if (tooltipOverlayRef.current) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ }
+ };
+ buttonElement = button;
+ button.addEventListener("click", buttonHandler);
+ }
+ }, 0);
+ }
+ };
+
+ avatarContainer.addEventListener("click", handleAvatarClick);
+
+ const overlay = new Overlay({
+ element: avatarContainer,
+ positioning: "center-center",
+ stopEvent: false,
+ });
+
+ overlay.setPosition(fromLonLat([session.lon, session.lat]));
+ map.addOverlay(overlay);
+
+ // Cleanup function to remove all event listeners and clear timeouts
+ const cleanup = () => {
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ }
+ if (buttonHandler && buttonElement) {
+ buttonElement.removeEventListener("click", buttonHandler);
+ }
+ avatarContainer.removeEventListener("click", handleAvatarClick);
+ };
+
+ overlaysMap.set(session.session_id, { overlay, element: avatarContainer, session, cleanup });
+ }
+ });
+ };
+
+ // Create or update cluster layer
+ if (!clusterLayerRef.current) {
+ const clusterLayer = new VectorLayer({
+ source: clusterSource,
+ style: styleFunction,
+ zIndex: 100,
+ });
+
+ map.addLayer(clusterLayer);
+ clusterLayerRef.current = clusterLayer;
+ } else {
+ clusterLayerRef.current.setSource(clusterSource);
+ clusterLayerRef.current.setStyle(styleFunction);
+ }
+
+ // Wait for next render cycle to query cluster features
+ requestAnimationFrame(() => {
+ updateUnclusteredOverlays();
+ });
+
+ // Also update overlays when map moves/zooms (clusters change)
+ const handleMoveEndForClusters = () => {
+ updateUnclusteredOverlays();
+ };
+ map.on("moveend", handleMoveEndForClusters);
+
+ // Store handler for cleanup
+ (map as any).__clusterMoveEndHandler = handleMoveEndForClusters;
+ } else {
+ // Not clustering - use individual overlays
+ // Remove cluster layer
+ if (clusterLayerRef.current) {
+ map.removeLayer(clusterLayerRef.current);
+ clusterLayerRef.current = null;
+ }
+
+ // Remove cluster moveend handler if it exists
+ if ((map as any).__clusterMoveEndHandler) {
+ map.un("moveend", (map as any).__clusterMoveEndHandler);
+ delete (map as any).__clusterMoveEndHandler;
+ }
+
+ // Build set of current session IDs
+ const currentSessionIds = new Set(activeSessions.map(s => s.session_id));
+
+ // Remove overlays that are no longer active
+ const toRemove: string[] = [];
+ overlaysMap.forEach(({ overlay, cleanup }, sessionId) => {
+ if (!currentSessionIds.has(sessionId)) {
+ cleanup();
+ map.removeOverlay(overlay);
+ toRemove.push(sessionId);
+ }
+ });
+ toRemove.forEach(id => overlaysMap.delete(id));
+
+ // Create or update overlays for active sessions
+ activeSessions.forEach(session => {
+ if (!session?.session_id || !session.lat || !session.lon) return;
+
+ const existing = overlaysMap.get(session.session_id);
+
+ if (existing) {
+ // Update position if needed
+ const currentPos = existing.overlay.getPosition();
+ const newPos = fromLonLat([session.lon, session.lat]);
+ if (!currentPos || currentPos[0] !== newPos[0] || currentPos[1] !== newPos[1]) {
+ existing.overlay.setPosition(newPos);
+ }
+ } else {
+ // Create new overlay
+ const avatarContainer = document.createElement("div");
+ avatarContainer.className = "timeline-avatar-marker";
+ avatarContainer.style.cursor = "pointer";
+ avatarContainer.style.borderRadius = "50%";
+ avatarContainer.style.overflow = "hidden";
+ avatarContainer.style.width = "32px";
+ avatarContainer.style.height = "32px";
+ avatarContainer.style.boxShadow = "0 2px 8px rgba(0,0,0,0.3)";
+ avatarContainer.style.transform = "translate(-50%, -50%)"; // Center the avatar
+
+ const avatarSVG = generateAvatarSVG(session.user_id, 32);
+ avatarContainer.innerHTML = avatarSVG;
+
+ // Track cleanup resources
+ let timeoutId: number | null = null;
+ let buttonHandler: ((e: Event) => void) | null = null;
+ let buttonElement: Element | null = null;
+
+ // Add click handler for tooltip
+ const handleAvatarClick = (e: MouseEvent) => {
+ e.stopPropagation();
+
+ // If clicking the same avatar that has the tooltip open, close it
+ if (openTooltipSessionId === session.session_id && tooltipOverlayRef.current) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ return;
+ }
+
+ // Show tooltip for this session
+ if (tooltipOverlayRef.current) {
+ const html = buildTooltipHTML(session, session.lon, session.lat);
+ tooltipOverlayRef.current.getElement()!.innerHTML = html;
+ tooltipOverlayRef.current.setPosition(fromLonLat([session.lon, session.lat]));
+ setOpenTooltipSessionId(session.session_id);
+
+ // Add click handler to "View Details" button
+ timeoutId = window.setTimeout(() => {
+ const button = document.querySelector(`[data-session-id="${session.session_id}"]`);
+ if (button) {
+ buttonHandler = (e: Event) => {
+ e.stopPropagation();
+ setSelectedSession(session);
+ if (tooltipOverlayRef.current) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ }
+ };
+ buttonElement = button;
+ button.addEventListener("click", buttonHandler);
+ }
+ }, 0);
+ }
+ };
+
+ avatarContainer.addEventListener("click", handleAvatarClick);
+
+ const overlay = new Overlay({
+ element: avatarContainer,
+ positioning: "center-center",
+ stopEvent: false,
+ });
+
+ overlay.setPosition(fromLonLat([session.lon, session.lat]));
+ map.addOverlay(overlay);
+
+ // Cleanup function to remove all event listeners and clear timeouts
+ const cleanup = () => {
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ }
+ if (buttonHandler && buttonElement) {
+ buttonElement.removeEventListener("click", buttonHandler);
+ }
+ avatarContainer.removeEventListener("click", handleAvatarClick);
+ };
+
+ overlaysMap.set(session.session_id, { overlay, element: avatarContainer, session, cleanup });
+ }
+ });
+ }
+
+ // Handle cluster clicks to zoom in
+ const handleClusterClick = (event: any) => {
+ if (!shouldCluster || !clusterLayerRef.current) return;
+
+ const pixel = map.getEventPixel(event.originalEvent);
+ const features = map.getFeaturesAtPixel(pixel, {
+ layerFilter: layer => layer === clusterLayerRef.current,
+ });
+
+ if (features.length > 0) {
+ const feature = features[0] as Feature;
+ const clusterFeatures = feature.get("features");
+
+ if (clusterFeatures && clusterFeatures.length >= MIN_CLUSTER_SIZE) {
+ // Zoom in on the cluster
+ const extent = feature.getGeometry()?.getExtent();
+ if (extent) {
+ const view = map.getView();
+ const currentZoom = view.getZoom() ?? view.getMinZoom() ?? 0;
+ const targetZoom = currentZoom + 2;
+ const viewMaxZoom = view.getMaxZoom();
+ const clampedMaxZoom = viewMaxZoom !== undefined ? Math.min(targetZoom, viewMaxZoom) : targetZoom;
+
+ view.fit(extent, {
+ duration: 500,
+ maxZoom: clampedMaxZoom,
+ padding: [50, 50, 50, 50],
+ });
+ }
+ }
+ }
+ };
+
+ // Handle map click to close tooltip
+ const handleMapClick = (event: any) => {
+ // First, check for cluster clicks
+ handleClusterClick(event);
+
+ // Then close tooltip
+ if (tooltipOverlayRef.current && openTooltipSessionId) {
+ tooltipOverlayRef.current.setPosition(undefined);
+ setOpenTooltipSessionId(null);
+ }
+ };
+
+ map.on("click", handleMapClick);
+
+ // Cleanup function
+ return () => {
+ map.un("click", handleMapClick);
+
+ // Clean up cluster moveend handler if it exists
+ if ((map as any).__clusterMoveEndHandler) {
+ map.un("moveend", (map as any).__clusterMoveEndHandler);
+ delete (map as any).__clusterMoveEndHandler;
+ }
+
+ overlaysMap.forEach(({ overlay, cleanup }) => {
+ cleanup();
+ map.removeOverlay(overlay);
+ });
+ overlaysMap.clear();
+
+ if (clusterLayerRef.current) {
+ map.removeLayer(clusterLayerRef.current);
+ clusterLayerRef.current = null;
+ }
+ };
+ }, [activeSessions, mapView, mapInstanceRef, mapViewRef, openTooltipSessionId]);
+
+ return {
+ selectedSession,
+ setSelectedSession,
+ };
+}
diff --git a/client/src/app/[site]/globe/3d/components/MapboxMap.tsx b/client/src/app/[site]/globe/3d/components/MapboxMap.tsx
new file mode 100644
index 000000000..991f88f2e
--- /dev/null
+++ b/client/src/app/[site]/globe/3d/components/MapboxMap.tsx
@@ -0,0 +1,39 @@
+import { RefObject } from "react";
+import { NothingFound } from "../../../../../components/NothingFound";
+import { useConfigs } from "../../../../../lib/configs";
+
+export const MapboxMap = ({ mapContainer }: { mapContainer: RefObject<HTMLDivElement | null> }) => {
+ const { configs, isLoading } = useConfigs();
+
+ return (
+ <>
+ {configs?.mapboxToken ? (
+ <div
+ ref={mapContainer}
+ className="w-full h-full [&_.mapboxgl-ctrl-bottom-left]:!hidden [&_.mapboxgl-ctrl-logo]:!hidden"
+ />
+ ) : isLoading ? null : (
+ <div className="w-full h-full flex items-center justify-center">
+ <NothingFound
+ title="Mapbox access token not found"
+ description={
+ <p className="text-sm max-w-[600px] text-center">
+ Please set the <code>MAPBOX_TOKEN</code> environment variable and rebuild all containers. To get a
+ Mapbox token, please visit{" "}
+ <a
+ href="https://docs.mapbox.com/help/dive-deeper/access-tokens/"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-400 hover:underline"
+ >
+ Mapbox
+ </a>{" "}
+ and create an account.
+ </p>
+ }
+ />
+ </div>
+ )}
+ </>
+ );
+};
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
similarity index 97%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
index 996d48099..9d1949a58 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineClusterUtils.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
@@ -1,6 +1,6 @@
import mapboxgl from "mapbox-gl";
import { isNil, round } from "lodash";
-import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/userSessions";
import { SOURCE_ID, MIN_CLUSTER_SIZE } from "./timelineLayerConstants";
import { spreadOverlappingPoints } from "./timelineLayerManager";
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerConstants.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerConstants.ts
new file mode 100644
index 000000000..9652848bb
--- /dev/null
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerConstants.ts
@@ -0,0 +1,22 @@
+import {
+ CLUSTER_MAX_ZOOM,
+ MIN_CLUSTER_SIZE,
+ CLUSTERING_THRESHOLD,
+ SPREAD_START_ZOOM,
+ SPREAD_RADIUS_DEGREES,
+} from "../../../utils/clusteringConstants";
+
+// Re-export shared constants
+export { CLUSTER_MAX_ZOOM, MIN_CLUSTER_SIZE, CLUSTERING_THRESHOLD, SPREAD_START_ZOOM, SPREAD_RADIUS_DEGREES };
+
+// Mapbox layer and source IDs
+export const SOURCE_ID = "timeline-sessions";
+export const CLUSTER_LAYER_ID = "timeline-clusters";
+export const CLUSTER_COUNT_LAYER_ID = "timeline-cluster-count";
+export const UNCLUSTERED_LAYER_ID = "timeline-unclustered-point";
+
+// Radius in pixels within which points are grouped into clusters (Mapbox-specific)
+export const CLUSTER_RADIUS = 25;
+
+export const PAGE_SIZE = 10000;
+export const MAX_PAGES = 10;
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
similarity index 98%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
index 86aa09861..fe9a55757 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
@@ -1,6 +1,6 @@
import mapboxgl from "mapbox-gl";
import { isNil, round } from "lodash";
-import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/userSessions";
import { CLUSTER_LAYER_ID, CLUSTER_COUNT_LAYER_ID, SOURCE_ID, SPREAD_RADIUS_DEGREES } from "./timelineLayerConstants";
/**
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerSetup.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts
similarity index 100%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerSetup.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerHelpers.ts
similarity index 98%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerHelpers.ts
index 8ae160df8..578d6f4b7 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerHelpers.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerHelpers.ts
@@ -20,7 +20,7 @@ import {
Calendar,
Headphones,
} from "lucide-react";
-import { AVATAR_COLORS } from "../../../../../components/Avatar";
+import { AVATAR_COLORS } from "../../../../../../components/Avatar";
// Generate avatar SVG using boring-avatars
export function generateAvatarSVG(userId: string, size: number): string {
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
similarity index 94%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
index 070989fb2..fdb4a0fd8 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineMarkerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
@@ -1,8 +1,8 @@
import mapboxgl from "mapbox-gl";
-import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/userSessions";
import { generateAvatarSVG } from "./timelineMarkerHelpers";
-import { buildTooltipHTML } from "./timelineTooltipBuilder";
import { getUnclusteredFeatures } from "./timelineClusterUtils";
+import { buildTooltipHTML } from "../../../utils/timelineTooltipBuilder";
export type MarkerData = {
marker: mapboxgl.Marker;
@@ -108,9 +108,7 @@ export async function updateMarkers(
);
// Build set of current session IDs
- const currentSessionIds = new Set(
- unclusteredFeatures.map(f => f.properties?.session_id).filter(Boolean)
- );
+ const currentSessionIds = new Set(unclusteredFeatures.map(f => f.properties?.session_id).filter(Boolean));
// Remove markers that are no longer unclustered
const toRemove: string[] = [];
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
similarity index 96%
rename from client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
index d4282aa3a..2d9aede7d 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
@@ -1,8 +1,8 @@
import mapboxgl from "mapbox-gl";
import { useEffect, useRef, useState, useCallback } from "react";
import { throttle } from "lodash";
-import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
-import { useTimelineStore, useActiveSessions } from "../../timelineStore";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/userSessions";
+import { useTimelineStore, useActiveSessions } from "../../../timelineStore";
import { initializeClusterSource, setupClusterClickHandler } from "./timelineClusterUtils";
import {
SOURCE_ID,
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
similarity index 90%
rename from client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts
rename to client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
index 89ace19c7..1108db3b1 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
@@ -1,12 +1,12 @@
import { useQuery } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useEffect, useMemo } from "react";
-import { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
-import { APIResponse } from "../../../../../api/types";
-import { authedFetch, getQueryParams } from "../../../../../api/utils";
-import { getFilteredFilters, SESSION_PAGE_FILTERS, useStore } from "../../../../../lib/store";
-import { useTimelineStore } from "../../timelineStore";
-import { calculateWindowSize } from "../../timelineUtils";
+import { GetSessionsResponse } from "../../../../../../api/analytics/userSessions";
+import { APIResponse } from "../../../../../../api/types";
+import { authedFetch, getQueryParams } from "../../../../../../api/utils";
+import { getFilteredFilters, SESSION_PAGE_FILTERS, useStore } from "../../../../../../lib/store";
+import { useTimelineStore } from "../../../timelineStore";
+import { calculateWindowSize } from "../../../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "./timelineLayerConstants";
export function useTimelineSessions() {
diff --git a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
similarity index 97%
rename from client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
rename to client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
index 9add6acdb..6e21b91c2 100644
--- a/client/src/app/[site]/globe/hooks/useCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
@@ -2,9 +2,9 @@ import { FilterParameter } from "@rybbit/shared/dist/filters";
import { round } from "lodash";
import mapboxgl from "mapbox-gl";
import { useEffect, useRef } from "react";
-import { useGetSessionLocations } from "../../../../api/analytics/useGetSessionLocations";
-import { addFilter, removeFilter, useStore } from "../../../../lib/store";
-import { renderCountryFlag } from "../utils/renderCountryFlag";
+import { useGetSessionLocations } from "../../../../../api/analytics/useGetSessionLocations";
+import { addFilter, removeFilter, useStore } from "../../../../../lib/store";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
const getSizeMultiplier = (total: number) => {
if (total <= 50) return 3; // Large dots
diff --git a/client/src/app/[site]/globe/hooks/useCountriesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
similarity index 81%
rename from client/src/app/[site]/globe/hooks/useCountriesLayer.ts
rename to client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
index 4ae4e8039..9ee180556 100644
--- a/client/src/app/[site]/globe/hooks/useCountriesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
@@ -1,12 +1,11 @@
-import { useEffect, useMemo, useRef } from "react";
-import mapboxgl from "mapbox-gl";
import { FilterParameter } from "@rybbit/shared";
-import { addFilter } from "../../../../lib/store";
-import { useSingleCol } from "../../../../api/analytics/useSingleCol";
-import { useCountries } from "../../../../lib/geo";
-import { processCountryData } from "../utils/processData";
-import { createColorScale } from "../utils/colorScale";
-import { renderCountryFlag } from "../utils/renderCountryFlag";
+import mapboxgl from "mapbox-gl";
+import { useEffect, useMemo, useRef } from "react";
+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";
+import { useCountries } from "../../../../../lib/geo";
+import { addFilter } from "../../../../../lib/store";
+import { createColorScale } from "../../utils/colorScale";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
interface UseCountriesLayerProps {
map: React.RefObject<mapboxgl.Map | null>;
@@ -17,13 +16,12 @@ interface UseCountriesLayerProps {
export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayerProps) {
const { data: countryData } = useSingleCol({ parameter: "country" });
const { data: countriesGeoData } = useCountries();
- const processedCountryData = useMemo(() => processCountryData(countryData), [countryData]);
- const colorScale = useMemo(() => createColorScale(processedCountryData), [processedCountryData]);
+ const colorScale = useMemo(() => createColorScale(countryData?.data), [countryData?.data]);
const popupRef = useRef<mapboxgl.Popup | null>(null);
useEffect(() => {
- if (!map.current || !countriesGeoData || !processedCountryData || !mapLoaded) return;
+ if (!map.current || !countriesGeoData || !countryData?.data || !mapLoaded) return;
// Initialize popup once
if (!popupRef.current) {
@@ -40,9 +38,9 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
const geoDataCopy = JSON.parse(JSON.stringify(countriesGeoData));
geoDataCopy.features.forEach((feature: any) => {
const code = feature.properties?.ISO_A2;
- const foundData = processedCountryData.find((d: any) => d.value === code);
+ const foundData = countryData?.data?.find((d: any) => d.value === code);
const count = foundData?.count || 0;
- const color = count > 0 ? colorScale(count) : "rgba(140, 140, 140, 0.5)";
+ const color = count > 0 ? colorScale(count) : "rgba(0, 0, 0, 0)";
feature.properties.fillColor = color;
feature.properties.count = count;
});
@@ -75,7 +73,7 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
paint: {
"line-color": "#ffffff",
"line-width": 0.5,
- "line-opacity": 0.3,
+ "line-opacity": 0.2,
},
layout: {
visibility: mapView === "countries" ? "visible" : "none",
@@ -137,5 +135,5 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
};
addCountriesLayer();
- }, [countriesGeoData, processedCountryData, colorScale, map, countryData, mapLoaded]);
+ }, [countriesGeoData, countryData?.data, colorScale, map, mapLoaded]);
}
diff --git a/client/src/app/[site]/globe/hooks/useLayerVisibility.ts b/client/src/app/[site]/globe/3d/hooks/useLayerVisibility.ts
similarity index 96%
rename from client/src/app/[site]/globe/hooks/useLayerVisibility.ts
rename to client/src/app/[site]/globe/3d/hooks/useLayerVisibility.ts
index a5300c83e..10647d523 100644
--- a/client/src/app/[site]/globe/hooks/useLayerVisibility.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useLayerVisibility.ts
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import mapboxgl from "mapbox-gl";
-import { MapView } from "../components/ModeSelector";
+import { MapView } from "../../components/ModeSelector";
export function useLayerVisibility(
map: React.RefObject<mapboxgl.Map | null>,
diff --git a/client/src/app/[site]/globe/hooks/useMapbox.ts b/client/src/app/[site]/globe/3d/hooks/useMapbox.ts
similarity index 69%
rename from client/src/app/[site]/globe/hooks/useMapbox.ts
rename to client/src/app/[site]/globe/3d/hooks/useMapbox.ts
index a9fd1e650..578165131 100644
--- a/client/src/app/[site]/globe/hooks/useMapbox.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useMapbox.ts
@@ -1,15 +1,26 @@
import { useEffect, useRef, useState } from "react";
import mapboxgl from "mapbox-gl";
-import { useConfigs } from "../../../../lib/configs";
+import { useConfigs } from "../../../../../lib/configs";
-export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>) {
+export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>, enabled: boolean = true) {
const map = useRef<mapboxgl.Map | null>(null);
const [mapLoaded, setMapLoaded] = useState(false);
const { configs } = useConfigs();
useEffect(() => {
- if (!containerRef.current || !configs?.mapboxToken) {
+ if (!enabled || !containerRef.current || !configs?.mapboxToken) {
+ // Clean up if disabled or no container
+ if (map.current) {
+ map.current.remove();
+ map.current = null;
+ setMapLoaded(false);
+ }
+ return;
+ }
+
+ // Don't reinitialize if already exists
+ if (map.current) {
return;
}
@@ -49,10 +60,13 @@ export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>)
});
return () => {
- map.current?.remove();
- map.current = null;
+ if (map.current) {
+ map.current.remove();
+ map.current = null;
+ setMapLoaded(false);
+ }
};
- }, [containerRef, configs?.mapboxToken]);
+ }, [enabled, containerRef, configs?.mapboxToken]);
return { map, mapLoaded };
}
diff --git a/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
similarity index 81%
rename from client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
rename to client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
index f09dbb5f0..865316fe8 100644
--- a/client/src/app/[site]/globe/hooks/useSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
@@ -1,12 +1,11 @@
-import { useEffect, useMemo, useRef } from "react";
-import mapboxgl from "mapbox-gl";
import { FilterParameter } from "@rybbit/shared";
-import { addFilter } from "../../../../lib/store";
-import { useSingleCol } from "../../../../api/analytics/useSingleCol";
-import { useSubdivisions } from "../../../../lib/geo";
-import { processSubdivisionData } from "../utils/processData";
-import { createColorScale } from "../utils/colorScale";
-import { renderCountryFlag } from "../utils/renderCountryFlag";
+import mapboxgl from "mapbox-gl";
+import { useEffect, useMemo, useRef } from "react";
+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";
+import { useSubdivisions } from "../../../../../lib/geo";
+import { addFilter } from "../../../../../lib/store";
+import { createColorScale } from "../../utils/colorScale";
+import { renderCountryFlag } from "../../utils/renderCountryFlag";
interface UseSubdivisionsLayerProps {
map: React.RefObject<mapboxgl.Map | null>;
@@ -19,11 +18,10 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
const { data: subdivisionData } = useSingleCol({ parameter: "region", limit: 10000 });
const { data: subdivisionsGeoData } = useSubdivisions();
- const processedSubdivisionData = useMemo(() => processSubdivisionData(subdivisionData), [subdivisionData]);
- const colorScale = useMemo(() => createColorScale(processedSubdivisionData), [processedSubdivisionData]);
+ const colorScale = useMemo(() => createColorScale(subdivisionData?.data), [subdivisionData?.data]);
useEffect(() => {
- if (!map.current || !subdivisionsGeoData || !processedSubdivisionData || !mapLoaded) return;
+ if (!map.current || !subdivisionsGeoData || !subdivisionData?.data || !mapLoaded) return;
// Initialize popup once
if (!popupRef.current) {
@@ -40,9 +38,9 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
const geoDataCopy = JSON.parse(JSON.stringify(subdivisionsGeoData));
geoDataCopy.features.forEach((feature: any) => {
const code = feature.properties?.iso_3166_2;
- const foundData = processedSubdivisionData.find((d: any) => d.value === code);
+ const foundData = subdivisionData?.data?.find((d: any) => d.value === code);
const count = foundData?.count || 0;
- const color = count > 0 ? colorScale(count) : "rgba(140, 140, 140, 0.5)";
+ const color = count > 0 ? colorScale(count) : "rgba(0, 0, 0, 0)";
feature.properties.fillColor = color;
feature.properties.count = count;
});
@@ -75,7 +73,7 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
paint: {
"line-color": "#ffffff",
"line-width": 0.5,
- "line-opacity": 0.3,
+ "line-opacity": 0.2,
},
layout: {
visibility: mapView === "subdivisions" ? "visible" : "none",
@@ -138,5 +136,5 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
};
addSubdivisionsLayer();
- }, [subdivisionsGeoData, processedSubdivisionData, colorScale, map, subdivisionData, mapLoaded]);
+ }, [subdivisionsGeoData, subdivisionData?.data, colorScale, map, mapLoaded]);
}
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index 317955877..a8fb54b74 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -175,7 +175,7 @@ export function GlobeSessions() {
return (
<>
- <div className="space-y-2 bg-neutral-850/60 p-2 rounded-lg w-[371px] backdrop-blur-sm">
+ <div className="space-y-2 bg-neutral-850/60 p-2 rounded-lg w-[371px] backdrop-blur-sm border border-neutral-800">
<div className="text-sm text-neutral-200 font-medium flex items-center justify-between">
SESSIONS
<Button variant="ghost" size="smIcon" onClick={() => setExpanded(!expanded)}>
diff --git a/client/src/app/[site]/globe/components/ModeSelector.tsx b/client/src/app/[site]/globe/components/ModeSelector.tsx
index f0697722f..107bd0c11 100644
--- a/client/src/app/[site]/globe/components/ModeSelector.tsx
+++ b/client/src/app/[site]/globe/components/ModeSelector.tsx
@@ -1,13 +1,14 @@
import { Clock, Globe2, HouseIcon, Radio } from "lucide-react";
import { cn } from "@/lib/utils";
import { useGlobeStore } from "../globeStore";
+import { IS_CLOUD } from "../../../../lib/const";
export type MapView = "countries" | "subdivisions" | "coordinates" | "timeline";
interface TabButtonProps {
active: boolean;
onClick: () => void;
- icon: React.ReactNode;
+ icon?: React.ReactNode;
label: string;
}
@@ -16,45 +17,53 @@ function TabButton({ active, onClick, icon, label }: TabButtonProps) {
<button
onClick={onClick}
className={cn(
- "inline-flex items-center justify-center whitespace-nowrap rounded px-2 py-1 text-xs font-medium transition-all",
+ "h-[24px] inline-flex items-center justify-center whitespace-nowrap rounded px-2 py-1 text-xs font-medium transition-all",
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400",
active ? "bg-white/10 text-white" : "text-neutral-400 hover:text-neutral-200 hover:bg-white/[0.03]"
)}
>
{icon}
- {label}
+ <div className="hidden md:block">{label}</div>
</button>
);
}
export default function MapViewSelector() {
- const { mapView, setMapView } = useGlobeStore();
+ const { mapView, setMapView, mapMode, setMapMode } = useGlobeStore();
return (
- <div>
- <div className="inline-flex items-center gap-0.5 rounded-lg bg-neutral-900/40 backdrop-blur-sm p-0.5 border border-white/10">
+ <div className="flex items-center gap-2 overflow-x-auto w-full">
+ {IS_CLOUD && (
+ <button
+ className="text-xs font-medium rounded-lg bg-neutral-900/60 text-neutral-200 backdrop-blur-sm p-1.5 border border-white/10 hover:bg-neutral-700/60 hover:text-white transition-all"
+ onClick={() => setMapMode(mapMode === "2D" ? "3D" : "2D")}
+ >
+ {mapMode === "2D" ? "2D" : "3D"}
+ </button>
+ )}
+ <div className="flex items-center gap-0.5 rounded-lg bg-neutral-900/40 backdrop-blur-sm p-0.5 border border-white/10">
<TabButton
active={mapView === "timeline"}
onClick={() => setMapView("timeline")}
- icon={<Clock className="mr-1 opacity-60" size={14} />}
+ icon={<Clock className="mr-1 md:opacity-60" size={14} />}
label="Timeline"
/>
<TabButton
active={mapView === "coordinates"}
onClick={() => setMapView("coordinates")}
- icon={<Radio className="mr-1 opacity-60" size={14} />}
+ icon={<Radio className="mr-1 md:opacity-60" size={14} />}
label="Coordinates"
/>
<TabButton
active={mapView === "countries"}
onClick={() => setMapView("countries")}
- icon={<Globe2 className="mr-1 opacity-60" size={14} />}
+ icon={<Globe2 className="mr-1 md:opacity-60" size={14} />}
label="Countries"
/>
<TabButton
active={mapView === "subdivisions"}
onClick={() => setMapView("subdivisions")}
- icon={<HouseIcon className="mr-1 opacity-60" size={14} />}
+ icon={<HouseIcon className="mr-1 md:opacity-60" size={14} />}
label="Subdivisions"
/>
</div>
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
index 3644363f1..1b2bddb02 100644
--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -5,7 +5,7 @@ import { TimelineSlider } from "../../../../components/ui/timeline-slider";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../../../../components/ui/tooltip";
import { useTimelineStore, useActiveSessions } from "../timelineStore";
import { formatTimelineTime, generateTimeWindows, getSessionCountsPerWindow } from "../timelineUtils";
-import { MAX_PAGES, PAGE_SIZE } from "../hooks/timelineLayer/timelineLayerConstants";
+import { MAX_PAGES, PAGE_SIZE } from "../3d/hooks/timelineLayer/timelineLayerConstants";
export function TimelineScrubber() {
const { currentTime, timeRange, windowSize, setCurrentTime, allSessions, isLoading, hasMoreData } =
diff --git a/client/src/app/[site]/globe/globeStore.ts b/client/src/app/[site]/globe/globeStore.ts
index 2205a25ca..a101d2d6f 100644
--- a/client/src/app/[site]/globe/globeStore.ts
+++ b/client/src/app/[site]/globe/globeStore.ts
@@ -1,12 +1,17 @@
import { create } from "zustand";
import { MapView } from "./components/ModeSelector";
+import { IS_CLOUD } from "../../../lib/const";
interface GlobeStore {
mapView: MapView;
setMapView: (view: MapView) => void;
+ mapMode: "3D" | "2D";
+ setMapMode: (mode: "3D" | "2D") => void;
}
export const useGlobeStore = create<GlobeStore>(set => ({
mapView: "timeline",
setMapView: view => set({ mapView: view }),
+ mapMode: IS_CLOUD ? "3D" : "2D",
+ setMapMode: mode => set({ mapMode: mode }),
}));
diff --git a/client/src/app/[site]/globe/page.tsx b/client/src/app/[site]/globe/page.tsx
index 5808eb08a..a38a0a490 100644
--- a/client/src/app/[site]/globe/page.tsx
+++ b/client/src/app/[site]/globe/page.tsx
@@ -6,7 +6,6 @@ import "./globe.css";
import { VisuallyHidden } from "radix-ui";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { NothingFound } from "../../../components/NothingFound";
import { SessionCard } from "../../../components/Sessions/SessionCard";
import { Dialog, DialogContent, DialogTitle } from "../../../components/ui/dialog";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
@@ -14,18 +13,19 @@ import { SubHeader } from "../components/SubHeader/SubHeader";
import { GlobeSessions } from "./components/GlobeSessions";
import MapViewSelector from "./components/ModeSelector";
import { TimelineScrubber } from "./components/TimelineScrubber";
+import { OpenLayersMap } from "./2d/components/OpenLayersMap";
+import { MapboxMap } from "./3d/components/MapboxMap";
import { useGlobeStore } from "./globeStore";
-import { useTimelineLayer } from "./hooks/timelineLayer/useTimelineLayer";
-import { useCoordinatesLayer } from "./hooks/useCoordinatesLayer";
-import { useCountriesLayer } from "./hooks/useCountriesLayer";
-import { useLayerVisibility } from "./hooks/useLayerVisibility";
-import { useMapbox } from "./hooks/useMapbox";
-import { useSubdivisionsLayer } from "./hooks/useSubdivisionsLayer";
+import { useTimelineLayer } from "./3d/hooks/timelineLayer/useTimelineLayer";
+import { useCoordinatesLayer } from "./3d/hooks/useCoordinatesLayer";
+import { useCountriesLayer } from "./3d/hooks/useCountriesLayer";
+import { useLayerVisibility } from "./3d/hooks/useLayerVisibility";
+import { useMapbox } from "./3d/hooks/useMapbox";
+import { useSubdivisionsLayer } from "./3d/hooks/useSubdivisionsLayer";
import { useTimelineStore } from "./timelineStore";
-import { useTimelineSessions } from "./hooks/timelineLayer/useTimelineSessions";
+import { useTimelineSessions } from "./3d/hooks/timelineLayer/useTimelineSessions";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
import { WINDOW_SIZE_OPTIONS } from "./timelineUtils";
-import { useConfigs } from "../../../lib/configs";
export default function GlobePage() {
useSetPageTitle("Rybbit · Globe");
@@ -35,44 +35,36 @@ export default function GlobePage() {
// Fetch timeline sessions and update store
useTimelineSessions();
- // Handle window size change
- const handleWindowSizeChange = (value: string) => {
- const newSize = parseInt(value, 10);
- setManualWindowSize(newSize);
- };
+ const { mapView, mapMode } = useGlobeStore();
- const mapView = useGlobeStore(state => state.mapView);
-
- const { map, mapLoaded } = useMapbox(mapContainer);
+ const { map, mapLoaded } = useMapbox(mapContainer, mapMode === "3D");
useCountriesLayer({
map,
- mapLoaded,
+ mapLoaded: mapMode === "3D" && mapLoaded,
mapView,
});
useSubdivisionsLayer({
map,
- mapLoaded,
+ mapLoaded: mapMode === "3D" && mapLoaded,
mapView,
});
useCoordinatesLayer({
map,
- mapLoaded,
+ mapLoaded: mapMode === "3D" && mapLoaded,
minutes: 30,
mapView,
});
const { selectedSession, setSelectedSession } = useTimelineLayer({
map,
- mapLoaded,
+ mapLoaded: mapMode === "3D" && mapLoaded,
mapView,
});
- useLayerVisibility(map, mapView, mapLoaded);
-
- const { configs, isLoading } = useConfigs();
+ useLayerVisibility(map, mapView, mapMode === "3D" && mapLoaded);
return (
<DisabledOverlay message="Globe" featurePath="globe">
@@ -81,41 +73,25 @@ export default function GlobePage() {
<SubHeader />
</div>
<div className="absolute top-0 left-0 right-0 bottom-0 z-10">
- {configs?.mapboxToken ? (
- <div
- ref={mapContainer}
- className="w-full h-full [&_.mapboxgl-ctrl-bottom-left]:!hidden [&_.mapboxgl-ctrl-logo]:!hidden"
- />
- ) : isLoading ? null : (
- <div className="w-full h-full flex items-center justify-center">
- <NothingFound
- title="Mapbox access token not found"
- description={
- <p className="text-sm max-w-[600px] text-center">
- Please set the <code>MAPBOX_TOKEN</code> environment variable and rebuild all containers. To get a
- Mapbox token, please visit{" "}
- <a
- href="https://docs.mapbox.com/help/dive-deeper/access-tokens/"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-400 hover:underline"
- >
- Mapbox
- </a>{" "}
- and create an account.
- </p>
- }
- />
- </div>
+ {mapMode === "3D" ? (
+ <MapboxMap mapContainer={mapContainer} />
+ ) : (
+ <OpenLayersMap key="openlayers-map" mapView={mapView} onSessionSelect={setSelectedSession} />
)}
- <div className="absolute bottom-2 left-4 z-99999 right-4 flex flex-col gap-2 pointer-events-none">
- <div className="flex items-end gap-2 justify-between">
+ <div className="absolute bottom-2 left-2 right-2 md:right-4 md:left-4 z-99999 flex flex-col gap-2 pointer-events-none ">
+ <div className="flex items-end gap-2 justify-between overflow-x-auto">
<div className="pointer-events-auto">
<MapViewSelector />
</div>
{mapView === "timeline" ? (
<div className="pointer-events-auto">
- <Select value={windowSize.toString()} onValueChange={handleWindowSizeChange}>
+ <Select
+ value={windowSize.toString()}
+ onValueChange={(value: string) => {
+ const newSize = parseInt(value, 10);
+ setManualWindowSize(newSize);
+ }}
+ >
<SelectTrigger className="w-[100px]" size="sm">
<SelectValue />
</SelectTrigger>
@@ -129,7 +105,7 @@ export default function GlobePage() {
</Select>
</div>
) : (
- <div className="pointer-events-auto">
+ <div className="pointer-events-auto hidden md:block">
<GlobeSessions />
</div>
)}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts b/client/src/app/[site]/globe/utils/clusteringConstants.ts
similarity index 59%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts
rename to client/src/app/[site]/globe/utils/clusteringConstants.ts
index a77cd9f9b..8fcd235ed 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineLayerConstants.ts
+++ b/client/src/app/[site]/globe/utils/clusteringConstants.ts
@@ -1,24 +1,20 @@
-// Mapbox layer and source IDs
-export const SOURCE_ID = "timeline-sessions";
-export const CLUSTER_LAYER_ID = "timeline-clusters";
-export const CLUSTER_COUNT_LAYER_ID = "timeline-cluster-count";
-export const UNCLUSTERED_LAYER_ID = "timeline-unclustered-point";
+/**
+ * Shared clustering constants for both 2D and 3D globe maps
+ */
// Clustering configuration
// Maximum zoom level where clustering is applied. Beyond this zoom, all points are shown individually
export const CLUSTER_MAX_ZOOM = 11;
-// Radius in pixels within which points are grouped into clusters
-export const CLUSTER_RADIUS = 25;
+
// Minimum number of points required to form a visible cluster
-export const MIN_CLUSTER_SIZE = 10;
+export const MIN_CLUSTER_SIZE = 20;
+
// Only enable clustering when total session count exceeds this threshold (performance optimization)
export const CLUSTERING_THRESHOLD = 500;
-export const PAGE_SIZE = 10000;
-export const MAX_PAGES = 10;
-
// Point spreading configuration (for overlapping coordinates)
// Zoom level at which points at the same location start spreading apart
export const SPREAD_START_ZOOM = 8;
+
// Maximum offset in degrees to apply when spreading points (roughly 11 meters at equator)
export const SPREAD_RADIUS_DEGREES = 0.006;
diff --git a/client/src/app/[site]/globe/utils/colorScale.ts b/client/src/app/[site]/globe/utils/colorScale.ts
index 4f54bb8db..319503ca8 100644
--- a/client/src/app/[site]/globe/utils/colorScale.ts
+++ b/client/src/app/[site]/globe/utils/colorScale.ts
@@ -1,7 +1,7 @@
import { scalePow } from "d3-scale";
-export function createColorScale(data: any[] | null): (value: number) => string {
- if (!data) return () => "#eee";
+export function createColorScale(data?: any[] | null): (value: number) => string {
+ if (!data) return () => "#222";
const getComputedColor = (cssVar: string) => {
const hslValues = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
diff --git a/client/src/app/[site]/globe/utils/processData.ts b/client/src/app/[site]/globe/utils/processData.ts
deleted file mode 100644
index dfea9b61b..000000000
--- a/client/src/app/[site]/globe/utils/processData.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { getCountryPopulation } from "../../../../lib/countryPopulation";
-
-export function processCountryData(countryData: any) {
- if (!countryData?.data) return null;
-
- return countryData.data.map((item: any) => {
- const population = getCountryPopulation(item.value);
- const perCapitaValue = population > 0 ? item.count / population : 0;
- return {
- ...item,
- perCapita: perCapitaValue,
- };
- });
-}
-
-export function processSubdivisionData(subdivisionData: any) {
- if (!subdivisionData?.data) return null;
-
- return subdivisionData.data.map((item: any) => {
- const countryCode = item.value?.split("-")[0];
- const population = getCountryPopulation(countryCode);
- const perCapitaValue = population > 0 ? item.count / (population / 10) : 0;
- return {
- ...item,
- perCapita: perCapitaValue,
- };
- });
-}
diff --git a/client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
similarity index 89%
rename from client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts
rename to client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
index 862ba84b9..2bdbb3e6e 100644
--- a/client/src/app/[site]/globe/hooks/timelineLayer/timelineTooltipBuilder.ts
+++ b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
@@ -3,10 +3,10 @@ import { createElement } from "react";
// @ts-ignore - React 19 has built-in types
import { renderToStaticMarkup } from "react-dom/server";
import { Eye, MousePointerClick } from "lucide-react";
-import { generateName } from "../../../../../components/Avatar";
-import { formatShortDuration, hour12, userLocale } from "../../../../../lib/dateTimeUtils";
-import type { GetSessionsResponse } from "../../../../../api/analytics/userSessions";
-import { extractDomain, getDisplayName } from "../../../../../components/Channel";
+import { generateName } from "../../../../components/Avatar";
+import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
+import type { GetSessionsResponse } from "../../../../api/analytics/userSessions";
+import { extractDomain, getDisplayName } from "../../../../components/Channel";
import {
generateAvatarSVG,
renderCountryFlag,
@@ -14,16 +14,12 @@ import {
renderChannelIcon,
getBrowserIconPath,
getOSIconPath,
-} from "./timelineMarkerHelpers";
+} from "../3d/hooks/timelineLayer/timelineMarkerHelpers";
/**
* Build the HTML content for a session tooltip
*/
-export function buildTooltipHTML(
- session: GetSessionsResponse[number],
- lng: number,
- lat: number
-): string {
+export function buildTooltipHTML(session: GetSessionsResponse[number], lng: number, lat: number): string {
const avatarSVG = generateAvatarSVG(session.user_id, 36);
const countryCode = session.country?.length === 2 ? session.country : "";
const flagSVG = renderCountryFlag(countryCode);
@@ -77,7 +73,7 @@ export function buildTooltipHTML(
</div>
</div>
</div>
- <div class="flex flex-wrap items-center gap-1.5">
+ <div class="flex flex-wrap items-center gap-1.5 whitespace-nowrap">
${browserIconPath ? `<img src="${browserIconPath}" alt="${session.browser}" title="${session.browser}" class="w-4 h-4" />` : ""}
${osIconPath ? `<img src="${osIconPath}" alt="${session.operating_system}" title="${session.operating_system}" class="w-4 h-4" />` : ""}
<span class="flex items-center" title="${session.device_type}">${deviceIconSVG}</span>
diff --git a/client/src/app/[site]/main/components/sections/Countries.tsx b/client/src/app/[site]/main/components/sections/Countries.tsx
index 2c98135b1..57b8a5513 100644
--- a/client/src/app/[site]/main/components/sections/Countries.tsx
+++ b/client/src/app/[site]/main/components/sections/Countries.tsx
@@ -7,8 +7,8 @@ import { getCountryName, getLanguageName } from "../../../../../lib/utils";
import { StandardSection } from "../../../components/shared/StandardSection/StandardSection";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
import { useSubdivisions } from "../../../../../lib/geo";
-import { MapComponent } from "../../../components/shared/Map";
import { Button } from "../../../../../components/ui/button";
+import { MapComponent } from "../../../components/shared/Map/MapComponent";
type Tab = "countries" | "regions" | "languages" | "cities" | "map";
diff --git a/client/src/app/[site]/map/page.tsx b/client/src/app/[site]/map/page.tsx
deleted file mode 100644
index f8a042e15..000000000
--- a/client/src/app/[site]/map/page.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-"use client";
-
-import { Switch } from "@/components/ui/switch";
-import { useState } from "react";
-import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
-import { cn } from "../../../lib/utils";
-import { MapComponent } from "../components/shared/Map";
-import { SubHeader } from "../components/SubHeader/SubHeader";
-import { DisabledOverlay } from "../../../components/DisabledOverlay";
-
-export default function MapPage() {
- useSetPageTitle("Rybbit · Map");
-
- const [mapMode, setMapMode] = useState<"total" | "perCapita">("total");
- const [mapView, setMapView] = useState<"countries" | "subdivisions">("countries");
-
- return (
- <DisabledOverlay message="Map" featurePath="map">
- <div className="relative w-full h-dvh">
- <div className="p-2 md:p-4 relative z-50">
- <SubHeader />
- </div>
- <div className="absolute bottom-2 md:bottom-4 left-2 md:left-4 z-50 bg-neutral-900 rounded-md">
- <div className="flex items-center gap-3 px-3 py-2 text-sm">
- <span className={cn(mapView === "countries" ? "text-white" : "text-neutral-400")}>Countries</span>
- <Switch
- checked={mapView === "subdivisions"}
- onCheckedChange={checked => setMapView(checked ? "subdivisions" : "countries")}
- className="data-[state=checked]:bg-accent-400"
- />
- <span className={cn(mapView === "subdivisions" ? "text-white" : "text-neutral-400")}>Subdivisions</span>
- </div>
- <div className="flex items-center gap-3 px-3 py-2 text-sm">
- <span className={cn(mapMode === "total" ? "text-white" : "text-neutral-400")}>Total Visits</span>
- <Switch
- checked={mapMode === "perCapita"}
- onCheckedChange={checked => setMapMode(checked ? "perCapita" : "total")}
- className="data-[state=checked]:bg-accent-400"
- />
- <span className={cn(mapMode === "perCapita" ? "text-white" : "text-neutral-400")}>Per Capita</span>
- </div>
- </div>
- <div className="absolute top-0 left-0 right-0 bottom-0 z-10">
- <MapComponent height="calc(100vh - 40px)" mode={mapMode} mapView={mapView} />
- </div>
- </div>
- </DisabledOverlay>
- );
-}
diff --git a/client/src/app/[site]/performance/components/PerformanceMap.tsx b/client/src/app/[site]/performance/components/PerformanceMap.tsx
index 3a5f7fc52..de34833db 100644
--- a/client/src/app/[site]/performance/components/PerformanceMap.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceMap.tsx
@@ -2,12 +2,16 @@
import { useGetPerformanceByDimension } from "@/api/analytics/performance/useGetPerformanceByDimension";
import { useMeasure } from "@uidotdev/usehooks";
-import { scalePow } from "d3-scale";
-import { Feature, GeoJsonObject } from "geojson";
-import { Layer } from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { useEffect, useMemo, useState } from "react";
-import { GeoJSON, MapContainer } from "react-leaflet";
+import { Feature } from "geojson";
+import "ol/ol.css";
+import { useEffect, useMemo, useRef, useState } from "react";
+import Map from "ol/Map";
+import View from "ol/View";
+import { fromLonLat } from "ol/proj";
+import VectorLayer from "ol/layer/Vector";
+import VectorSource from "ol/source/Vector";
+import GeoJSON from "ol/format/GeoJSON";
+import { Style, Fill, Stroke } from "ol/style";
import { useCountries } from "../../../../lib/geo";
import { addFilter } from "../../../../lib/store";
import { CountryFlag } from "../../components/shared/icons/CountryFlag";
@@ -19,6 +23,7 @@ import {
getMetricUnit,
METRIC_LABELS_SHORT,
} from "../utils/performanceUtils";
+import type { FeatureLike } from "ol/Feature";
interface TooltipContent {
name: string;
@@ -66,6 +71,11 @@ export function PerformanceMap({ height }: { height: string }) {
// Track which feature is currently hovered to control opacity without conflicts
const [hoveredId, setHoveredId] = useState<string | null>(null);
+ const mapRef = useRef<HTMLDivElement>(null);
+ const mapInstanceRef = useRef<Map | null>(null);
+ const vectorLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
+ const processedPerformanceDataRef = useRef<any>(null);
+
// Process performance data to get the selected metric values
const processedPerformanceData = useMemo(() => {
if (!performanceData?.data) return null;
@@ -82,6 +92,11 @@ export function PerformanceMap({ height }: { height: string }) {
});
}, [performanceData?.data, selectedPercentile, selectedPerformanceMetric]);
+ // Update ref when data changes
+ useEffect(() => {
+ processedPerformanceDataRef.current = processedPerformanceData;
+ }, [processedPerformanceData]);
+
// Create color scale from green (good) to red (poor) based on Web Vitals thresholds
const colorScale = useMemo(() => {
if (!processedPerformanceData) return () => "#eee";
@@ -112,34 +127,43 @@ export function PerformanceMap({ height }: { height: string }) {
const { data: countriesGeoData } = useCountries();
- const handleStyle = (feature: Feature | undefined) => {
- const countryCode = feature?.properties?.["ISO_A2"];
+ const isLoadingData = isLoading || isFetching;
- const foundData = processedPerformanceData?.find((item: any) => item.country === countryCode);
+ const [ref, { height: resolvedHeight }] = useMeasure();
- const metricValue = foundData?.metricValue || 0;
- const color = foundData && metricValue > 0 ? colorScale(metricValue) : "rgba(140, 140, 140, 0.3)";
+ const zoom = resolvedHeight ? Math.log2(resolvedHeight / 400) + 1 : 1;
- return {
- color: color,
- weight: 1,
- fill: true,
- fillColor: color,
- // Increase opacity if this feature is currently hovered
- fillOpacity: hoveredId === countryCode ? 0.9 : 0.6,
- };
- };
+ // Initialize map
+ useEffect(() => {
+ if (!mapRef.current) return;
+
+ const map = new Map({
+ target: mapRef.current,
+ view: new View({
+ center: fromLonLat([3, 40]),
+ zoom: zoom,
+ }),
+ controls: [],
+ });
+
+ mapInstanceRef.current = map;
+
+ // Handle pointer move for hover effects
+ map.on("pointermove", (evt) => {
+ if (evt.dragging) {
+ return;
+ }
- const handleEachFeature = (feature: Feature, layer: Layer) => {
- layer.on({
- mouseover: () => {
- const countryCode = feature.properties?.["ISO_A2"];
- const countryName = feature.properties?.["ADMIN"];
+ const pixel = map.getEventPixel(evt.originalEvent);
+ const feature = map.forEachFeatureAtPixel(pixel, (feature) => feature);
+
+ if (feature) {
+ const countryCode = feature.get("ISO_A2");
+ const countryName = feature.get("ADMIN");
- // Mark this feature as hovered
setHoveredId(countryCode);
- const foundData = processedPerformanceData?.find((item: any) => item.country === countryCode);
+ const foundData = processedPerformanceDataRef.current?.find((item: any) => item.country === countryCode);
if (foundData) {
setTooltipContent({
@@ -158,14 +182,29 @@ export function PerformanceMap({ height }: { height: string }) {
metricName: METRIC_LABELS_SHORT[selectedPerformanceMetric],
});
}
- },
- mouseout: () => {
- // Clear hover state
+
+ // Update tooltip position
+ const [x, y] = evt.pixel;
+ const rect = mapRef.current?.getBoundingClientRect();
+ if (rect) {
+ setTooltipPosition({
+ x: rect.left + x,
+ y: rect.top + y,
+ });
+ }
+ } else {
setHoveredId(null);
setTooltipContent(null);
- },
- click: () => {
- const countryCode = feature.properties?.["ISO_A2"];
+ }
+ });
+
+ // Handle click for filtering
+ map.on("click", (evt) => {
+ const pixel = map.getEventPixel(evt.originalEvent);
+ const feature = map.forEachFeatureAtPixel(pixel, (feature) => feature);
+
+ if (feature) {
+ const countryCode = feature.get("ISO_A2");
// Add country filter
addFilter({
@@ -173,26 +212,99 @@ export function PerformanceMap({ height }: { height: string }) {
value: [countryCode],
type: "equals",
});
- },
+ }
});
- };
- const isLoadingData = isLoading || isFetching;
+ return () => {
+ map.setTarget(undefined);
+ };
+ }, []);
- const [ref, { height: resolvedHeight }] = useMeasure();
+ // Update zoom when height changes
+ useEffect(() => {
+ if (mapInstanceRef.current && zoom) {
+ mapInstanceRef.current.getView().setZoom(zoom);
+ }
+ }, [zoom]);
- const zoom = resolvedHeight ? Math.log2(resolvedHeight / 400) + 1 : 1;
+ // Update vector layer when geo data changes
+ useEffect(() => {
+ if (!mapInstanceRef.current) return;
+ if (!countriesGeoData) return;
+
+ // Wait for performance data to be available
+ if (!processedPerformanceData) return;
+
+ // Remove existing layer
+ if (vectorLayerRef.current) {
+ mapInstanceRef.current.removeLayer(vectorLayerRef.current);
+ }
+
+ // Create new vector source with GeoJSON data
+ const vectorSource = new VectorSource({
+ features: new GeoJSON().readFeatures(countriesGeoData, {
+ featureProjection: "EPSG:3857",
+ }),
+ });
+
+ // Create new vector layer with inline style function
+ const vectorLayer = new VectorLayer({
+ source: vectorSource,
+ style: (feature) => {
+ const countryCode = feature.get("ISO_A2");
+
+ const foundData = processedPerformanceDataRef.current?.find((item: any) => item.country === countryCode);
+
+ const metricValue = foundData?.metricValue || 0;
+
+ let fillColor: string;
+ let strokeColor: string;
+
+ if (foundData && metricValue > 0) {
+ // Get the color from the scale (already has opacity built in)
+ const baseColor = colorScale(metricValue);
+
+ if (hoveredId === countryCode) {
+ // Increase opacity on hover
+ fillColor = baseColor.replace(/,\s*([\d.]+)\)$/, (match, opacity) => {
+ const newOpacity = Math.min(parseFloat(opacity) + 0.2, 1);
+ return `, ${newOpacity})`;
+ });
+ } else {
+ // Use the color directly from the scale
+ fillColor = baseColor;
+ }
+ strokeColor = baseColor;
+ } else {
+ fillColor = "rgba(140, 140, 140, 0.2)";
+ strokeColor = "rgba(140, 140, 140, 0.3)";
+ }
+
+ return new Style({
+ fill: new Fill({
+ color: fillColor,
+ }),
+ stroke: new Stroke({
+ color: strokeColor,
+ width: 1,
+ }),
+ });
+ },
+ });
+
+ vectorLayerRef.current = vectorLayer;
+ mapInstanceRef.current.addLayer(vectorLayer);
+ }, [countriesGeoData, dataVersion, selectedPercentile, selectedPerformanceMetric, colorScale, processedPerformanceData]);
+
+ // Update styles when hoveredId changes (without recreating the layer)
+ useEffect(() => {
+ if (vectorLayerRef.current) {
+ vectorLayerRef.current.changed();
+ }
+ }, [hoveredId]);
return (
<div
- onMouseMove={e => {
- if (tooltipContent) {
- setTooltipPosition({
- x: e.clientX,
- y: e.clientY,
- });
- }
- }}
style={{
height: height,
}}
@@ -206,29 +318,16 @@ export function PerformanceMap({ height }: { height: string }) {
</div>
</div>
)}
- {countriesGeoData && (
- <MapContainer
- preferCanvas={true}
- attributionControl={false}
- zoomControl={false}
- center={[40, 3]}
- zoom={zoom}
- style={{
- height: "100%",
- background: "none",
- cursor: "default",
- outline: "none",
- zIndex: "1",
- }}
- >
- <GeoJSON
- key={`performance-countries-${dataVersion}-${selectedPercentile}-${selectedPerformanceMetric}`}
- data={countriesGeoData as GeoJsonObject}
- style={handleStyle}
- onEachFeature={handleEachFeature}
- />
- </MapContainer>
- )}
+ <div
+ ref={mapRef}
+ style={{
+ height: "100%",
+ width: "100%",
+ background: "none",
+ cursor: "default",
+ outline: "none",
+ }}
+ />
{tooltipContent && (
<div
className="fixed z-50 bg-neutral-1000 text-white rounded-md p-3 shadow-lg text-sm pointer-events-none max-w-xs"
diff --git a/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx b/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
deleted file mode 100644
index ba34764b5..000000000
--- a/client/src/app/[site]/realtime/RealtimeMap/RealtimeMap.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-"use client";
-
-import { useGetSessionLocations } from "@/api/analytics/useGetSessionLocations";
-import { scaleSqrt } from "d3-scale";
-import { Feature, GeoJsonObject } from "geojson";
-import { Layer } from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { useMemo, useState } from "react";
-import { Circle, GeoJSON, MapContainer, useMapEvent } from "react-leaflet";
-import { useCountries } from "../../../../lib/geo";
-
-// Component to handle zoom events and update circle sizes
-function ZoomHandler({ setZoom }: { setZoom: (zoom: number) => void }) {
- const map = useMapEvent("zoom", () => {
- setZoom(map.getZoom());
- });
- return null;
-}
-
-interface TooltipContent {
- count: number;
- city: string;
-}
-
-interface TooltipPosition {
- x: number;
- y: number;
-}
-
-export function RealtimeMap() {
- const { data: liveSessionLocations, isLoading: isLiveSessionLocationsLoading } = useGetSessionLocations();
- const { data: countriesGeoData } = useCountries();
- const [currentZoom, setCurrentZoom] = useState(1.5); // Initial zoom level
- const [tooltipContent, setTooltipContent] = useState<TooltipContent | null>(null);
- const [tooltipPosition, setTooltipPosition] = useState<TooltipPosition>({
- x: 0,
- y: 0,
- });
-
- // Create a scale for circle radius based on count
- const radiusScale = useMemo(() => {
- if (!liveSessionLocations?.length) return () => 0;
-
- const maxCount = Math.max(...liveSessionLocations.map(loc => loc.count));
-
- // Use sqrt scale to make small values more visible
- // This directly scales radius (not area) which makes small circles more noticeable
- const baseScale = scaleSqrt().domain([1, maxCount]).range([50000, 500000]); // Min/max radius in meters
-
- return (count: number) => {
- const baseRadius = baseScale(count);
- // Reduce radius gradually as zoom increases
- const zoomFactor = Math.pow(0.75, currentZoom - 1.5);
- return baseRadius * zoomFactor;
- };
- }, [liveSessionLocations, currentZoom]);
-
- const handleStyle = (feature: Feature | undefined) => {
- const count = feature?.properties?.["count"] || 0;
- return {
- color: "rgba(140, 140, 140, 0.5)",
- weight: 0.5,
- fill: true,
- fillColor: "rgba(140, 140, 140, 0.5)",
- fillOpacity: 0.2,
- };
- };
-
- const handleEachFeature = (feature: Feature, layer: Layer) => {
- layer.on({
- mouseover: () => {
- // @ts-ignore
- layer.setStyle({
- fillOpacity: 0.5,
- });
- },
- mouseout: () => {
- // @ts-ignore
- layer.setStyle({
- fillOpacity: 0.2,
- });
- },
- });
- };
-
- return (
- <div>
- <div
- className="w-full h-[600px] rounded-lg overflow-hidden border border-neutral-850"
- onMouseMove={e => {
- if (tooltipContent) {
- setTooltipPosition({
- x: e.clientX,
- y: e.clientY,
- });
- }
- }}
- >
- <MapContainer
- center={[30, 0]}
- zoom={1.5}
- minZoom={1}
- style={{ height: "100%", width: "100%", background: "none" }}
- attributionControl={false}
- zoomControl={false}
- >
- <ZoomHandler setZoom={setCurrentZoom} />
- {countriesGeoData && (
- <GeoJSON
- data={countriesGeoData as GeoJsonObject}
- style={handleStyle}
- // onEachFeature={handleEachFeature}
- />
- )}
- {liveSessionLocations?.map((location, index) => (
- <Circle
- key={`${location.lat}-${location.lon}-${index}`}
- center={[location.lat, location.lon]}
- radius={radiusScale(location.count)}
- pathOptions={{
- fillColor: "hsl(var(--accent-500))",
- fillOpacity: 0.4,
- color: "hsl(var(--accent-400))",
- weight: 0,
- }}
- eventHandlers={{
- mouseover: e => {
- setTooltipContent({
- count: location.count,
- city: location.city,
- });
- setTooltipPosition({
- x: e.originalEvent.clientX,
- y: e.originalEvent.clientY,
- });
- },
- mouseout: () => {
- setTooltipContent(null);
- },
- mousemove: e => {
- setTooltipPosition({
- x: e.originalEvent.clientX,
- y: e.originalEvent.clientY,
- });
- },
- }}
- />
- ))}
- </MapContainer>
-
- {tooltipContent && (
- <div
- className="fixed bg-neutral-1000 text-white rounded-md p-2 shadow-lg text-sm pointer-events-none"
- style={{
- left: tooltipPosition.x,
- top: tooltipPosition.y - 10,
- transform: "translate(-50%, -100%)",
- zIndex: 500,
- }}
- >
- <div className="font-sm">
- <span className="font-bold text-accent-400">{tooltipContent.count.toLocaleString()}</span>{" "}
- <span className="text-neutral-300">
- active {tooltipContent.count === 1 ? "user" : "users"}
- {tooltipContent.city ? ` from ${tooltipContent.city}` : ""}
- </span>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/client/src/lib/countryPopulation.ts b/client/src/lib/countryPopulation.ts
deleted file mode 100644
index 002cbeda1..000000000
--- a/client/src/lib/countryPopulation.ts
+++ /dev/null
@@ -1,213 +0,0 @@
-// Population data in millions (2023 estimates)
-export const countryPopulations: Record<string, number> = {
- // Major countries
- US: 331.9, // United States
- CN: 1412.2, // China
- IN: 1408.0, // India
- ID: 273.8, // Indonesia
- PK: 231.4, // Pakistan
- BR: 214.3, // Brazil
- NG: 213.4, // Nigeria
- BD: 169.4, // Bangladesh
- RU: 145.5, // Russia
- MX: 126.7, // Mexico
- JP: 125.7, // Japan
- PH: 115.6, // Philippines
- ET: 123.4, // Ethiopia
- EG: 110.0, // Egypt
- VN: 98.2, // Vietnam
- CD: 99.0, // DR Congo
- TR: 84.3, // Turkey
- IR: 87.9, // Iran
- DE: 83.8, // Germany
- TH: 71.7, // Thailand
- GB: 67.3, // United Kingdom
- FR: 65.5, // France
- TZ: 63.6, // Tanzania
- ZA: 59.3, // South Africa
- IT: 60.3, // Italy
- KE: 54.0, // Kenya
- MM: 54.8, // Myanmar
- CO: 51.5, // Colombia
- KR: 51.3, // South Korea
- UG: 47.1, // Uganda
- ES: 47.4, // Spain
- AR: 45.8, // Argentina
- DZ: 44.6, // Algeria
- SD: 45.7, // Sudan
- UA: 43.8, // Ukraine (pre-war estimate)
- IQ: 43.5, // Iraq
- AF: 38.9, // Afghanistan
- PL: 37.8, // Poland
- CA: 38.2, // Canada
- MR: 3.0, // Mauritania
- SA: 35.3, // Saudi Arabia
- UZ: 34.2, // Uzbekistan
- PE: 33.4, // Peru
- AO: 34.5, // Angola
- MY: 33.6, // Malaysia
- GH: 32.8, // Ghana
- MZ: 32.9, // Mozambique
- YE: 33.7, // Yemen
- NP: 30.0, // Nepal
- VE: 28.4, // Venezuela
- CM: 27.9, // Cameroon
- CI: 27.5, // Côte d'Ivoire
- AU: 25.7, // Australia
- NE: 25.4, // Niger
- TW: 23.8, // Taiwan
- SY: 21.3, // Syria
- ML: 21.9, // Mali
- BF: 21.5, // Burkina Faso
- MW: 19.6, // Malawi
- ZM: 19.4, // Zambia
- KZ: 18.9, // Kazakhstan
- CL: 19.2, // Chile
- EC: 17.9, // Ecuador
- GT: 17.1, // Guatemala
- SN: 17.2, // Senegal
- RS: 6.7, // Serbia
- NL: 17.5, // Netherlands
- KH: 16.7, // Cambodia
- TD: 17.4, // Chad
- SO: 17.1, // Somalia
- ZW: 15.2, // Zimbabwe
- GN: 13.5, // Guinea
- RW: 13.4, // Rwanda
- BJ: 13.0, // Benin
- BI: 12.5, // Burundi
- TN: 12.0, // Tunisia
- BO: 11.7, // Bolivia
- BE: 11.6, // Belgium
- HT: 11.5, // Haiti
- CU: 11.3, // Cuba
- SS: 11.3, // South Sudan
- DO: 10.9, // Dominican Republic
- JO: 10.2, // Jordan
- CZ: 10.7, // Czech Republic
- SE: 10.4, // Sweden
- AZ: 10.2, // Azerbaijan
- GR: 10.6, // Greece
- PT: 10.2, // Portugal
- AE: 9.9, // United Arab Emirates
- HU: 9.7, // Hungary
- TJ: 9.5, // Tajikistan
- BY: 9.4, // Belarus
- IL: 9.2, // Israel
- AT: 9.1, // Austria
- CH: 8.7, // Switzerland
- PG: 9.1, // Papua New Guinea
- HN: 10.0, // Honduras
- TG: 8.6, // Togo
- SL: 8.1, // Sierra Leone
- LA: 7.4, // Laos
- PY: 7.3, // Paraguay
- NI: 6.8, // Nicaragua
- LY: 7.0, // Libya
- SV: 6.5, // El Salvador
- KG: 6.5, // Kyrgyzstan
- TM: 6.0, // Turkmenistan
- SG: 5.9, // Singapore
- DK: 5.8, // Denmark
- FI: 5.5, // Finland
- SK: 5.4, // Slovakia
- NO: 5.4, // Norway
- CG: 5.8, // Congo (Brazzaville)
- ER: 3.6, // Eritrea
- IE: 5.0, // Ireland
- PS: 5.1, // Palestine
- CR: 5.1, // Costa Rica
- NZ: 5.1, // New Zealand
- LB: 6.8, // Lebanon
- CF: 4.9, // Central African Republic
- OM: 5.1, // Oman
- PA: 4.3, // Panama
- KW: 4.3, // Kuwait
- HR: 4.0, // Croatia
- GE: 3.7, // Georgia
- UY: 3.5, // Uruguay
- BA: 3.3, // Bosnia and Herzegovina
- MN: 3.3, // Mongolia
- MD: 2.6, // Moldova
- JM: 2.9, // Jamaica
- AM: 2.9, // Armenia
- AL: 2.8, // Albania
- QA: 2.9, // Qatar
- RO: 19.1, // Romania
- LT: 2.8, // Lithuania
- BW: 2.4, // Botswana
- NA: 2.5, // Namibia
- GM: 2.4, // Gambia
- GA: 2.3, // Gabon
- LS: 2.1, // Lesotho
- SI: 2.1, // Slovenia
- MK: 2.1, // North Macedonia
- LV: 1.9, // Latvia
- GW: 2.0, // Guinea-Bissau
- GQ: 1.4, // Equatorial Guinea
- TT: 1.4, // Trinidad and Tobago
- BH: 1.7, // Bahrain
- TL: 1.3, // Timor-Leste
- EE: 1.3, // Estonia
- MU: 1.3, // Mauritius
- CY: 0.9, // Cyprus
- SZ: 1.2, // Eswatini
- DJ: 1.0, // Djibouti
- FJ: 0.9, // Fiji
- RE: 0.9, // Réunion
- KM: 0.8, // Comoros
- GY: 0.8, // Guyana
- BT: 0.8, // Bhutan
- SB: 0.7, // Solomon Islands
- MQ: 0.4, // Martinique
- LU: 0.6, // Luxembourg
- SR: 0.6, // Suriname
- CV: 0.6, // Cabo Verde
- MV: 0.5, // Maldives
- MT: 0.5, // Malta
- BN: 0.4, // Brunei
- BG: 6.8, // Bulgaria
- BZ: 0.4, // Belize
- BS: 0.4, // Bahamas
- IS: 0.4, // Iceland
- GP: 0.4, // Guadeloupe
- VU: 0.3, // Vanuatu
- NC: 0.3, // New Caledonia
- PF: 0.3, // French Polynesia
- WS: 0.2, // Samoa
- ST: 0.2, // Sao Tome and Principe
- KI: 0.1, // Kiribati
- FM: 0.1, // Micronesia
- TO: 0.1, // Tonga
- SC: 0.1, // Seychelles
- VC: 0.1, // Saint Vincent and the Grenadines
- GD: 0.1, // Grenada
- LC: 0.1, // Saint Lucia
- AG: 0.1, // Antigua and Barbuda
- DM: 0.1, // Dominica
- KN: 0.05, // Saint Kitts and Nevis
- MH: 0.06, // Marshall Islands
- SM: 0.03, // San Marino
- MC: 0.04, // Monaco
- LI: 0.04, // Liechtenstein
- AD: 0.08, // Andorra
- PW: 0.02, // Palau
- TV: 0.01, // Tuvalu
- NR: 0.01, // Nauru
- VA: 0.001, // Vatican City
-
- // Default population for countries not in the list (use with caution)
- XX: 1.0, // Default value (reduced from 5.0)
-};
-
-// Helper function to get population with fallback
-export function getCountryPopulation(countryCode: string): number {
- if (!countryCode) return 1;
-
- // Normalize to uppercase and get first 2 characters (ISO2 code)
- const normalizedCode = countryCode.slice(0, 2).toUpperCase();
-
- // Use 1 million as default if country not found or has 0 pop
- const population = countryPopulations[normalizedCode] || countryPopulations.XX || 1;
- return Math.max(population, 0.001); // Ensure a minimum population to avoid division by zero
-}
diff --git a/docker-compose.yml b/docker-compose.yml
index 3881da3ff..bdefc37e9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -94,7 +94,6 @@ services:
- BASE_URL=${BASE_URL}
- DISABLE_SIGNUP=${DISABLE_SIGNUP}
- DISABLE_TELEMETRY=${DISABLE_TELEMETRY}
- - MAPBOX_TOKEN=${MAPBOX_TOKEN}
# # Redis configuration
# - REDIS_HOST=redis
# - REDIS_PORT=6379
@@ -122,14 +121,12 @@ services:
args:
NEXT_PUBLIC_BACKEND_URL: ${BASE_URL}
NEXT_PUBLIC_DISABLE_SIGNUP: ${DISABLE_SIGNUP}
- NEXT_PUBLIC_MAPBOX_TOKEN: ${MAPBOX_TOKEN}
ports:
- "${HOST_CLIENT_PORT:-127.0.0.1:3002:3002}"
environment:
- NODE_ENV=production
- NEXT_PUBLIC_BACKEND_URL=${BASE_URL}
- NEXT_PUBLIC_DISABLE_SIGNUP=${DISABLE_SIGNUP}
- - NEXT_PUBLIC_MAPBOX_TOKEN=${MAPBOX_TOKEN}
depends_on:
- backend
restart: unless-stopped