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

22.72% Statements 5/22
0% Branches 0/27
0% Functions 0/5
22.72% Lines 5/22

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                                      1x 1x 1x                   1x                                                                                                                                                                                                                                               1x      
// core/src/apps/user/pages/settings/SessionFlatMap.tsx
import React, { useMemo, useRef } from "react";
import { MapContainer, CircleMarker, Tooltip } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { useTheme } from "chainr-frontend-shared";
import { Loader2, Map as MapIcon } from "lucide-react";
import { BasemapLayer } from "@/components/map";
import type { AccountSession } from "@/hooks/useSessions";
import { groupSessionsByLocation } from "./sessionLocations";
import { SessionLocationEmptyState as EmptyState } from "./SessionLocationEmptyState";
 
interface SessionFlatMapProps {
  sessions: AccountSession[];
  loading?: boolean;
  /** Called with every session clustered at the pin the user clicked. */
  onSelectSessions?: (sessions: AccountSession[]) => void;
}
 
const INDIGO = "#4f46e5";
const SLATE = "#9ca3af";
const MAP_HEIGHT = 280;
 
type InitialView =
  | { bounds: L.LatLngBoundsExpression; boundsOptions: L.FitBoundsOptions }
  | { center: L.LatLngExpression; zoom: number };
 
/** Flat, zoomable/pannable map plotting each session's geolocated IP —
 * an alternative to SessionGlobe for pinpointing exact locations. Shares
 * clustering with the globe view via `groupSessionsByLocation`, and reports
 * every session at a clicked pin via `onSelectSessions`. */
const SessionFlatMapImpl: React.FC<SessionFlatMapProps> = ({
  sessions,
  loading = false,
  onSelectSessions,
}) => {
  const { resolvedTheme } = useTheme();
 
  const { groups, unknownCount } = useMemo(
    () => groupSessionsByLocation(sessions),
    [sessions],
  );
 
  // Computed once, the first time markers exist — a session ending or being
  // revoked afterwards must not recentre the map out from under the user.
  // A lazy useState initializer would run on mount before sessions have
  // loaded (groups still empty), locking in an invalid empty bounds forever
  // and crashing Leaflet's fitBounds once real markers arrive — so this is
  // gated on groups actually being non-empty instead.
  const initialViewRef = useRef<InitialView | null>(null);
  if (initialViewRef.current === null && groups.length > 0) {
    initialViewRef.current =
      groups.length === 1
        ? { center: [groups[0].lat, groups[0].lng], zoom: 4 }
        : {
            bounds: L.latLngBounds(
              groups.map((g) => [g.lat, g.lng] as [number, number]),
            ),
            boundsOptions: { padding: [32, 32], maxZoom: 6 },
          };
  }
  const initialView = initialViewRef.current;
 
  if (loading) {
    return (
      <EmptyState>
        <Loader2 className="size-4 shrink-0 animate-spin" />
        Loading session locations…
      </EmptyState>
    );
  }
 
  if (sessions.length === 0) {
    return (
      <EmptyState>
        <MapIcon className="size-4 shrink-0" />
        No sessions to show yet.
      </EmptyState>
    );
  }
 
  if (groups.length === 0 || initialView === null) {
    return (
      <EmptyState>
        <MapIcon className="size-4 shrink-0" />
        Location data isn't available for your sessions yet.
      </EmptyState>
    );
  }
 
  return (
    <div>
      <div className="rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700">
        <MapContainer
          {...initialView}
          style={{ height: MAP_HEIGHT, width: "100%" }}
          scrollWheelZoom
          // `!`: leaflet.css is unlayered, so its #ddd beats any utility.
          // It shows before tiles load, and wherever there are none.
          className="!bg-gray-100 dark:!bg-gray-900"
        >
          <BasemapLayer dark={resolvedTheme === "dark"} />
          {groups.map((group) => (
            <CircleMarker
              key={group.key}
              center={[group.lat, group.lng]}
              radius={group.current ? 9 : 7}
              pathOptions={{
                color: "white",
                weight: 2,
                fillColor: group.current ? INDIGO : SLATE,
                fillOpacity: 0.9,
              }}
              eventHandlers={{
                click: () => onSelectSessions?.(group.sessions),
              }}
            >
              <Tooltip direction="top" offset={[0, -6]} opacity={1}>
                {[group.sessions[0].location.city, group.sessions[0].location.country]
                  .filter(Boolean)
                  .join(", ") || "Unknown location"}
                {" · "}
                {group.sessions.length} session{group.sessions.length === 1 ? "" : "s"}
              </Tooltip>
            </CircleMarker>
          ))}
        </MapContainer>
      </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 this
// component — Leaflet's map instance is expensive to recreate and would lose
// the user's current pan/zoom position.
export const SessionFlatMap = React.memo(SessionFlatMapImpl);
 
export default SessionFlatMap;