🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor Sidebar and Map components for enhanced functionality and user experience
Bill Yang974db81ec141
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 33426b0b4..d8adab2c9 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -52,18 +52,6 @@ export function Sidebar() {href={getTabPath("main")}icon={<LayoutDashboard className="w-4 h-4" />}/>- <SidebarLink- label="Sessions"- active={isActiveTab("sessions")}- href={getTabPath("sessions")}- icon={<Rewind className="w-4 h-4" />}- />- <SidebarLink- label="Users"- active={isActiveTab("users")}- href={getTabPath("users")}- icon={<User className="w-4 h-4" />}- /><SidebarLinklabel="Realtime"active={isActiveTab("realtime")}@@ -76,6 +64,18 @@ export function Sidebar() {href={getTabPath("map")}icon={<Map className="w-4 h-4" />}/>+ <SidebarLink+ label="Sessions"+ active={isActiveTab("sessions")}+ href={getTabPath("sessions")}+ icon={<Rewind className="w-4 h-4" />}+ />+ <SidebarLink+ label="Users"+ active={isActiveTab("users")}+ href={getTabPath("users")}+ icon={<User className="w-4 h-4" />}+ /><SidebarLinklabel="Retention"active={isActiveTab("retention")}diff --git a/client/src/app/[site]/components/shared/Map.tsx b/client/src/app/[site]/components/shared/Map.tsxindex 7c01d34e3..553e8a3a4 100644--- a/client/src/app/[site]/components/shared/Map.tsx+++ b/client/src/app/[site]/components/shared/Map.tsx@@ -11,12 +11,14 @@ import { GeoJSON, MapContainer, useMapEvent } from "react-leaflet";import { useCountries, useSubdivisions } from "../../../../lib/geo";import { addFilter, FilterParameter } from "../../../../lib/store";import { CountryFlag } from "./icons/CountryFlag";+import { getCountryPopulation } from "../../../../lib/countryPopulation";interface TooltipContent {name: string;code: string;count: number;percentage: number;+ perCapita?: number; // Visits per million people}interface TooltipPosition {@@ -24,7 +26,13 @@ interface TooltipPosition {y: number;}-export function MapComponent({ height }: { height: string }) {+export function MapComponent({+ height,+ mode = "total",+}: {+ height: string;+ mode?: "total" | "perCapita";+}) {const {data: countryData,isLoading: isCountryLoading,@@ -62,13 +70,44 @@ export function MapComponent({ height }: { height: string }) {// Track which feature is currently hovered to control opacity without conflictsconst [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" && !countryData?.data) return () => "#eee";- if (mapView === "subdivisions" && !subdivisionData?.data)+ if (mapView === "countries" && !processedCountryData) return () => "#eee";+ if (mapView === "subdivisions" && !processedSubdivisionData)return () => "#eee";const dataToUse =- mapView === "countries" ? countryData?.data : subdivisionData?.data;+ mapView === "countries" ? processedCountryData : processedSubdivisionData;// Get computed values from CSS variablesconst getComputedColor = (cssVar: string) => {@@ -88,8 +127,9 @@ export function MapComponent({ height }: { height: string }) {const [h, s, l] = hslValues;// Get the range of values- const counts = dataToUse?.map((d) => d.count) || [0];- const maxValue = Math.max(...counts);+ 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@@ -97,7 +137,7 @@ export function MapComponent({ height }: { height: 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)`]);- }, [countryData?.data, subdivisionData?.data, mapView]);+ }, [processedCountryData, processedSubdivisionData, mapView, mode]);const { data: subdivisionsGeoData } = useSubdivisions();const { data: countriesGeoData } = useCountries();@@ -117,11 +157,21 @@ export function MapComponent({ height }: { height: string }) {const borderKey = isCountryView? feature?.properties?.["BORDER"]: feature?.properties?.["border"];- const foundData = isCountryView- ? countryData?.data?.find(({ value }: any) => value === dataKey)- : subdivisionData?.data.find(({ value }: any) => value === dataKey);- const count = foundData?.count || 0;- const color = count > 0 ? colorScale(count) : "rgba(140, 140, 140, 0.5)";++ // 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,@@ -146,12 +196,24 @@ export function MapComponent({ height }: { height: string }) {const name = isCountryView? feature.properties?.["ADMIN"]: feature.properties?.["name"];- const foundData = isCountryView- ? countryData?.data?.find(({ value }: any) => value === code)- : subdivisionData?.data.find(({ value }: any) => value === code);++ // 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;- setTooltipContent({ name, code, count, percentage });+ const perCapita = foundData?.perCapita || 0;++ setTooltipContent({+ name,+ code,+ count,+ percentage,+ perCapita,+ });},mouseout: () => {// Clear hover state@@ -243,7 +305,7 @@ export function MapComponent({ height }: { height: string }) {<MapEventHandler />{mapView === "subdivisions" && subdivisionsGeoData && (<GeoJSON- key={`subdivisions-${dataVersion}`}+ key={`subdivisions-${dataVersion}-${mode}`}data={subdivisionsGeoData as GeoJsonObject}style={handleStyle}onEachFeature={handleEachFeature}@@ -251,7 +313,7 @@ export function MapComponent({ height }: { height: string }) {)}{mapView === "countries" && countriesGeoData && (<GeoJSON- key={`countries-${dataVersion}`}+ key={`countries-${dataVersion}-${mode}`}data={countriesGeoData as GeoJsonObject}style={handleStyle}onEachFeature={handleEachFeature}@@ -282,6 +344,14 @@ export function MapComponent({ height }: { height: string }) {({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">+ {tooltipContent.perCapita?.toFixed(2)}+ </span>{" "}+ per million people+ </div>+ )}</div>)}</div>diff --git a/client/src/app/[site]/map/page.tsx b/client/src/app/[site]/map/page.tsxindex 8efee6629..2f5e66432 100644--- a/client/src/app/[site]/map/page.tsx+++ b/client/src/app/[site]/map/page.tsx@@ -1,14 +1,49 @@+"use client";++import { useState } from "react";import { MobileSidebar } from "../../../components/MobileSidebar";import { MapComponent } from "../components/shared/Map";import { SubHeader } from "../components/SubHeader/SubHeader";+import { Switch } from "@/components/ui/switch";export default function MapPage() {+ const [mapMode, setMapMode] = useState<"total" | "perCapita">("total");+return (<div className="relative w-full"><div className="p-4"><SubHeader /></div>- <MapComponent height="calc(100vh - 45px - 76px)" />+ <div className="absolute bottom-4 left-4 z-10">+ <div className="flex items-center gap-3 bg-neutral-900 rounded-md px-3 py-2 text-sm">+ <span+ className={+ mapMode === "total"+ ? "text-white font-medium"+ : "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={+ mapMode === "perCapita"+ ? "text-white font-medium"+ : "text-neutral-400"+ }+ >+ Per Capita+ </span>+ </div>+ </div>+ <MapComponent height="calc(100vh - 45px - 76px - 40px)" mode={mapMode} /></div>);}diff --git a/client/src/lib/countryPopulation.ts b/client/src/lib/countryPopulation.tsnew file mode 100644index 000000000..3c4d08cbe--- /dev/null+++ b/client/src/lib/countryPopulation.ts@@ -0,0 +1,123 @@+// 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++ // European countries+ DE: 83.8, // Germany+ GB: 67.3, // United Kingdom+ FR: 65.5, // France+ IT: 60.3, // Italy+ ES: 47.4, // Spain+ PL: 37.8, // Poland+ RO: 19.1, // Romania+ NL: 17.5, // Netherlands+ BE: 11.6, // Belgium+ GR: 10.6, // Greece+ CZ: 10.7, // Czech Republic+ PT: 10.2, // Portugal+ SE: 10.4, // Sweden+ HU: 9.7, // Hungary+ AT: 9.1, // Austria+ CH: 8.7, // Switzerland+ DK: 5.8, // Denmark+ FI: 5.5, // Finland+ SK: 5.4, // Slovakia+ NO: 5.4, // Norway+ IE: 5.0, // Ireland+ HR: 4.0, // Croatia+ LT: 2.8, // Lithuania+ SI: 2.1, // Slovenia+ LV: 1.9, // Latvia+ EE: 1.3, // Estonia+ CY: 0.9, // Cyprus+ LU: 0.6, // Luxembourg+ MT: 0.5, // Malta++ // North America+ CA: 38.2, // Canada+ CU: 11.3, // Cuba+ HT: 11.5, // Haiti+ DO: 10.9, // Dominican Republic++ // South/Central America+ CO: 51.5, // Colombia+ AR: 45.8, // Argentina+ PE: 33.4, // Peru+ VE: 28.4, // Venezuela+ CL: 19.2, // Chile+ EC: 17.9, // Ecuador+ BO: 11.7, // Bolivia++ // Asia/Oceania+ AU: 25.7, // Australia+ MY: 33.6, // Malaysia+ SA: 35.3, // Saudi Arabia+ UZ: 34.2, // Uzbekistan+ YE: 33.7, // Yemen+ NP: 30.0, // Nepal+ AF: 38.9, // Afghanistan+ IQ: 43.5, // Iraq+ TH: 71.7, // Thailand+ TR: 84.3, // Turkey+ IR: 87.9, // Iran+ KR: 51.3, // South Korea+ MM: 54.8, // Myanmar+ TW: 23.8, // Taiwan+ LK: 22.2, // Sri Lanka+ KH: 16.7, // Cambodia+ AE: 9.9, // United Arab Emirates+ IL: 9.2, // Israel+ TJ: 9.5, // Tajikistan+ AZ: 10.2, // Azerbaijan+ JO: 10.2, // Jordan+ SG: 5.9, // Singapore+ KG: 6.5, // Kyrgyzstan+ TM: 6.0, // Turkmenistan+ NZ: 5.1, // New Zealand++ // Africa+ ZA: 59.3, // South Africa+ TZ: 63.6, // Tanzania+ KE: 54.0, // Kenya+ DZ: 44.6, // Algeria+ SD: 45.7, // Sudan+ UG: 47.1, // Uganda+ MA: 37.3, // Morocco+ GH: 32.8, // Ghana+ MZ: 32.9, // Mozambique+ AO: 34.5, // Angola+ CI: 27.5, // Côte d'Ivoire+ CM: 27.9, // Cameroon+ MG: 28.9, // Madagascar+ LY: 7.0, // Libya+ TN: 12.0, // Tunisia+ SN: 17.2, // Senegal++ // Default population for countries not in the list (use with caution)+ XX: 5.0, // Default value+};++// 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();++ return countryPopulations[normalizedCode] || countryPopulations.XX || 1;+}