Skip to content

armgit / ente

Public Imported from GitHub
0

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

refactor: split index.tsx into multiple files

anandbaburajan21043026a59f
diff --git a/web/apps/photos/src/components/TripTemplate/PhotoFan.tsx b/web/apps/photos/src/components/TripTemplate/PhotoFan.tsx
index 7432f7e772..ffbc932c0d 100644
--- a/web/apps/photos/src/components/TripTemplate/PhotoFan.tsx
+++ b/web/apps/photos/src/components/TripTemplate/PhotoFan.tsx
@@ -1,6 +1,6 @@
import { memo } from "react";
import Image from "next/image";
-import { JourneyPoint } from "./types";
+import type { JourneyPoint } from "./types";
interface PhotoFanProps {
cluster: JourneyPoint[];
diff --git a/web/apps/photos/src/components/TripTemplate/TimelineLocation.tsx b/web/apps/photos/src/components/TripTemplate/TimelineLocation.tsx
index ac398b5810..7a3568e258 100644
--- a/web/apps/photos/src/components/TripTemplate/TimelineLocation.tsx
+++ b/web/apps/photos/src/components/TripTemplate/TimelineLocation.tsx
@@ -1,5 +1,5 @@
import { memo } from "react";
-import { JourneyPoint } from "./types";
+import type { JourneyPoint } from "./types";
import { PhotoFan } from "./PhotoFan";
interface TimelineLocationProps {
diff --git a/web/apps/photos/src/components/TripTemplate/TimelineProgressLine.tsx b/web/apps/photos/src/components/TripTemplate/TimelineProgressLine.tsx
index 4da07364a5..331a3e0e19 100644
--- a/web/apps/photos/src/components/TripTemplate/TimelineProgressLine.tsx
+++ b/web/apps/photos/src/components/TripTemplate/TimelineProgressLine.tsx
@@ -1,5 +1,5 @@
import { memo } from "react";
-import { JourneyPoint } from "./types";
+import type { JourneyPoint } from "./types";
interface TimelineProgressLineProps {
locationPositions: { top: number; center: number }[];
diff --git a/web/apps/photos/src/components/TripTemplate/TopNavButtons.tsx b/web/apps/photos/src/components/TripTemplate/TopNavButtons.tsx
new file mode 100644
index 0000000000..e1a52c8cd9
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/TopNavButtons.tsx
@@ -0,0 +1,152 @@
+import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";
+import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
+import ShareIcon from "@mui/icons-material/Share";
+import { useIsTouchscreen } from "ente-base/components/utils/hooks";
+import { t } from "i18next";
+import { useState } from "react";
+
+interface TopNavButtonsProps {
+ onAddPhotos?: () => void;
+ downloadAllFiles: () => void;
+ enableDownload?: boolean;
+}
+
+export const TopNavButtons: React.FC<TopNavButtonsProps> = ({
+ onAddPhotos,
+ downloadAllFiles,
+ enableDownload,
+}) => {
+ const [showCopiedMessage, setShowCopiedMessage] = useState(false);
+ const isTouchscreen = useIsTouchscreen();
+
+ const handleShare = () => {
+ if (typeof window !== "undefined") {
+ void navigator.clipboard.writeText(window.location.href);
+ setShowCopiedMessage(true);
+ setTimeout(() => setShowCopiedMessage(false), 2000);
+ }
+ };
+
+ const handleSignUp = () => {
+ if (typeof window !== "undefined") {
+ window.open("https://ente.io", "_blank", "noopener,noreferrer");
+ }
+ };
+
+ const buttonStyle = {
+ padding: "12px",
+ backgroundColor: "rgba(255, 255, 255, 0.9)",
+ border: "none",
+ borderRadius: "8px",
+ cursor: "pointer",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ color: "#1f2937",
+ transition: "background-color 0.2s",
+ backdropFilter: "blur(10px)",
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
+ width: "44px",
+ height: "44px",
+ } as const;
+
+ const signUpButtonStyle = {
+ ...buttonStyle,
+ padding: "12px 16px",
+ marginLeft: "12px",
+ fontSize: "16px",
+ fontWeight: "600",
+ whiteSpace: "nowrap",
+ width: "auto",
+ } as const;
+
+ const handleButtonHover = (e: React.MouseEvent<HTMLButtonElement>) => {
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 1)";
+ };
+
+ const handleButtonLeave = (e: React.MouseEvent<HTMLButtonElement>) => {
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
+ };
+
+ return (
+ <>
+ {/* Top right buttons - Fixed to viewport */}
+ <div
+ style={{
+ position: "fixed",
+ top: "58px",
+ right: "58px",
+ display: "flex",
+ gap: "8px",
+ zIndex: 2000,
+ }}
+ >
+ <button
+ onClick={handleShare}
+ style={buttonStyle}
+ onMouseEnter={handleButtonHover}
+ onMouseLeave={handleButtonLeave}
+ >
+ <ShareIcon style={{ fontSize: "20px" }} />
+ </button>
+
+ {onAddPhotos && (
+ <button
+ onClick={onAddPhotos}
+ style={buttonStyle}
+ onMouseEnter={handleButtonHover}
+ onMouseLeave={handleButtonLeave}
+ >
+ <AddPhotoAlternateOutlinedIcon
+ style={{ fontSize: "22px" }}
+ />
+ </button>
+ )}
+
+ {!enableDownload && (
+ <button
+ onClick={downloadAllFiles}
+ style={buttonStyle}
+ onMouseEnter={handleButtonHover}
+ onMouseLeave={handleButtonLeave}
+ >
+ <FileDownloadOutlinedIcon
+ style={{ fontSize: "23px" }}
+ />
+ </button>
+ )}
+
+ <button
+ onClick={handleSignUp}
+ style={signUpButtonStyle}
+ onMouseEnter={handleButtonHover}
+ onMouseLeave={handleButtonLeave}
+ >
+ {isTouchscreen ? t("install") : t("sign_up")}
+ </button>
+ </div>
+
+ {/* Copied message */}
+ {showCopiedMessage && (
+ <div
+ style={{
+ position: "fixed",
+ top: "118px",
+ right: "180px",
+ backgroundColor: "#22c55e",
+ color: "white",
+ padding: "8px 16px",
+ borderRadius: "8px",
+ fontSize: "14px",
+ fontWeight: "500",
+ zIndex: 2001,
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.2)",
+ animation: "fadeInOut 2s ease-in-out forwards",
+ }}
+ >
+ Copied!
+ </div>
+ )}
+ </>
+ );
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/TripCover.tsx b/web/apps/photos/src/components/TripTemplate/TripCover.tsx
index 049a67f260..7c8c56023d 100644
--- a/web/apps/photos/src/components/TripTemplate/TripCover.tsx
+++ b/web/apps/photos/src/components/TripTemplate/TripCover.tsx
@@ -1,7 +1,7 @@
import { memo } from "react";
import Image from "next/image";
import { EnteLogo } from "ente-base/components/EnteLogo";
-import { JourneyPoint } from "./types";
+import type { JourneyPoint } from "./types";
interface TripCoverProps {
journeyData: JourneyPoint[];
diff --git a/web/apps/photos/src/components/TripTemplate/TripMap.tsx b/web/apps/photos/src/components/TripTemplate/TripMap.tsx
new file mode 100644
index 0000000000..a6d3636768
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/TripMap.tsx
@@ -0,0 +1,200 @@
+import L from "leaflet";
+import dynamic from "next/dynamic";
+import type { JourneyPoint } from "./types";
+import { MapEvents } from "./MapEvents";
+import {
+ createIcon,
+ createSuperClusterIcon,
+ detectScreenCollisions,
+ getMapCenter,
+} from "./mapHelpers";
+
+// Dynamically import react-leaflet components to prevent SSR issues
+const MapContainer = dynamic(
+ () => import("react-leaflet").then((mod) => mod.MapContainer),
+ { ssr: false },
+);
+const TileLayer = dynamic(
+ () => import("react-leaflet").then((mod) => mod.TileLayer),
+ { ssr: false },
+);
+const Marker = dynamic(
+ () => import("react-leaflet").then((mod) => mod.Marker),
+ { ssr: false },
+);
+
+interface TripMapProps {
+ journeyData: JourneyPoint[];
+ photoClusters: JourneyPoint[][];
+ hasPhotoData: boolean;
+ optimalZoom: number;
+ currentZoom: number;
+ targetZoom: number | null;
+ mapRef: L.Map | null;
+ scrollProgress: number;
+ screenDimensions: { width: number; height: number };
+ setMapRef: (map: L.Map | null) => void;
+ setCurrentZoom: (zoom: number) => void;
+ setTargetZoom: (zoom: number | null) => void;
+ onMarkerClick: (
+ clusterIndex: number,
+ clusterLat: number,
+ clusterLng: number,
+ ) => void;
+}
+
+export const TripMap: React.FC<TripMapProps> = ({
+ journeyData,
+ photoClusters,
+ hasPhotoData,
+ optimalZoom,
+ currentZoom,
+ targetZoom,
+ mapRef,
+ scrollProgress,
+ screenDimensions,
+ setMapRef,
+ setCurrentZoom,
+ setTargetZoom,
+ onMarkerClick,
+}) => {
+ // Calculate super-clusters based on screen collisions
+ const { superClusters, visibleClusters } = detectScreenCollisions(
+ photoClusters,
+ currentZoom,
+ targetZoom,
+ mapRef,
+ optimalZoom,
+ );
+
+ return (
+ <div
+ style={{
+ width: "100%",
+ height: "100%",
+ backgroundColor: hasPhotoData ? "transparent" : "#000000",
+ }}
+ >
+ {hasPhotoData ? (
+ <MapContainer
+ center={getMapCenter(
+ photoClusters,
+ journeyData,
+ screenDimensions,
+ )}
+ zoom={optimalZoom}
+ style={{ width: "100%", height: "100%" }}
+ scrollWheelZoom={true}
+ zoomControl={false}
+ >
+ <MapEvents
+ setMapRef={setMapRef}
+ setCurrentZoom={setCurrentZoom}
+ setTargetZoom={setTargetZoom}
+ />
+ {/* Stadia Alidade Satellite - includes both imagery and labels */}
+ <TileLayer
+ attribution='&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
+ url="https://tiles.stadiamaps.com/tiles/alidade_satellite/{z}/{x}/{y}{r}.jpg"
+ maxZoom={20}
+ />
+
+ {/* Draw super-clusters (clickable for zoom and gallery) */}
+ {superClusters.map((superCluster, index) => {
+ // Check if this super-cluster has been reached
+ const firstClusterIndex = superCluster.clustersInvolved[0];
+ const isReached =
+ firstClusterIndex !== undefined &&
+ scrollProgress >=
+ firstClusterIndex /
+ Math.max(1, photoClusters.length - 1);
+
+ return (
+ <Marker
+ key={`super-cluster-${index}`}
+ position={[superCluster.lat, superCluster.lng]}
+ icon={createSuperClusterIcon(
+ superCluster.image, // Use representative photo (first photo of first cluster)
+ superCluster.clusterCount,
+ 55,
+ isReached,
+ )}
+ eventHandlers={{
+ click: () => {
+ const firstClusterIndex =
+ superCluster.clustersInvolved[0];
+ if (firstClusterIndex !== undefined) {
+ onMarkerClick(
+ firstClusterIndex,
+ superCluster.lat,
+ superCluster.lng,
+ );
+ }
+ },
+ }}
+ />
+ );
+ })}
+
+ {/* Draw visible regular clusters */}
+ {visibleClusters.map((cluster, index) => {
+ const firstPhoto = cluster[0];
+ if (!firstPhoto) return null;
+ const avgLat =
+ cluster.reduce((sum, p) => sum + p.lat, 0) /
+ cluster.length;
+ const avgLng =
+ cluster.reduce((sum, p) => sum + p.lng, 0) /
+ cluster.length;
+
+ // Find the original cluster index
+ const originalClusterIndex = photoClusters.findIndex(
+ (originalCluster) =>
+ originalCluster.length === cluster.length &&
+ originalCluster[0]?.image === cluster[0]?.image,
+ );
+ // Check if this location has been reached based on progress
+ const isReached =
+ scrollProgress >=
+ originalClusterIndex /
+ Math.max(1, photoClusters.length - 1);
+
+ return (
+ <Marker
+ key={`cluster-${index}`}
+ position={[avgLat, avgLng]}
+ icon={createIcon(
+ firstPhoto.image,
+ 55,
+ "#ffffff",
+ cluster.length,
+ isReached,
+ )}
+ eventHandlers={{
+ click: () => {
+ // Calculate cluster center
+ const avgLat =
+ cluster.reduce(
+ (sum, p) => sum + p.lat,
+ 0,
+ ) / cluster.length;
+ const avgLng =
+ cluster.reduce(
+ (sum, p) => sum + p.lng,
+ 0,
+ ) / cluster.length;
+ onMarkerClick(
+ originalClusterIndex,
+ avgLat,
+ avgLng,
+ );
+ },
+ }}
+ />
+ );
+ })}
+ </MapContainer>
+ ) : null}
+ </div>
+ );
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/TripStartedSection.tsx b/web/apps/photos/src/components/TripTemplate/TripStartedSection.tsx
index 230b318e0c..a909ac2a1d 100644
--- a/web/apps/photos/src/components/TripTemplate/TripStartedSection.tsx
+++ b/web/apps/photos/src/components/TripTemplate/TripStartedSection.tsx
@@ -1,5 +1,5 @@
import { memo } from "react";
-import { JourneyPoint } from "./types";
+import type { JourneyPoint } from "./types";
interface TripStartedSectionProps {
journeyData: JourneyPoint[];
diff --git a/web/apps/photos/src/components/TripTemplate/index.tsx b/web/apps/photos/src/components/TripTemplate/index.tsx
index ac670d5445..61920a0532 100644
--- a/web/apps/photos/src/components/TripTemplate/index.tsx
+++ b/web/apps/photos/src/components/TripTemplate/index.tsx
@@ -1,8 +1,4 @@
-import AddPhotoAlternateOutlinedIcon from "@mui/icons-material/AddPhotoAlternateOutlined";
-import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
-import ShareIcon from "@mui/icons-material/Share";
import { DownloadStatusNotifications } from "components/DownloadStatusNotifications";
-import { useIsTouchscreen } from "ente-base/components/utils/hooks";
import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
import { FileViewer } from "ente-gallery/components/viewer/FileViewer";
import { downloadManager } from "ente-gallery/services/download";
@@ -10,9 +6,7 @@ import { downloadAndSaveCollectionFiles } from "ente-gallery/services/save";
import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
-import { t } from "i18next";
import L from "leaflet";
-import dynamic from "next/dynamic";
import {
startTransition,
useCallback,
@@ -23,30 +17,21 @@ import {
} from "react";
// Import extracted components
-import { MapEvents } from "./MapEvents";
import { TimelineBaseLine } from "./TimelineBaseLine";
import { TimelineLocation } from "./TimelineLocation";
import { TimelineProgressLine } from "./TimelineProgressLine";
+import { TopNavButtons } from "./TopNavButtons";
import { TripCover } from "./TripCover";
+import { TripMap } from "./TripMap";
import { TripStartedSection } from "./TripStartedSection";
+// Import hooks
+import { useFileViewer } from "./useFileViewer";
+
// Import types and utils
+import { calculateOptimalZoom, clusterPhotosByProximity } from "./mapHelpers";
import type { JourneyPoint } from "./types";
-import { getLocationName, iconCache, throttle } from "./utils";
-
-// Dynamically import react-leaflet components to prevent SSR issues
-const MapContainer = dynamic(
- () => import("react-leaflet").then((mod) => mod.MapContainer),
- { ssr: false },
-);
-const TileLayer = dynamic(
- () => import("react-leaflet").then((mod) => mod.TileLayer),
- { ssr: false },
-);
-const Marker = dynamic(
- () => import("react-leaflet").then((mod) => mod.Marker),
- { ssr: false },
-);
+import { getLocationName, throttle } from "./utils";
interface TripTemplateProps {
files: EnteFile[];
@@ -76,8 +61,15 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
// Save groups hook for download progress tracking
const { saveGroups, onAddSaveGroup, onRemoveSaveGroup } = useSaveGroups();
- // Check if device is touchscreen for signup button text
- const isTouchscreen = useIsTouchscreen();
+ // File viewer hook
+ const {
+ openFileViewer,
+ currentFileIndex,
+ viewerFiles,
+ handleOpenFileViewer,
+ handleCloseFileViewer,
+ handleTriggerRemotePull,
+ } = useFileViewer({ files, onSetOpenFileViewer, onRemotePull });
// Download all files functionality
const downloadAllFiles = () => {
@@ -151,12 +143,6 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
>(new Map()); // Track location data to prevent resets
const filesCountRef = useRef<number>(0); // Track files count to detect real changes
- // FileViewer state
- const [openFileViewer, setOpenFileViewer] = useState(false);
- const [currentFileIndex, setCurrentFileIndex] = useState(0);
- const [viewerFiles, setViewerFiles] = useState<EnteFile[]>([]); // Files to show in viewer
- const [showCopiedMessage, setShowCopiedMessage] = useState(false);
-
// Track screen dimensions for responsive zoom calculation
useEffect(() => {
const updateScreenDimensions = () => {
@@ -179,104 +165,11 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
};
}, []);
- // FileViewer handlers
- const handleOpenFileViewer = useCallback(
- (_cluster: JourneyPoint[], clickedFileId: number) => {
- // Sort all files by creation time
- const sortedFiles = [...files].sort(
- (a, b) =>
- new Date(a.metadata.creationTime / 1000).getTime() -
- new Date(b.metadata.creationTime / 1000).getTime(),
- );
-
- // Find the index of the clicked photo in all files
- const clickedIndex = sortedFiles.findIndex(
- (f) => f.id === clickedFileId,
- );
-
- if (clickedIndex !== -1 && sortedFiles.length > 0) {
- // Batch state updates to avoid multiple re-renders
- setViewerFiles(sortedFiles);
- setCurrentFileIndex(clickedIndex);
- setOpenFileViewer(true);
- onSetOpenFileViewer?.(true);
- }
- },
- [files, onSetOpenFileViewer],
- );
-
- const handleCloseFileViewer = useCallback(() => {
- // Batch state updates
- setOpenFileViewer(false);
- onSetOpenFileViewer?.(false);
- }, [onSetOpenFileViewer]);
-
- const handleTriggerRemotePull = useCallback(() => {
- return onRemotePull?.() || Promise.resolve();
- }, [onRemotePull]);
-
- // Geographic clustering with responsive distance thresholds and day separation
- const clusterPhotosByProximity = (photos: JourneyPoint[]) => {
- if (photos.length === 0) return [];
-
- // Mobile: no clustering for better timeline experience
- // Desktop: 1km clustering for cleaner map display
- const isMobile = screenDimensions.width < 768;
- if (isMobile) {
- // Return each photo as its own cluster on mobile
- return photos.map((photo) => [photo]);
- }
-
- // Desktop: 10km clustering distance (roughly 0.1 degrees)
- const distanceThreshold = 0.1; // About 10km in degrees
-
- // First, group photos by day
- const photosByDay = new Map<string, JourneyPoint[]>();
- photos.forEach((photo) => {
- const date = new Date(photo.timestamp);
- const dayKey = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
-
- if (!photosByDay.has(dayKey)) {
- photosByDay.set(dayKey, []);
- }
- photosByDay.get(dayKey)!.push(photo);
- });
-
- // Then cluster within each day
- const allClusters: JourneyPoint[][] = [];
-
- photosByDay.forEach((dayPhotos) => {
- const visited = new Set<number>();
-
- dayPhotos.forEach((photo, i) => {
- if (visited.has(i)) return;
-
- const cluster = [photo];
- visited.add(i);
-
- dayPhotos.forEach((otherPhoto, j) => {
- if (i === j || visited.has(j)) return;
-
- const distance = Math.sqrt(
- Math.pow(photo.lat - otherPhoto.lat, 2) +
- Math.pow(photo.lng - otherPhoto.lng, 2),
- );
-
- if (distance < distanceThreshold) {
- cluster.push(otherPhoto);
- visited.add(j);
- }
- });
-
- allClusters.push(cluster);
- });
- });
-
- return allClusters;
- };
-
const photoClusters = useMemo(() => {
- const clusters = clusterPhotosByProximity(journeyData);
+ const clusters = clusterPhotosByProximity(
+ journeyData,
+ screenDimensions,
+ );
// Sort clusters by their earliest timestamp to maintain chronological order
return clusters.sort((a, b) => {
@@ -288,107 +181,11 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
);
return earliestA - earliestB;
});
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [journeyData, screenDimensions]);
// Calculate optimal zoom level based on cluster spread
const optimalZoom = useMemo(() => {
- if (photoClusters.length === 0) return 7;
-
- // Calculate cluster centers
- const clusterCenters = photoClusters.map((cluster) => {
- const avgLat =
- cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
- const avgLng =
- cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
- return { lat: avgLat, lng: avgLng };
- });
-
- // Find the bounding box of all clusters (only need lng values for calculations)
- const allLats = clusterCenters.map((c) => c.lat);
- const allLngs = clusterCenters.map((c) => c.lng);
-
- // Calculate the span (not used directly but kept for potential future use)
- // const latSpan = maxLat - minLat;
- // const lngSpan = maxLng - minLng;
-
- // Calculate minimum distances between clusters to avoid over-clustering
- let minDistance = Infinity;
- for (let i = 0; i < clusterCenters.length - 1; i++) {
- for (let j = i + 1; j < clusterCenters.length; j++) {
- const centerI = clusterCenters[i];
- const centerJ = clusterCenters[j];
- if (!centerI || !centerJ) continue;
- const distance = Math.sqrt(
- Math.pow(centerI.lat - centerJ.lat, 2) +
- Math.pow(centerI.lng - centerJ.lng, 2),
- );
- minDistance = Math.min(minDistance, distance);
- }
- }
-
- // Calculate zoom based on cluster density and actual screen dimensions
- // Timeline takes more space on mobile (50%) vs desktop (50%)
- const isMobile = screenDimensions.width < 768;
- const timelineSizeRatio = isMobile ? 0.5 : 0.5;
- const visibleMapWidth =
- screenDimensions.width * (1 - timelineSizeRatio);
-
- // Calculate effective span considering cluster density
- // Sort clusters by longitude to find the core data area
- const sortedClusterLngs = allLngs.slice().sort((a, b) => a - b);
- const sortedClusterLats = allLats.slice().sort((a, b) => a - b);
-
- // Use 90th percentile span instead of full min/max to ignore outliers
- const p10Index = Math.floor(sortedClusterLngs.length * 0.1);
- const p90Index = Math.floor(sortedClusterLngs.length * 0.9);
- const p10Lng = sortedClusterLngs[p10Index];
- const p90Lng = sortedClusterLngs[p90Index];
- const p10Lat = sortedClusterLats[p10Index];
- const p90Lat = sortedClusterLats[p90Index];
- if (
- p10Lng === undefined ||
- p90Lng === undefined ||
- p10Lat === undefined ||
- p90Lat === undefined
- ) {
- return 7; // fallback zoom
- }
- const effectiveLngSpan = p90Lng - p10Lng;
- const effectiveLatSpan = p90Lat - p10Lat;
-
- // Add more padding (40%) to prevent cropping at edges
- const paddedLngSpan = effectiveLngSpan * 1.4;
- const paddedLatSpan = effectiveLatSpan * 1.4;
-
- // Calculate zoom to fit the padded effective span
- const zoomForLngSpan = Math.log2(
- (visibleMapWidth * 360) / (paddedLngSpan * 256),
- );
- const visibleMapHeight = screenDimensions.height; // Full height available for map
- const zoomForLatSpan = Math.log2(
- (visibleMapHeight * 360) / (paddedLatSpan * 256),
- );
-
- // Take the more restrictive zoom
- const zoomToFitBounds = Math.min(zoomForLngSpan, zoomForLatSpan);
-
- // Also ensure reasonable cluster separation
- const targetPixelSeparation = 100;
- const pixelsPerDegreeAtOptimalZoom =
- targetPixelSeparation / minDistance;
- const optimalZoomFromSeparation = Math.log2(
- (pixelsPerDegreeAtOptimalZoom * 360) / 256,
- );
-
- // Prioritize fitting bounds with some buffer for cluster separation
- const calculatedZoom = Math.min(
- zoomToFitBounds,
- optimalZoomFromSeparation,
- );
- const clampedZoom = Math.max(6, Math.min(14, calculatedZoom));
-
- return Math.round(clampedZoom);
+ return calculateOptimalZoom(photoClusters, screenDimensions);
}, [photoClusters, screenDimensions]);
// Update currentZoom when optimalZoom changes and there's no mapRef yet
@@ -657,329 +454,6 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
};
}, []);
- // Function to create icon with specific image and progress styling
- const createIcon = useCallback(
- (
- imageSrc: string,
- size = 40,
- borderColor = "#ffffff",
- _clusterCount?: number,
- isReached = false,
- ): L.DivIcon => {
- if (typeof window === "undefined") {
- // Fallback icon for SSR
- return L.divIcon({ html: "", className: "empty-marker" });
- }
-
- // Create cache key based on all parameters
- const cacheKey = `icon_${imageSrc}_${size}_${borderColor}_${isReached}`;
-
- const cachedIcon = iconCache.get(cacheKey);
- if (cachedIcon) {
- return cachedIcon;
- }
-
- const pinSize = size + 16; // Make it square and bigger
- const pinHeight = pinSize + 12; // Add space for triangle
- const triangleHeight = 10;
-
- // L is imported at the top of the file
- const icon = L.divIcon({
- html: `
- <div class="photo-pin${isReached ? " reached" : ""}" style="
- width: ${pinSize}px;
- height: ${pinHeight}px;
- position: relative;
- cursor: pointer;
- transition: all 0.3s ease;
- ">
- <!-- Main rounded rectangle container -->
- <div style="
- width: ${pinSize}px;
- height: ${pinSize}px;
- border-radius: 16px;
- background: ${isReached ? "#22c55e" : "white"};
- border: 2px solid ${isReached ? "#22c55e" : borderColor};
- box-shadow: 0 4px 8px rgba(0,0,0,0.3);
- padding: 4px;
- position: relative;
- overflow: hidden;
- transition: background-color 0.3s ease, border-color 0.3s ease;
- "
- onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"
- onmouseout="this.style.background='${isReached ? "#22c55e" : "white"}'; this.style.borderColor='${isReached ? "#22c55e" : "#ffffff"}'; this.nextElementSibling.style.borderTopColor='${isReached ? "#22c55e" : "white"}';"
- >
- <!-- Image inside the rounded rectangle -->
- <img
- src="${imageSrc}"
- style="
- width: 100%;
- height: 100%;
- object-fit: cover;
- border-radius: 12px;
- "
- alt="Location"
- />
- </div>
-
- <!-- Triangle at the bottom -->
- <div style="
- position: absolute;
- bottom: 2px;
- left: 50%;
- transform: translateX(-50%);
- width: 0;
- height: 0;
- border-left: ${triangleHeight}px solid transparent;
- border-right: ${triangleHeight}px solid transparent;
- border-top: ${triangleHeight}px solid ${isReached ? "#22c55e" : "white"};
- filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
- transition: border-top-color 0.3s ease;
- "></div>
- </div>
- `,
- className: "custom-pin-marker",
- iconSize: [pinSize, pinHeight],
- iconAnchor: [pinSize / 2, pinHeight],
- popupAnchor: [0, -pinHeight],
- });
-
- // Cache the icon
- iconCache.set(cacheKey, icon);
- return icon;
- },
- [],
- );
-
- // Function to create super-cluster icon with badge
- const createSuperClusterIcon = useCallback(
- (
- imageSrc: string,
- clusterCount: number,
- size = 45,
- isReached = false,
- ): L.DivIcon => {
- if (typeof window === "undefined") {
- // Fallback icon for SSR
- return L.divIcon({ html: "", className: "empty-marker" });
- }
-
- // Create cache key based on all parameters
- const cacheKey = `super_icon_${imageSrc}_${clusterCount}_${size}_${isReached}`;
-
- const cachedIcon = iconCache.get(cacheKey);
- if (cachedIcon) {
- return cachedIcon;
- }
-
- const pinSize = size + 16; // Make it square and bigger
- const pinHeight = pinSize + 12; // Add space for triangle
- const triangleHeight = 10;
- const containerSize = pinSize + 24;
-
- const icon = L.divIcon({
- html: `
- <div class="super-cluster-container" style="
- width: ${containerSize}px;
- height: ${pinHeight + 12}px;
- position: relative;
- cursor: pointer;
- ">
- <!-- Main pin container -->
- <div class="photo-pin${isReached ? " reached" : ""}" style="
- width: ${pinSize}px;
- height: ${pinHeight}px;
- position: absolute;
- left: 12px;
- top: 0;
- transition: all 0.3s ease;
- ">
- <!-- Main rounded rectangle container -->
- <div style="
- width: ${pinSize}px;
- height: ${pinSize}px;
- border-radius: 16px;
- background: ${isReached ? "#22c55e" : "white"};
- border: 2px solid ${isReached ? "#22c55e" : "#ffffff"};
- box-shadow: 0 4px 8px rgba(0,0,0,0.3);
- padding: 4px;
- position: relative;
- overflow: hidden;
- transition: background-color 0.3s ease, border-color 0.3s ease;
- "
- onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"
- onmouseout="this.style.background='${isReached ? "#22c55e" : "white"}'; this.style.borderColor='${isReached ? "#22c55e" : "#ffffff"}'; this.nextElementSibling.style.borderTopColor='${isReached ? "#22c55e" : "white"}';"
- >
- <!-- Image inside the rounded rectangle -->
- <img
- src="${imageSrc}"
- style="
- width: 100%;
- height: 100%;
- object-fit: cover;
- border-radius: 12px;
- "
- alt="Location"
- />
- </div>
-
- <!-- Triangle at the bottom -->
- <div style="
- position: absolute;
- bottom: 2px;
- left: 50%;
- transform: translateX(-50%);
- width: 0;
- height: 0;
- border-left: ${triangleHeight}px solid transparent;
- border-right: ${triangleHeight}px solid transparent;
- border-top: ${triangleHeight}px solid ${isReached ? "#22c55e" : "white"};
- filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
- transition: border-top-color 0.3s ease;
- "></div>
- </div>
-
- <!-- Badge -->
- <div style="
- position: absolute;
- top: -6px;
- right: 0;
- background: #000000;
- color: white;
- border-radius: 50%;
- width: 22px;
- height: 22px;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 11px;
- font-weight: 600;
- border: 2px solid white;
- box-shadow: 0 2px 6px rgba(0,0,0,0.3);
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
- z-index: 10;
- ">${clusterCount}</div>
- </div>
- `,
- className: "super-cluster-pin-marker",
- iconSize: [containerSize, pinHeight + 12],
- iconAnchor: [containerSize / 2, pinHeight + 12],
- popupAnchor: [0, -(pinHeight + 12)],
- });
-
- // Cache the icon
- iconCache.set(cacheKey, icon);
- return icon;
- },
- [],
- );
-
- // Calculate super-clusters based on screen collisions
- const { superClusters, visibleClusters } = useMemo(() => {
- const detectScreenCollisions = (
- clusters: JourneyPoint[][],
- zoom: number,
- ) => {
- // Use target zoom if we're in the middle of a zoom animation, otherwise use optimal zoom
- const effectiveZoom =
- targetZoom !== null ? targetZoom : mapRef ? zoom : optimalZoom;
-
- // Convert geographic distance to screen pixels
- // At zoom Z, roughly 2^Z * 256 pixels per 360 degrees
- const pixelsPerDegree = (Math.pow(2, effectiveZoom) * 256) / 360;
- // Use a more conservative collision threshold to show more individual clusters
- const collisionThreshold = 50 / pixelsPerDegree; // 50 pixel collision radius
-
- const superClusters: {
- lat: number;
- lng: number;
- clusterCount: number;
- clustersInvolved: number[];
- image: string;
- }[] = [];
- const hiddenClusterIndices = new Set<number>();
-
- // Check each cluster against others for screen-space collision
- clusters.forEach((cluster, i) => {
- if (hiddenClusterIndices.has(i)) return;
-
- const clusterLat =
- cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
- const clusterLng =
- cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
-
- const overlappingClusters = [i];
-
- clusters.forEach((otherCluster, j) => {
- if (i === j || hiddenClusterIndices.has(j)) return;
-
- const otherLat =
- otherCluster.reduce((sum, p) => sum + p.lat, 0) /
- otherCluster.length;
- const otherLng =
- otherCluster.reduce((sum, p) => sum + p.lng, 0) /
- otherCluster.length;
-
- const distance = Math.sqrt(
- Math.pow(clusterLat - otherLat, 2) +
- Math.pow(clusterLng - otherLng, 2),
- );
-
- if (distance < collisionThreshold) {
- overlappingClusters.push(j);
- hiddenClusterIndices.add(j);
- }
- });
-
- // If we found overlapping clusters, create a super-cluster
- if (overlappingClusters.length > 1) {
- hiddenClusterIndices.add(i); // Hide the original cluster too
-
- // Calculate center position of all overlapping clusters
- let totalLat = 0,
- totalLng = 0;
- overlappingClusters.forEach((idx) => {
- const c = clusters[idx];
- if (!c) return;
- totalLat +=
- c.reduce((sum, p) => sum + p.lat, 0) / c.length;
- totalLng +=
- c.reduce((sum, p) => sum + p.lng, 0) / c.length;
- });
-
- // Get the first photo from the first cluster as representative image
- const firstClusterIdx = overlappingClusters[0];
- const firstCluster =
- firstClusterIdx !== undefined
- ? clusters[firstClusterIdx]
- : undefined;
- const representativePhoto = firstCluster?.[0];
- if (!representativePhoto) {
- return;
- }
-
- superClusters.push({
- lat: totalLat / overlappingClusters.length,
- lng: totalLng / overlappingClusters.length,
- clusterCount: overlappingClusters.length,
- clustersInvolved: overlappingClusters,
- image: representativePhoto.image,
- });
- }
- });
-
- // Return visible clusters (those not hidden by super-clusters)
- const visibleClusters = clusters.filter(
- (_, idx) => !hiddenClusterIndices.has(idx),
- );
-
- return { superClusters, visibleClusters };
- };
-
- const result = detectScreenCollisions(photoClusters, currentZoom);
- return result;
- }, [photoClusters, currentZoom, mapRef, targetZoom, optimalZoom]);
-
// Update location positions when layout changes
const updateLocationPositions = useCallback(() => {
if (locationRefs.current.length === 0) return;
@@ -1284,54 +758,6 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
],
);
- // Calculate map center - start at first location to match timeline initial state
- const getMapCenter = (): [number, number] => {
- // If no clusters yet, check journey data
- if (photoClusters.length === 0) {
- const firstPoint = journeyData[0];
- if (!firstPoint) return [0, 0]; // Fallback, but map won't render anyway
- return [firstPoint.lat, firstPoint.lng];
- }
-
- // Start at first cluster center to match the timeline starting position
- const firstCluster = photoClusters[0];
- if (!firstCluster || firstCluster.length === 0) return [0, 0]; // Fallback, but map won't render anyway
-
- const firstLat =
- firstCluster.reduce((sum, p) => sum + p.lat, 0) /
- firstCluster.length;
- const firstLng =
- firstCluster.reduce((sum, p) => sum + p.lng, 0) /
- firstCluster.length;
-
- // Calculate shift for timeline positioning
- const clusterCenters = photoClusters.map((cluster) => {
- const avgLat =
- cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
- const avgLng =
- cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
- return { lat: avgLat, lng: avgLng };
- });
-
- const allLngs = clusterCenters.map((c) => c.lng);
- const minLng = Math.min(...allLngs);
- const maxLng = Math.max(...allLngs);
- const lngSpan = maxLng - minLng;
- const paddedSpan = Math.max(lngSpan * 1.4, 0.1); // Minimum span for single locations
-
- const isMobile = screenDimensions.width < 768;
- const timelineSizeRatio = isMobile ? 0.5 : 0.5;
- const mapSizeRatio = 1 - timelineSizeRatio;
-
- const screenWidthInDegrees = paddedSpan / mapSizeRatio;
- const shiftAmount = screenWidthInDegrees * (timelineSizeRatio / 2);
-
- // Shift the first location left so it appears centered in visible area
- const adjustedLng = firstLng - shiftAmount;
-
- return [firstLat, adjustedLng];
- };
-
// Only wait for client-side rendering (needed for maps), but show layout immediately
// Let individual components handle their own loading states
if (!isClient) {
@@ -1343,182 +769,11 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
return (
<div style={{ position: "relative", width: "100%", height: "100%" }}>
- {/* Top right buttons - Fixed to viewport */}
- <div
- style={{
- position: "fixed",
- top: "58px",
- right: "58px",
- display: "flex",
- gap: "8px",
- zIndex: 2000,
- }}
- >
- <button
- onClick={() => {
- if (typeof window !== "undefined") {
- void navigator.clipboard.writeText(
- window.location.href,
- );
- setShowCopiedMessage(true);
- setTimeout(() => setShowCopiedMessage(false), 2000);
- }
- }}
- style={{
- padding: "12px",
- backgroundColor: "rgba(255, 255, 255, 0.9)",
- border: "none",
- borderRadius: "8px",
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "#1f2937",
- transition: "background-color 0.2s",
- backdropFilter: "blur(10px)",
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
- width: "44px",
- height: "44px",
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 1)";
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 0.9)";
- }}
- >
- <ShareIcon style={{ fontSize: "20px" }} />
- </button>
- {onAddPhotos && (
- <button
- onClick={onAddPhotos}
- style={{
- padding: "12px",
- backgroundColor: "rgba(255, 255, 255, 0.9)",
- border: "none",
- borderRadius: "8px",
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "#1f2937",
- transition: "background-color 0.2s",
- backdropFilter: "blur(10px)",
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
- width: "44px",
- height: "44px",
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 1)";
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 0.9)";
- }}
- >
- <AddPhotoAlternateOutlinedIcon
- style={{ fontSize: "22px" }}
- />
- </button>
- )}
- {!enableDownload && (
- <button
- onClick={downloadAllFiles}
- style={{
- padding: "12px",
- backgroundColor: "rgba(255, 255, 255, 0.9)",
- border: "none",
- borderRadius: "8px",
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "#1f2937",
- transition: "background-color 0.2s",
- backdropFilter: "blur(10px)",
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
- width: "44px",
- height: "44px",
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 1)";
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 0.9)";
- }}
- >
- <FileDownloadOutlinedIcon
- style={{ fontSize: "23px" }}
- />
- </button>
- )}
- <button
- onClick={() => {
- if (typeof window !== "undefined") {
- window.open(
- "https://ente.io",
- "_blank",
- "noopener,noreferrer",
- );
- }
- }}
- style={{
- padding: "12px 16px",
- marginLeft: "12px",
- backgroundColor: "rgba(255, 255, 255, 0.9)",
- border: "none",
- borderRadius: "8px",
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "#1f2937",
- transition: "background-color 0.2s",
- backdropFilter: "blur(10px)",
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
- fontSize: "16px",
- fontWeight: "600",
- whiteSpace: "nowrap",
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 1)";
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor =
- "rgba(255, 255, 255, 0.9)";
- }}
- >
- {isTouchscreen ? t("install") : t("sign_up")}
- </button>
- </div>
-
- {/* Copied message */}
- {showCopiedMessage && (
- <div
- style={{
- position: "fixed",
- top: "118px",
- right: "180px",
- backgroundColor: "#22c55e",
- color: "white",
- padding: "8px 16px",
- borderRadius: "8px",
- fontSize: "14px",
- fontWeight: "500",
- zIndex: 2001,
- boxShadow: "0 4px 12px rgba(0, 0, 0, 0.2)",
- animation: "fadeInOut 2s ease-in-out forwards",
- }}
- >
- Copied!
- </div>
- )}
+ <TopNavButtons
+ onAddPhotos={onAddPhotos}
+ downloadAllFiles={downloadAllFiles}
+ enableDownload={enableDownload}
+ />
{/* Left Sidebar - Floating Timeline */}
<div
ref={timelineRef}
@@ -1719,147 +974,21 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
</div>
{/* Map Container */}
- <div
- style={{
- width: "100%",
- height: "100%",
- backgroundColor: hasPhotoData ? "transparent" : "#000000",
- }}
- >
- {hasPhotoData ? (
- <MapContainer
- center={getMapCenter()}
- zoom={optimalZoom}
- style={{ width: "100%", height: "100%" }}
- scrollWheelZoom={true}
- zoomControl={false}
- >
- <MapEvents
- setMapRef={setMapRef}
- setCurrentZoom={setCurrentZoom}
- setTargetZoom={setTargetZoom}
- />
- {/* Stadia Alidade Satellite - includes both imagery and labels */}
- <TileLayer
- attribution='&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
- url="https://tiles.stadiamaps.com/tiles/alidade_satellite/{z}/{x}/{y}{r}.jpg"
- maxZoom={20}
- />
-
- {/* Draw super-clusters (clickable for zoom and gallery) */}
- {superClusters.map((superCluster, index) => {
- // Get all photos from all clusters involved in this supercluster
- const allPhotosInSuperCluster =
- superCluster.clustersInvolved.flatMap(
- (clusterIdx) =>
- photoClusters[clusterIdx] || [],
- );
-
- // Check if this super-cluster has been reached
- const firstClusterIndex =
- superCluster.clustersInvolved[0];
- const isReached =
- firstClusterIndex !== undefined &&
- scrollProgress >=
- firstClusterIndex /
- Math.max(1, photoClusters.length - 1);
-
- return (
- <Marker
- key={`super-cluster-${index}`}
- position={[
- superCluster.lat,
- superCluster.lng,
- ]}
- icon={createSuperClusterIcon(
- superCluster.image, // Use representative photo (first photo of first cluster)
- superCluster.clusterCount,
- 55,
- isReached,
- )}
- eventHandlers={{
- click: () => {
- const firstClusterIndex =
- superCluster
- .clustersInvolved[0];
- if (
- firstClusterIndex !== undefined
- ) {
- handleMarkerClick(
- firstClusterIndex,
- superCluster.lat,
- superCluster.lng,
- );
- }
- },
- }}
- />
- );
- })}
-
- {/* Draw visible regular clusters */}
- {visibleClusters.map((cluster, index) => {
- const firstPhoto = cluster[0];
- if (!firstPhoto) return null;
- const avgLat =
- cluster.reduce((sum, p) => sum + p.lat, 0) /
- cluster.length;
- const avgLng =
- cluster.reduce((sum, p) => sum + p.lng, 0) /
- cluster.length;
-
- // Find the original cluster index
- const originalClusterIndex =
- photoClusters.findIndex(
- (originalCluster) =>
- originalCluster.length ===
- cluster.length &&
- originalCluster[0]?.image ===
- cluster[0]?.image,
- );
- // Check if this location has been reached based on progress
- const isReached =
- scrollProgress >=
- originalClusterIndex /
- Math.max(1, photoClusters.length - 1);
-
- return (
- <Marker
- key={`cluster-${index}`}
- position={[avgLat, avgLng]}
- icon={createIcon(
- firstPhoto.image,
- 55,
- "#ffffff",
- cluster.length,
- isReached,
- )}
- eventHandlers={{
- click: () => {
- // Calculate cluster center
- const avgLat =
- cluster.reduce(
- (sum, p) => sum + p.lat,
- 0,
- ) / cluster.length;
- const avgLng =
- cluster.reduce(
- (sum, p) => sum + p.lng,
- 0,
- ) / cluster.length;
- handleMarkerClick(
- originalClusterIndex,
- avgLat,
- avgLng,
- );
- },
- }}
- />
- );
- })}
- </MapContainer>
- ) : null}
- </div>
+ <TripMap
+ journeyData={journeyData}
+ photoClusters={photoClusters}
+ hasPhotoData={hasPhotoData}
+ optimalZoom={optimalZoom}
+ currentZoom={currentZoom}
+ targetZoom={targetZoom}
+ mapRef={mapRef}
+ scrollProgress={scrollProgress}
+ screenDimensions={screenDimensions}
+ setMapRef={setMapRef}
+ setCurrentZoom={setCurrentZoom}
+ setTargetZoom={setTargetZoom}
+ onMarkerClick={handleMarkerClick}
+ />
{/* FileViewer for photo gallery */}
<FileViewer
diff --git a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
new file mode 100644
index 0000000000..9223381640
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
@@ -0,0 +1,525 @@
+import L from "leaflet";
+import type { JourneyPoint } from "./types";
+import { iconCache } from "./utils";
+
+// Geographic clustering with responsive distance thresholds and day separation
+export const clusterPhotosByProximity = (
+ photos: JourneyPoint[],
+ screenDimensions: { width: number; height: number },
+) => {
+ if (photos.length === 0) return [];
+
+ // Mobile: no clustering for better timeline experience
+ // Desktop: 1km clustering for cleaner map display
+ const isMobile = screenDimensions.width < 768;
+ if (isMobile) {
+ // Return each photo as its own cluster on mobile
+ return photos.map((photo) => [photo]);
+ }
+
+ // Desktop: 10km clustering distance (roughly 0.1 degrees)
+ const distanceThreshold = 0.1; // About 10km in degrees
+
+ // First, group photos by day
+ const photosByDay = new Map<string, JourneyPoint[]>();
+ photos.forEach((photo) => {
+ const date = new Date(photo.timestamp);
+ const dayKey = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
+
+ if (!photosByDay.has(dayKey)) {
+ photosByDay.set(dayKey, []);
+ }
+ photosByDay.get(dayKey)!.push(photo);
+ });
+
+ // Then cluster within each day
+ const allClusters: JourneyPoint[][] = [];
+
+ photosByDay.forEach((dayPhotos) => {
+ const visited = new Set<number>();
+
+ dayPhotos.forEach((photo, i) => {
+ if (visited.has(i)) return;
+
+ const cluster = [photo];
+ visited.add(i);
+
+ dayPhotos.forEach((otherPhoto, j) => {
+ if (i === j || visited.has(j)) return;
+
+ const distance = Math.sqrt(
+ Math.pow(photo.lat - otherPhoto.lat, 2) +
+ Math.pow(photo.lng - otherPhoto.lng, 2),
+ );
+
+ if (distance < distanceThreshold) {
+ cluster.push(otherPhoto);
+ visited.add(j);
+ }
+ });
+
+ allClusters.push(cluster);
+ });
+ });
+
+ return allClusters;
+};
+
+// Calculate optimal zoom level based on cluster spread
+export const calculateOptimalZoom = (
+ photoClusters: JourneyPoint[][],
+ screenDimensions: { width: number; height: number },
+): number => {
+ if (photoClusters.length === 0) return 7;
+
+ // Calculate cluster centers
+ const clusterCenters = photoClusters.map((cluster) => {
+ const avgLat =
+ cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
+ const avgLng =
+ cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
+ return { lat: avgLat, lng: avgLng };
+ });
+
+ // Find the bounding box of all clusters (only need lng values for calculations)
+ const allLats = clusterCenters.map((c) => c.lat);
+ const allLngs = clusterCenters.map((c) => c.lng);
+
+ // Calculate minimum distances between clusters to avoid over-clustering
+ let minDistance = Infinity;
+ for (let i = 0; i < clusterCenters.length - 1; i++) {
+ for (let j = i + 1; j < clusterCenters.length; j++) {
+ const centerI = clusterCenters[i];
+ const centerJ = clusterCenters[j];
+ if (!centerI || !centerJ) continue;
+ const distance = Math.sqrt(
+ Math.pow(centerI.lat - centerJ.lat, 2) +
+ Math.pow(centerI.lng - centerJ.lng, 2),
+ );
+ minDistance = Math.min(minDistance, distance);
+ }
+ }
+
+ // Calculate zoom based on cluster density and actual screen dimensions
+ // Timeline takes more space on mobile (50%) vs desktop (50%)
+ const isMobile = screenDimensions.width < 768;
+ const timelineSizeRatio = isMobile ? 0.5 : 0.5;
+ const visibleMapWidth = screenDimensions.width * (1 - timelineSizeRatio);
+
+ // Calculate effective span considering cluster density
+ // Sort clusters by longitude to find the core data area
+ const sortedClusterLngs = allLngs.slice().sort((a, b) => a - b);
+ const sortedClusterLats = allLats.slice().sort((a, b) => a - b);
+
+ // Use 90th percentile span instead of full min/max to ignore outliers
+ const p10Index = Math.floor(sortedClusterLngs.length * 0.1);
+ const p90Index = Math.floor(sortedClusterLngs.length * 0.9);
+ const p10Lng = sortedClusterLngs[p10Index];
+ const p90Lng = sortedClusterLngs[p90Index];
+ const p10Lat = sortedClusterLats[p10Index];
+ const p90Lat = sortedClusterLats[p90Index];
+ if (
+ p10Lng === undefined ||
+ p90Lng === undefined ||
+ p10Lat === undefined ||
+ p90Lat === undefined
+ ) {
+ return 7; // fallback zoom
+ }
+ const effectiveLngSpan = p90Lng - p10Lng;
+ const effectiveLatSpan = p90Lat - p10Lat;
+
+ // Add more padding (40%) to prevent cropping at edges
+ const paddedLngSpan = effectiveLngSpan * 1.4;
+ const paddedLatSpan = effectiveLatSpan * 1.4;
+
+ // Calculate zoom to fit the padded effective span
+ const zoomForLngSpan = Math.log2(
+ (visibleMapWidth * 360) / (paddedLngSpan * 256),
+ );
+ const visibleMapHeight = screenDimensions.height; // Full height available for map
+ const zoomForLatSpan = Math.log2(
+ (visibleMapHeight * 360) / (paddedLatSpan * 256),
+ );
+
+ // Take the more restrictive zoom
+ const zoomToFitBounds = Math.min(zoomForLngSpan, zoomForLatSpan);
+
+ // Also ensure reasonable cluster separation
+ const targetPixelSeparation = 100;
+ const pixelsPerDegreeAtOptimalZoom = targetPixelSeparation / minDistance;
+ const optimalZoomFromSeparation = Math.log2(
+ (pixelsPerDegreeAtOptimalZoom * 360) / 256,
+ );
+
+ // Prioritize fitting bounds with some buffer for cluster separation
+ const calculatedZoom = Math.min(
+ zoomToFitBounds,
+ optimalZoomFromSeparation,
+ );
+ const clampedZoom = Math.max(6, Math.min(14, calculatedZoom));
+
+ return Math.round(clampedZoom);
+};
+
+// Function to create icon with specific image and progress styling
+export const createIcon = (
+ imageSrc: string,
+ size = 40,
+ borderColor = "#ffffff",
+ _clusterCount?: number,
+ isReached = false,
+): L.DivIcon => {
+ if (typeof window === "undefined") {
+ // Fallback icon for SSR
+ return L.divIcon({ html: "", className: "empty-marker" });
+ }
+
+ // Create cache key based on all parameters
+ const cacheKey = `icon_${imageSrc}_${size}_${borderColor}_${isReached}`;
+
+ const cachedIcon = iconCache.get(cacheKey);
+ if (cachedIcon) {
+ return cachedIcon;
+ }
+
+ const pinSize = size + 16; // Make it square and bigger
+ const pinHeight = pinSize + 12; // Add space for triangle
+ const triangleHeight = 10;
+
+ const icon = L.divIcon({
+ html: `
+ <div class="photo-pin${isReached ? " reached" : ""}" style="
+ width: ${pinSize}px;
+ height: ${pinHeight}px;
+ position: relative;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ ">
+ <!-- Main rounded rectangle container -->
+ <div style="
+ width: ${pinSize}px;
+ height: ${pinSize}px;
+ border-radius: 16px;
+ background: ${isReached ? "#22c55e" : "white"};
+ border: 2px solid ${isReached ? "#22c55e" : borderColor};
+ box-shadow: 0 4px 8px rgba(0,0,0,0.3);
+ padding: 4px;
+ position: relative;
+ overflow: hidden;
+ transition: background-color 0.3s ease, border-color 0.3s ease;
+ "
+ onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"
+ onmouseout="this.style.background='${isReached ? "#22c55e" : "white"}'; this.style.borderColor='${isReached ? "#22c55e" : "#ffffff"}'; this.nextElementSibling.style.borderTopColor='${isReached ? "#22c55e" : "white"}';"
+ >
+ <!-- Image inside the rounded rectangle -->
+ <img
+ src="${imageSrc}"
+ style="
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: 12px;
+ "
+ alt="Location"
+ />
+ </div>
+
+ <!-- Triangle at the bottom -->
+ <div style="
+ position: absolute;
+ bottom: 2px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 0;
+ height: 0;
+ border-left: ${triangleHeight}px solid transparent;
+ border-right: ${triangleHeight}px solid transparent;
+ border-top: ${triangleHeight}px solid ${isReached ? "#22c55e" : "white"};
+ filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
+ transition: border-top-color 0.3s ease;
+ "></div>
+ </div>
+ `,
+ className: "custom-pin-marker",
+ iconSize: [pinSize, pinHeight],
+ iconAnchor: [pinSize / 2, pinHeight],
+ popupAnchor: [0, -pinHeight],
+ });
+
+ // Cache the icon
+ iconCache.set(cacheKey, icon);
+ return icon;
+};
+
+// Function to create super-cluster icon with badge
+export const createSuperClusterIcon = (
+ imageSrc: string,
+ clusterCount: number,
+ size = 45,
+ isReached = false,
+): L.DivIcon => {
+ if (typeof window === "undefined") {
+ // Fallback icon for SSR
+ return L.divIcon({ html: "", className: "empty-marker" });
+ }
+
+ // Create cache key based on all parameters
+ const cacheKey = `super_icon_${imageSrc}_${clusterCount}_${size}_${isReached}`;
+
+ const cachedIcon = iconCache.get(cacheKey);
+ if (cachedIcon) {
+ return cachedIcon;
+ }
+
+ const pinSize = size + 16; // Make it square and bigger
+ const pinHeight = pinSize + 12; // Add space for triangle
+ const triangleHeight = 10;
+ const containerSize = pinSize + 24;
+
+ const icon = L.divIcon({
+ html: `
+ <div class="super-cluster-container" style="
+ width: ${containerSize}px;
+ height: ${pinHeight + 12}px;
+ position: relative;
+ cursor: pointer;
+ ">
+ <!-- Main pin container -->
+ <div class="photo-pin${isReached ? " reached" : ""}" style="
+ width: ${pinSize}px;
+ height: ${pinHeight}px;
+ position: absolute;
+ left: 12px;
+ top: 0;
+ transition: all 0.3s ease;
+ ">
+ <!-- Main rounded rectangle container -->
+ <div style="
+ width: ${pinSize}px;
+ height: ${pinSize}px;
+ border-radius: 16px;
+ background: ${isReached ? "#22c55e" : "white"};
+ border: 2px solid ${isReached ? "#22c55e" : "#ffffff"};
+ box-shadow: 0 4px 8px rgba(0,0,0,0.3);
+ padding: 4px;
+ position: relative;
+ overflow: hidden;
+ transition: background-color 0.3s ease, border-color 0.3s ease;
+ "
+ onmouseover="this.style.background='#22c55e'; this.style.borderColor='#22c55e'; this.nextElementSibling.style.borderTopColor='#22c55e';"
+ onmouseout="this.style.background='${isReached ? "#22c55e" : "white"}'; this.style.borderColor='${isReached ? "#22c55e" : "#ffffff"}'; this.nextElementSibling.style.borderTopColor='${isReached ? "#22c55e" : "white"}';"
+ >
+ <!-- Image inside the rounded rectangle -->
+ <img
+ src="${imageSrc}"
+ style="
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: 12px;
+ "
+ alt="Location"
+ />
+ </div>
+
+ <!-- Triangle at the bottom -->
+ <div style="
+ position: absolute;
+ bottom: 2px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 0;
+ height: 0;
+ border-left: ${triangleHeight}px solid transparent;
+ border-right: ${triangleHeight}px solid transparent;
+ border-top: ${triangleHeight}px solid ${isReached ? "#22c55e" : "white"};
+ filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
+ transition: border-top-color 0.3s ease;
+ "></div>
+ </div>
+
+ <!-- Badge -->
+ <div style="
+ position: absolute;
+ top: -6px;
+ right: 0;
+ background: #000000;
+ color: white;
+ border-radius: 50%;
+ width: 22px;
+ height: 22px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 11px;
+ font-weight: 600;
+ border: 2px solid white;
+ box-shadow: 0 2px 6px rgba(0,0,0,0.3);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
+ z-index: 10;
+ ">${clusterCount}</div>
+ </div>
+ `,
+ className: "super-cluster-pin-marker",
+ iconSize: [containerSize, pinHeight + 12],
+ iconAnchor: [containerSize / 2, pinHeight + 12],
+ popupAnchor: [0, -(pinHeight + 12)],
+ });
+
+ // Cache the icon
+ iconCache.set(cacheKey, icon);
+ return icon;
+};
+
+// Calculate super-clusters based on screen collisions
+export const detectScreenCollisions = (
+ clusters: JourneyPoint[][],
+ zoom: number,
+ targetZoom: number | null,
+ mapRef: L.Map | null,
+ optimalZoom: number,
+) => {
+ // Use target zoom if we're in the middle of a zoom animation, otherwise use optimal zoom
+ const effectiveZoom =
+ targetZoom !== null ? targetZoom : mapRef ? zoom : optimalZoom;
+
+ // Convert geographic distance to screen pixels
+ // At zoom Z, roughly 2^Z * 256 pixels per 360 degrees
+ const pixelsPerDegree = (Math.pow(2, effectiveZoom) * 256) / 360;
+ // Use a more conservative collision threshold to show more individual clusters
+ const collisionThreshold = 50 / pixelsPerDegree; // 50 pixel collision radius
+
+ const superClusters: {
+ lat: number;
+ lng: number;
+ clusterCount: number;
+ clustersInvolved: number[];
+ image: string;
+ }[] = [];
+ const hiddenClusterIndices = new Set<number>();
+
+ // Check each cluster against others for screen-space collision
+ clusters.forEach((cluster, i) => {
+ if (hiddenClusterIndices.has(i)) return;
+
+ const clusterLat =
+ cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
+ const clusterLng =
+ cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
+
+ const overlappingClusters = [i];
+
+ clusters.forEach((otherCluster, j) => {
+ if (i === j || hiddenClusterIndices.has(j)) return;
+
+ const otherLat =
+ otherCluster.reduce((sum, p) => sum + p.lat, 0) /
+ otherCluster.length;
+ const otherLng =
+ otherCluster.reduce((sum, p) => sum + p.lng, 0) /
+ otherCluster.length;
+
+ const distance = Math.sqrt(
+ Math.pow(clusterLat - otherLat, 2) +
+ Math.pow(clusterLng - otherLng, 2),
+ );
+
+ if (distance < collisionThreshold) {
+ overlappingClusters.push(j);
+ hiddenClusterIndices.add(j);
+ }
+ });
+
+ // If we found overlapping clusters, create a super-cluster
+ if (overlappingClusters.length > 1) {
+ hiddenClusterIndices.add(i); // Hide the original cluster too
+
+ // Calculate center position of all overlapping clusters
+ let totalLat = 0,
+ totalLng = 0;
+ overlappingClusters.forEach((idx) => {
+ const c = clusters[idx];
+ if (!c) return;
+ totalLat += c.reduce((sum, p) => sum + p.lat, 0) / c.length;
+ totalLng += c.reduce((sum, p) => sum + p.lng, 0) / c.length;
+ });
+
+ // Get the first photo from the first cluster as representative image
+ const firstClusterIdx = overlappingClusters[0];
+ const firstCluster =
+ firstClusterIdx !== undefined
+ ? clusters[firstClusterIdx]
+ : undefined;
+ const representativePhoto = firstCluster?.[0];
+ if (!representativePhoto) {
+ return;
+ }
+
+ superClusters.push({
+ lat: totalLat / overlappingClusters.length,
+ lng: totalLng / overlappingClusters.length,
+ clusterCount: overlappingClusters.length,
+ clustersInvolved: overlappingClusters,
+ image: representativePhoto.image,
+ });
+ }
+ });
+
+ // Return visible clusters (those not hidden by super-clusters)
+ const visibleClusters = clusters.filter(
+ (_, idx) => !hiddenClusterIndices.has(idx),
+ );
+
+ return { superClusters, visibleClusters };
+};
+
+// Calculate map center - start at first location to match timeline initial state
+export const getMapCenter = (
+ photoClusters: JourneyPoint[][],
+ journeyData: JourneyPoint[],
+ screenDimensions: { width: number; height: number },
+): [number, number] => {
+ // If no clusters yet, check journey data
+ if (photoClusters.length === 0) {
+ const firstPoint = journeyData[0];
+ if (!firstPoint) return [0, 0]; // Fallback, but map won't render anyway
+ return [firstPoint.lat, firstPoint.lng];
+ }
+
+ // Start at first cluster center to match the timeline starting position
+ const firstCluster = photoClusters[0];
+ if (!firstCluster || firstCluster.length === 0) return [0, 0]; // Fallback, but map won't render anyway
+
+ const firstLat =
+ firstCluster.reduce((sum, p) => sum + p.lat, 0) / firstCluster.length;
+ const firstLng =
+ firstCluster.reduce((sum, p) => sum + p.lng, 0) / firstCluster.length;
+
+ // Calculate shift for timeline positioning
+ const clusterCenters = photoClusters.map((cluster) => {
+ const avgLat =
+ cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
+ const avgLng =
+ cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
+ return { lat: avgLat, lng: avgLng };
+ });
+
+ const allLngs = clusterCenters.map((c) => c.lng);
+ const minLng = Math.min(...allLngs);
+ const maxLng = Math.max(...allLngs);
+ const lngSpan = maxLng - minLng;
+ const paddedSpan = Math.max(lngSpan * 1.4, 0.1); // Minimum span for single locations
+
+ const isMobile = screenDimensions.width < 768;
+ const timelineSizeRatio = isMobile ? 0.5 : 0.5;
+ const mapSizeRatio = 1 - timelineSizeRatio;
+
+ const screenWidthInDegrees = paddedSpan / mapSizeRatio;
+ const shiftAmount = screenWidthInDegrees * (timelineSizeRatio / 2);
+
+ // Shift the first location left so it appears centered in visible area
+ const adjustedLng = firstLng - shiftAmount;
+
+ return [firstLat, adjustedLng];
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/useFileViewer.ts b/web/apps/photos/src/components/TripTemplate/useFileViewer.ts
new file mode 100644
index 0000000000..92455d5b48
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/useFileViewer.ts
@@ -0,0 +1,65 @@
+import { type EnteFile } from "ente-media/file";
+import { useCallback, useState } from "react";
+import type { JourneyPoint } from "./types";
+
+interface UseFileViewerProps {
+ files: EnteFile[];
+ onSetOpenFileViewer?: (open: boolean) => void;
+ onRemotePull?: () => Promise<void>;
+}
+
+export const useFileViewer = ({
+ files,
+ onSetOpenFileViewer,
+ onRemotePull,
+}: UseFileViewerProps) => {
+ const [openFileViewer, setOpenFileViewer] = useState(false);
+ const [currentFileIndex, setCurrentFileIndex] = useState(0);
+ const [viewerFiles, setViewerFiles] = useState<EnteFile[]>([]);
+
+ const handleOpenFileViewer = useCallback(
+ (_cluster: JourneyPoint[], clickedFileId: number) => {
+ // Sort all files by creation time
+ const sortedFiles = [...files].sort(
+ (a, b) =>
+ new Date(a.metadata.creationTime / 1000).getTime() -
+ new Date(b.metadata.creationTime / 1000).getTime(),
+ );
+
+ // Find the index of the clicked photo in all files
+ const clickedIndex = sortedFiles.findIndex(
+ (f) => f.id === clickedFileId,
+ );
+
+ if (clickedIndex !== -1 && sortedFiles.length > 0) {
+ // Batch state updates to avoid multiple re-renders
+ setViewerFiles(sortedFiles);
+ setCurrentFileIndex(clickedIndex);
+ setOpenFileViewer(true);
+ onSetOpenFileViewer?.(true);
+ }
+ },
+ [files, onSetOpenFileViewer],
+ );
+
+ const handleCloseFileViewer = useCallback(() => {
+ // Batch state updates
+ setOpenFileViewer(false);
+ onSetOpenFileViewer?.(false);
+ }, [onSetOpenFileViewer]);
+
+ const handleTriggerRemotePull = useCallback(() => {
+ return onRemotePull?.() || Promise.resolve();
+ }, [onRemotePull]);
+
+ return {
+ // State
+ openFileViewer,
+ currentFileIndex,
+ viewerFiles,
+ // Handlers
+ handleOpenFileViewer,
+ handleCloseFileViewer,
+ handleTriggerRemotePull,
+ };
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/utils.ts b/web/apps/photos/src/components/TripTemplate/utils.ts
index 21fec9ba36..1b60e4af07 100644
--- a/web/apps/photos/src/components/TripTemplate/utils.ts
+++ b/web/apps/photos/src/components/TripTemplate/utils.ts
@@ -1,5 +1,5 @@
import L from "leaflet";
-import { GeocodingResponse } from "./types";
+import type { GeocodingResponse } from "./types";
// Geocoding cache to avoid repeated API calls
export const geocodingCache = new Map<string, { place: string; country: string }>();
@@ -8,7 +8,7 @@ export const geocodingCache = new Map<string, { place: string; country: string }
export const iconCache = new Map<string, L.DivIcon>();
// Throttle function for performance optimization
-export const throttle = <T extends (...args: any[]) => void>(
+export const throttle = <T extends (...args: unknown[]) => void>(
func: T,
delay: number
): ((...args: Parameters<T>) => void) => {