All files / src/apps/user/pages/settings SessionGlobe.tsx

37.03% Statements 40/108
12.28% Branches 7/57
21.05% Functions 4/19
37.62% Lines 38/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                              1x 1x 1x 1x 1x           1x                                                                               1x                 2x 2x     2x 2x   2x 2x 2x 2x       2x 2x 2x         2x 2x 2x             2x     2x 1x                 2x 2x 2x       2x                               2x                                               2x           2x                       2x                   2x                 2x 1x               1x 1x                                                                                                                                                                               1x      
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import createGlobe from "cobe";
import { useTheme } from "chainr-frontend-shared";
import { Globe, Loader2 } from "lucide-react";
import type { AccountSession } from "@/hooks/useSessions";
import { groupSessionsByLocation } from "./sessionLocations";
import { SessionLocationEmptyState as EmptyState } from "./SessionLocationEmptyState";
 
interface SessionGlobeProps {
  sessions: AccountSession[];
  loading?: boolean;
  /** Called with every session clustered at the pin the user clicked. */
  onSelectSessions?: (sessions: AccountSession[]) => void;
}
 
interface GlobeMarker {
  key: string;
  location: [number, number];
  size: number;
  color: [number, number, number];
  sessions: AccountSession[];
}
 
const INDIGO: [number, number, number] = [0.29, 0.33, 0.84];
const SLATE: [number, number, number] = [0.55, 0.58, 0.64];
const AUTO_ROTATE_SPEED = 0.003;
const DRAG_SENSITIVITY = 0.005;
const MAX_TILT = 1.2;
 
// -- Projection math, mirroring cobe's internal camera transform --------- //
// cobe doesn't expose marker screen positions, so pin click-targets are
// projected here using the same formula, kept in sync with a square canvas
// at scale=1/offset=[0,0] (this component never sets either).
const DEG2RAD = Math.PI / 180;
 
function toUnitVector(lat: number, lng: number): [number, number, number] {
  const latRad = lat * DEG2RAD;
  const lngRad = lng * DEG2RAD - Math.PI;
  const cosLat = Math.cos(latRad);
  return [-cosLat * Math.cos(lngRad), Math.sin(latRad), cosLat * Math.sin(lngRad)];
}
 
function projectMarker(
  lat: number,
  lng: number,
  phi: number,
  theta: number,
  elevation = 0.05,
): { x: number; y: number; visible: boolean } {
  const r = 0.8 + elevation;
  const [ux, uy, uz] = toUnitVector(lat, lng);
  const x = ux * r;
  const y = uy * r;
  const z = uz * r;
 
  const cosT = Math.cos(theta);
  const sinT = Math.sin(theta);
  const cosP = Math.cos(phi);
  const sinP = Math.sin(phi);
 
  const cx = cosP * x + sinP * z;
  const cy = sinP * sinT * x + cosT * y - cosP * sinT * z;
  const facingCamera = -sinP * cosT * x + sinT * y + cosP * cosT * z >= 0;
  const nearRim = cx * cx + cy * cy >= 0.64;
 
  return { x: (cx + 1) / 2, y: (-cy + 1) / 2, visible: facingCamera || nearRim };
}
 
/** Rotating, draggable globe plotting each session's geolocated IP. Handles:
 * still loading, no sessions at all, sessions with no location data (e.g.
 * GEOIP_DB_PATH unset), and a mix of located/unlocated sessions. Auto-rotates
 * unless the user is actively dragging; clicking a pin reports every session
 * clustered there via `onSelectSessions`. */
const SessionGlobeImpl: React.FC<SessionGlobeProps> = ({
  sessions,
  loading = false,
  onSelectSessions,
}) => {
  // Ref callback (not useRef + a mount-only effect) so the ResizeObserver
  // attaches whenever the container DOM node actually appears — including
  // when it wasn't there yet on first render (e.g. sessions arrive after an
  // async fetch and the component was showing an empty state at mount time).
  const [container, setContainer] = useState<HTMLDivElement | null>(null);
  const containerRefCallback = useCallback((node: HTMLDivElement | null) => {
    setContainer(node);
  }, []);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const markerElsRef = useRef<Map<string, HTMLButtonElement>>(new Map());
 
  const phiRef = useRef(0);
  const thetaRef = useRef(0.3);
  const draggingRef = useRef(false);
  const dragStartRef = useRef<{ x: number; y: number; phi: number; theta: number } | null>(
    null,
  );
 
  const [size, setSize] = useState(0);
  const { resolvedTheme } = useTheme();
  const isDark = resolvedTheme === "dark";
 
  // One marker per distinct location; a session sharing a spot with the
  // current device promotes that marker to the "this device" styling.
  // Sessions with no lat/lng are counted separately, not silently dropped.
  const { markers, unknownCount } = useMemo(() => {
    const { groups, unknownCount: unknown } = groupSessionsByLocation(sessions);
    const markers: GlobeMarker[] = groups.map((group) => ({
      key: group.key,
      location: [group.lat, group.lng],
      size: group.current ? 0.09 : 0.05,
      color: group.current ? INDIGO : SLATE,
      sessions: group.sessions,
    }));
    return { markers, unknownCount: unknown };
  }, [sessions]);
 
  useEffect(() => {
    Eif (!container) return;
    const ro = new ResizeObserver(([entry]) => {
      const next = Math.round(entry.contentRect.width);
      setSize((prev) => (Math.abs(next - prev) >= 4 ? next : prev));
    });
    ro.observe(container);
    return () => ro.disconnect();
  }, [container]);
 
  useEffect(() => {
    const canvas = canvasRef.current;
    Eif (!canvas || size === 0 || markers.length === 0) return;
 
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
 
    const globe = createGlobe(canvas, {
      devicePixelRatio: dpr,
      width: size * dpr,
      height: size * dpr,
      phi: phiRef.current,
      theta: thetaRef.current,
      dark: isDark ? 1 : 0,
      diffuse: 1.2,
      mapSamples: 16000,
      mapBrightness: isDark ? 6 : 5,
      baseColor: isDark ? [0.35, 0.35, 0.4] : [0.9, 0.9, 0.9],
      markerColor: INDIGO,
      glowColor: isDark ? [0.15, 0.15, 0.2] : [1, 1, 1],
      markers,
    });
 
    let raf = requestAnimationFrame(function loop() {
      if (!draggingRef.current) {
        phiRef.current += AUTO_ROTATE_SPEED;
      }
      globe.update({ phi: phiRef.current, theta: thetaRef.current });
 
      for (const marker of markers) {
        const el = markerElsRef.current.get(marker.key);
        if (!el) continue;
        const { x, y, visible } = projectMarker(
          marker.location[0],
          marker.location[1],
          phiRef.current,
          thetaRef.current,
        );
        el.style.left = `${x * 100}%`;
        el.style.top = `${y * 100}%`;
        el.style.opacity = visible ? "1" : "0";
        el.style.pointerEvents = visible ? "auto" : "none";
      }
 
      raf = requestAnimationFrame(loop);
    });
 
    return () => {
      cancelAnimationFrame(raf);
      globe.destroy();
    };
  }, [size, isDark, markers]);
 
  const handlePointerDown = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => {
    draggingRef.current = true;
    dragStartRef.current = {
      x: e.clientX,
      y: e.clientY,
      phi: phiRef.current,
      theta: thetaRef.current,
    };
    e.currentTarget.style.cursor = "grabbing";
    e.currentTarget.setPointerCapture(e.pointerId);
  }, []);
 
  const handlePointerMove = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => {
    if (!draggingRef.current || !dragStartRef.current) return;
    const { x, y, phi, theta } = dragStartRef.current;
    phiRef.current = phi + (e.clientX - x) * DRAG_SENSITIVITY;
    thetaRef.current = Math.max(
      -MAX_TILT,
      Math.min(MAX_TILT, theta - (e.clientY - y) * DRAG_SENSITIVITY),
    );
  }, []);
 
  const endDrag = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => {
    draggingRef.current = false;
    dragStartRef.current = null;
    e.currentTarget.style.cursor = "grab";
    if (e.currentTarget.hasPointerCapture(e.pointerId)) {
      e.currentTarget.releasePointerCapture(e.pointerId);
    }
  }, []);
 
  if (loading) {
    return (
      <EmptyState>
        <Loader2 className="size-4 shrink-0 animate-spin" />
        Loading session locations…
      </EmptyState>
    );
  }
 
  Eif (sessions.length === 0) {
    return (
      <EmptyState>
        <Globe className="size-4 shrink-0" />
        No sessions to show yet.
      </EmptyState>
    );
  }
 
  if (markers.length === 0) {
    return (
      <EmptyState>
        <Globe className="size-4 shrink-0" />
        Location data isn't available for your sessions yet.
      </EmptyState>
    );
  }
 
  return (
    <div>
      <div
        ref={containerRefCallback}
        className="relative mx-auto aspect-square w-full max-w-[280px] select-none"
      >
        <canvas
          ref={canvasRef}
          onPointerDown={handlePointerDown}
          onPointerMove={handlePointerMove}
          onPointerUp={endDrag}
          onPointerCancel={endDrag}
          style={{
            width: size,
            height: size,
            cursor: "grab",
            touchAction: "none",
          }}
        />
        {markers.map((marker) => (
          <button
            key={marker.key}
            // left/top/opacity are owned entirely by the rAF loop below, not
            // React's style prop — if React re-applied a static style object
            // on every re-render (e.g. the parent's marker modal opening),
            // it would stomp the imperative per-frame position for a tick.
            ref={(el) => {
              if (el) {
                markerElsRef.current.set(marker.key, el);
                el.style.left = "0px";
                el.style.top = "0px";
                el.style.opacity = "0";
              } else {
                markerElsRef.current.delete(marker.key);
              }
            }}
            type="button"
            onClick={() => onSelectSessions?.(marker.sessions)}
            aria-label={`${marker.sessions.length} session${marker.sessions.length === 1 ? "" : "s"} at ${
              [marker.sessions[0].location.city, marker.sessions[0].location.country]
                .filter(Boolean)
                .join(", ") || "unknown location"
            }`}
            className="absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full cursor-pointer ring-0 hover:ring-4 hover:ring-indigo-400/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 transition-[box-shadow]"
          />
        ))}
      </div>
      <div className="flex items-center justify-center gap-4 mt-3 text-xs text-gray-400 dark:text-gray-500">
        <span className="flex items-center gap-1.5">
          <span className="size-2 rounded-full bg-indigo-600 inline-block" />
          This device
        </span>
        <span className="flex items-center gap-1.5">
          <span className="size-2 rounded-full bg-gray-400 inline-block" />
          Other sessions
        </span>
      </div>
      {unknownCount > 0 && (
        <p className="text-center text-xs text-gray-400 dark:text-gray-500 mt-1.5">
          {unknownCount} session{unknownCount === 1 ? "" : "s"} without a known
          location
        </p>
      )}
    </div>
  );
};
 
// Parent re-renders (e.g. opening the marker modal) must not remount/re-run
// this component's render — it isn't state the globe/markers depend on, and
// re-rendering would briefly stomp the rAF-owned marker positions (see the
// ref callback above).
export const SessionGlobe = React.memo(SessionGlobeImpl);
 
export default SessionGlobe;