Skip to content

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

Refactor lodash imports for consistency and performance improvements (#991)

Goldflagf44a85c04c66
diff --git a/client/src/app/Providers.tsx b/client/src/app/Providers.tsx
index b905a5a93..f70feb128 100644
--- a/client/src/app/Providers.tsx
+++ b/client/src/app/Providers.tsx
@@ -25,8 +25,8 @@ export function Providers({ children }: { children: React.ReactNode }) {
<OrganizationInitializer />
<AuthenticationGuard />
{children}
+ <VersionCheck />
</QueryProvider>
- <VersionCheck />
<Toaster />
</TooltipProvider>
</ThemeProvider>
diff --git a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
index 2be115333..68c79eb20 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
@@ -102,10 +102,10 @@ function ValueStep({
const suggestions = useMemo(() => {
const fromData =
- data?.data
- ?.map(item => item.value)
- .filter(Boolean)
- .map(val => ({ value: String(val), label: String(getValueLabel(val)) })) ?? [];
+ data?.data?.flatMap(item => {
+ const val = item.value;
+ return val ? [{ value: String(val), label: String(getValueLabel(val)) }] : [];
+ }) ?? [];
const present = new Set(fromData.map(o => o.value));
const selectedExtras = selected
.map(v => String(v))
diff --git a/client/src/app/[site]/components/SubHeader/Filters/ValuePopover.tsx b/client/src/app/[site]/components/SubHeader/Filters/ValuePopover.tsx
index 0d7ca82df..c31739621 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/ValuePopover.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/ValuePopover.tsx
@@ -93,10 +93,10 @@ export function ValuePopover({
const suggestions = useMemo(() => {
const fromData =
- data?.data
- ?.map(item => item.value)
- .filter(Boolean)
- .map(val => ({ value: String(val), label: String(getValueLabel(val)) })) ?? [];
+ data?.data?.flatMap(item => {
+ const val = item.value;
+ return val ? [{ value: String(val), label: String(getValueLabel(val)) }] : [];
+ }) ?? [];
const present = new Set(fromData.map(o => o.value));
const selectedExtras = filter.value
.map(v => String(v))
diff --git a/client/src/app/[site]/components/shared/Map/MapComponent.tsx b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
index 95c96057d..2d20a07a2 100644
--- a/client/src/app/[site]/components/shared/Map/MapComponent.tsx
+++ b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
@@ -92,7 +92,7 @@ export function MapComponent({ height, mapView: controlledMapView }: MapComponen
<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>
+ <span className="text-sm text-neutral-300">Loading map data&hellip;</span>
</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
index 231f4aad8..e6cae51e9 100644
--- a/client/src/app/[site]/components/shared/Map/hooks/useMapInstance.ts
+++ b/client/src/app/[site]/components/shared/Map/hooks/useMapInstance.ts
@@ -1,5 +1,6 @@
import { FilterParameter } from "@rybbit/shared";
import Map from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import View from "ol/View";
import { fromLonLat } from "ol/proj";
import { useEffect, useRef } from "react";
@@ -62,17 +63,18 @@ export function useMapInstance({
mapInstanceRef.current = map;
// Handle zoom changes
- map.getView().on("change:resolution", () => {
+ const handleResolutionChange = () => {
const currentZoom = map.getView().getZoom() || 1;
const newMapView = currentZoom >= 5 ? "subdivisions" : "countries";
if (newMapView !== mapViewRef.current) {
setInternalMapView(newMapView);
setTooltipContent(null);
}
- });
+ };
+ const resolutionChangeKey = map.getView().on("change:resolution", handleResolutionChange);
// Handle pointer move for hover effects
- map.on("pointermove", evt => {
+ const handlePointerMove = (evt: any) => {
if (evt.dragging) {
return;
}
@@ -112,10 +114,11 @@ export function useMapInstance({
setHoveredId(null);
setTooltipContent(null);
}
- });
+ };
+ const pointerMoveKey = map.on("pointermove", handlePointerMove);
// Handle click for filtering
- map.on("click", evt => {
+ const handleClick = (evt: any) => {
const pixel = map.getEventPixel(evt.originalEvent);
const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
@@ -131,9 +134,11 @@ export function useMapInstance({
type: "equals",
});
}
- });
+ };
+ const clickKey = map.on("click", handleClick);
return () => {
+ dispose([resolutionChangeKey, pointerMoveKey, clickKey]);
map.setTarget(undefined);
};
}, []);
diff --git a/client/src/app/[site]/components/shared/StandardSection/Row.tsx b/client/src/app/[site]/components/shared/StandardSection/Row.tsx
index e1d2c0614..bc2dce12f 100644
--- a/client/src/app/[site]/components/shared/StandardSection/Row.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/Row.tsx
@@ -1,6 +1,6 @@
import { FilterParameter } from "@rybbit/shared";
import NumberFlow from "@number-flow/react";
-import { round } from "lodash";
+import round from "lodash/round";
import { ChevronDown, ChevronRight, SquareArrowOutUpRight } from "lucide-react";
import { ReactNode, useState, useCallback } from "react";
import { usePaginatedMetric } from "../../../../../api/analytics/hooks/useGetMetric";
diff --git a/client/src/app/[site]/events/components/CustomEventsChart.tsx b/client/src/app/[site]/events/components/CustomEventsChart.tsx
index 447793d45..9fcb8f14f 100644
--- a/client/src/app/[site]/events/components/CustomEventsChart.tsx
+++ b/client/src/app/[site]/events/components/CustomEventsChart.tsx
@@ -198,7 +198,7 @@ export function CustomEventsChart({ eventLimit }: { eventLimit: number }) {
lineWidth={2}
sliceTooltip={({ slice }: SliceTooltipProps<EventSeries>) => {
const currentTime = slice.points[0]?.data.currentTime as DateTime | undefined;
- const sortedPoints = [...slice.points].sort(
+ const sortedPoints = slice.points.toSorted(
(a, b) => Number(b.data.yFormatted) - Number(a.data.yFormatted)
);
diff --git a/client/src/app/[site]/events/components/EventTypesChart.tsx b/client/src/app/[site]/events/components/EventTypesChart.tsx
index d6ca7b356..7160fcb1f 100644
--- a/client/src/app/[site]/events/components/EventTypesChart.tsx
+++ b/client/src/app/[site]/events/components/EventTypesChart.tsx
@@ -79,7 +79,7 @@ export function EventTypesChart() {
return { series: [] as Series[], legendItems: [], maxValue: 1, totalPoints: 0 };
}
- const sortedData = [...data].sort((a, b) => {
+ const sortedData = data.toSorted((a, b) => {
const ta = DateTime.fromSQL(a.time, { zone: timezone }).toMillis();
const tb = DateTime.fromSQL(b.time, { zone: timezone }).toMillis();
return ta - tb;
@@ -202,7 +202,7 @@ export function EventTypesChart() {
lineWidth={2}
sliceTooltip={({ slice }: SliceTooltipProps<Series>) => {
const currentTime = slice.points[0]?.data.currentTime as DateTime | undefined;
- const sortedPoints = [...slice.points].sort(
+ const sortedPoints = slice.points.toSorted(
(a, b) => Number(b.data.yFormatted) - Number(a.data.yFormatted)
);
const total = sortedPoints.reduce((acc, p) => acc + Number(p.data.yFormatted), 0);
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index 87f84997a..1013658e3 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -1,7 +1,7 @@
"use client";
import { useExtracted } from "next-intl";
-import { round } from "lodash";
+import round from "lodash/round";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useState } from "react";
import { FunnelResponse, FunnelStep } from "../../../../api/analytics/endpoints";
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
index 84aa762ee..e8104bf1b 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
@@ -1,7 +1,8 @@
import { FilterParameter } from "@rybbit/shared/dist/filters";
-import { round } from "lodash";
+import round from "lodash/round";
import { useEffect, useRef } from "react";
import Map from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature, { FeatureLike } from "ol/Feature";
@@ -149,11 +150,11 @@ export function useOpenLayersCoordinatesLayer({ mapInstanceRef, mapViewRef, mapV
}
};
- map.on("moveend", handleZoomChange);
+ const moveEndKey = map.on("moveend", handleZoomChange);
// Cleanup
return () => {
- map.un("moveend", handleZoomChange);
+ dispose(moveEndKey);
// Remove layer on cleanup
if (vectorLayerRef.current) {
@@ -192,9 +193,6 @@ export function useOpenLayersCoordinatesLayer({ mapInstanceRef, mapViewRef, mapV
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);
}
@@ -211,9 +209,9 @@ export function useOpenLayersCoordinatesLayer({ mapInstanceRef, mapViewRef, mapV
</div>
`;
- tooltip.style.left = event.originalEvent.pageX + 10 + "px";
- tooltip.style.top = event.originalEvent.pageY + 10 + "px";
- tooltip.style.display = "block";
+ tooltip.style.cssText = `position: absolute; pointer-events: none; z-index: 10000; left: ${
+ event.originalEvent.pageX + 10
+ }px; top: ${event.originalEvent.pageY + 10}px; display: block;`;
} else {
map.getTargetElement().style.cursor = "";
if (tooltip) {
@@ -264,12 +262,11 @@ export function useOpenLayersCoordinatesLayer({ mapInstanceRef, mapViewRef, mapV
}
};
- map.on("pointermove", handlePointerMove);
- map.on("click", handleClick);
+ const pointerMoveKey = map.on("pointermove", handlePointerMove);
+ const clickKey = map.on("click", handleClick);
return () => {
- map.un("pointermove", handlePointerMove);
- map.un("click", handleClick);
+ dispose([pointerMoveKey, clickKey]);
// Remove tooltip from DOM
if (tooltip && tooltip.parentNode) {
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
index e9b42a719..447698a31 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
@@ -1,5 +1,6 @@
import { FilterParameter } from "@rybbit/shared";
import Map from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import GeoJSON from "ol/format/GeoJSON";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
@@ -153,13 +154,12 @@ export function useOpenLayersCountriesLayer({ mapInstanceRef, mapViewRef, mapVie
}
};
- mapInstanceRef.current.on("pointermove", handlePointerMove);
- mapInstanceRef.current.on("click", handleClick);
+ const pointerMoveKey = mapInstanceRef.current.on("pointermove", handlePointerMove);
+ const clickKey = mapInstanceRef.current.on("click", handleClick);
return () => {
if (mapInstanceRef.current) {
- mapInstanceRef.current.un("pointermove", handlePointerMove);
- mapInstanceRef.current.un("click", handleClick);
+ dispose([pointerMoveKey, clickKey]);
// Remove layer on cleanup
if (vectorLayerRef.current) {
@@ -198,9 +198,6 @@ export function useOpenLayersCountriesLayer({ mapInstanceRef, mapViewRef, mapVie
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);
}
@@ -219,9 +216,9 @@ export function useOpenLayersCountriesLayer({ mapInstanceRef, mapViewRef, mapVie
</div>
`;
- tooltip.style.left = `${tooltipData.x}px`;
- tooltip.style.top = `${tooltipData.y - 10}px`;
- tooltip.style.transform = "translate(-50%, -100%)";
+ tooltip.style.cssText = `position: fixed; pointer-events: none; z-index: 9999; left: ${tooltipData.x}px; top: ${
+ tooltipData.y - 10
+ }px; transform: translate(-50%, -100%);`;
return () => {
const existingTooltip = document.getElementById("ol-countries-tooltip");
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
index be6138b95..6dc60c6f5 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
@@ -1,5 +1,6 @@
import { FilterParameter } from "@rybbit/shared";
import Map from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import GeoJSON from "ol/format/GeoJSON";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
@@ -157,13 +158,12 @@ export function useOpenLayersSubdivisionsLayer({
}
};
- mapInstanceRef.current.on("pointermove", handlePointerMove);
- mapInstanceRef.current.on("click", handleClick);
+ const pointerMoveKey = mapInstanceRef.current.on("pointermove", handlePointerMove);
+ const clickKey = mapInstanceRef.current.on("click", handleClick);
return () => {
if (mapInstanceRef.current) {
- mapInstanceRef.current.un("pointermove", handlePointerMove);
- mapInstanceRef.current.un("click", handleClick);
+ dispose([pointerMoveKey, clickKey]);
// Remove layer on cleanup
if (vectorLayerRef.current) {
@@ -202,9 +202,6 @@ export function useOpenLayersSubdivisionsLayer({
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);
}
@@ -225,9 +222,9 @@ export function useOpenLayersSubdivisionsLayer({
</div>
`;
- tooltip.style.left = `${tooltipData.x}px`;
- tooltip.style.top = `${tooltipData.y - 10}px`;
- tooltip.style.transform = "translate(-50%, -100%)";
+ tooltip.style.cssText = `position: fixed; pointer-events: none; z-index: 9999; left: ${tooltipData.x}px; top: ${
+ tooltipData.y - 10
+ }px; transform: translate(-50%, -100%);`;
return () => {
const existingTooltip = document.getElementById("ol-subdivisions-tooltip");
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
index 09d90713f..b4687e2f1 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
@@ -1,7 +1,9 @@
import Feature, { FeatureLike } from "ol/Feature";
import OLMap from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import Overlay from "ol/Overlay";
import Point from "ol/geom/Point";
+import type { EventsKey } from "ol/events";
import VectorLayer from "ol/layer/Vector";
import { fromLonLat } from "ol/proj";
import Cluster from "ol/source/Cluster";
@@ -16,6 +18,8 @@ import { buildTooltipHTML } from "../../utils/timelineTooltipBuilder";
// OpenLayers-specific clustering constants
const CLUSTER_RADIUS = 50; // pixels (OpenLayers specific)
+const AVATAR_MARKER_STYLE =
+ "cursor: pointer; border-radius: 50%; overflow: hidden; width: 32px; height: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.3); transform: translate(-50%, -50%);";
interface TimelineLayerProps {
mapInstanceRef: React.RefObject<OLMap | null>;
@@ -61,10 +65,10 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
// Set initial zoom
handleZoomChange();
- map.on("moveend", handleZoomChange);
+ const moveEndKey = map.on("moveend", handleZoomChange);
return () => {
- map.un("moveend", handleZoomChange);
+ dispose(moveEndKey);
};
}, [mapInstanceRef]);
@@ -76,8 +80,7 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
if (!tooltipOverlayRef.current) {
const tooltipElement = document.createElement("div");
tooltipElement.className = "ol-timeline-tooltip";
- tooltipElement.style.position = "absolute";
- tooltipElement.style.zIndex = "1000";
+ tooltipElement.style.cssText = "position: absolute; z-index: 1000;";
const tooltip = new Overlay({
element: tooltipElement,
@@ -122,27 +125,27 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
return;
}
+ let clusterMoveEndKey: EventsKey | EventsKey[] | null = null;
+
// 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 features = activeSessions.flatMap(session => {
+ if (!session.lat || !session.lon) return [];
- const feature = new Feature({
- geometry: new Point(fromLonLat([session.lon, session.lat])),
- });
+ const feature = new Feature({
+ geometry: new Point(fromLonLat([session.lon, session.lat])),
+ });
- feature.setProperties({
- session_id: session.session_id,
- session,
- });
+ feature.setProperties({
+ session_id: session.session_id,
+ session,
+ });
- return feature;
- })
- .filter(Boolean) as Feature[];
+ return [feature];
+ });
// Create vector source
const vectorSource = new VectorSource({
@@ -253,13 +256,7 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
// 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%)";
+ avatarContainer.style.cssText = AVATAR_MARKER_STYLE;
const avatarSVG = generateAvatarSVG(session.user_id, 32);
avatarContainer.innerHTML = avatarSVG;
@@ -353,10 +350,7 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
const handleMoveEndForClusters = () => {
updateUnclusteredOverlays();
};
- map.on("moveend", handleMoveEndForClusters);
-
- // Store handler for cleanup
- (map as any).__clusterMoveEndHandler = handleMoveEndForClusters;
+ clusterMoveEndKey = map.on("moveend", handleMoveEndForClusters);
} else {
// Not clustering - use individual overlays
// Remove cluster layer
@@ -365,12 +359,6 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
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));
@@ -402,13 +390,7 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
// 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
+ avatarContainer.style.cssText = AVATAR_MARKER_STYLE;
const avatarSVG = generateAvatarSVG(session.user_id, 32);
avatarContainer.innerHTML = avatarSVG;
@@ -527,16 +509,14 @@ export function useOpenLayersTimelineLayer({ mapInstanceRef, mapViewRef, mapView
}
};
- map.on("click", handleMapClick);
+ const mapClickKey = map.on("click", handleMapClick);
// Cleanup function
return () => {
- map.un("click", handleMapClick);
+ dispose(mapClickKey);
- // 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;
+ if (clusterMoveEndKey) {
+ dispose(clusterMoveEndKey);
}
overlaysMap.forEach(({ overlay, cleanup }) => {
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
index 11d84cc85..8889a98b3 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
@@ -1,4 +1,5 @@
-import { isNil, round } from "lodash";
+import isNil from "lodash/isNil";
+import round from "lodash/round";
import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { MIN_CLUSTER_SIZE } from "../../../utils/clusteringConstants";
import { SOURCE_ID } from "./timelineLayerConstants";
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
index a52770236..3b1456306 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
@@ -1,4 +1,5 @@
-import { isNil, round } from "lodash";
+import isNil from "lodash/isNil";
+import round from "lodash/round";
import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { SPREAD_RADIUS_DEGREES } from "../../../utils/clusteringConstants";
import { CLUSTER_COUNT_LAYER_ID, CLUSTER_LAYER_ID, SOURCE_ID } from "./timelineLayerConstants";
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts
index d6b3b038e..b0596fe24 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerSetup.ts
@@ -1,10 +1,5 @@
import mapboxgl from "mapbox-gl";
-import {
- SOURCE_ID,
- CLUSTER_LAYER_ID,
- CLUSTER_COUNT_LAYER_ID,
- UNCLUSTERED_LAYER_ID,
-} from "./timelineLayerConstants";
+import { SOURCE_ID, CLUSTER_LAYER_ID, CLUSTER_COUNT_LAYER_ID, UNCLUSTERED_LAYER_ID } from "./timelineLayerConstants";
import { MIN_CLUSTER_SIZE } from "../../../utils/clusteringConstants";
/**
@@ -81,12 +76,19 @@ export function disableClusterTransitions(mapInstance: mapboxgl.Map): void {
* Setup cursor change on cluster hover
*/
export function setupClusterHoverHandlers(mapInstance: mapboxgl.Map, layerId: string): () => void {
+ const setCursor = (cursor: string) => {
+ const canvas = mapInstance.getCanvas() as HTMLCanvasElement | undefined;
+ if (canvas) {
+ canvas.style.cursor = cursor;
+ }
+ };
+
const handleClusterMouseEnter = () => {
- mapInstance.getCanvas().style.cursor = "pointer";
+ setCursor("pointer");
};
const handleClusterMouseLeave = () => {
- mapInstance.getCanvas().style.cursor = "";
+ setCursor("");
};
mapInstance.on("mouseenter", layerId, handleClusterMouseEnter);
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
index 0cdedfd42..64f5d42e8 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
@@ -25,12 +25,8 @@ export function createAvatarMarker(
): { marker: mapboxgl.Marker; element: HTMLDivElement; cleanup: () => void } {
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.cssText =
+ "cursor: pointer; border-radius: 50%; overflow: hidden; width: 32px; height: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.3);";
const avatarSVG = generateAvatarSVG(session.user_id, 32);
avatarContainer.innerHTML = avatarSVG;
@@ -108,7 +104,12 @@ 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.flatMap(f => {
+ const sessionId = f.properties?.session_id;
+ return sessionId ? [sessionId] : [];
+ })
+ );
// Remove markers that are no longer unclustered
const toRemove: string[] = [];
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
index b5f137eff..d964f1753 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
@@ -1,4 +1,4 @@
-import { throttle } from "lodash";
+import throttle from "lodash/throttle";
import { useEffect, useRef, useState } from "react";
import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { useActiveSessions, useTimelineStore } from "../../../timelineStore";
diff --git a/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
index e2b4b8a98..ba64b76b4 100644
--- a/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
@@ -1,5 +1,5 @@
import { FilterParameter } from "@rybbit/shared/dist/filters";
-import { round } from "lodash";
+import round from "lodash/round";
import mapboxgl from "mapbox-gl";
import { useEffect, useRef } from "react";
import { useGetSessionLocations } from "../../../../../api/analytics/hooks/useGetSessionLocations";
@@ -31,6 +31,7 @@ export function useCoordinatesLayer({
useEffect(() => {
if (!map.current || !liveSessionLocations || !mapLoaded) return;
+ const mapInstance = map.current;
// Initialize popup once
if (!popupRef.current) {
@@ -42,8 +43,6 @@ export function useCoordinatesLayer({
}
const addCoordinatesLayer = () => {
- if (!map.current) return;
-
const maxCount = liveSessionLocations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;
const topSize = Math.pow(maxCount, 0.5);
@@ -91,16 +90,16 @@ export function useCoordinatesLayer({
};
// Add or update source
- if (map.current.getSource("realtime-coordinates")) {
- (map.current.getSource("realtime-coordinates") as mapboxgl.GeoJSONSource).setData(geojsonData);
+ if (mapInstance.getSource("realtime-coordinates")) {
+ (mapInstance.getSource("realtime-coordinates") as mapboxgl.GeoJSONSource).setData(geojsonData);
} else {
- map.current.addSource("realtime-coordinates", {
+ mapInstance.addSource("realtime-coordinates", {
type: "geojson",
data: geojsonData,
});
// Add hexbin layer (using circle layer for simplicity, can be enhanced with custom hexbin implementation)
- map.current.addLayer({
+ mapInstance.addLayer({
id: "realtime-coordinates-layer",
type: "circle",
source: "realtime-coordinates",
@@ -173,89 +172,11 @@ export function useCoordinatesLayer({
visibility: mapView === "coordinates" ? "visible" : "none",
},
});
-
- // Add mouse events for tooltip and popover
- map.current.on("mouseenter", "realtime-coordinates-layer", () => {
- if (!map.current) return;
- map.current.getCanvas().style.cursor = "pointer";
- });
-
- map.current.on("mousemove", "realtime-coordinates-layer", e => {
- if (!map.current || !e.features || e.features.length === 0 || !popupRef.current) return;
-
- const feature = e.features[0];
- const city = feature.properties?.city || "Unknown";
- const count = feature.properties?.count || 0;
-
- const countryCode = feature.properties?.country?.length === 2 ? feature.properties?.country : "";
- const flagSVG = renderCountryFlag(countryCode);
-
- const coordinates = e.lngLat;
- const html = `
- <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2" style="pointer-events: none;">
- <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>
- `;
-
- popupRef.current.setLngLat(coordinates).setHTML(html).addTo(map.current);
- });
-
- map.current.on("mouseleave", "realtime-coordinates-layer", () => {
- if (!map.current || !popupRef.current) return;
- map.current.getCanvas().style.cursor = "";
- popupRef.current.remove();
- });
-
- map.current.on("click", "realtime-coordinates-layer", e => {
- if (!map.current || !e.features || e.features.length === 0) return;
-
- const feature = e.features[0];
- const city = feature.properties?.city || "Unknown";
- const count = feature.properties?.count || 0;
- const isCurrentlyFiltered = feature.properties?.isFiltered;
-
- // Use the stored lat/lon properties instead of geometry coordinates
- // to avoid Mapbox coordinate transformations at different zoom levels
- const lat = feature.properties?.lat;
- const lon = feature.properties?.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",
- });
- }
- });
}
// Update paint properties when data changes
- if (map.current.getLayer("realtime-coordinates-layer")) {
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-radius", [
+ if (mapInstance.getLayer("realtime-coordinates-layer")) {
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-radius", [
"interpolate",
["exponential", 2],
["zoom"],
@@ -268,31 +189,31 @@ export function useCoordinatesLayer({
15,
["interpolate", ["linear"], ["sqrt", ["get", "count"]], 1, 15 * sizeMultiplier, topSize, 40 * sizeMultiplier],
]);
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-color", [
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-color", [
"case",
["get", "isFiltered"],
"#3b82f6",
"#fff4d6",
]);
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-opacity", [
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-opacity", [
"case",
["get", "isFiltered"],
0.9,
0.7,
]);
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-stroke-width", [
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-stroke-width", [
"case",
["get", "isFiltered"],
2,
1,
]);
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-stroke-color", [
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-stroke-color", [
"case",
["get", "isFiltered"],
"#60a5fa",
"#fff",
]);
- map.current.setPaintProperty("realtime-coordinates-layer", "circle-stroke-opacity", [
+ mapInstance.setPaintProperty("realtime-coordinates-layer", "circle-stroke-opacity", [
"case",
["get", "isFiltered"],
1,
@@ -302,5 +223,101 @@ export function useCoordinatesLayer({
};
addCoordinatesLayer();
- }, [liveSessionLocations, mapLoaded, map, minutes, filters]);
+
+ const setCursor = (cursor: string) => {
+ const canvas = mapInstance.getCanvas() as HTMLCanvasElement | undefined;
+ if (canvas) {
+ canvas.style.cursor = cursor;
+ }
+ };
+
+ // Add mouse events for tooltip and popover
+ const handleMouseEnter = () => {
+ setCursor("pointer");
+ };
+
+ const handleMouseMove = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0 || !popupRef.current) return;
+
+ const feature = e.features[0];
+ const city = feature.properties?.city || "Unknown";
+ const count = feature.properties?.count || 0;
+
+ const countryCode = feature.properties?.country?.length === 2 ? feature.properties?.country : "";
+ const flagSVG = renderCountryFlag(countryCode);
+
+ const coordinates = e.lngLat;
+ const html = `
+ <div class="bg-neutral-850 border border-neutral-750 rounded-lg p-2" style="pointer-events: none;">
+ <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>
+ `;
+
+ popupRef.current.setLngLat(coordinates).setHTML(html).addTo(mapInstance);
+ };
+
+ const handleMouseLeave = () => {
+ if (!popupRef.current) return;
+ setCursor("");
+ popupRef.current.remove();
+ };
+
+ const handleClick = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0) return;
+
+ const feature = e.features[0];
+ const isCurrentlyFiltered = feature.properties?.isFiltered;
+
+ // Use the stored lat/lon properties instead of geometry coordinates
+ // to avoid Mapbox coordinate transformations at different zoom levels
+ const lat = feature.properties?.lat;
+ const lon = feature.properties?.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",
+ });
+ }
+ };
+
+ mapInstance.on("mouseenter", "realtime-coordinates-layer", handleMouseEnter);
+ mapInstance.on("mousemove", "realtime-coordinates-layer", handleMouseMove);
+ mapInstance.on("mouseleave", "realtime-coordinates-layer", handleMouseLeave);
+ mapInstance.on("click", "realtime-coordinates-layer", handleClick);
+
+ return () => {
+ mapInstance.off("mouseenter", "realtime-coordinates-layer", handleMouseEnter);
+ mapInstance.off("mousemove", "realtime-coordinates-layer", handleMouseMove);
+ mapInstance.off("mouseleave", "realtime-coordinates-layer", handleMouseLeave);
+ mapInstance.off("click", "realtime-coordinates-layer", handleClick);
+ setCursor("");
+ popupRef.current?.remove();
+ };
+ }, [liveSessionLocations, mapLoaded, map, minutes, filters, mapView]);
}
diff --git a/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
index cb0f88f37..31d08e0e1 100644
--- a/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
@@ -22,6 +22,7 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
useEffect(() => {
if (!map.current || !countriesGeoData || !countryData?.data || !mapLoaded) return;
+ const mapInstance = map.current;
// Initialize popup once
if (!popupRef.current) {
@@ -33,8 +34,6 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
}
const addCountriesLayer = () => {
- if (!map.current) return;
-
const geoDataCopy = JSON.parse(JSON.stringify(countriesGeoData));
geoDataCopy.features.forEach((feature: any) => {
const code = feature.properties?.ISO_A2;
@@ -45,15 +44,15 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
feature.properties.count = count;
});
- if (map.current.getSource("countries")) {
- (map.current.getSource("countries") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
+ if (mapInstance.getSource("countries")) {
+ (mapInstance.getSource("countries") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
} else {
- map.current.addSource("countries", {
+ mapInstance.addSource("countries", {
type: "geojson",
data: geoDataCopy,
});
- map.current.addLayer({
+ mapInstance.addLayer({
id: "countries-fill",
type: "fill",
source: "countries",
@@ -66,7 +65,7 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
},
});
- map.current.addLayer({
+ mapInstance.addLayer({
id: "countries-outline",
type: "line",
source: "countries",
@@ -79,25 +78,36 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
visibility: mapView === "countries" ? "visible" : "none",
},
});
+ }
+ };
- map.current.on("mousemove", "countries-fill", e => {
- if (!map.current || !e.features || e.features.length === 0 || !popupRef.current) return;
- map.current.getCanvas().style.cursor = "pointer";
+ addCountriesLayer();
- const feature = e.features[0];
- const code = feature.properties?.ISO_A2;
- const name = feature.properties?.ADMIN;
- const count = feature.properties?.count || 0;
+ const setCursor = (cursor: string) => {
+ const canvas = mapInstance.getCanvas() as HTMLCanvasElement | undefined;
+ if (canvas) {
+ canvas.style.cursor = cursor;
+ }
+ };
+
+ const handleMouseMove = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0 || !popupRef.current) return;
+ setCursor("pointer");
- const currentData = countryData?.data;
- const foundData = currentData?.find((d: any) => d.value === code);
- const percentage = foundData?.percentage || 0;
+ const feature = e.features[0];
+ const code = feature.properties?.ISO_A2;
+ const name = feature.properties?.ADMIN;
+ const count = feature.properties?.count || 0;
- const flagSVG = renderCountryFlag(code);
+ const currentData = countryData?.data;
+ const foundData = currentData?.find((d: any) => d.value === code);
+ const percentage = foundData?.percentage || 0;
- // Use Mapbox native popup
- const coordinates = e.lngLat;
- const html = `
+ const flagSVG = renderCountryFlag(code);
+
+ // Use Mapbox native popup
+ const coordinates = e.lngLat;
+ const html = `
<div class="bg-neutral-850 border border-neutral-700 rounded-lg p-2">
<div class="flex items-center gap-2 mb-1">
${flagSVG}
@@ -110,30 +120,38 @@ export function useCountriesLayer({ map, mapLoaded, mapView }: UseCountriesLayer
</div>
`;
- popupRef.current.setLngLat(coordinates).setHTML(html).addTo(map.current);
- });
+ popupRef.current.setLngLat(coordinates).setHTML(html).addTo(mapInstance);
+ };
- map.current.on("mouseleave", "countries-fill", () => {
- if (!map.current || !popupRef.current) return;
- map.current.getCanvas().style.cursor = "";
- popupRef.current.remove();
- });
+ const handleMouseLeave = () => {
+ if (!popupRef.current) return;
+ setCursor("");
+ popupRef.current.remove();
+ };
- map.current.on("click", "countries-fill", e => {
- if (!e.features || e.features.length === 0) return;
+ const handleClick = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0) return;
- const feature = e.features[0];
- const code = feature.properties?.ISO_A2;
+ const feature = e.features[0];
+ const code = feature.properties?.ISO_A2;
- addFilter({
- parameter: "country" as FilterParameter,
- value: [code],
- type: "equals",
- });
- });
- }
+ addFilter({
+ parameter: "country" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
};
- addCountriesLayer();
- }, [countriesGeoData, countryData?.data, colorScale, map, mapLoaded]);
+ mapInstance.on("mousemove", "countries-fill", handleMouseMove);
+ mapInstance.on("mouseleave", "countries-fill", handleMouseLeave);
+ mapInstance.on("click", "countries-fill", handleClick);
+
+ return () => {
+ mapInstance.off("mousemove", "countries-fill", handleMouseMove);
+ mapInstance.off("mouseleave", "countries-fill", handleMouseLeave);
+ mapInstance.off("click", "countries-fill", handleClick);
+ setCursor("");
+ popupRef.current?.remove();
+ };
+ }, [countriesGeoData, countryData?.data, colorScale, map, mapLoaded, mapView]);
}
diff --git a/client/src/app/[site]/globe/3d/hooks/useMapbox.ts b/client/src/app/[site]/globe/3d/hooks/useMapbox.ts
index f171b8a50..016d99792 100644
--- a/client/src/app/[site]/globe/3d/hooks/useMapbox.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useMapbox.ts
@@ -53,7 +53,7 @@ export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>,
mapboxgl.accessToken = configs.mapboxToken;
- map.current = new mapboxgl.Map({
+ const mapInstance = new mapboxgl.Map({
container: containerRef.current,
style: mapStyle,
projection: { name: "globe" },
@@ -65,18 +65,22 @@ export function useMapbox(containerRef: React.RefObject<HTMLDivElement | null>,
attributionControl: false,
});
- map.current.on("style.load", () => {
- if (!map.current) return;
- applyCustomStyling(map.current);
+ map.current = mapInstance;
+
+ const handleStyleLoad = () => {
+ applyCustomStyling(mapInstance);
setMapLoaded(true);
- });
+ };
+
+ mapInstance.on("style.load", handleStyleLoad);
return () => {
- if (map.current) {
- map.current.remove();
+ mapInstance.off("style.load", handleStyleLoad);
+ mapInstance.remove();
+ if (map.current === mapInstance) {
map.current = null;
- setMapLoaded(false);
}
+ setMapLoaded(false);
};
}, [enabled, containerRef, configs?.mapboxToken]);
diff --git a/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
index 0c87ff173..23c55f37f 100644
--- a/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
@@ -22,6 +22,7 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
useEffect(() => {
if (!map.current || !subdivisionsGeoData || !subdivisionData?.data || !mapLoaded) return;
+ const mapInstance = map.current;
// Initialize popup once
if (!popupRef.current) {
@@ -33,8 +34,6 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
}
const addSubdivisionsLayer = () => {
- if (!map.current) return;
-
const geoDataCopy = JSON.parse(JSON.stringify(subdivisionsGeoData));
geoDataCopy.features.forEach((feature: any) => {
const code = feature.properties?.iso_3166_2;
@@ -45,15 +44,15 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
feature.properties.count = count;
});
- if (map.current.getSource("subdivisions")) {
- (map.current.getSource("subdivisions") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
+ if (mapInstance.getSource("subdivisions")) {
+ (mapInstance.getSource("subdivisions") as mapboxgl.GeoJSONSource).setData(geoDataCopy);
} else {
- map.current.addSource("subdivisions", {
+ mapInstance.addSource("subdivisions", {
type: "geojson",
data: geoDataCopy,
});
- map.current.addLayer({
+ mapInstance.addLayer({
id: "subdivisions-fill",
type: "fill",
source: "subdivisions",
@@ -66,7 +65,7 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
},
});
- map.current.addLayer({
+ mapInstance.addLayer({
id: "subdivisions-outline",
type: "line",
source: "subdivisions",
@@ -79,26 +78,37 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
visibility: mapView === "subdivisions" ? "visible" : "none",
},
});
+ }
+ };
- map.current.on("mousemove", "subdivisions-fill", e => {
- if (!map.current || !e.features || e.features.length === 0 || !popupRef.current) return;
- map.current.getCanvas().style.cursor = "pointer";
+ addSubdivisionsLayer();
- const feature = e.features[0];
- const code = feature.properties?.iso_3166_2;
- const name = feature.properties?.name;
- const count = feature.properties?.count || 0;
+ const setCursor = (cursor: string) => {
+ const canvas = mapInstance.getCanvas() as HTMLCanvasElement | undefined;
+ if (canvas) {
+ canvas.style.cursor = cursor;
+ }
+ };
+
+ const handleMouseMove = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0 || !popupRef.current) return;
+ setCursor("pointer");
- const currentData = subdivisionData?.data;
- const foundData = currentData?.find((d: any) => d.value === code);
- const percentage = foundData?.percentage || 0;
+ const feature = e.features[0];
+ const code = feature.properties?.iso_3166_2;
+ const name = feature.properties?.name;
+ const count = feature.properties?.count || 0;
- // Extract country code from iso_3166_2 (e.g., "US-CA" -> "US")
- const countryCode = code?.split("-")[0] || "";
- const flagSVG = renderCountryFlag(countryCode);
+ const currentData = subdivisionData?.data;
+ const foundData = currentData?.find((d: any) => d.value === code);
+ const percentage = foundData?.percentage || 0;
- const coordinates = e.lngLat;
- const html = `
+ // Extract country code from iso_3166_2 (e.g., "US-CA" -> "US")
+ const countryCode = code?.split("-")[0] || "";
+ const flagSVG = renderCountryFlag(countryCode);
+
+ const coordinates = e.lngLat;
+ const html = `
<div class="bg-neutral-850 border border-neutral-700 rounded-lg p-2">
<div class="flex items-center gap-2 mb-1">
${flagSVG}
@@ -111,30 +121,38 @@ export function useSubdivisionsLayer({ map, mapLoaded, mapView }: UseSubdivision
</div>
`;
- popupRef.current.setLngLat(coordinates).setHTML(html).addTo(map.current);
- });
+ popupRef.current.setLngLat(coordinates).setHTML(html).addTo(mapInstance);
+ };
- map.current.on("mouseleave", "subdivisions-fill", () => {
- if (!map.current || !popupRef.current) return;
- map.current.getCanvas().style.cursor = "";
- popupRef.current.remove();
- });
+ const handleMouseLeave = () => {
+ if (!popupRef.current) return;
+ setCursor("");
+ popupRef.current.remove();
+ };
- map.current.on("click", "subdivisions-fill", e => {
- if (!e.features || e.features.length === 0) return;
+ const handleClick = (e: mapboxgl.MapLayerMouseEvent) => {
+ if (!e.features || e.features.length === 0) return;
- const feature = e.features[0];
- const code = feature.properties?.iso_3166_2;
+ const feature = e.features[0];
+ const code = feature.properties?.iso_3166_2;
- addFilter({
- parameter: "region" as FilterParameter,
- value: [code],
- type: "equals",
- });
- });
- }
+ addFilter({
+ parameter: "region" as FilterParameter,
+ value: [code],
+ type: "equals",
+ });
};
- addSubdivisionsLayer();
- }, [subdivisionsGeoData, subdivisionData?.data, colorScale, map, mapLoaded]);
+ mapInstance.on("mousemove", "subdivisions-fill", handleMouseMove);
+ mapInstance.on("mouseleave", "subdivisions-fill", handleMouseLeave);
+ mapInstance.on("click", "subdivisions-fill", handleClick);
+
+ return () => {
+ mapInstance.off("mousemove", "subdivisions-fill", handleMouseMove);
+ mapInstance.off("mouseleave", "subdivisions-fill", handleMouseLeave);
+ mapInstance.off("click", "subdivisions-fill", handleClick);
+ setCursor("");
+ popupRef.current?.remove();
+ };
+ }, [subdivisionsGeoData, subdivisionData?.data, colorScale, map, mapLoaded, mapView]);
}
diff --git a/client/src/app/[site]/globe/components/TimelineScrubber.tsx b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
index 347ad5d2a..58c678876 100644
--- a/client/src/app/[site]/globe/components/TimelineScrubber.tsx
+++ b/client/src/app/[site]/globe/components/TimelineScrubber.tsx
@@ -1,4 +1,4 @@
-import { debounce } from "lodash";
+import debounce from "lodash/debounce";
import { AlertTriangle, Pause, Play } from "lucide-react";
import { useExtracted } from "next-intl";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
diff --git a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
index dade064ac..2842d84ae 100644
--- a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
+++ b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
@@ -507,10 +507,16 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
tooltip.style("visibility", "hidden");
});
- // Cleanup tooltip on unmount
- return () => {
+ const dispose = () => {
+ svg.selectAll("*").on("mouseenter", null).on("mousemove", null).on("mouseleave", null);
+ svg.selectAll("*").remove();
tooltip.remove();
};
+
+ // Cleanup tooltip and D3 handlers on unmount
+ return () => {
+ dispose();
+ };
}, [journeys, steps, maxJourneys, domain, theme]);
return (
diff --git a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
index 018358379..0ac3b7949 100644
--- a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
+++ b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
@@ -166,7 +166,7 @@ export function OutboundLinksDialog({ outboundLinks, expanded, close }: Outbound
rowIndex % 2 === 0 ? "bg-white dark:bg-neutral-900" : "bg-neutral-50 dark:bg-neutral-950"
)}
>
- <td className="px-2 py-2">
+ <td className="p-2">
<div className="flex items-center gap-1">
<a
href={row.url}
@@ -185,9 +185,9 @@ export function OutboundLinksDialog({ outboundLinks, expanded, close }: Outbound
</a>
</div>
</td>
- <td className="px-2 py-2 text-right">{row.count.toLocaleString()}</td>
- <td className="px-2 py-2 text-right">{row.percentage.toFixed(1)}%</td>
- <td className="px-2 py-2 text-right text-neutral-600 dark:text-neutral-300">
+ <td className="p-2 text-right">{row.count.toLocaleString()}</td>
+ <td className="p-2 text-right">{row.percentage.toFixed(1)}%</td>
+ <td className="p-2 text-right text-neutral-600 dark:text-neutral-300">
{(() => {
try {
const dt = DateTime.fromSQL(row.lastClicked, { zone: "utc" }).setZone(getTimezone());
diff --git a/client/src/app/[site]/main/components/sections/SearchConsole.tsx b/client/src/app/[site]/main/components/sections/SearchConsole.tsx
index a8e38a532..d34ddce43 100644
--- a/client/src/app/[site]/main/components/sections/SearchConsole.tsx
+++ b/client/src/app/[site]/main/components/sections/SearchConsole.tsx
@@ -1,5 +1,5 @@
import { SiGoogle } from "@icons-pack/react-simple-icons";
-import { round } from "lodash";
+import round from "lodash/round";
import { Expand, Info, SquareArrowOutUpRight } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
diff --git a/client/src/app/[site]/page.tsx b/client/src/app/[site]/page.tsx
index 2be3265d1..1b62da143 100644
--- a/client/src/app/[site]/page.tsx
+++ b/client/src/app/[site]/page.tsx
@@ -7,7 +7,7 @@ export default function SiteRedirect() {
<div className="min-h-dvh flex items-center justify-center">
<div className="text-center">
<div className="inline-block w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
- <p className="mt-4">Redirecting...</p>
+ <p className="mt-4">Redirecting&hellip;</p>
</div>
</div>
);
diff --git a/client/src/app/[site]/performance/components/PerformanceMap.tsx b/client/src/app/[site]/performance/components/PerformanceMap.tsx
index 7dfe86a42..67bbf0b75 100644
--- a/client/src/app/[site]/performance/components/PerformanceMap.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceMap.tsx
@@ -7,6 +7,7 @@ import { Feature } from "geojson";
import "ol/ol.css";
import { useEffect, useMemo, useRef, useState } from "react";
import Map from "ol/Map";
+import { unByKey as dispose } from "ol/Observable";
import View from "ol/View";
import { fromLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
@@ -151,7 +152,7 @@ export function PerformanceMap({ height }: { height: string }) {
mapInstanceRef.current = map;
// Handle pointer move for hover effects
- map.on("pointermove", evt => {
+ const handlePointerMove = (evt: any) => {
if (evt.dragging) {
return;
}
@@ -198,10 +199,11 @@ export function PerformanceMap({ height }: { height: string }) {
setHoveredId(null);
setTooltipContent(null);
}
- });
+ };
+ const pointerMoveKey = map.on("pointermove", handlePointerMove);
// Handle click for filtering
- map.on("click", evt => {
+ const handleClick = (evt: any) => {
const pixel = map.getEventPixel(evt.originalEvent);
const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
@@ -215,9 +217,11 @@ export function PerformanceMap({ height }: { height: string }) {
type: "equals",
});
}
- });
+ };
+ const clickKey = map.on("click", handleClick);
return () => {
+ dispose([pointerMoveKey, clickKey]);
map.setTarget(undefined);
};
}, []);
diff --git a/client/src/app/[site]/performance/utils/performanceUtils.ts b/client/src/app/[site]/performance/utils/performanceUtils.ts
index 38e670726..d7d9687d5 100644
--- a/client/src/app/[site]/performance/utils/performanceUtils.ts
+++ b/client/src/app/[site]/performance/utils/performanceUtils.ts
@@ -1,4 +1,4 @@
-import { round } from "lodash";
+import round from "lodash/round";
import { PerformanceMetric } from "../performanceStore";
// Performance metric thresholds for color coding based on Web Vitals standards
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index 9f42f88b4..7916f0867 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -240,7 +240,7 @@ export default function RetentionPage() {
{cohortKeys.map(cohortPeriod => (
<Fragment key={cohortPeriod}>
{/* Cohort Info Cell */}
- <div className="py-2 px-2 bg-white dark:bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-50 dark:border-neutral-800">
+ <div className="p-2 bg-white dark:bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-50 dark:border-neutral-800">
<div className="whitespace-nowrap text-neutral-700 dark:text-neutral-100">
{formatDate(cohortPeriod)}
</div>
diff --git a/client/src/app/[site]/user/[userId]/components/Calendar.tsx b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
index 96d850660..051e4fed1 100644
--- a/client/src/app/[site]/user/[userId]/components/Calendar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
@@ -1,6 +1,7 @@
import { ResponsiveTimeRange } from "@nivo/calendar";
-import _ from "lodash";
import { DateTime } from "luxon";
+import get from "lodash/get";
+import sortBy from "lodash/sortBy";
import { useExtracted } from "next-intl";
import { useTheme } from "next-themes";
import { UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
@@ -20,7 +21,7 @@ export const VisitCalendar = ({ sessionCount }: { sessionCount: UserSessionCount
.reverse();
- const maxValue = _.get(_.sortBy(data, "value")[Math.floor(data.length * 0.95)], "value");
+ const maxValue = get(sortBy(data, "value")[Math.floor(data.length * 0.95)], "value");
if (data.length === 0) {
return null;
diff --git a/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx b/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
index d97aa4d8c..d78fa1100 100644
--- a/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserLocationMap.tsx
@@ -2,7 +2,8 @@
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
-import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useEffect, useRef } from "react";
import { useTheme } from "next-themes";
import { useConfigs } from "../../../../../lib/configs";
@@ -18,21 +19,22 @@ export function UserLocationMap({ country, region, city }: UserLocationMapProps)
const markerRef = useRef<mapboxgl.Marker | null>(null);
const { configs } = useConfigs();
const { resolvedTheme } = useTheme();
- const [error, setError] = useState(false);
- const style =
- resolvedTheme === "dark"
- ? "mapbox://styles/mapbox/dark-v11"
- : "mapbox://styles/mapbox/light-v11";
+ const query = [city, region, country].filter(Boolean).join(", ");
- useEffect(() => {
- if (!containerRef.current || !configs?.mapboxToken) return;
+ const style = resolvedTheme === "dark" ? "mapbox://styles/mapbox/dark-v11" : "mapbox://styles/mapbox/light-v11";
+
+ const { data: coordinates } = useQuery({
+ queryKey: ["user-location-geocode", configs?.mapboxToken, query],
+ queryFn: () => geocodeUserLocation(configs!.mapboxToken, query),
+ enabled: Boolean(configs?.mapboxToken && query),
+ staleTime: 24 * 60 * 60 * 1000,
+ retry: false,
+ refetchOnWindowFocus: false,
+ });
- const query = [city, region, country].filter(Boolean).join(", ");
- if (!query) {
- setError(true);
- return;
- }
+ useEffect(() => {
+ if (!containerRef.current || !configs?.mapboxToken || !coordinates) return;
// Clean up previous map instance before creating a new one
markerRef.current?.remove();
@@ -42,37 +44,21 @@ export function UserLocationMap({ country, region, city }: UserLocationMapProps)
mapboxgl.accessToken = configs.mapboxToken;
- fetch(
- `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(query)}.json?access_token=${configs.mapboxToken}&limit=1`
- )
- .then(res => res.json())
- .then(data => {
- if (!data.features?.length || !containerRef.current) {
- setError(true);
- return;
- }
-
- const [lng, lat] = data.features[0].center;
-
- const map = new mapboxgl.Map({
- container: containerRef.current,
- style,
- center: [lng, lat],
- zoom: 1,
- pitch: 0,
- bearing: 0,
- antialias: true,
- attributionControl: false,
- interactive: true,
- });
-
- mapRef.current = map;
-
- markerRef.current = new mapboxgl.Marker({ color: "#10b981" })
- .setLngLat([lng, lat])
- .addTo(map);
- })
- .catch(() => setError(true));
+ const map = new mapboxgl.Map({
+ container: containerRef.current,
+ style,
+ center: coordinates,
+ zoom: 1,
+ pitch: 0,
+ bearing: 0,
+ antialias: true,
+ attributionControl: false,
+ interactive: true,
+ });
+
+ mapRef.current = map;
+
+ markerRef.current = new mapboxgl.Marker({ color: "#10b981" }).setLngLat(coordinates).addTo(map);
return () => {
markerRef.current?.remove();
@@ -80,9 +66,9 @@ export function UserLocationMap({ country, region, city }: UserLocationMapProps)
mapRef.current?.remove();
mapRef.current = null;
};
- }, [configs?.mapboxToken, country, region, city, style]);
+ }, [configs?.mapboxToken, coordinates, style]);
- if (error) return null;
+ if (!query || coordinates === null) return null;
return (
<div
@@ -91,3 +77,36 @@ export function UserLocationMap({ country, region, city }: UserLocationMapProps)
/>
);
}
+
+interface MapboxGeocodingResponse {
+ features?: Array<{
+ center?: unknown;
+ }>;
+}
+
+async function geocodeUserLocation(token: string, query: string): Promise<[number, number] | null> {
+ try {
+ const params = new URLSearchParams({
+ access_token: token,
+ limit: "1",
+ });
+
+ const response = await fetch(
+ `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(query)}.json?${params}`
+ );
+
+ if (!response.ok) return null;
+
+ const data = (await response.json()) as MapboxGeocodingResponse;
+ const center = data.features?.[0]?.center;
+
+ if (!Array.isArray(center) || center.length < 2) return null;
+
+ const [lng, lat] = center;
+ if (typeof lng !== "number" || typeof lat !== "number") return null;
+
+ return [lng, lat];
+ } catch {
+ return null;
+ }
+}
diff --git a/client/src/app/[site]/users/components/UsersTable.tsx b/client/src/app/[site]/users/components/UsersTable.tsx
index f362fc0ca..da4dad596 100644
--- a/client/src/app/[site]/users/components/UsersTable.tsx
+++ b/client/src/app/[site]/users/components/UsersTable.tsx
@@ -376,7 +376,7 @@ export function UsersTable() {
Array.from({ length: 15 }).map((_, index) => (
<tr key={index} className="border-b border-neutral-100 dark:border-neutral-800 animate-pulse">
{Array.from({ length: columns.length }).map((_, cellIndex) => (
- <td key={cellIndex} className="px-3 py-3">
+ <td key={cellIndex} className="p-3">
<div className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
</td>
))}
@@ -399,7 +399,7 @@ export function UsersTable() {
return (
<tr key={row.id} className="border-b border-neutral-100 dark:border-neutral-800 group hover:bg-neutral-50 dark:hover:bg-neutral-850">
{row.getVisibleCells().map(cell => (
- <td key={cell.id} className="px-3 py-3 relative">
+ <td key={cell.id} className="p-3 relative">
{/* <Link
href={href}
className="absolute inset-0 z-10"
diff --git a/client/src/app/admin/components/database/QueryLogTable.tsx b/client/src/app/admin/components/database/QueryLogTable.tsx
index ae13ec28c..acca54a3f 100644
--- a/client/src/app/admin/components/database/QueryLogTable.tsx
+++ b/client/src/app/admin/components/database/QueryLogTable.tsx
@@ -148,7 +148,7 @@ export function QueryLogTable() {
</Select>
</div>
{isFetching && !isLoading && (
- <span className="text-xs text-neutral-400">Updating...</span>
+ <span className="text-xs text-neutral-400">Updating&hellip;</span>
)}
</div>
diff --git a/client/src/app/admin/components/shared/GrowthChart.tsx b/client/src/app/admin/components/shared/GrowthChart.tsx
index 0c92bbab1..5f8475329 100644
--- a/client/src/app/admin/components/shared/GrowthChart.tsx
+++ b/client/src/app/admin/components/shared/GrowthChart.tsx
@@ -50,7 +50,7 @@ export function GrowthChart({ data, color = "#3b82f6", title }: GrowthChartProps
if (data === undefined) {
return (
<div className="h-64 flex items-center justify-center text-neutral-500 dark:text-neutral-400 text-sm">
- Loading...
+ Loading&hellip;
</div>
);
}
diff --git a/client/src/app/as/callback/page.tsx b/client/src/app/as/callback/page.tsx
index 7ec6310ca..50e93baf2 100644
--- a/client/src/app/as/callback/page.tsx
+++ b/client/src/app/as/callback/page.tsx
@@ -438,7 +438,7 @@ export default function AppSumoSignupPage() {
<div className="flex justify-center items-center h-dvh w-full p-4 bg-background">
<div className="flex flex-col items-center gap-4">
<Loader2 className="h-8 w-8 animate-spin text-emerald-600 dark:text-emerald-500" />
- <p className="text-muted-foreground">Loading...</p>
+ <p className="text-muted-foreground">Loading&hellip;</p>
</div>
</div>
);
diff --git a/client/src/app/auth/subscription/success/page.tsx b/client/src/app/auth/subscription/success/page.tsx
index a4dedcf05..236ea8de7 100644
--- a/client/src/app/auth/subscription/success/page.tsx
+++ b/client/src/app/auth/subscription/success/page.tsx
@@ -27,7 +27,7 @@ export default function StripeSuccessPage() {
<p className="text-lg text-neutral-600 dark:text-neutral-400">
Your subscription has been processed successfully.
</p>
- <p className="text-neutral-600 dark:text-neutral-400 mt-2">Redirecting you to your subscription details...</p>
+ <p className="text-neutral-600 dark:text-neutral-400 mt-2">Redirecting you to your subscription details&hellip;</p>
</div>
</div>
);
diff --git a/client/src/app/page.tsx b/client/src/app/page.tsx
index 2d541f2d6..f0fcfc448 100644
--- a/client/src/app/page.tsx
+++ b/client/src/app/page.tsx
@@ -79,7 +79,7 @@ export default function Home() {
// Compute unique tags from all sites
const allTags = useMemo(() => {
const tags = sites?.sites?.flatMap((s) => s.tags || []) || [];
- return [...new Set(tags)].sort();
+ return Array.from(new Set(tags)).toSorted();
}, [sites?.sites]);
// Track hydration to avoid mismatch with date-dependent disabled states
diff --git a/client/src/app/rollup/components/sections/RollupSection.tsx b/client/src/app/rollup/components/sections/RollupSection.tsx
index 3ecf57a9f..612c049db 100644
--- a/client/src/app/rollup/components/sections/RollupSection.tsx
+++ b/client/src/app/rollup/components/sections/RollupSection.tsx
@@ -7,7 +7,7 @@ import { ReactNode } from "react";
import { ErrorState } from "@/components/ErrorState";
import { CardLoader } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { round } from "lodash";
+import round from "lodash/round";
import { StandardSkeleton } from "@/app/[site]/components/shared/StandardSection/Skeleton";
import { MetricResponse } from "@/api/analytics/endpoints";
import { useRollupMetric } from "../../hooks/useRollupMetric";
diff --git a/client/src/app/settings/organization/components/SiteAccessMultiSelect.tsx b/client/src/app/settings/organization/components/SiteAccessMultiSelect.tsx
index bd570d36e..bf96413c6 100644
--- a/client/src/app/settings/organization/components/SiteAccessMultiSelect.tsx
+++ b/client/src/app/settings/organization/components/SiteAccessMultiSelect.tsx
@@ -34,7 +34,7 @@ export function SiteAccessMultiSelect({ selectedSiteIds, onChange, disabled = fa
};
if (isLoading) {
- return <div className="text-sm text-muted-foreground">Loading sites...</div>;
+ return <div className="text-sm text-muted-foreground">Loading sites&hellip;</div>;
}
if (sites.length === 0) {
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
index 56572d558..8c4374184 100644
--- a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
+++ b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
@@ -245,7 +245,7 @@ export function EventsTable({ monitor, monitorId }: { monitor?: UptimeMonitor; m
<div className="flex justify-center">
<Button variant="ghost" size="sm" disabled>
<Loader2 className="h-4 w-4 animate-spin" />
- Loading more events...
+ Loading more events&hellip;
</Button>
</div>
)}
diff --git a/client/src/components/DisabledOverlay.tsx b/client/src/components/DisabledOverlay.tsx
index 248a6229a..d83e1cd74 100644
--- a/client/src/components/DisabledOverlay.tsx
+++ b/client/src/components/DisabledOverlay.tsx
@@ -124,6 +124,17 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
useEffect(() => {
if (!disabled || !containerRef.current || !contentRef.current) return;
+ const restoreContentStyles = () => {
+ const content = contentRef.current;
+ if (!content) return;
+
+ Object.assign(content.style, {
+ filter: `blur(${blur}px)`,
+ pointerEvents: "none",
+ userSelect: "none",
+ });
+ };
+
// Watch for overlay removal
const containerObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => {
@@ -147,9 +158,7 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
const currentStyle = contentRef.current.getAttribute("style") || "";
// Check if critical styles are missing
if (!currentStyle.includes("blur") || !currentStyle.includes("pointer-events: none")) {
- contentRef.current.style.filter = `blur(${blur}px)`;
- contentRef.current.style.pointerEvents = "none";
- contentRef.current.style.userSelect = "none";
+ restoreContentStyles();
}
}
});
@@ -166,9 +175,7 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
if (contentRef.current && disabled) {
const currentStyle = contentRef.current.getAttribute("style") || "";
if (!currentStyle.includes("blur") || !currentStyle.includes("pointer-events: none")) {
- contentRef.current.style.filter = `blur(${blur}px)`;
- contentRef.current.style.pointerEvents = "none";
- contentRef.current.style.userSelect = "none";
+ restoreContentStyles();
}
}
}, 2000); // Check every 2 seconds
diff --git a/client/src/components/SiteSettings/ImportManager.tsx b/client/src/components/SiteSettings/ImportManager.tsx
index 269f536ca..71124e1b1 100644
--- a/client/src/components/SiteSettings/ImportManager.tsx
+++ b/client/src/components/SiteSettings/ImportManager.tsx
@@ -196,7 +196,7 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
return [];
}
- return [...data.data].sort((a, b) => {
+ return data.data.toSorted((a, b) => {
const aTime = new Date(a.startedAt).getTime();
const bTime = new Date(b.startedAt).getTime();
return bTime - aTime;
diff --git a/client/src/components/SpinningGlobe.tsx b/client/src/components/SpinningGlobe.tsx
index 0ced525da..d674820bb 100644
--- a/client/src/components/SpinningGlobe.tsx
+++ b/client/src/components/SpinningGlobe.tsx
@@ -1,6 +1,8 @@
"use client";
-import { isNil, round, throttle } from "lodash";
+import isNil from "lodash/isNil";
+import round from "lodash/round";
+import throttle from "lodash/throttle";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { useEffect, useRef, useState } from "react";
@@ -178,7 +180,67 @@ export function SpinningGlobe() {
mapRef.current = map;
- map.on("style.load", () => {
+ // Spin globe function using easeTo for smooth animation
+ const spinGlobe = () => {
+ if (!mapRef.current) return;
+ const zoom = mapRef.current.getZoom();
+ if (!isUserInteractingRef.current && zoom < MAX_SPIN_ZOOM) {
+ let distancePerSecond = 360 / SECONDS_PER_REVOLUTION;
+ if (zoom > SLOW_SPIN_ZOOM) {
+ // Slow spinning at higher zooms
+ const zoomDif = (MAX_SPIN_ZOOM - zoom) / (MAX_SPIN_ZOOM - SLOW_SPIN_ZOOM);
+ distancePerSecond *= zoomDif;
+ }
+ const center = mapRef.current.getCenter();
+ center.lng -= distancePerSecond;
+ // Smoothly animate the map over one second
+ mapRef.current.easeTo({ center, duration: 1000, easing: n => n });
+ }
+ };
+
+ const handleClusterClick = (e: mapboxgl.MapLayerMouseEvent) => {
+ const features = map.queryRenderedFeatures(e.point, { layers: [CLUSTER_LAYER_ID] });
+ if (!features.length) return;
+
+ const clusterId = features[0].properties?.cluster_id;
+ const source = map.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
+
+ source.getClusterExpansionZoom(clusterId, (err, zoom) => {
+ if (err || !zoom) return;
+ const coordinates = (features[0].geometry as any).coordinates;
+ map.easeTo({ center: coordinates, zoom, duration: 500 });
+ });
+ };
+
+ const setCursor = (cursor: string) => {
+ const canvas = map.getCanvas() as HTMLCanvasElement | undefined;
+ if (canvas) {
+ canvas.style.cursor = cursor;
+ }
+ };
+
+ const handleClusterMouseEnter = () => {
+ setCursor("pointer");
+ };
+
+ const handleClusterMouseLeave = () => {
+ setCursor("");
+ };
+
+ const handleMouseDown = () => {
+ isUserInteractingRef.current = true;
+ };
+
+ const handleInteractionEnd = () => {
+ isUserInteractingRef.current = false;
+ spinGlobe();
+ };
+
+ const handleMoveEnd = () => {
+ spinGlobe();
+ };
+
+ const handleStyleLoad = () => {
// Apply custom styling
try {
if (map.getLayer("water")) {
@@ -252,81 +314,43 @@ export function SpinningGlobe() {
});
// Cluster click handler
- map.on("click", CLUSTER_LAYER_ID, e => {
- const features = map.queryRenderedFeatures(e.point, { layers: [CLUSTER_LAYER_ID] });
- if (!features.length) return;
-
- const clusterId = features[0].properties?.cluster_id;
- const source = map.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
-
- source.getClusterExpansionZoom(clusterId, (err, zoom) => {
- if (err || !zoom) return;
- const coordinates = (features[0].geometry as any).coordinates;
- map.easeTo({ center: coordinates, zoom, duration: 500 });
- });
- });
+ map.on("click", CLUSTER_LAYER_ID, handleClusterClick);
// Cursor change on cluster hover
- map.on("mouseenter", CLUSTER_LAYER_ID, () => {
- map.getCanvas().style.cursor = "pointer";
- });
- map.on("mouseleave", CLUSTER_LAYER_ID, () => {
- map.getCanvas().style.cursor = "";
- });
-
- // Spin globe function using easeTo for smooth animation
- const spinGlobe = () => {
- if (!mapRef.current) return;
- const zoom = mapRef.current.getZoom();
- if (!isUserInteractingRef.current && zoom < MAX_SPIN_ZOOM) {
- let distancePerSecond = 360 / SECONDS_PER_REVOLUTION;
- if (zoom > SLOW_SPIN_ZOOM) {
- // Slow spinning at higher zooms
- const zoomDif = (MAX_SPIN_ZOOM - zoom) / (MAX_SPIN_ZOOM - SLOW_SPIN_ZOOM);
- distancePerSecond *= zoomDif;
- }
- const center = mapRef.current.getCenter();
- center.lng -= distancePerSecond;
- // Smoothly animate the map over one second
- mapRef.current.easeTo({ center, duration: 1000, easing: n => n });
- }
- };
+ map.on("mouseenter", CLUSTER_LAYER_ID, handleClusterMouseEnter);
+ map.on("mouseleave", CLUSTER_LAYER_ID, handleClusterMouseLeave);
// Pause spinning on interaction
- map.on("mousedown", () => {
- isUserInteractingRef.current = true;
- });
+ map.on("mousedown", handleMouseDown);
// Restart spinning after interaction ends
- map.on("mouseup", () => {
- isUserInteractingRef.current = false;
- spinGlobe();
- });
- map.on("dragend", () => {
- isUserInteractingRef.current = false;
- spinGlobe();
- });
- map.on("pitchend", () => {
- isUserInteractingRef.current = false;
- spinGlobe();
- });
- map.on("rotateend", () => {
- isUserInteractingRef.current = false;
- spinGlobe();
- });
+ map.on("mouseup", handleInteractionEnd);
+ map.on("dragend", handleInteractionEnd);
+ map.on("pitchend", handleInteractionEnd);
+ map.on("rotateend", handleInteractionEnd);
// When animation completes, spin again (creates continuous rotation)
- map.on("moveend", () => {
- spinGlobe();
- });
+ map.on("moveend", handleMoveEnd);
setMapLoaded(true);
// Start spinning
spinGlobe();
- });
+ };
+
+ map.on("style.load", handleStyleLoad);
return () => {
+ map.off("style.load", handleStyleLoad);
+ map.off("click", CLUSTER_LAYER_ID, handleClusterClick);
+ map.off("mouseenter", CLUSTER_LAYER_ID, handleClusterMouseEnter);
+ map.off("mouseleave", CLUSTER_LAYER_ID, handleClusterMouseLeave);
+ map.off("mousedown", handleMouseDown);
+ map.off("mouseup", handleInteractionEnd);
+ map.off("dragend", handleInteractionEnd);
+ map.off("pitchend", handleInteractionEnd);
+ map.off("rotateend", handleInteractionEnd);
+ map.off("moveend", handleMoveEnd);
// Clear markers
markersMapRef.current.forEach(({ marker }) => marker.remove());
markersMapRef.current.clear();
@@ -429,7 +453,12 @@ export function SpinningGlobe() {
}
// Build set of current session IDs
- const currentSessionIds = new Set(unclusteredFeatures.map(f => f.properties?.session_id).filter(Boolean));
+ const currentSessionIds = new Set(
+ unclusteredFeatures.flatMap(f => {
+ const sessionId = f.properties?.session_id;
+ return sessionId ? [sessionId] : [];
+ })
+ );
// Remove markers no longer visible
const toRemove: string[] = [];
@@ -458,12 +487,8 @@ export function SpinningGlobe() {
// Create avatar marker
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.cssText =
+ "cursor: pointer; border-radius: 50%; overflow: hidden; width: 32px; height: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.3);";
avatarContainer.innerHTML = generateAvatarSVG(session.user_id, 32);
const marker = new mapboxgl.Marker({
diff --git a/client/src/components/StandardPage.tsx b/client/src/components/StandardPage.tsx
index 517844094..067e6f0da 100644
--- a/client/src/components/StandardPage.tsx
+++ b/client/src/components/StandardPage.tsx
@@ -4,7 +4,7 @@ export function StandardPage({ children, showSidebar = true }: { children: React
return (
<div className="h-full flex w-full">
{showSidebar && <AppSidebar />}
- <main className="flex flex-col items-center px-4 py-4 w-full h-dvh overflow-y-auto">
+ <main className="flex flex-col items-center p-4 w-full h-dvh overflow-y-auto">
<div className="w-full max-w-6xl">{children}</div>
</main>
</div>
diff --git a/client/src/components/VersionCheck.tsx b/client/src/components/VersionCheck.tsx
index c32ca311d..52629291d 100644
--- a/client/src/components/VersionCheck.tsx
+++ b/client/src/components/VersionCheck.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import { useExtracted } from "next-intl";
import { toast } from "@/components/ui/sonner";
@@ -9,63 +10,85 @@ import packageJson from "../../package.json";
import { X } from "lucide-react";
import { Button } from "./ui/button";
+const VERSION_CHECK_DONE_KEY = "version-check-done";
+
export function VersionCheck() {
const t = useExtracted();
- useEffect(() => {
- if (IS_CLOUD) return;
- if (sessionStorage.getItem("version-check-done")) return;
- sessionStorage.setItem("version-check-done", "1");
+ const [shouldCheckVersion] = useState(() => {
+ if (IS_CLOUD || typeof window === "undefined") return false;
+ return !sessionStorage.getItem(VERSION_CHECK_DONE_KEY);
+ });
+
+ const { data: latestVersion } = useQuery({
+ queryKey: ["version-check"],
+ queryFn: fetchLatestVersion,
+ enabled: shouldCheckVersion,
+ staleTime: Infinity,
+ gcTime: Infinity,
+ retry: false,
+ refetchOnWindowFocus: false,
+ });
- fetch("https://app.rybbit.io/api/version")
- .then((res) => res.json())
- .then((data: { version: string }) => {
- const latest = data.version;
- const current = packageJson.version;
+ useEffect(() => {
+ if (!shouldCheckVersion || !latestVersion) return;
+
+ const current = packageJson.version;
- if (latest && latest !== current && isNewer(latest, current)) {
- toast.custom(
- (toastInstance) => (
- <div
- style={{
- opacity: toastInstance.visible ? 1 : 0,
- transform: toastInstance.visible ? "translateY(0)" : "translateY(-8px)",
- transition: "opacity 200ms ease, transform 200ms ease",
- }}
- className="flex items-center gap-3 bg-white dark:bg-neutral-850 border border-neutral-150 dark:border-neutral-850 rounded-lg shadow-lg py-2 px-3 text-sm"
- >
- <span>
- {t("Rybbit v{latest} is available (you're on v{current})", { latest, current })}
- </span>
- <a
- href="https://rybbit.com/docs/managing-your-installation#updating-your-installation"
- target="_blank"
- rel="noopener noreferrer"
- >
- <Button variant="success" size="sm">
- {t("Upgrade")}
- </Button>
- </a>
- <button
- onClick={() => toast.dismiss(toastInstance.id)}
- className="text-neutral-400 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-300"
- >
- <X size={16} />
- </button>
- </div>
- ),
- { duration: 10000 }
- );
- }
- })
- .catch(() => {
- // Silently ignore - user may be offline or app.rybbit.io unreachable
- });
- }, []);
+ if (latestVersion !== current && isNewer(latestVersion, current)) {
+ toast.custom(
+ toastInstance => (
+ <div
+ style={{
+ opacity: toastInstance.visible ? 1 : 0,
+ transform: toastInstance.visible ? "translateY(0)" : "translateY(-8px)",
+ transition: "opacity 200ms ease, transform 200ms ease",
+ }}
+ className="flex items-center gap-3 bg-white dark:bg-neutral-850 border border-neutral-150 dark:border-neutral-850 rounded-lg shadow-lg py-2 px-3 text-sm"
+ >
+ <span>{t("Rybbit v{latest} is available (you're on v{current})", { latest: latestVersion, current })}</span>
+ <a
+ href="https://rybbit.com/docs/managing-your-installation#updating-your-installation"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <Button variant="success" size="sm">
+ {t("Upgrade")}
+ </Button>
+ </a>
+ <button
+ onClick={() => toast.dismiss(toastInstance.id)}
+ className="text-neutral-400 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-300"
+ >
+ <X size={16} />
+ </button>
+ </div>
+ ),
+ { duration: 10000 }
+ );
+ }
+ }, [latestVersion, shouldCheckVersion, t]);
return null;
}
+async function fetchLatestVersion(): Promise<string | null> {
+ if (typeof window === "undefined") return null;
+
+ sessionStorage.setItem(VERSION_CHECK_DONE_KEY, "1");
+
+ try {
+ const res = await fetch("https://app.rybbit.io/api/version");
+ if (!res.ok) return null;
+
+ const data = (await res.json()) as { version?: string };
+ return data.version ?? null;
+ } catch {
+ // Silently ignore - user may be offline or app.rybbit.io unreachable
+ return null;
+ }
+}
+
function isNewer(latest: string, current: string): boolean {
const l = latest.split(".").map(Number);
const c = current.split(".").map(Number);
diff --git a/client/src/components/replay/player/ReplayPlayerTopbar.tsx b/client/src/components/replay/player/ReplayPlayerTopbar.tsx
index 5a2492939..f76d48329 100644
--- a/client/src/components/replay/player/ReplayPlayerTopbar.tsx
+++ b/client/src/components/replay/player/ReplayPlayerTopbar.tsx
@@ -58,7 +58,7 @@ export function ReplayPlayerTopbar() {
if (!pageUrl || !metadata) {
return (
- <div className="border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900 px-2 py-2 rounded-t-lg overflow-hidden">
+ <div className="border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-2 rounded-t-lg overflow-hidden">
<div className="flex items-center justify-between min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div className="h-4 w-32 bg-neutral-150 dark:bg-neutral-700 rounded animate-pulse" />
@@ -72,7 +72,7 @@ export function ReplayPlayerTopbar() {
}
return (
- <div className="border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900 px-2 py-2 rounded-t-lg overflow-hidden">
+ <div className="border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-2 rounded-t-lg overflow-hidden">
<div className="flex items-center justify-between min-w-0">
{/* Left side: Page path with external link */}
<Link
diff --git a/client/src/components/subscription/PaidPlain/CancellationDialog.tsx b/client/src/components/subscription/PaidPlain/CancellationDialog.tsx
index 265de4ffc..6444786fb 100644
--- a/client/src/components/subscription/PaidPlain/CancellationDialog.tsx
+++ b/client/src/components/subscription/PaidPlain/CancellationDialog.tsx
@@ -381,7 +381,7 @@ export function CancellationDialog({
{submitFeedback.isPending ? (
<span className="flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
- Processing...
+ Processing&hellip;
</span>
) : isTrial ? (
"Cancel Trial"
diff --git a/client/src/components/subscription/components/PlanChangePreviewDialog.tsx b/client/src/components/subscription/components/PlanChangePreviewDialog.tsx
index bdc1c5455..6ad99bccf 100644
--- a/client/src/components/subscription/components/PlanChangePreviewDialog.tsx
+++ b/client/src/components/subscription/components/PlanChangePreviewDialog.tsx
@@ -114,7 +114,7 @@ export function PlanChangePreviewDialog({
{isUpdating ? (
<span className="flex items-center justify-center gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
- Updating...
+ Updating&hellip;
</span>
) : (
"Confirm Change"
diff --git a/client/src/components/ui/hooks/useTouchPrimary.ts b/client/src/components/ui/hooks/useTouchPrimary.ts
index 76fdc5cc1..d708c84b2 100644
--- a/client/src/components/ui/hooks/useTouchPrimary.ts
+++ b/client/src/components/ui/hooks/useTouchPrimary.ts
@@ -6,9 +6,6 @@ export function useTouchPrimary() {
useEffect(() => {
if (typeof window === "undefined") return;
- const controller = new AbortController();
- const { signal } = controller;
-
const handleTouch = () => {
const hasTouch = "ontouchstart" in window || navigator.maxTouchPoints > 0;
const prefersTouch = window.matchMedia("(pointer: coarse)").matches;
@@ -16,12 +13,15 @@ export function useTouchPrimary() {
};
const mq = window.matchMedia("(pointer: coarse)");
- mq.addEventListener("change", handleTouch, { signal });
- window.addEventListener("pointerdown", handleTouch, { signal });
+ mq.addEventListener("change", handleTouch);
+ window.addEventListener("pointerdown", handleTouch);
handleTouch();
- return () => controller.abort();
+ return () => {
+ mq.removeEventListener("change", handleTouch);
+ window.removeEventListener("pointerdown", handleTouch);
+ };
}, []);
return isTouchPrimary;
diff --git a/client/src/components/ui/input-with-suggestions.tsx b/client/src/components/ui/input-with-suggestions.tsx
index 24e412b10..836b0562e 100644
--- a/client/src/components/ui/input-with-suggestions.tsx
+++ b/client/src/components/ui/input-with-suggestions.tsx
@@ -144,7 +144,7 @@ export const InputWithSuggestions = React.forwardRef<HTMLInputElement, InputWith
{filteredSuggestions.map(suggestion => (
<div
key={suggestion.value}
- className="relative cursor-pointer mx-1 px-2 py-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-md"
+ className="relative cursor-pointer mx-1 p-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-md"
onMouseDown={e => e.preventDefault()}
onClick={() => handleSuggestionClick(suggestion.value)}
>
diff --git a/client/src/components/ui/scroll-area.tsx b/client/src/components/ui/scroll-area.tsx
index 0f0ae4229..a41e673fe 100644
--- a/client/src/components/ui/scroll-area.tsx
+++ b/client/src/components/ui/scroll-area.tsx
@@ -57,20 +57,18 @@ const ScrollArea = React.forwardRef<
const element = viewportRef.current;
if (!element) return;
- const controller = new AbortController();
- const { signal } = controller;
-
const resizeObserver = new ResizeObserver(checkScrollability);
resizeObserver.observe(element);
- element.addEventListener("scroll", checkScrollability, { signal });
- window.addEventListener("resize", checkScrollability, { signal });
+ element.addEventListener("scroll", checkScrollability);
+ window.addEventListener("resize", checkScrollability);
// Run an initial check whenever dependencies change (including pointer mode)
checkScrollability();
return () => {
- controller.abort();
+ element.removeEventListener("scroll", checkScrollability);
+ window.removeEventListener("resize", checkScrollability);
resizeObserver.disconnect();
};
}, [checkScrollability, isTouch]);