Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

fix: resolve leaflet SSR build errors in TripTemplate

anandbaburajan4dfec500a305
diff --git a/web/apps/photos/src/components/TripTemplate/MapEvents.tsx b/web/apps/photos/src/components/TripTemplate/MapEvents.tsx
index 17665b0293..c85b8f5fad 100644
--- a/web/apps/photos/src/components/TripTemplate/MapEvents.tsx
+++ b/web/apps/photos/src/components/TripTemplate/MapEvents.tsx
@@ -1,9 +1,8 @@
-import L from "leaflet";
import { memo, useEffect } from "react";
import { useMap } from "react-leaflet";
interface MapEventsProps {
- setMapRef: (map: L.Map) => void;
+ setMapRef: (map: import("leaflet").Map) => void;
setCurrentZoom: (zoom: number) => void;
setTargetZoom: (zoom: number | null) => void;
}
diff --git a/web/apps/photos/src/components/TripTemplate/TripMap.tsx b/web/apps/photos/src/components/TripTemplate/TripMap.tsx
index 0895fe0f85..c2ac5652d9 100644
--- a/web/apps/photos/src/components/TripTemplate/TripMap.tsx
+++ b/web/apps/photos/src/components/TripTemplate/TripMap.tsx
@@ -1,7 +1,7 @@
import { Box, styled } from "@mui/material";
import { useIsTouchscreen } from "ente-base/components/utils/hooks";
-import L from "leaflet";
import dynamic from "next/dynamic";
+
import { MapEvents } from "./MapEvents";
import {
createIcon,
@@ -32,9 +32,9 @@ interface TripMapProps {
optimalZoom: number;
currentZoom: number;
targetZoom: number | null;
- mapRef: L.Map | null;
+ mapRef: import("leaflet").Map | null;
scrollProgress: number;
- setMapRef: (map: L.Map | null) => void;
+ setMapRef: (map: import("leaflet").Map | null) => void;
setCurrentZoom: (zoom: number) => void;
setTargetZoom: (zoom: number | null) => void;
onMarkerClick: (
@@ -120,16 +120,18 @@ export const TripMap: React.FC<TripMapProps> = ({
clusterIndex <= currentLocationIndex,
);
- return (
+ const icon = createSuperClusterIcon(
+ superCluster.image, // Use representative photo (first photo of first cluster)
+ superCluster.clusterCount,
+ isTouchDevice ? 40 : 55,
+ isCovered,
+ );
+
+ return icon ? (
<Marker
key={`super-cluster-${index}`}
position={[superCluster.lat, superCluster.lng]}
- icon={createSuperClusterIcon(
- superCluster.image, // Use representative photo (first photo of first cluster)
- superCluster.clusterCount,
- isTouchDevice ? 40 : 55,
- isCovered,
- )}
+ icon={icon}
eventHandlers={{
click: () => {
const firstClusterIndex =
@@ -144,7 +146,7 @@ export const TripMap: React.FC<TripMapProps> = ({
},
}}
/>
- );
+ ) : null;
})}
{/* Draw visible regular clusters */}
@@ -181,17 +183,19 @@ export const TripMap: React.FC<TripMapProps> = ({
const isCovered =
originalClusterIndex <= currentLocationIndex;
- return (
+ const icon = createIcon(
+ firstPhoto.image,
+ isTouchDevice ? 40 : 55,
+ "#ffffff",
+ cluster.length,
+ isCovered,
+ );
+
+ return icon ? (
<Marker
key={`cluster-${index}`}
position={[avgLat, avgLng]}
- icon={createIcon(
- firstPhoto.image,
- isTouchDevice ? 40 : 55,
- "#ffffff",
- cluster.length,
- isCovered,
- )}
+ icon={icon}
eventHandlers={{
click: () => {
// Calculate cluster center
@@ -213,7 +217,7 @@ export const TripMap: React.FC<TripMapProps> = ({
},
}}
/>
- );
+ ) : null;
})}
</StyledMapContainer>
) : null}
diff --git a/web/apps/photos/src/components/TripTemplate/index.tsx b/web/apps/photos/src/components/TripTemplate/index.tsx
index 3b09945510..70be24dc52 100644
--- a/web/apps/photos/src/components/TripTemplate/index.tsx
+++ b/web/apps/photos/src/components/TripTemplate/index.tsx
@@ -6,8 +6,8 @@ import { FileViewer } from "ente-gallery/components/viewer/FileViewer";
import { downloadAndSaveCollectionFiles } from "ente-gallery/services/save";
import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
-import L from "leaflet";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
+
// Import extracted components
import { MobileCover } from "./MobileCover";
@@ -19,7 +19,6 @@ import { TimelineLocation } from "./TimelineLocation";
import { TimelineProgressLine } from "./TimelineProgressLine";
import { TopNavButtons } from "./TopNavButtons";
import { TripCover } from "./TripCover";
-import { TripMap } from "./TripMap";
// Import hooks
import { useDataProcessing } from "./hooks/useDataProcessing";
@@ -29,7 +28,6 @@ import { useScrollHandling } from "./hooks/useScrollHandling";
import { useThumbnailGeneration } from "./hooks/useThumbnailGeneration";
// Import types and utils
-import { calculateOptimalZoom, clusterPhotosByProximity } from "./mapHelpers";
import type { JourneyPoint } from "./types";
import type { PositionInfo } from "./utils/scrollUtils";
@@ -92,7 +90,7 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
const [isLoadingLocations, setIsLoadingLocations] = useState(false);
const [isInitialLoad, setIsInitialLoad] = useState(true);
const [currentZoom, setCurrentZoom] = useState(7); // Default zoom, will be updated by MapEvents and optimalZoom
- const [mapRef, setMapRef] = useState<L.Map | null>(null);
+ const [mapRef, setMapRef] = useState<import("leaflet").Map | null>(null);
const [targetZoom, setTargetZoom] = useState<number | null>(null);
const [scrollProgress, setScrollProgress] = useState(0); // 0 to 1 representing scroll progress
const [hasUserScrolled, setHasUserScrolled] = useState(false); // Track if user has actually scrolled
@@ -112,25 +110,53 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
const filesCountRef = useRef<number>(0); // Track files count to detect real changes
const previousActiveLocationRef = useRef<number>(-1); // Track previous active location for discrete panning
- const photoClusters = useMemo(() => {
- const clusters = clusterPhotosByProximity(journeyData);
-
- // Sort clusters by their earliest timestamp to maintain chronological order
- return clusters.sort((a, b) => {
- const earliestA = Math.min(
- ...a.map((p) => new Date(p.timestamp).getTime()),
- );
- const earliestB = Math.min(
- ...b.map((p) => new Date(p.timestamp).getTime()),
- );
- return earliestA - earliestB;
- });
- }, [journeyData]);
-
- // Calculate optimal zoom level based on cluster spread
- const optimalZoom = useMemo(() => {
- return calculateOptimalZoom();
- }, []);
+ const [photoClusters, setPhotoClusters] = useState<JourneyPoint[][]>([]);
+ const [optimalZoom, setOptimalZoom] = useState(7);
+ const [TripMapComponent, setTripMapComponent] = useState<React.ComponentType<{
+ journeyData: JourneyPoint[];
+ photoClusters: JourneyPoint[][];
+ hasPhotoData: boolean;
+ optimalZoom: number;
+ currentZoom: number;
+ targetZoom: number | null;
+ mapRef: import("leaflet").Map | null;
+ scrollProgress: number;
+ setMapRef: (map: import("leaflet").Map | null) => void;
+ setCurrentZoom: (zoom: number) => void;
+ setTargetZoom: (zoom: number | null) => void;
+ onMarkerClick: (clusterIndex: number, clusterLat: number, clusterLng: number) => void;
+ }> | null>(null);
+
+ // Load client-side components and calculations
+ useEffect(() => {
+ if (isClient) {
+ // Load TripMap component
+ void import("./TripMap").then(({ TripMap }) => {
+ setTripMapComponent(() => TripMap);
+ });
+
+ // Load mapHelpers and calculate clusters if we have data
+ if (journeyData.length > 0) {
+ void import("./mapHelpers").then(({ clusterPhotosByProximity, calculateOptimalZoom }) => {
+ const clusters = clusterPhotosByProximity(journeyData);
+
+ // Sort clusters by their earliest timestamp to maintain chronological order
+ const sortedClusters = clusters.sort((a, b) => {
+ const earliestA = Math.min(
+ ...a.map((p) => new Date(p.timestamp).getTime()),
+ );
+ const earliestB = Math.min(
+ ...b.map((p) => new Date(p.timestamp).getTime()),
+ );
+ return earliestA - earliestB;
+ });
+
+ setPhotoClusters(sortedClusters);
+ setOptimalZoom(calculateOptimalZoom());
+ });
+ }
+ }
+ }, [isClient, journeyData]);
// Update currentZoom when optimalZoom changes and there's no mapRef yet
useEffect(() => {
@@ -240,20 +266,22 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
<MobileContainer>
{/* Map takes 60% of height */}
<MobileMapContainer>
- <TripMap
- journeyData={journeyData}
- photoClusters={photoClusters}
- hasPhotoData={hasPhotoData}
- optimalZoom={optimalZoom}
- currentZoom={currentZoom}
- targetZoom={targetZoom}
- mapRef={mapRef}
- scrollProgress={scrollProgress}
- setMapRef={setMapRef}
- setCurrentZoom={setCurrentZoom}
- setTargetZoom={setTargetZoom}
- onMarkerClick={markerClickHandler}
- />
+ {TripMapComponent && (
+ <TripMapComponent
+ journeyData={journeyData}
+ photoClusters={photoClusters}
+ hasPhotoData={hasPhotoData}
+ optimalZoom={optimalZoom}
+ currentZoom={currentZoom}
+ targetZoom={targetZoom}
+ mapRef={mapRef}
+ scrollProgress={scrollProgress}
+ setMapRef={setMapRef}
+ setCurrentZoom={setCurrentZoom}
+ setTargetZoom={setTargetZoom}
+ onMarkerClick={markerClickHandler}
+ />
+ )}
{/* Cover overlay */}
{!isInitialLoad && journeyData.length > 0 && (
<MobileCoverOverlay show={showMobileCover}>
@@ -455,20 +483,22 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
</TimelineSidebar>
{/* Desktop Map Container */}
- <TripMap
- journeyData={journeyData}
- photoClusters={photoClusters}
- hasPhotoData={hasPhotoData}
- optimalZoom={optimalZoom}
- currentZoom={currentZoom}
- targetZoom={targetZoom}
- mapRef={mapRef}
- scrollProgress={scrollProgress}
- setMapRef={setMapRef}
- setCurrentZoom={setCurrentZoom}
- setTargetZoom={setTargetZoom}
- onMarkerClick={markerClickHandler}
- />
+ {TripMapComponent && (
+ <TripMapComponent
+ journeyData={journeyData}
+ photoClusters={photoClusters}
+ hasPhotoData={hasPhotoData}
+ optimalZoom={optimalZoom}
+ currentZoom={currentZoom}
+ targetZoom={targetZoom}
+ mapRef={mapRef}
+ scrollProgress={scrollProgress}
+ setMapRef={setMapRef}
+ setCurrentZoom={setCurrentZoom}
+ setTargetZoom={setTargetZoom}
+ onMarkerClick={markerClickHandler}
+ />
+ )}
</>
)}
diff --git a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
index ddc809f39b..27bb8fa38c 100644
--- a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
+++ b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
@@ -1,7 +1,16 @@
-import L from "leaflet";
+import { haveWindow } from "ente-base/env";
import type { JourneyPoint } from "./types";
import { iconCache } from "./utils/geocoding";
+// Conditionally import leaflet only in browser environment
+const getLeaflet = () => {
+ if (haveWindow()) {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ return require("leaflet") as typeof import("leaflet");
+ }
+ return null;
+};
+
// Calculate distance between two points using Haversine formula (returns distance in km)
export const calculateDistance = (
lat1: number,
@@ -87,10 +96,11 @@ export const createIcon = (
borderColor = "#ffffff",
_clusterCount?: number,
isReached = false,
-): L.DivIcon => {
- if (typeof window === "undefined") {
+): import("leaflet").DivIcon | null => {
+ const leaflet = getLeaflet();
+ if (typeof window === "undefined" || !leaflet) {
// Fallback icon for SSR
- return L.divIcon({ html: "", className: "empty-marker" });
+ return null;
}
// Create cache key based on all parameters
@@ -106,7 +116,7 @@ export const createIcon = (
const triangleHeight = 10;
const hasImage = imageSrc && imageSrc.trim() !== "";
- const icon = L.divIcon({
+ const icon = leaflet.divIcon({
html: `
<div class="photo-pin${isReached ? " reached" : ""}" style="
width: ${pinSize}px;
@@ -196,10 +206,11 @@ export const createSuperClusterIcon = (
clusterCount: number,
size = 45,
isReached = false,
-): L.DivIcon => {
- if (typeof window === "undefined") {
+): import("leaflet").DivIcon | null => {
+ const leaflet = getLeaflet();
+ if (typeof window === "undefined" || !leaflet) {
// Fallback icon for SSR
- return L.divIcon({ html: "", className: "empty-marker" });
+ return null;
}
// Create cache key based on all parameters
@@ -216,7 +227,7 @@ export const createSuperClusterIcon = (
const containerSize = pinSize + 24;
const hasImage = imageSrc && imageSrc.trim() !== "";
- const icon = L.divIcon({
+ const icon = leaflet.divIcon({
html: `
<div class="super-cluster-container" style="
width: ${containerSize}px;
@@ -333,7 +344,7 @@ export const detectScreenCollisions = (
clusters: JourneyPoint[][],
zoom: number,
targetZoom: number | null,
- mapRef: L.Map | null,
+ mapRef: import("leaflet").Map | null,
optimalZoom: number,
) => {
// Use target zoom if we're in the middle of a zoom animation, otherwise use optimal zoom
diff --git a/web/apps/photos/src/components/TripTemplate/utils/geocoding.ts b/web/apps/photos/src/components/TripTemplate/utils/geocoding.ts
index dc3444a1cf..896c04b444 100644
--- a/web/apps/photos/src/components/TripTemplate/utils/geocoding.ts
+++ b/web/apps/photos/src/components/TripTemplate/utils/geocoding.ts
@@ -1,4 +1,3 @@
-import L from "leaflet";
interface GeocodingResponse {
features?: {
@@ -20,7 +19,7 @@ export const geocodingCache = new Map<
>();
// Icon cache to avoid recreating identical icons
-export const iconCache = new Map<string, L.DivIcon>();
+export const iconCache = new Map<string, import("leaflet").DivIcon>();
// Throttle function for performance optimization
export const throttle = <T extends (...args: unknown[]) => void>(
diff --git a/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
index 25090af2ad..fd92fdb1d4 100644
--- a/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
+++ b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
@@ -1,4 +1,3 @@
-import L from "leaflet";
import { startTransition } from "react";
import { calculateDistance, getLocationPosition } from "../mapHelpers";
@@ -37,7 +36,7 @@ export interface HandleTimelineScrollParams {
timelineRef: React.RefObject<HTMLDivElement | null>;
photoClusters: JourneyPoint[][];
locationPositions: PositionInfo[];
- mapRef: L.Map | null;
+ mapRef: import("leaflet").Map | null;
isClusterClickScrollingRef: React.RefObject<boolean>;
setHasUserScrolled: (scrolled: boolean) => void;
setScrollProgress: (progress: number) => void;
@@ -237,7 +236,7 @@ export interface HandleMarkerClickParams {
clusterLat: number;
clusterLng: number;
photoClusters: JourneyPoint[][];
- mapRef: L.Map | null;
+ mapRef: import("leaflet").Map | null;
isClusterClickScrollingRef: React.RefObject<boolean>;
clusterClickTimeoutRef: React.RefObject<NodeJS.Timeout | null>;
setScrollProgress: (progress: number) => void;
diff --git a/web/apps/photos/src/pages/shared-albums.tsx b/web/apps/photos/src/pages/shared-albums.tsx
index 0874b6ae39..8a86941648 100644
--- a/web/apps/photos/src/pages/shared-albums.tsx
+++ b/web/apps/photos/src/pages/shared-albums.tsx
@@ -17,6 +17,7 @@ import Typography from "@mui/material/Typography";
import { DownloadStatusNotifications } from "components/DownloadStatusNotifications";
import { type FileListHeaderOrFooter } from "components/FileList";
import { FileListWithViewer } from "components/FileListWithViewer";
+import { TripTemplate } from "components/TripTemplate";
import { Upload } from "components/Upload";
import {
AccountsPageContents,
@@ -91,7 +92,6 @@ import {
import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
-import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { type FileWithPath } from "react-dropzone";
@@ -466,14 +466,6 @@ export default function PublicCollectionGallery() {
const isTripsTemplate =
publicCollection?.pubMagicMetadata?.data.template === "trip";
- const TripTemplate = dynamic(
- () =>
- import("components/TripTemplate").then((mod) => ({
- default: mod.TripTemplate,
- })),
- { ssr: false },
- );
-
return (
<FullScreenDropZone
disabled={shouldDisableDropzone}