💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
update(CollectionMapDialog):logic-optimization
Aswin Asoke87fb4ecda2d
diff --git a/web/apps/photos/package.json b/web/apps/photos/package.jsonindex ba799e138a..2fa2820de3 100644--- a/web/apps/photos/package.json+++ b/web/apps/photos/package.json@@ -19,13 +19,13 @@"react": "^19.2.0","react-dom": "^19.2.0","react-leaflet": "^5.0.0",- "react-leaflet-cluster": "^4.0.0","react-select": "^5.10.2","react-top-loading-bar": "^3.0.2","react-virtualized-auto-sizer": "^1.0.26","react-window": "^1.8.11","sanitize-filename": "^1.6.3",- "similarity-transformation": "^0.0.1"+ "similarity-transformation": "^0.0.1",+ "supercluster": "^8.0.1"},"devDependencies": {"@types/node": "^22.15.32",diff --git a/web/apps/photos/src/components/Collections/CollectionMapDialog.md b/web/apps/photos/src/components/Collections/CollectionMapDialog.mdnew file mode 100644index 0000000000..ce0999b01b--- /dev/null+++ b/web/apps/photos/src/components/Collections/CollectionMapDialog.md@@ -0,0 +1,245 @@+# CollectionMapDialog.tsx Function Guide++This document describes what each function in `web/apps/photos/src/components/Collections/CollectionMapDialog.tsx` does, including its purpose, inputs, outputs, and notable side effects. Functions are grouped by responsibility and follow their appearance in the file.++Type note: `Supercluster` typing is provided by the local module declaration in `web/apps/photos/src/types/supercluster.d.ts` to avoid missing-type fallbacks and keep cluster unions strongly typed.++## Map Component Loading++### `useMapComponents()`++- Purpose: Dynamically loads Leaflet React components on the client to avoid SSR issues.+- Inputs: None.+- Returns: `MapComponents | null` containing `MapContainer`, `TileLayer`, `Marker`, `useMap`.+- Side effects: Imports `react-leaflet` on the client and logs to console on failure.++### `useCurrentUser()`++- Purpose: Reads the authenticated user for favorites/visibility actions.+- Inputs: None.+- Returns: The local user object or `undefined` if unavailable.+- Side effects: None (safe memoized read).++## Map Index Utilities++### `mapIndexKey(collectionSummary)`++- Purpose: Computes the KV storage key for a collection’s map index.+- Inputs: `CollectionSummary`.+- Returns: `string` formatted as `photos-map-index-v1:{type}:{id}`.+- Side effects: None.++### `toMapIndexMeta(collectionSummary)`++- Purpose: Builds metadata used to validate cached map indexes.+- Inputs: `CollectionSummary`.+- Returns: `{ fileCount, updationTime }`.+- Side effects: None.++### `isStoredMapIndexValid(stored, meta)`++- Purpose: Guards cached index reads by verifying metadata and shape.+- Inputs: `stored: unknown`, `meta: MapIndexMeta`.+- Returns: `boolean` type guard for `MapIndexStorage`.+- Side effects: None.++### `buildMapIndexPoints(files)`++- Purpose: Extracts map points from files with geolocation and finds the newest file.+- Inputs: `EnteFile[]`.+- Returns: `{ points: MapIndexPoint[], latestFileId?: number }`.+- Side effects: Yields to the event loop every 5000 files to avoid blocking.++### `buildClusterIndex(points)`++- Purpose: Builds a `Supercluster` index for fast clustering and leaf queries.+- Inputs: `MapIndexPoint[]`.+- Returns: `Supercluster` instance with mapped `latestTimestamp` and `latestFileId` reductions.+- Type note: The map/reduce callbacks are typed via the local `MapClusterOptions` interface, and the returned value conforms to the `MapIndex` interface.+- Side effects: None.++## Map Data Hook++### `useMapData(open, collectionSummary, activeCollection, onGenericError)`++- Purpose: Loads collection files, builds/persists the spatial index, and manages thumbnails.+- Inputs:+ - `open`: dialog open state.+ - `collectionSummary`: target collection summary.+ - `activeCollection`: active collection entity (if any).+ - `onGenericError`: error handler.+- Returns: `MapDataResult` containing map state plus `removeFiles`, `updateFileVisibility`, and `queueThumbnailFetch`.+- Side effects:+ - Reads and writes to KV storage for the map index.+ - Starts a thumbnail worker that fetches thumbnails via `downloadManager`.+ - Updates local state with index, files, and thumbnails.++Internal callbacks inside `useMapData`:++- `queueThumbnailFetch(fileIDs)`: batches thumbnail requests, skips existing thumbs, and updates `thumbByFileID` as results arrive.+- `loadMapData()`: fetches files, loads or rebuilds the spatial index, computes map center, and seeds cover thumbnails.+- `removeFiles(fileIDs)`: removes files from `filesByID`, map points, and index; recomputes `latestFileId`.+- `updateFileVisibility(file, visibility)`: updates local visibility state and updates points/index when a file becomes hidden or visible again.++## Favorites Hook++### `useFavorites(open, user)`++- Purpose: Loads favorites from IndexedDB and updates favorites/visibility.+- Inputs: `open` dialog state, `user`.+- Returns: Favorite/visibility sets and handler functions.+- Side effects: Reads favorites from IndexedDB; updates favorite status via services.++Internal callbacks inside `useFavorites`:++- `loadFavorites()`: loads favorites from collections and files.+- `addToSet(set, id)` / `removeFromSet(set, id)`: immutable set helpers.+- `handleToggleFavorite(file)`: toggles favorite state and updates pending sets.+- `handleFileVisibilityUpdate(file, visibility)`: updates visibility via service and pending sets.++## Visible Photos Hook++### `useVisiblePhotos()`++- Purpose: Tracks which photos are currently visible on the map and whether the list is updating.+- Inputs: None.+- Returns: `{ visiblePhotos, setVisiblePhotos, isVisiblePhotosUpdating, setIsVisiblePhotosUpdating }`.+- Side effects: None.++## Marker Icon Builders++### `createMarkerIcon(imageSrc, size)`++- Purpose: Builds a Leaflet `DivIcon` for individual photo pins.+- Inputs: `imageSrc: string`, `size: number`.+- Returns: `DivIcon | null` (null on SSR).+- Side effects: Requires `leaflet` at runtime; generates HTML with hover styling.++### `createClusterIcon(imageSrc, size, clusterCount, interactive?)`++- Purpose: Builds a `DivIcon` for clusters with a badge and optional hover/interactive styling.+- Inputs: `imageSrc: string`, `size: number`, `clusterCount: number`, `interactive: boolean` (optional).+- Returns: `DivIcon | null` (null on SSR).+- Side effects: Requires `leaflet` at runtime; generates HTML with hover styling based on `interactive`.++## Collection Filtering Helpers++### `isFileVisible(file)`++- Purpose: Determines whether a file should be displayed (not hidden/archived).+- Inputs: `EnteFile`.+- Returns: `boolean`.+- Side effects: None.++### `getFilesForCollection(collectionSummary, activeCollection)`++- Purpose: Retrieves files for a collection, filters hidden/archived items, and removes duplicates.+- Inputs: `CollectionSummary`, `Collection | undefined`.+- Returns: `Promise<EnteFile[]>`.+- Side effects: Reads from IndexedDB via `savedCollectionFiles` and `savedCollections`.++## Main Component++### `CollectionMapDialog(props)`++- Purpose: Orchestrates map data, visible photos, favorites, and UI layout for the map dialog.+- Inputs: `CollectionMapDialogProps`.+- Returns: `ReactElement`.+- Side effects: Sets dialog z-index when the file viewer opens.++Internal callbacks inside `CollectionMapDialog`:++- `handleSetFileViewerOpen(next)`: keeps `isFileViewerOpen` in sync with viewer state.+- `handleRemotePull()`: triggers remote pull (silent) when available.+- `handleMarkTempDeleted(files)`: updates visible list and map state after deletions.+- `handleFileVisibilityUpdateWithLocalState(file, visibility)`: syncs server visibility and local map index.+- `noOpSetSelected()`: placeholder selection setter for map view.++## Layout Components++### `MapLayout(props)`++- Purpose: Lays out the sidebar and map canvas.+- Inputs: `MapLayoutProps`.+- Returns: `ReactElement`.+- Side effects: None.++### `CollectionSidebar(props)`++- Purpose: Renders collection details, cover, and file list for visible photos.+- Inputs: `CollectionSidebarProps`.+- Returns: `ReactElement`.+- Side effects: None.++Internal callbacks inside `CollectionSidebar`:++- `handleScroll(offset)`: updates scroll offset for sticky header behavior.+- `handleVisibleDateChange(date)`: updates visible date label in the header.++## Map Components++### `MapCanvas(props)`++- Purpose: Renders the Leaflet map container, tile layer, controls, and clusters.+- Inputs: `MapCanvasProps`.+- Returns: `ReactElement`.+- Side effects: None.++### `MapControls(props)`++- Purpose: Renders zoom, maps link, and attribution UI.+- Inputs: `MapControlsProps`.+- Returns: `ReactElement`.+- Side effects: Opens external map links in a new tab.++Internal callbacks inside `MapControls`:++- `handleOpenInMaps()`: opens Google Maps at the current center and zoom.+- `handleZoomIn()` / `handleZoomOut()`: controls map zoom.+- `toggleAttribution()`: toggles the attribution popup on mobile.++### `MapClusters(props)`++- Purpose: Renders cluster/point markers from `Supercluster`, manages visible photo derivation, and prefetches thumbnails.+- Inputs: `MapClustersProps`.+- Returns: `ReactElement`.+- Side effects:+ - Reads map bounds/zoom and updates visible photos.+ - Prefetches thumbnails for visible and near-visible clusters.++Internal callbacks inside `MapClusters`:++- `isClusterFeature(feature)`: type guard for cluster features.+- `updateVisibleLeaves(requestId, clusters, bounds)`: gathers in-bounds leaves, sorts by timestamp, and updates visible photos.+- `updateClusters()`: computes clusters for the current view and triggers prefetching.+- `handleClusterClick(lat, lng, expansionZoom)`: zooms into a cluster when interactive.++## Small UI Helpers++### `FloatingIconButton(props)`++- Purpose: Styled `IconButton` with consistent hover and shadow behavior.+- Inputs: `IconButtonProps`.+- Returns: `ReactElement`.+- Side effects: None.++### `CenteredBox({ children, onClose, closeLabel })`++- Purpose: Centers content for loading/error/empty states with an optional close button.+- Inputs: `children`, optional `onClose`, optional `closeLabel`.+- Returns: `ReactElement`.+- Side effects: None.++### `EmptyState({ children })`++- Purpose: Wrapper for the empty-state layout.+- Inputs: `children`.+- Returns: `ReactElement`.+- Side effects: None.++### `MapCover(props)`++- Purpose: Renders the cover hero with image, title, count, and close button.+- Inputs: `MapCoverProps`.+- Returns: `ReactElement`.+- Side effects: None.diff --git a/web/apps/photos/src/components/Collections/CollectionMapDialog.tsx b/web/apps/photos/src/components/Collections/CollectionMapDialog.tsxindex 741f1e5d9b..b76a3e8146 100644--- a/web/apps/photos/src/components/Collections/CollectionMapDialog.tsx+++ b/web/apps/photos/src/components/Collections/CollectionMapDialog.tsx@@ -19,13 +19,13 @@ import { ensureLocalUser } from "ente-accounts/services/user";import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";import type { ModalVisibilityProps } from "ente-base/components/utils/modal";import { useBaseContext } from "ente-base/context";+import { getKV, setKV } from "ente-base/kv";import { downloadManager } from "ente-gallery/services/download";import { uniqueFilesByID } from "ente-gallery/utils/file";import { type Collection } from "ente-media/collection";import { type EnteFile } from "ente-media/file";import {fileCreationTime,- fileFileName,fileLocation,ItemVisibility,} from "ente-media/file-metadata";@@ -43,27 +43,22 @@ import {savedCollections,} from "ente-new/photos/services/photos-fdb";import { t } from "i18next";-import "leaflet.markercluster/dist/MarkerCluster.css";-import "leaflet.markercluster/dist/MarkerCluster.Default.css";import "leaflet/dist/leaflet.css";import type { Dispatch, SetStateAction } from "react";import React, {+ startTransition,useCallback,useEffect,useMemo,useRef,useState,} from "react";+import Supercluster from "supercluster";import type { SelectedState } from "utils/file";import type { FileListWithViewerProps } from "../FileListWithViewer";import { FileListWithViewer } from "../FileListWithViewer";import { calculateOptimalZoom, getMapCenter } from "../TripLayout/mapHelpers";import type { JourneyPoint } from "../TripLayout/types";-import { generateNeededThumbnails } from "../TripLayout/utils/dataProcessing";--// ============================================================================-// Types-// ============================================================================interface CollectionMapDialogPropsextends ModalVisibilityProps,@@ -84,40 +79,194 @@ interface CollectionMapDialogPropsonRemotePull?: (opts?: RemotePullOpts) => Promise<void>;}+// Describes all map-related state used in the dialog:+// - mapCenter: current map center, typically derived from the latest file with location+// - mapIndex/mapPoints/latestFileId: spatial index and its source points, plus the newest file id+// - filesByID/thumbByFileID: cached file metadata and lazily-fetched thumbnails+// - isLoading/error: loading/error flags for map data fetches+interface MapDataState {mapCenter: [number, number] | null;- mapPhotos: JourneyPoint[];+ mapIndex: MapIndex | null;+ mapPoints: MapIndexPoint[];+ latestFileId: number | undefined;filesByID: Map<number, EnteFile>;thumbByFileID: Map<number, string>;isLoading: boolean;error: string | null;}+/**+ * When files are being opened from the the Sidebar, there is ablity to add them as favoriate,+ * archive them or unarchieve them and this interface is for facilitating that. Where the favoruteFileIds+ * hols the existing favorites, pending holds the ones which are in progress for respective ones+ */+interface FavoritesState {favoriteFileIDs: Set<number>;pendingFavoriteUpdates: Set<number>;pendingVisibilityUpdates: Set<number>;}+/**+ * Extension of MapDataState that adds mutation functions for map data management.+ * - removeFiles: Removes files from the map index when deleted from FileListWithViewer+ * - updateFileVisibility: Updates file visibility state and removes hidden files from the map+ * - queueThumbnailFetch: Batches and fetches thumbnails on demand for visible files+ */+interface MapDataResult extends MapDataState {removeFiles: (fileIDs: number[]) => void;updateFileVisibility: (file: EnteFile, visibility: ItemVisibility) => void;+ queueThumbnailFetch: (fileIDs: number[]) => void;}/**- * Dynamically loaded map components to avoid SSR issues with Leaflet+ * Dynamically loaded map components to avoid SSR issues with Leaflet. Normal imports actually caused+ * the app to break in some instances, thus dynamically loading them instead.+ * Loaded lazily in useMapComponents() hook when the dialog opens to ensure window exists.*/interface MapComponents {MapContainer: typeof import("react-leaflet").MapContainer;TileLayer: typeof import("react-leaflet").TileLayer;Marker: typeof import("react-leaflet").Marker;useMap: typeof import("react-leaflet").useMap;- MarkerClusterGroup: typeof import("react-leaflet-cluster").default;}-// ============================================================================-// Custom Hooks-// ============================================================================+/**+ * Represents a geotagged photo point stored in the map spatial index.+ * Each point corresponds to a photo with location metadata.+ * - fileId: Unique identifier for the photo file+ * - lat: Latitude coordinate of the photo location+ * - lng: Longitude coordinate of the photo location+ * - timestamp: Unix timestamp (milliseconds) of when the photo was created+ */++interface MapIndexPoint {+ fileId: number;+ lat: number;+ lng: number;+ timestamp: number;+}++/**+ * Along with the GeoTagged photos we are also storing a metadata, which changes+ * only when there is change in the stored values, to prevent this from updating+ * each time when there is change. Currently fileCount and updationTime are the+ * two metrics kept to analyse this change.+ */++interface MapIndexMeta {+ fileCount: number;+ updationTime: number | null;+}+/**+ * Structure of the data stored in IndexedDB for the map view.+ * - meta: Metadata tracking file count and last update time for cache validation+ * - points: Array of geotagged photo locations with timestamps+ * - latestFileId: ID of the most recently created file, used for cover image caching optimization+ */++interface MapIndexStorage {+ meta: MapIndexMeta;+ points: MapIndexPoint[];+ latestFileId?: number;+}++/**+ * The small payload we attach to a point: fileId points to the photo, and timestamp keeps+ * enough context for sorting or choosing the freshest item in a cluster.+ */+interface MapPointProperties {+ fileId: number;+ timestamp: number;+}++/**+ * A GeoJSON feature for a single photo point. GeoJSON is the small, common shape most map+ * libraries expect for geographic data, so we stick with it even when we only need a+ * couple of fields. type stays "Feature" because that is the GeoJSON spec's envelope for+ * real-world points; it does not change our logic, but it keeps the data recognizable to+ * tooling like Supercluster. properties carry the fileId and timestamp (and keep cluster+ * as false), and geometry stores the point in [lng, lat] order for map libs.+ */+interface MapPointFeature {+ type: "Feature";+ properties: MapPointProperties & { cluster?: false };+ geometry: { type: "Point"; coordinates: [number, number] };+}++/**+ * Summary info for a cluster: latestTimestamp and latestFileId keep track of the freshest+ * photo inside the cluster so we can choose a representative cover.+ */+interface MapClusterProperties {+ latestTimestamp: number;+ latestFileId: number;+}++/**+ * A GeoJSON feature that represents a cluster instead of a single point. properties mark+ * it as a cluster, carry cluster_id for expansion, point_count for the raw size, and+ * point_count_abbreviated for a compact label, while geometry still gives the centroid.+ */+interface MapClusterFeature {+ type: "Feature";+ properties: MapClusterProperties & {+ cluster: true;+ cluster_id: number;+ point_count: number;+ point_count_abbreviated?: number | string;+ };+ geometry: { type: "Point"; coordinates: [number, number] };+}++/**+ * Convenience union so callers can handle clusters and single points together.+ */+type MapFeature = MapClusterFeature | MapPointFeature;++/**+ * The small contract we rely on from Supercluster: load ingests points, getClusters+ * returns mixed clusters/points for bounds and zoom, getLeaves expands a cluster into+ * its points, and getClusterExpansionZoom tells us how far to zoom to break it apart.+ */+interface MapIndex {+ load(points: MapPointFeature[]): MapIndex;+ getClusters(+ bbox: [number, number, number, number],+ zoom: number,+ ): MapFeature[];+ getLeaves(+ clusterId: number,+ limit: number,+ offset: number,+ ): MapPointFeature[];+ getClusterExpansionZoom(clusterId: number): number;+}++/**+ * Tuning knobs for building the index: radius controls cluster size in pixels, maxZoom+ * caps clustering depth, map shapes point data into the cluster properties we track,+ * and reduce merges those properties as clusters grow.+ */+interface MapClusterOptions {+ radius?: number;+ maxZoom?: number;+ map?: (props: MapPointProperties) => MapClusterProperties;+ reduce?: (+ accumulated: MapClusterProperties,+ props: MapClusterProperties,+ ) => void;+}++type SuperclusterConstructor = new (options?: MapClusterOptions) => MapIndex;++//Prefix for storing the map view data specific to the current active collection, so they aren't recomputed when reopend+const MAP_INDEX_KEY_PREFIX = "photos-map-index-v1";+const MAX_MAP_ZOOM = 19;+const PREFETCH_BOUNDS_PADDING = 0.15;+const THUMBNAIL_BATCH_SIZE = 40;/*** Dynamically loads map-related React components (Leaflet) to avoid SSR issues@@ -132,17 +281,13 @@ function useMapComponents() {// Only load on client-side where window existsif (typeof window === "undefined") return;- void Promise.all([- import("react-leaflet"),- import("react-leaflet-cluster"),- ])- .then(([leaflet, cluster]) =>+ void import("react-leaflet")+ .then((leaflet) =>setMapComponents({MapContainer: leaflet.MapContainer,TileLayer: leaflet.TileLayer,Marker: leaflet.Marker,useMap: leaflet.useMap,- MarkerClusterGroup: cluster.default,}),).catch((e: unknown) => {@@ -167,9 +312,96 @@ function useCurrentUser() {}, []);}+const mapIndexKey = (collectionSummary: CollectionSummary) =>+ `${MAP_INDEX_KEY_PREFIX}:${collectionSummary.type}:${collectionSummary.id}`;++const toMapIndexMeta = (+ collectionSummary: CollectionSummary,+): MapIndexMeta => ({+ fileCount: collectionSummary.fileCount,+ updationTime: collectionSummary.updationTime ?? null,+});++const isStoredMapIndexValid = (+ stored: unknown,+ meta: MapIndexMeta,+): stored is MapIndexStorage => {+ if (!stored || typeof stored !== "object") return false;+ const candidate = stored as Partial<MapIndexStorage>;+ if (!candidate.meta || !Array.isArray(candidate.points)) return false;+ return (+ candidate.meta.fileCount === meta.fileCount &&+ candidate.meta.updationTime === meta.updationTime+ );+};++const buildMapIndexPoints = async (files: EnteFile[]) => {+ const points: MapIndexPoint[] = [];+ let latestTimestamp = -1;+ let latestFileId: number | undefined;++ for (let index = 0; index < files.length; index += 1) {+ const file = files[index];+ if (!file) continue;+ const loc = fileLocation(file);+ if (!loc) continue;++ const timestamp = fileCreationTime(file);+ points.push({+ fileId: file.id,+ lat: loc.latitude,+ lng: loc.longitude,+ timestamp,+ });++ if (timestamp > latestTimestamp) {+ latestTimestamp = timestamp;+ latestFileId = file.id;+ }++ if (index % 5000 === 0) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ }++ return { points, latestFileId };+};++const buildClusterIndex = (points: MapIndexPoint[]): MapIndex => {+ const options: MapClusterOptions = {+ radius: 80,+ maxZoom: MAX_MAP_ZOOM,+ map: (props) => ({+ latestTimestamp: props.timestamp,+ latestFileId: props.fileId,+ }),+ reduce: (accumulated, props) => {+ if (props.latestTimestamp > accumulated.latestTimestamp) {+ accumulated.latestTimestamp = props.latestTimestamp;+ accumulated.latestFileId = props.latestFileId;+ }+ },+ };++ const SuperclusterCtor = Supercluster as unknown as SuperclusterConstructor;+ const index = new SuperclusterCtor(options);++ const features: MapPointFeature[] = points.map((point) => ({+ type: "Feature" as const,+ properties: { fileId: point.fileId, timestamp: point.timestamp },+ geometry: {+ type: "Point" as const,+ coordinates: [point.lng, point.lat] as [number, number],+ },+ }));++ index.load(features);+ return index;+};+/**- * Loads and manages map data including photos, locations, and thumbnails- * Responsibility: Fetch collection files, extract locations, generate thumbnails+ * Loads and manages map data including index, files, and thumbnails.+ * Responsibility: Fetch collection files, build/persist spatial index, prefetch thumbnails on demand.*/function useMapData(open: boolean,@@ -179,58 +411,101 @@ function useMapData(): MapDataResult {const [state, setState] = useState<MapDataState>({mapCenter: null,- mapPhotos: [],+ mapIndex: null,+ mapPoints: [],+ latestFileId: undefined,filesByID: new Map(),thumbByFileID: new Map(),isLoading: false,error: null,});+ const filesByIDRef = useRef<Map<number, EnteFile>>(new Map());+ const thumbsByFileIDRef = useRef<Map<number, string>>(new Map());+ const pendingThumbsRef = useRef<Set<number>>(new Set());+ const isThumbnailWorkerRunningRef = useRef(false);+// Track which collection we've loaded to avoid unnecessary reloads// Include fileCount to detect when collection content changesconst loadedCollectionRef = useRef<{summaryId: number;collectionId: number | undefined;fileCount: number;+ updationTime: number | null;} | null>(null);- const loadAllThumbs = useCallback(- async (points: JourneyPoint[], files: EnteFile[]) => {- // Build a Map for O(1) file lookup instead of O(n) find- const filesById = new Map(files.map((f) => [f.id, f]));+ useEffect(() => {+ filesByIDRef.current = state.filesByID;+ }, [state.filesByID]);- const entries = await Promise.all(- points.map(async (p) => {- if (p.image) return [p.fileId, p.image] as const;- const file = filesById.get(p.fileId);- if (!file) return [p.fileId, undefined] as const;- try {- const thumb =- await downloadManager.renderableThumbnailURL(file);- return [p.fileId, thumb] as const;- } catch {- return [p.fileId, undefined] as const;- }- }),- );+ useEffect(() => {+ thumbsByFileIDRef.current = state.thumbByFileID;+ }, [state.thumbByFileID]);- setState((prev) => ({- ...prev,- thumbByFileID: new Map(- entries.filter(([, t]) => t !== undefined) as [- number,- string,- ][],- ),- }));- },- [],- );+ const queueThumbnailFetch = useCallback((fileIDs: number[]) => {+ if (!fileIDs.length) return;++ const pending = pendingThumbsRef.current;+ const existingThumbs = thumbsByFileIDRef.current;+ const filesByID = filesByIDRef.current;++ for (const fileId of fileIDs) {+ if (existingThumbs.has(fileId)) continue;+ if (!filesByID.has(fileId)) continue;+ pending.add(fileId);+ }++ if (isThumbnailWorkerRunningRef.current) return;+ isThumbnailWorkerRunningRef.current = true;++ void (async () => {+ while (pendingThumbsRef.current.size > 0) {+ const batchIds = Array.from(pendingThumbsRef.current).slice(+ 0,+ THUMBNAIL_BATCH_SIZE,+ );+ batchIds.forEach((id) => pendingThumbsRef.current.delete(id));++ const entries = await Promise.all(+ batchIds.map(async (fileId) => {+ const file = filesByIDRef.current.get(fileId);+ if (!file) return [fileId, undefined] as const;+ try {+ const thumb =+ await downloadManager.renderableThumbnailURL(+ file,+ );+ return [fileId, thumb] as const;+ } catch {+ return [fileId, undefined] as const;+ }+ }),+ );++ setState((prev) => {+ const nextThumbs = new Map(prev.thumbByFileID);+ entries.forEach(([fileId, thumb]) => {+ if (!thumb || nextThumbs.has(fileId)) return;+ nextThumbs.set(fileId, thumb);+ });+ return nextThumbs.size > prev.thumbByFileID.size+ ? { ...prev, thumbByFileID: nextThumbs }+ : prev;+ });++ await new Promise((resolve) => setTimeout(resolve, 0));+ }++ isThumbnailWorkerRunningRef.current = false;+ })();+ }, []);// Clear loaded ref when dialog closes so we reload fresh data next time.useEffect(() => {if (!open) {loadedCollectionRef.current = null;+ pendingThumbsRef.current.clear();+ isThumbnailWorkerRunningRef.current = false;}}, [open]);@@ -241,17 +516,20 @@ function useMapData(const currentSummaryId = collectionSummary.id;const currentCollectionId = activeCollection?.id;const currentFileCount = collectionSummary.fileCount;+ const currentUpdationTime = collectionSummary.updationTime ?? null;const loaded = loadedCollectionRef.current;if (loaded &&loaded.summaryId === currentSummaryId &&loaded.collectionId === currentCollectionId &&- loaded.fileCount === currentFileCount+ loaded.fileCount === currentFileCount &&+ loaded.updationTime === currentUpdationTime) {return;}const loadMapData = async () => {+ pendingThumbsRef.current.clear();setState((prev) => ({ ...prev, isLoading: true, error: null }));try {@@ -259,59 +537,95 @@ function useMapData(collectionSummary,activeCollection,);- const locationPoints = extractLocationPoints(files); // transforms the files into JourneyData[]+ const filesByID = new Map(files.map((file) => [file.id, file]));+ filesByIDRef.current = filesByID;- if (locationPoints.length) {- const sortedPoints = sortPhotosByTimestamp(locationPoints);+ const meta = toMapIndexMeta(collectionSummary);+ const indexKey = mapIndexKey(collectionSummary);- const { thumbnailUpdates } = await generateNeededThumbnails(- { photoClusters: [sortedPoints], files },- );+ console.log(indexKey);- const pointsWithThumbs = sortedPoints.map((point) => {- const thumb = thumbnailUpdates.get(point.fileId);- return thumb ? { ...point, image: thumb } : point;- });+ let points: MapIndexPoint[] | undefined;+ let latestFileId: number | undefined;- setState({- filesByID: new Map(- files.map((file) => [file.id, file]),- ),- mapCenter: getMapCenter([], pointsWithThumbs),- mapPhotos: pointsWithThumbs,- thumbByFileID: new Map(),- isLoading: false,- error: null,- });+ try {+ const stored = await getKV(indexKey);+ if (isStoredMapIndexValid(stored, meta)) {+ points = stored.points;+ latestFileId = stored.latestFileId;+ }+ } catch {+ // Ignore index read errors and rebuild+ }- // Mark this collection as loaded- loadedCollectionRef.current = {- summaryId: currentSummaryId,- collectionId: currentCollectionId,- fileCount: currentFileCount,- };+ if (!points) {+ const built = await buildMapIndexPoints(files);+ points = built.points;+ latestFileId = built.latestFileId;+ try {+ await setKV(indexKey, { meta, points, latestFileId });+ } catch {+ // Ignore index persistence errors+ }+ }- void loadAllThumbs(pointsWithThumbs, files);- return;+ if (latestFileId === undefined && points.length > 0) {+ let latestTimestamp = -1;+ points.forEach((point) => {+ if (point.timestamp > latestTimestamp) {+ latestTimestamp = point.timestamp;+ latestFileId = point.fileId;+ }+ });}- // Reset state when no geotagged locations exist to avoid showing stale data+ const mapIndex =+ points.length > 0 ? buildClusterIndex(points) : null;+ const latestPoint =+ latestFileId !== undefined+ ? points.find((point) => point.fileId === latestFileId)+ : points[0];+ const mapCenter = latestPoint+ ? getMapCenter(+ [],+ [+ {+ lat: latestPoint.lat,+ lng: latestPoint.lng,+ name: "",+ country: "",+ timestamp: "",+ image: "",+ fileId: latestPoint.fileId,+ },+ ],+ )+ : null;+setState({- filesByID: new Map(),- mapCenter: null,- mapPhotos: [],+ filesByID,+ mapCenter,+ mapIndex,+ mapPoints: points,+ latestFileId,thumbByFileID: new Map(),isLoading: false,error: null,});- // Mark this collection as loaded (even with no photos)+ // Mark this collection as loadedloadedCollectionRef.current = {summaryId: currentSummaryId,collectionId: currentCollectionId,fileCount: currentFileCount,+ updationTime: currentUpdationTime,};+ const coverId = collectionSummary.coverFile?.id ?? latestFileId;+ if (coverId !== undefined) {+ queueThumbnailFetch([coverId]);+ }+return;} catch (e) {setState((prev) => ({@@ -334,7 +648,7 @@ function useMapData(collectionSummary,activeCollection,onGenericError,- loadAllThumbs,+ queueThumbnailFetch,]);const removeFiles = useCallback((fileIDs: number[]) => {@@ -347,15 +661,32 @@ function useMapData(filesByID.delete(id);thumbByFileID.delete(id);});- const mapPhotos = prev.mapPhotos.filter(- (photo) => !ids.has(photo.fileId),+ const mapPoints = prev.mapPoints.filter(+ (point) => !ids.has(point.fileId),);+ const mapIndex =+ mapPoints.length > 0 ? buildClusterIndex(mapPoints) : null;++ let latestFileId = prev.latestFileId;+ if (latestFileId && ids.has(latestFileId)) {+ let latestTimestamp = -1;+ let nextLatestFileId: number | undefined;+ mapPoints.forEach((point) => {+ if (point.timestamp > latestTimestamp) {+ latestTimestamp = point.timestamp;+ nextLatestFileId = point.fileId;+ }+ });+ latestFileId = nextLatestFileId;+ }return {...prev,filesByID,thumbByFileID,- mapPhotos,- mapCenter: mapPhotos.length ? prev.mapCenter : null,+ mapIndex,+ mapPoints,+ latestFileId,+ mapCenter: mapPoints.length ? prev.mapCenter : null,};});}, []);@@ -377,13 +708,88 @@ function useMapData(};const filesByID = new Map(prev.filesByID);filesByID.set(file.id, updatedFile);- return { ...prev, filesByID };++ let mapPoints = prev.mapPoints;+ let mapIndex = prev.mapIndex;+ let latestFileId = prev.latestFileId;++ if (visibility !== ItemVisibility.visible) {+ const filtered = prev.mapPoints.filter(+ (point) => point.fileId !== file.id,+ );+ if (filtered.length !== prev.mapPoints.length) {+ mapPoints = filtered;+ mapIndex =+ mapPoints.length > 0+ ? buildClusterIndex(mapPoints)+ : null;+ if (latestFileId === file.id) {+ let latestTimestamp = -1;+ let nextLatestFileId: number | undefined;+ mapPoints.forEach((point) => {+ if (point.timestamp > latestTimestamp) {+ latestTimestamp = point.timestamp;+ nextLatestFileId = point.fileId;+ }+ });+ latestFileId = nextLatestFileId;+ }+ }+ } else if (!prev.mapPoints.some((p) => p.fileId === file.id)) {+ const loc = fileLocation(file);+ if (loc) {+ const timestamp = fileCreationTime(file);+ mapPoints = [+ ...prev.mapPoints,+ {+ fileId: file.id,+ lat: loc.latitude,+ lng: loc.longitude,+ timestamp,+ },+ ];+ mapIndex = buildClusterIndex(mapPoints);+ const currentLatestTimestamp =+ latestFileId !== undefined+ ? (prev.mapPoints.find(+ (p) => p.fileId === latestFileId,+ )?.timestamp ?? -1)+ : -1;+ if (timestamp > currentLatestTimestamp) {+ latestFileId = file.id;+ }+ }+ }++ let mapCenter = prev.mapCenter;+ if (!mapPoints.length) {+ mapCenter = null;+ } else if (!mapCenter) {+ const centerPoint =+ latestFileId !== undefined+ ? mapPoints.find(+ (point) => point.fileId === latestFileId,+ )+ : mapPoints[0];+ if (centerPoint) {+ mapCenter = [centerPoint.lat, centerPoint.lng];+ }+ }++ return {+ ...prev,+ filesByID,+ mapPoints,+ mapIndex,+ latestFileId,+ mapCenter,+ };});},[],);- return { ...state, removeFiles, updateFileVisibility };+ return { ...state, removeFiles, updateFileVisibility, queueThumbnailFetch };}/**@@ -512,8 +918,15 @@ function useFavorites(*/function useVisiblePhotos() {const [visiblePhotos, setVisiblePhotos] = useState<JourneyPoint[]>([]);+ const [isVisiblePhotosUpdating, setIsVisiblePhotosUpdating] =+ useState(false);- return { visiblePhotos, setVisiblePhotos };+ return {+ visiblePhotos,+ setVisiblePhotos,+ isVisiblePhotosUpdating,+ setIsVisiblePhotosUpdating,+ };}/**@@ -598,6 +1011,7 @@ function createClusterIcon(imageSrc: string,size: number,clusterCount: number,+ interactive = true,): import("leaflet").DivIcon | null {if (typeof window === "undefined") return null;@@ -614,6 +1028,10 @@ function createClusterIcon(const outerBorderRadius = 16;const innerBorderRadius = 12;+ const hoverHandlers = interactive+ ? "onmouseover=\"this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.parentElement.querySelector('.triangle').style.borderTopColor='#22c55e';\" onmouseout=\"this.style.background='white'; this.style.borderColor='#ffffff'; this.parentElement.querySelector('.triangle').style.borderTopColor='white';\""+ : "";+const badgeLabel =clusterCount >= 2000? `${Math.floor((clusterCount - 1) / 1000)}K+`@@ -629,7 +1047,7 @@ function createClusterIcon(width: ${pinSize}px;height: ${pinHeight}px;position: relative;- cursor: pointer;+ cursor: ${interactive ? "pointer" : "default"};transition: all 0.3s ease;overflow: visible;filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3)) drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));@@ -645,8 +1063,7 @@ function createClusterIcon(overflow: hidden;transition: background-color 0.3s ease, border-color 0.3s ease;"- onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.parentElement.querySelector('.triangle').style.borderTopColor='#22c55e';"- onmouseout="this.style.background='white'; this.style.borderColor='#ffffff'; this.parentElement.querySelector('.triangle').style.borderTopColor='white';"+ ${hoverHandlers}>${hasImage@@ -695,77 +1112,10 @@ function createClusterIcon(});}-/**- * Creates custom icons for map marker clusters with thumbnails- * Responsibility: Generate cluster icons showing photo thumbnail and count- */-function useClusterIcon(- mapPhotos: JourneyPoint[],- thumbByFileID: Map<number, string>,-) {- const photosByPosition = useMemo(() => {- const map = new Map<string, JourneyPoint>();- mapPhotos.forEach((photo) => {- map.set(`${photo.lat},${photo.lng}`, photo);- });- return map;- }, [mapPhotos]);-- return useCallback(- // eslint-disable-next-line @typescript-eslint/no-explicit-any- (cluster: any) => {- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call- const count: number = cluster.getChildCount();- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call- const childMarkers = cluster.getAllChildMarkers();-- let thumbnailUrl = "";- for (const marker of childMarkers) {- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call- const latlng = marker.getLatLng();- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const key = `${latlng.lat},${latlng.lng}`;- const photo = photosByPosition.get(key);- if (photo) {- const thumb = getPhotoThumbnail(photo, thumbByFileID);- if (thumb) {- thumbnailUrl = thumb;- break;- }- }- }-- return createClusterIcon(thumbnailUrl, 68, count);- },- [photosByPosition, thumbByFileID],- );-}-// ============================================================================// Helper Functions// ============================================================================-/**- * Extracts thumbnail URL - prioritizes photo.image (loaded first with mapPhotos),- * then falls back to thumbByFileID (loaded afterward with higher quality thumbs)- */-function getPhotoThumbnail(- photo: JourneyPoint,- thumbByFileID: Map<number, string>,-): string | undefined {- return photo.image || thumbByFileID.get(photo.fileId);-}--/**- * Sorts journey points by timestamp in descending order (newest first)- */-function sortPhotosByTimestamp(photos: JourneyPoint[]): JourneyPoint[] {- return [...photos].sort(- (a, b) =>- new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),- );-}-/*** Returns true if the file is visible (not archived or hidden).*/@@ -830,28 +1180,6 @@ async function getFilesForCollection(return uniqueFilesByID(filtered);}-function extractLocationPoints(files: EnteFile[]): JourneyPoint[] {- const points: JourneyPoint[] = [];-- for (const file of files) {- const loc = fileLocation(file);- if (!loc) continue;- if (loc.latitude === 0 && loc.longitude === 0) continue; // Ignore invalid default coordinates-- points.push({- lat: loc.latitude,- lng: loc.longitude,- name: fileFileName(file),- country: "",- timestamp: new Date(fileCreationTime(file) / 1000).toISOString(),- image: "",- fileId: file.id,- });- }-- return points;-}-// ============================================================================// Main Component// ============================================================================@@ -884,16 +1212,24 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({const {mapCenter,- mapPhotos,+ mapIndex,+ mapPoints,+ latestFileId,filesByID,thumbByFileID,isLoading,error,removeFiles: removeFilesFromMap,updateFileVisibility,+ queueThumbnailFetch,} = useMapData(open, collectionSummary, activeCollection, onGenericError);- const { visiblePhotos, setVisiblePhotos } = useVisiblePhotos();+ const {+ visiblePhotos,+ setVisiblePhotos,+ isVisiblePhotosUpdating,+ setIsVisiblePhotosUpdating,+ } = useVisiblePhotos();const {favoriteFileIDs,@@ -903,7 +1239,11 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({handleFileVisibilityUpdate,} = useFavorites(open, user);- const createClusterCustomIcon = useClusterIcon(mapPhotos, thumbByFileID);+ useEffect(() => {+ if (!open) {+ setIsVisiblePhotosUpdating(false);+ }+ }, [open, setIsVisiblePhotosUpdating]);const handleSetFileViewerOpen: Dispatch<SetStateAction<boolean>> =useCallback(@@ -1003,7 +1343,7 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({);}- if (!mapPhotos.length || !mapCenter) {+ if (!mapPoints.length || !mapCenter || !mapIndex) {return (<CenteredBox onClose={onClose} closeLabel={t("close")}><Typography variant="body" color="text.secondary">@@ -1018,14 +1358,17 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({collectionSummary={collectionSummary}visiblePhotos={visiblePhotos}visibleFiles={visibleFiles}- mapPhotos={mapPhotos}+ mapIndex={mapIndex}+ latestFileId={latestFileId}thumbByFileID={thumbByFileID}mapComponents={mapComponents}mapCenter={mapCenter}optimalZoom={optimalZoom}- createClusterCustomIcon={createClusterCustomIcon}onClose={onClose}onVisiblePhotosChange={setVisiblePhotos}+ onVisiblePhotosLoadingChange={setIsVisiblePhotosUpdating}+ visiblePhotosUpdating={isVisiblePhotosUpdating}+ onPrefetchThumbnails={queueThumbnailFetch}user={user}favoriteFileIDs={favoriteFileIDs}pendingFavoriteUpdates={pendingFavoriteUpdates}@@ -1051,7 +1394,6 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({);}, [collectionSummary,- createClusterCustomIcon,emptySelected,error,favoriteFileIDs,@@ -1062,7 +1404,9 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({isLoading,mapCenter,mapComponents,- mapPhotos,+ mapIndex,+ mapPoints,+ latestFileId,noOpSetSelected,optimalZoom,onAddFileToCollection,@@ -1070,6 +1414,7 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({onRemoteFilesPull,pendingFavoriteUpdates,pendingVisibilityUpdates,+ setIsVisiblePhotosUpdating,setVisiblePhotos,collectionNameByID,fileNormalCollectionIDs,@@ -1077,9 +1422,11 @@ export const CollectionMapDialog: React.FC<CollectionMapDialogProps> = ({onSelectCollection,onSelectPerson,thumbByFileID,+ queueThumbnailFetch,user,visibleFiles,visiblePhotos,+ isVisiblePhotosUpdating,onClose,handleSetFileViewerOpen,]);@@ -1129,14 +1476,17 @@ interface MapLayoutProps {collectionSummary: CollectionSummary;visiblePhotos: JourneyPoint[];visibleFiles: EnteFile[];- mapPhotos: JourneyPoint[];+ visiblePhotosUpdating: boolean;+ mapIndex: MapIndex | null;+ latestFileId: number | undefined;thumbByFileID: Map<number, string>;mapComponents: MapComponents;mapCenter: [number, number];optimalZoom: number;- createClusterCustomIcon: (cluster: unknown) => unknown;onClose: () => void;onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;user: ReturnType<typeof useCurrentUser>;favoriteFileIDs: Set<number>;pendingFavoriteUpdates: Set<number>;@@ -1165,14 +1515,17 @@ function MapLayout({collectionSummary,visiblePhotos,visibleFiles,- mapPhotos,+ visiblePhotosUpdating,+ mapIndex,+ latestFileId,thumbByFileID,mapComponents,mapCenter,optimalZoom,- createClusterCustomIcon,onClose,onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,user,favoriteFileIDs,pendingFavoriteUpdates,@@ -1199,7 +1552,8 @@ function MapLayout({collectionSummary={collectionSummary}visibleCount={visiblePhotos.length}visibleFiles={visibleFiles}- mapPhotos={mapPhotos}+ isVisiblePhotosUpdating={visiblePhotosUpdating}+ latestFileId={latestFileId}thumbByFileID={thumbByFileID}onClose={onClose}user={user}@@ -1226,11 +1580,12 @@ function MapLayout({<MapCanvasmapComponents={mapComponents}mapCenter={mapCenter}- mapPhotos={mapPhotos}+ mapIndex={mapIndex}optimalZoom={optimalZoom}thumbByFileID={thumbByFileID}- createClusterCustomIcon={createClusterCustomIcon}onVisiblePhotosChange={onVisiblePhotosChange}+ onVisiblePhotosLoadingChange={onVisiblePhotosLoadingChange}+ onPrefetchThumbnails={onPrefetchThumbnails}/></Box></Box>@@ -1249,7 +1604,8 @@ interface CollectionSidebarProps {collectionSummary: CollectionSummary;visibleCount: number;visibleFiles: EnteFile[];- mapPhotos: JourneyPoint[];+ isVisiblePhotosUpdating: boolean;+ latestFileId: number | undefined;thumbByFileID: Map<number, string>;onClose: () => void;user: ReturnType<typeof useCurrentUser>;@@ -1286,7 +1642,8 @@ const COVER_HEADER_HEIGHT = COVER_IMAGE_HEIGHT + 34;function CollectionSidebar({collectionSummary,visibleFiles,- mapPhotos,+ isVisiblePhotosUpdating,+ latestFileId,thumbByFileID,onClose,user,@@ -1324,11 +1681,9 @@ function CollectionSidebar({const coverThumb = coverFile && thumbByFileID.get(coverFile.id);if (coverThumb) return coverThumb;- const fallbackPhoto = mapPhotos[0];- return fallbackPhoto- ? getPhotoThumbnail(fallbackPhoto, thumbByFileID)- : undefined;- }, [coverFile, mapPhotos, thumbByFileID]);+ const fallbackId = latestFileId;+ return fallbackId ? thumbByFileID.get(fallbackId) : undefined;+ }, [coverFile, latestFileId, thumbByFileID]);// Create header component for FileListWithViewer (cover scrolls with content)const coverHeader = useMemo(() => {@@ -1420,6 +1775,14 @@ function CollectionSidebar({</Box></StickyDateHeader><FileListContainer>+ {isVisiblePhotosUpdating ? (+ <SidebarLoadingOverlay>+ <ActivityIndicator size="24px" />+ <Typography variant="small">+ {t("loading")}+ </Typography>+ </SidebarLoadingOverlay>+ ) : null}{visibleFiles.length > 0 ? (<FileListWithViewerfiles={visibleFiles}@@ -1450,7 +1813,7 @@ function CollectionSidebar({onScroll={handleScroll}onVisibleDateChange={handleVisibleDateChange}/>- ) : (+ ) : isVisiblePhotosUpdating ? null : (<EmptyState>{shouldShowCover && (<MapCover@@ -1494,35 +1857,25 @@ function CollectionSidebar({interface MapCanvasProps {mapComponents: MapComponents;mapCenter: [number, number];- mapPhotos: JourneyPoint[];+ mapIndex: MapIndex | null;optimalZoom: number;thumbByFileID: Map<number, string>;- createClusterCustomIcon: (cluster: unknown) => unknown;onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;}const MapCanvas = React.memo(function MapCanvas({mapComponents,mapCenter,- mapPhotos,+ mapIndex,optimalZoom,thumbByFileID,- createClusterCustomIcon,onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,}: MapCanvasProps) {- const { MapContainer, TileLayer, Marker, useMap, MarkerClusterGroup } =- mapComponents;-- // Memoize marker icons to prevent recreation on every render- // Key: fileId, Value: Leaflet icon instance- const markerIcons = useMemo(() => {- const icons = new Map<number, ReturnType<typeof createMarkerIcon>>();- for (const photo of mapPhotos) {- const thumbnail = getPhotoThumbnail(photo, thumbByFileID);- icons.set(photo.fileId, createMarkerIcon(thumbnail ?? "", 68));- }- return icons;- }, [mapPhotos, thumbByFileID]);+ const { MapContainer, TileLayer, Marker, useMap } = mapComponents;return (<MapContainer@@ -1535,35 +1888,21 @@ const MapCanvas = React.memo(function MapCanvas({<TileLayerattribution=""url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"- maxZoom={19}+ maxZoom={MAX_MAP_ZOOM}updateWhenZooming/><MapControls useMap={useMap} />- <MapViewportListener- useMap={useMap}- photos={mapPhotos}- onVisiblePhotosChange={onVisiblePhotosChange}- />- <MarkerClusterGroup- key={thumbByFileID.size}- chunkedLoading- iconCreateFunction={createClusterCustomIcon}- maxClusterRadius={80}- spiderfyOnMaxZoom- showCoverageOnHover={false}- zoomToBoundsOnClick- animate={false}- animateAddingMarkers={false}- spiderfyDistanceMultiplier={1.5}- >- {mapPhotos.map((photo) => (- <Marker- key={photo.fileId}- position={[photo.lat, photo.lng]}- icon={markerIcons.get(photo.fileId) ?? undefined}- />- ))}- </MarkerClusterGroup>+ {mapIndex && (+ <MapClusters+ useMap={useMap}+ mapIndex={mapIndex}+ thumbByFileID={thumbByFileID}+ onVisiblePhotosChange={onVisiblePhotosChange}+ onVisiblePhotosLoadingChange={onVisiblePhotosLoadingChange}+ onPrefetchThumbnails={onPrefetchThumbnails}+ Marker={Marker}+ />+ )}</MapContainer>);});@@ -1747,77 +2086,289 @@ const AttributionPopup = styled(Box)(({ theme }) => ({"& a": { textDecoration: "underline", "&:hover": { opacity: 0.8 } },}));-/**- * Listens to map viewport changes and updates visible photos- * Responsibility: Track map bounds and notify parent of visible photos when viewport changes- */-interface MapViewportListenerProps {+interface MapClustersProps {useMap: typeof import("react-leaflet").useMap;- photos: JourneyPoint[];+ mapIndex: MapIndex;+ thumbByFileID: Map<number, string>;onVisiblePhotosChange: (photosInView: JourneyPoint[]) => void;+ onVisiblePhotosLoadingChange: (loading: boolean) => void;+ onPrefetchThumbnails: (fileIDs: number[]) => void;+ Marker: typeof import("react-leaflet").Marker;}-function MapViewportListener({+const MapClusters = React.memo(function MapClusters({useMap,- photos,+ mapIndex,+ thumbByFileID,onVisiblePhotosChange,-}: MapViewportListenerProps) {+ onVisiblePhotosLoadingChange,+ onPrefetchThumbnails,+ Marker,+}: MapClustersProps) {const map = useMap();+ const [features, setFeatures] = useState<MapFeature[]>([]);const previousVisibleIdsRef = useRef<Set<number>>(new Set());- const previousClusterCountRef = useRef<number>(0);+ const visibleRequestIdRef = useRef(0);+ const iconCacheRef = useRef(+ new Map<string, ReturnType<typeof createMarkerIcon>>(),+ );- // Cache cluster count query result to avoid repeated DOM queries- const getClusterCount = useCallback(- () => map.getContainer().querySelectorAll(".marker-cluster").length,- [map],+ const isClusterFeature = useCallback(+ (feature: MapFeature): feature is MapClusterFeature =>+ feature.properties.cluster === true,+ [],);- const updateVisiblePhotos = useCallback(() => {- const bounds = map.getBounds();- const inView = photos.filter((p) => bounds.contains([p.lat, p.lng]));+ const updateVisibleLeaves = useCallback(+ async (+ requestId: number,+ clusters: MapFeature[],+ bounds: { contains: (latlng: [number, number]) => boolean },+ ) => {+ if (requestId !== visibleRequestIdRef.current) return;+ onVisiblePhotosLoadingChange(true);++ const inBounds = (lat: number, lng: number) =>+ bounds.contains([lat, lng]);++ const leaves: MapPointFeature[] = [];+ let processedClusters = 0;++ for (const feature of clusters) {+ if (requestId !== visibleRequestIdRef.current) return;++ if (isClusterFeature(feature)) {+ const clusterProps = feature.properties;+ const totalLeaves = clusterProps.point_count;+ const batchSize = 1000;+ for (+ let offset = 0;+ offset < totalLeaves;+ offset += batchSize+ ) {+ if (requestId !== visibleRequestIdRef.current) return;+ const clusterLeaves = mapIndex.getLeaves(+ clusterProps.cluster_id,+ batchSize,+ offset,+ );+ clusterLeaves.forEach((leaf) => {+ const [lng, lat] = leaf.geometry.coordinates;+ if (inBounds(lat, lng)) {+ leaves.push(leaf);+ }+ });+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ processedClusters += 1;+ if (processedClusters % 5 === 0) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ } else {+ const [lng, lat] = feature.geometry.coordinates;+ if (inBounds(lat, lng)) {+ leaves.push(feature);+ }+ }+ }++ if (requestId !== visibleRequestIdRef.current) return;++ leaves.sort(+ (a, b) => b.properties.timestamp - a.properties.timestamp,+ );++ const visibleIds = new Set(+ leaves.map((leaf) => leaf.properties.fileId),+ );+ const previousIds = previousVisibleIdsRef.current;+ const idsChanged =+ visibleIds.size !== previousIds.size ||+ [...visibleIds].some((id) => !previousIds.has(id));++ if (idsChanged) {+ previousVisibleIdsRef.current = visibleIds;+ const nextVisiblePhotos = leaves.map((leaf) => {+ const [lng, lat] = leaf.geometry.coordinates;+ return {+ lat,+ lng,+ name: "",+ country: "",+ timestamp: new Date(+ leaf.properties.timestamp / 1000,+ ).toISOString(),+ image: "",+ fileId: leaf.properties.fileId,+ };+ });+ startTransition(() => {+ onVisiblePhotosChange(nextVisiblePhotos);+ });+ }- // Use Set comparison instead of string join for O(n) vs O(n log n + n)- const currentIds = new Set(inView.map((p) => p.fileId));- const previousIds = previousVisibleIdsRef.current;+ if (requestId === visibleRequestIdRef.current) {+ onVisiblePhotosLoadingChange(false);+ }+ },+ [+ isClusterFeature,+ mapIndex,+ onVisiblePhotosChange,+ onVisiblePhotosLoadingChange,+ ],+ );- const clusterCount = getClusterCount();- const clusterChanged = previousClusterCountRef.current !== clusterCount;+ const updateClusters = useCallback(() => {+ const bounds = map.getBounds();+ const zoom = Math.round(map.getZoom());+ const bbox: [number, number, number, number] = [+ bounds.getWest(),+ bounds.getSouth(),+ bounds.getEast(),+ bounds.getNorth(),+ ];++ const nextZoom = Math.min(zoom + 1, MAX_MAP_ZOOM);+ const clusters = mapIndex.getClusters(bbox, zoom);+ setFeatures(clusters);++ const requestId = ++visibleRequestIdRef.current;+ void updateVisibleLeaves(requestId, clusters, bounds);++ const prefetchBounds = bounds.pad(PREFETCH_BOUNDS_PADDING);+ const prefetchBbox: [number, number, number, number] = [+ prefetchBounds.getWest(),+ prefetchBounds.getSouth(),+ prefetchBounds.getEast(),+ prefetchBounds.getNorth(),+ ];++ const prefetchTargets = new Set<number>();+ const collectTargets = (items: MapFeature[]) => {+ items.forEach((feature) => {+ if (isClusterFeature(feature)) {+ prefetchTargets.add(feature.properties.latestFileId);+ } else {+ prefetchTargets.add(feature.properties.fileId);+ }+ });+ };- // Check if sets are equal (same size and all elements match)- const setsEqual =- currentIds.size === previousIds.size &&- [...currentIds].every((id) => previousIds.has(id));+ collectTargets(clusters);+ collectTargets(mapIndex.getClusters(prefetchBbox, nextZoom));- if (setsEqual && !clusterChanged) {- return;+ if (prefetchTargets.size > 0) {+ onPrefetchThumbnails(Array.from(prefetchTargets));}+ }, [+ isClusterFeature,+ map,+ mapIndex,+ onPrefetchThumbnails,+ updateVisibleLeaves,+ ]);- previousVisibleIdsRef.current = currentIds;- previousClusterCountRef.current = clusterCount;- onVisiblePhotosChange(inView);- }, [getClusterCount, map, onVisiblePhotosChange, photos]);+ useEffect(() => {+ iconCacheRef.current.clear();+ previousVisibleIdsRef.current = new Set();+ visibleRequestIdRef.current += 1;+ }, [mapIndex]);++ const handleClusterClick = useCallback(+ (lat: number, lng: number, expansionZoom: number) => {+ map.setView([lat, lng], expansionZoom, { animate: true });+ },+ [map],+ );useEffect(() => {- if (!photos.length) {- previousVisibleIdsRef.current = new Set();- previousClusterCountRef.current = getClusterCount();- onVisiblePhotosChange([]);- return;- }- updateVisiblePhotos();- }, [getClusterCount, photos, onVisiblePhotosChange, updateVisiblePhotos]);+ updateClusters();+ }, [updateClusters]);useEffect(() => {- map.on("moveend", updateVisiblePhotos);- map.on("zoomend", updateVisiblePhotos);+ map.on("moveend", updateClusters);+ map.on("zoomend", updateClusters);return () => {- map.off("moveend", updateVisiblePhotos);- map.off("zoomend", updateVisiblePhotos);+ map.off("moveend", updateClusters);+ map.off("zoomend", updateClusters);};- }, [map, updateVisiblePhotos]);+ }, [map, updateClusters]);- return null;-}+ const currentZoom = Math.round(map.getZoom());++ return (+ <>+ {features.map((feature) => {+ const [lng, lat] = feature.geometry.coordinates;+ const isCluster = isClusterFeature(feature);++ if (isCluster) {+ const clusterProps = feature.properties;+ const clusterId = clusterProps.cluster_id;+ const count = clusterProps.point_count;+ const expansionZoom = Math.min(+ mapIndex.getClusterExpansionZoom(clusterId),+ MAX_MAP_ZOOM,+ );+ const isInteractive = expansionZoom > currentZoom;+ const thumb =+ thumbByFileID.get(clusterProps.latestFileId) ?? "";+ const cacheKey = `cluster-${clusterId}-${count}-${thumb}-${isInteractive ? "i" : "n"}`;+ let icon = iconCacheRef.current.get(cacheKey);+ if (!icon) {+ icon = createClusterIcon(+ thumb,+ 68,+ count,+ isInteractive,+ );+ if (icon) {+ iconCacheRef.current.set(cacheKey, icon);+ }+ }+ return (+ <Marker+ key={`cluster-${clusterId}`}+ position={[lat, lng]}+ icon={icon ?? undefined}+ eventHandlers={+ isInteractive+ ? {+ click: () =>+ handleClusterClick(+ lat,+ lng,+ expansionZoom,+ ),+ }+ : undefined+ }+ />+ );+ }++ const fileId = feature.properties.fileId;+ const thumb = thumbByFileID.get(fileId) ?? "";+ const cacheKey = `point-${fileId}-${thumb}`;+ let icon = iconCacheRef.current.get(cacheKey);+ if (!icon) {+ icon = createMarkerIcon(thumb, 68);+ if (icon) {+ iconCacheRef.current.set(cacheKey, icon);+ }+ }+ return (+ <Marker+ key={`point-${fileId}`}+ position={[lat, lng]}+ icon={icon ?? undefined}+ />+ );+ })}+ </>+ );+});// ============================================================================// UI Components@@ -2061,6 +2612,7 @@ const SidebarGradient = styled(Box)(({ theme }) => ({const FileListContainer = styled(Box)(({ theme }) => ({flex: 1,minHeight: 0,+ position: "relative",display: "flex",flexDirection: "column",paddingLeft: "8px",@@ -2075,6 +2627,25 @@ const FileListContainer = styled(Box)(({ theme }) => ({},}));+const SidebarLoadingOverlay = styled(Box)(({ theme }) => ({+ position: "absolute",+ inset: 0,+ zIndex: 2,+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: theme.spacing(1),+ textAlign: "center",+ color: theme.vars.palette.text.primary,+ backgroundColor:+ theme.palette.mode === "dark"+ ? "rgba(0, 0, 0, 0.45)"+ : "rgba(255, 255, 255, 0.75)",+ backdropFilter: "blur(2px)",+ pointerEvents: "auto",+}));+const StickyDateHeader = styled(Box)<{visible: boolean;variant: "overlay" | "static";diff --git a/web/apps/photos/src/components/TripLayout/utils/dataProcessing.ts b/web/apps/photos/src/components/TripLayout/utils/dataProcessing.tsindex f8f02fb160..fe2e643e2a 100644--- a/web/apps/photos/src/components/TripLayout/utils/dataProcessing.ts+++ b/web/apps/photos/src/components/TripLayout/utils/dataProcessing.ts@@ -144,6 +144,17 @@ export const generateNeededThumbnails = async ({return { thumbnailUpdates };}+ const filesById = new Map(files.map((file) => [file.id, file]));+ const includedIds = new Set<number>();++ const addIfUnique = (group: EnteFile[], fileId: number) => {+ const file = filesById.get(fileId);+ if (!file) return;+ if (includedIds.has(file.id)) return;+ includedIds.add(file.id);+ group.push(file);+ };+// Define priority groups with specific file collectionsconst priorityGroups: EnteFile[][] = [];@@ -153,10 +164,7 @@ export const generateNeededThumbnails = async ({const firstLocationsFiles: EnteFile[] = [];photoClusters.slice(0, 3).forEach((cluster) => {cluster.slice(0, 3).forEach((photo) => {- const file = files.find((f) => f.id === photo.fileId);- if (file && !firstLocationsFiles.includes(file)) {- firstLocationsFiles.push(file);- }+ addIfUnique(firstLocationsFiles, photo.fileId);});});if (firstLocationsFiles.length > 0) {@@ -168,14 +176,7 @@ export const generateNeededThumbnails = async ({photoClusters.forEach((cluster) => {if (cluster.length > 0 && cluster[0]) {const firstPhoto = cluster[0];- const file = files.find((f) => f.id === firstPhoto.fileId);- if (- file &&- !firstLocationsFiles.includes(file) &&- !mapMarkerFiles.includes(file)- ) {- mapMarkerFiles.push(file);- }+ addIfUnique(mapMarkerFiles, firstPhoto.fileId);}});if (mapMarkerFiles.length > 0) {@@ -186,15 +187,7 @@ export const generateNeededThumbnails = async ({const remainingLocationFiles: EnteFile[] = [];photoClusters.slice(3).forEach((cluster) => {cluster.slice(0, 3).forEach((photo) => {- const file = files.find((f) => f.id === photo.fileId);- if (- file &&- !firstLocationsFiles.includes(file) &&- !mapMarkerFiles.includes(file) &&- !remainingLocationFiles.includes(file)- ) {- remainingLocationFiles.push(file);- }+ addIfUnique(remainingLocationFiles, photo.fileId);});});if (remainingLocationFiles.length > 0) {diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsxindex 018e98efbb..f2f9527d8b 100644--- a/web/apps/photos/src/pages/_app.tsx+++ b/web/apps/photos/src/pages/_app.tsx@@ -53,6 +53,87 @@ import "photoswipe/dist/photoswipe.css";import "styles/global.css";import "styles/photoswipe.css";+const installPerformanceMeasureGuard = () => {+ if (typeof window === "undefined") return;+ if (process.env.NODE_ENV !== "development") return;++ const perf = window.performance;+ if (typeof perf.measure !== "function") return;+ if ((perf as { __enteMeasureGuard?: boolean }).__enteMeasureGuard) return;++ const originalMeasure = perf.measure.bind(perf);+ const isDataCloneError = (error: unknown) => {+ if (error instanceof DOMException) {+ return error.name === "DataCloneError";+ }+ return (+ !!error &&+ typeof error === "object" &&+ "name" in error &&+ (error as { name?: string }).name === "DataCloneError"+ );+ };++ // Dev-only: avoid crashing when React's user timing clones huge props.+ const createFallbackMeasure = (name: string): PerformanceMeasure =>+ ({+ name,+ entryType: "measure",+ startTime: 0,+ duration: 0,+ toJSON: () => ({+ name,+ entryType: "measure",+ startTime: 0,+ duration: 0,+ }),+ }) as PerformanceMeasure;++ const guardedMeasure: Performance["measure"] = (+ name,+ startOrOptions,+ endMark,+ ) => {+ try {+ return originalMeasure(name, startOrOptions, endMark);+ } catch (error) {+ if (!isDataCloneError(error)) throw error;++ if (+ startOrOptions &&+ typeof startOrOptions === "object" &&+ !Array.isArray(startOrOptions)+ ) {+ const { start, end, duration } = startOrOptions;+ try {+ return originalMeasure(name, { start, end, duration });+ } catch {+ try {+ return originalMeasure(name);+ } catch {+ return createFallbackMeasure(name);+ }+ }+ }++ try {+ return originalMeasure(name);+ } catch {+ return createFallbackMeasure(name);+ }+ }+ };++ try {+ perf.measure = guardedMeasure;+ (perf as { __enteMeasureGuard?: boolean }).__enteMeasureGuard = true;+ } catch {+ // Ignore if the environment blocks overrides.+ }+};++installPerformanceMeasureGuard();+const App: React.FC<AppProps> = ({ Component, pageProps }) => {useSetupLogs();diff --git a/web/apps/photos/src/types/supercluster.d.ts b/web/apps/photos/src/types/supercluster.d.tsnew file mode 100644index 0000000000..7b0c5be69a--- /dev/null+++ b/web/apps/photos/src/types/supercluster.d.ts@@ -0,0 +1,89 @@+declare module "supercluster" {+ export type BBox = [number, number, number, number];++ export interface PointGeometry {+ type: "Point";+ coordinates: [number, number];+ }++ export interface PointFeature<+ TPointProperties = Record<string, unknown>,+ > {+ type: "Feature";+ properties: TPointProperties;+ geometry: PointGeometry;+ }++ export interface ClusterProperties {+ cluster: true;+ cluster_id: number;+ point_count: number;+ point_count_abbreviated?: number | string;+ }++ export interface ClusterFeature<+ TClusterProperties = Record<string, unknown>,+ > {+ type: "Feature";+ properties: TClusterProperties & ClusterProperties;+ geometry: PointGeometry;+ }++ export type ClusterOrPoint<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > = PointFeature<TPointProperties> | ClusterFeature<TClusterProperties>;++ export interface SuperclusterOptions<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > {+ radius?: number;+ maxZoom?: number;+ minZoom?: number;+ minPoints?: number;+ extent?: number;+ nodeSize?: number;+ log?: boolean;+ generateId?: boolean;+ map?: (props: TPointProperties) => TClusterProperties;+ reduce?: (+ accumulated: TClusterProperties,+ props: TClusterProperties,+ ) => void;+ }++ export default class Supercluster<+ TPointProperties = Record<string, unknown>,+ TClusterProperties = Record<string, unknown>,+ > {+ constructor(+ options?: SuperclusterOptions<TPointProperties, TClusterProperties>,+ );+ load(points: PointFeature<TPointProperties>[]): this;+ getClusters(+ bbox: BBox,+ zoom: number,+ ): ClusterOrPoint<TPointProperties, TClusterProperties>[];+ getChildren(+ clusterId: number,+ ): ClusterOrPoint<TPointProperties, TClusterProperties>[];+ getLeaves(+ clusterId: number,+ limit: number,+ offset: number,+ ): PointFeature<TPointProperties>[];+ getClusterExpansionZoom(clusterId: number): number;+ getTile?(+ z: number,+ x: number,+ y: number,+ ): {+ features: Array<{+ type: "Feature";+ geometry: { type: "Point"; coordinates: [number, number] };+ properties: Record<string, unknown>;+ }>;+ } | null;+ }+}diff --git a/web/yarn.lock b/web/yarn.lockindex c33ce0ddd0..7c9df49f72 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -3148,6 +3148,11 @@ jszip@^3.10.1:readable-stream "~2.3.6"setimmediate "^1.0.5"+kdbush@^4.0.2:+ version "4.0.2"+ resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.0.2.tgz#2f7b7246328b4657dd122b6c7f025fbc2c868e39"+ integrity sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA==+keyv@^4.5.4:version "4.5.4"resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93"@@ -3160,11 +3165,6 @@ leaflet-defaulticon-compatibility@^0.1.2:resolved "https://registry.yarnpkg.com/leaflet-defaulticon-compatibility/-/leaflet-defaulticon-compatibility-0.1.2.tgz#f5e1a5841aeab9d1682d17887348855a741b3c2a"integrity sha512-IrKagWxkTwzxUkFIumy/Zmo3ksjuAu3zEadtOuJcKzuXaD76Gwvg2Z1mLyx7y52ykOzM8rAH5ChBs4DnfdGa6Q==-leaflet.markercluster@^1.5.3:- version "1.5.3"- resolved "https://registry.yarnpkg.com/leaflet.markercluster/-/leaflet.markercluster-1.5.3.tgz#9cdb52a4eab92671832e1ef9899669e80efc4056"- integrity sha512-vPTw/Bndq7eQHjLBVlWpnGeLa3t+3zGiuM7fJwCkiMFq+nmRuG3RI3f7f4N4TDX7T4NpbAXpR2+NTRSEGfCSeA==-leaflet@^1.9.4:version "1.9.4"resolved "https://registry.yarnpkg.com/leaflet/-/leaflet-1.9.4.tgz#23fae724e282fa25745aff82ca4d394748db7d8d"@@ -3749,13 +3749,6 @@ react-is@^19.1.1:resolved "https://registry.yarnpkg.com/react-is/-/react-is-19.2.0.tgz#ddc3b4a4e0f3336c3847f18b806506388d7b9973"integrity sha512-x3Ax3kNSMIIkyVYhWPyO09bu0uttcAIoecO/um/rKGQ4EltYWVYtyiGkS/3xMynrbVQdS69Jhlv8FXUEZehlzA==-react-leaflet-cluster@^4.0.0:- version "4.0.0"- resolved "https://registry.yarnpkg.com/react-leaflet-cluster/-/react-leaflet-cluster-4.0.0.tgz#8a1025fbf4c7f3d39458c4b14f85b992aa4f9a59"- integrity sha512-Lu75+KOu2ruGyAx8LoCQvlHuw+3CLLJQGEoSk01ymsDN/YnCiRV6ChkpsvaruVyYBPzUHwiskFw4Jo7WHj5qNw==- dependencies:- leaflet.markercluster "^1.5.3"-react-leaflet@^5.0.0:version "5.0.0"resolved "https://registry.yarnpkg.com/react-leaflet/-/react-leaflet-5.0.0.tgz#945d40bad13b69e8606278b19446b00bab57376a"@@ -4306,6 +4299,13 @@ [email protected]:resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.2.0.tgz#79daee0208964c8fe695a42fcffcac633a211a51"integrity sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==+supercluster@^8.0.1:+ version "8.0.1"+ resolved "https://registry.yarnpkg.com/supercluster/-/supercluster-8.0.1.tgz#9946ba123538e9e9ab15de472531f604e7372df5"+ integrity sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ==+ dependencies:+ kdbush "^4.0.2"+version "8.1.1"resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c"