Skip to content

armgit / ente

Public Imported from GitHub
0

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

refactor: trip index file further

anandbaburajand3976865c130
diff --git a/web/apps/photos/src/components/TripTemplate/hooks/useDataProcessing.ts b/web/apps/photos/src/components/TripTemplate/hooks/useDataProcessing.ts
new file mode 100644
index 0000000000..e21b030132
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/hooks/useDataProcessing.ts
@@ -0,0 +1,75 @@
+import { useEffect } from "react";
+import { type EnteFile } from "ente-media/file";
+import { type Collection } from "ente-media/collection";
+
+import type { JourneyPoint } from "../types";
+import {
+ processPhotosData,
+ loadCoverImage,
+} from "../utils/dataProcessing";
+
+export interface UseDataProcessingParams {
+ files: EnteFile[];
+ collection?: Collection;
+ journeyData: JourneyPoint[];
+ thumbnailsGeneratedRef: React.MutableRefObject<boolean>;
+ filesCountRef: React.MutableRefObject<number>;
+ locationDataRef: React.MutableRefObject<Map<number, { name: string; country: string }>>;
+ setJourneyData: (data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[])) => void;
+ setIsInitialLoad: (loading: boolean) => void;
+ setIsLoadingLocations: (loading: boolean) => void;
+ setCoverImageUrl: (url: string | null) => void;
+}
+
+export const useDataProcessing = ({
+ files,
+ collection,
+ journeyData,
+ thumbnailsGeneratedRef,
+ filesCountRef,
+ locationDataRef,
+ setJourneyData,
+ setIsInitialLoad,
+ setIsLoadingLocations,
+ setCoverImageUrl,
+}: UseDataProcessingParams) => {
+ // Process photos data when files change
+ useEffect(() => {
+ const hasFilesCountChanged = files.length !== filesCountRef.current;
+ filesCountRef.current = files.length;
+
+ if (!hasFilesCountChanged && journeyData.length > 0) {
+ return;
+ }
+
+ thumbnailsGeneratedRef.current = false;
+
+ const { photoData, hasLocationData } = processPhotosData({
+ files,
+ locationDataRef,
+ });
+
+ setJourneyData(photoData);
+ setIsInitialLoad(false);
+
+ if (hasLocationData) {
+ setIsLoadingLocations(true);
+ }
+ }, [files, journeyData.length, filesCountRef, locationDataRef, thumbnailsGeneratedRef, setJourneyData, setIsInitialLoad, setIsLoadingLocations]);
+
+ // Load cover image after data loads
+ useEffect(() => {
+ const loadCover = async () => {
+ const coverUrl = await loadCoverImage({
+ journeyData,
+ files,
+ collection,
+ });
+ if (coverUrl) {
+ setCoverImageUrl(coverUrl);
+ }
+ };
+
+ void loadCover();
+ }, [journeyData, files, collection, setCoverImageUrl]);
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/useFileViewer.ts b/web/apps/photos/src/components/TripTemplate/hooks/useFileViewer.ts
similarity index 100%
rename from web/apps/photos/src/components/TripTemplate/useFileViewer.ts
rename to web/apps/photos/src/components/TripTemplate/hooks/useFileViewer.ts
diff --git a/web/apps/photos/src/components/TripTemplate/hooks/useLocationFetching.ts b/web/apps/photos/src/components/TripTemplate/hooks/useLocationFetching.ts
new file mode 100644
index 0000000000..3e2b5b087e
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/hooks/useLocationFetching.ts
@@ -0,0 +1,52 @@
+import { useEffect } from "react";
+
+import type { JourneyPoint } from "../types";
+import { fetchLocationNames } from "../utils/dataProcessing";
+
+export interface UseLocationFetchingParams {
+ photoClusters: JourneyPoint[][];
+ journeyData: JourneyPoint[];
+ locationDataRef: React.MutableRefObject<Map<number, { name: string; country: string }>>;
+ setJourneyData: (data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[])) => void;
+ setIsLoadingLocations: (loading: boolean) => void;
+}
+
+export const useLocationFetching = ({
+ photoClusters,
+ locationDataRef,
+ setJourneyData,
+ setIsLoadingLocations,
+}: UseLocationFetchingParams) => {
+ // Fetch location names for clusters
+ useEffect(() => {
+ const fetchNames = async () => {
+ if (photoClusters.length === 0) return;
+
+ setIsLoadingLocations(true);
+
+ try {
+ const { updatedPhotos } = await fetchLocationNames({
+ photoClusters,
+ journeyData: [],
+ locationDataRef,
+ });
+
+ if (updatedPhotos.size > 0) {
+ setJourneyData((prevData) =>
+ prevData.map((photo) => {
+ const update = updatedPhotos.get(photo.fileId);
+ if (update) {
+ return { ...photo, ...update };
+ }
+ return photo;
+ }),
+ );
+ }
+ } finally {
+ setIsLoadingLocations(false);
+ }
+ };
+
+ void fetchNames();
+ }, [photoClusters.length, locationDataRef, setJourneyData, setIsLoadingLocations]);
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts b/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts
new file mode 100644
index 0000000000..aafe9dcfc0
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts
@@ -0,0 +1,162 @@
+import { useCallback, useEffect, useMemo } from "react";
+
+import type { JourneyPoint } from "../types";
+import { throttle } from "../utils/geocoding";
+import {
+ updateLocationPositions,
+ handleTimelineScroll,
+ scrollTimelineToLocation,
+ handleMarkerClick,
+ type PositionInfo,
+} from "../utils/scrollUtils";
+
+export interface UseScrollHandlingParams {
+ timelineRef: React.RefObject<HTMLDivElement | null>;
+ photoClusters: JourneyPoint[][];
+ locationPositions: PositionInfo[];
+ mapRef: L.Map | null;
+ screenDimensions: { width: number; height: number };
+ optimalZoom: number;
+ locationRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;
+ isClusterClickScrollingRef: React.MutableRefObject<boolean>;
+ clusterClickTimeoutRef: React.MutableRefObject<NodeJS.Timeout | null>;
+ setLocationPositions: (positions: PositionInfo[]) => void;
+ setHasUserScrolled: (scrolled: boolean) => void;
+ setScrollProgress: (progress: number) => void;
+}
+
+export const useScrollHandling = ({
+ timelineRef,
+ photoClusters,
+ locationPositions,
+ mapRef,
+ screenDimensions,
+ optimalZoom,
+ locationRefs,
+ isClusterClickScrollingRef,
+ clusterClickTimeoutRef,
+ setLocationPositions,
+ setHasUserScrolled,
+ setScrollProgress,
+}: UseScrollHandlingParams) => {
+ // Update location positions callback
+ const updatePositions = useCallback(() => {
+ updateLocationPositions({
+ locationRefs: locationRefs.current,
+ setLocationPositions,
+ });
+ }, [locationRefs, setLocationPositions]);
+
+ // Timeline scroll handler
+ const timelineScrollHandler = useCallback(() => {
+ handleTimelineScroll({
+ timelineRef,
+ photoClusters,
+ locationPositions,
+ mapRef,
+ screenDimensions,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ setHasUserScrolled,
+ setScrollProgress,
+ });
+ }, [
+ timelineRef,
+ photoClusters,
+ locationPositions,
+ mapRef,
+ screenDimensions,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ setHasUserScrolled,
+ setScrollProgress,
+ ]);
+
+ // Throttled scroll handler
+ const throttledTimelineScroll = useMemo(
+ () => throttle(timelineScrollHandler, 16),
+ [timelineScrollHandler],
+ );
+
+ // Timeline scroll to location function
+ const scrollToLocation = useCallback(
+ (locationIndex: number) => {
+ scrollTimelineToLocation({
+ timelineRef,
+ locationIndex,
+ photoClusters,
+ locationPositions,
+ });
+ },
+ [timelineRef, photoClusters, locationPositions],
+ );
+
+ // Marker click handler
+ const markerClickHandler = useCallback(
+ (clusterIndex: number, clusterLat: number, clusterLng: number) => {
+ handleMarkerClick({
+ clusterIndex,
+ clusterLat,
+ clusterLng,
+ photoClusters,
+ screenDimensions,
+ mapRef,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ clusterClickTimeoutRef,
+ setScrollProgress,
+ scrollTimelineToLocation: scrollToLocation,
+ });
+ },
+ [
+ photoClusters,
+ screenDimensions,
+ mapRef,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ clusterClickTimeoutRef,
+ setScrollProgress,
+ scrollToLocation,
+ ],
+ );
+
+ // Update positions when locations render
+ useEffect(() => {
+ if (
+ locationRefs.current.length === photoClusters.length &&
+ photoClusters.length > 0
+ ) {
+ const timer = setTimeout(updatePositions, 100);
+ return () => clearTimeout(timer);
+ }
+ return undefined;
+ }, [photoClusters, updatePositions, locationRefs]);
+
+ // Add scroll event listener
+ useEffect(() => {
+ const timelineContainer = timelineRef.current;
+ if (!timelineContainer) return;
+
+ timelineContainer.addEventListener("scroll", throttledTimelineScroll);
+
+ return () => {
+ timelineContainer.removeEventListener("scroll", throttledTimelineScroll);
+ };
+ }, [throttledTimelineScroll, timelineRef]);
+
+ // Cleanup timeout on unmount
+ useEffect(() => {
+ return () => {
+ if (clusterClickTimeoutRef.current) {
+ clearTimeout(clusterClickTimeoutRef.current);
+ clusterClickTimeoutRef.current = null;
+ }
+ };
+ }, [clusterClickTimeoutRef]);
+
+ return {
+ updatePositions,
+ scrollToLocation,
+ markerClickHandler,
+ };
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/hooks/useThumbnailGeneration.ts b/web/apps/photos/src/components/TripTemplate/hooks/useThumbnailGeneration.ts
new file mode 100644
index 0000000000..356ccaa31c
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/hooks/useThumbnailGeneration.ts
@@ -0,0 +1,47 @@
+import { useEffect } from "react";
+import { type EnteFile } from "ente-media/file";
+
+import type { JourneyPoint } from "../types";
+import { generateNeededThumbnails } from "../utils/dataProcessing";
+
+export interface UseThumbnailGenerationParams {
+ photoClusters: JourneyPoint[][];
+ journeyData: JourneyPoint[];
+ files: EnteFile[];
+ thumbnailsGeneratedRef: React.MutableRefObject<boolean>;
+ setJourneyData: (data: JourneyPoint[] | ((prev: JourneyPoint[]) => JourneyPoint[])) => void;
+}
+
+export const useThumbnailGeneration = ({
+ photoClusters,
+ files,
+ thumbnailsGeneratedRef,
+ setJourneyData,
+}: UseThumbnailGenerationParams) => {
+ // Generate thumbnails for needed photos
+ useEffect(() => {
+ const generateThumbs = async () => {
+ if (photoClusters.length === 0 || thumbnailsGeneratedRef.current) return;
+
+ const { thumbnailUpdates } = await generateNeededThumbnails({
+ photoClusters,
+ files,
+ });
+
+ if (thumbnailUpdates.size > 0) {
+ setJourneyData((prevData) =>
+ prevData.map((photo) => {
+ const thumbnailUrl = thumbnailUpdates.get(photo.fileId);
+ if (thumbnailUrl && !photo.image) {
+ return { ...photo, image: thumbnailUrl };
+ }
+ return photo;
+ }),
+ );
+ }
+ thumbnailsGeneratedRef.current = true;
+ };
+
+ void generateThumbs();
+ }, [photoClusters.length, files, thumbnailsGeneratedRef, setJourneyData]);
+};
\ No newline at end of file
diff --git a/web/apps/photos/src/components/TripTemplate/index.tsx b/web/apps/photos/src/components/TripTemplate/index.tsx
index 1b6a90ff73..d2faa4a4df 100644
--- a/web/apps/photos/src/components/TripTemplate/index.tsx
+++ b/web/apps/photos/src/components/TripTemplate/index.tsx
@@ -2,20 +2,11 @@ import { Box, styled } from "@mui/material";
import { DownloadStatusNotifications } from "components/DownloadStatusNotifications";
import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
import { FileViewer } from "ente-gallery/components/viewer/FileViewer";
-import { downloadManager } from "ente-gallery/services/download";
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 L from "leaflet";
-import {
- startTransition,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
// Import extracted components
import { TimelineBaseLine } from "./TimelineBaseLine";
@@ -27,12 +18,16 @@ import { TripMap } from "./TripMap";
import { TripStartedSection } from "./TripStartedSection";
// Import hooks
-import { useFileViewer } from "./useFileViewer";
+import { useFileViewer } from "./hooks/useFileViewer";
+import { useDataProcessing } from "./hooks/useDataProcessing";
+import { useLocationFetching } from "./hooks/useLocationFetching";
+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 { getLocationName, throttle } from "./utils";
+import type { PositionInfo } from "./utils/scrollUtils";
interface TripTemplateProps {
files: EnteFile[];
@@ -98,9 +93,9 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
width: number;
height: number;
}>({ width: 1400, height: 800 });
- const [locationPositions, setLocationPositions] = useState<
- { top: number; center: number }[]
- >([]);
+ const [locationPositions, setLocationPositions] = useState<PositionInfo[]>(
+ [],
+ );
const timelineRef = useRef<HTMLDivElement>(null);
const locationRefs = useRef<(HTMLDivElement | null)[]>([]);
const isClusterClickScrollingRef = useRef(false); // Use ref for immediate updates
@@ -163,568 +158,56 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
}
}, [optimalZoom, mapRef, currentZoom]);
+ // Set client-side rendering flag
useEffect(() => {
setIsClient(true);
-
- // Check if the files count has actually changed (not just array reference)
- const hasFilesCountChanged = files.length !== filesCountRef.current;
- filesCountRef.current = files.length;
-
- // Only reload data if the count changed or this is the initial load
- if (!hasFilesCountChanged && journeyData.length > 0) {
- return;
- }
-
- // Reset thumbnail generation flag when files change
- thumbnailsGeneratedRef.current = false;
-
- // Process EnteFiles to extract location data
- const loadPhotosData = () => {
- const photoData: JourneyPoint[] = [];
-
- if (files.length === 0) {
- return;
- }
-
- // Use cached location data to preserve location names
-
- // Process each EnteFile (without thumbnails first)
- for (const file of files) {
- try {
- // Extract location from metadata
- const lat = file.metadata.latitude;
- const lng = file.metadata.longitude;
-
- if (lat && lng) {
- // Check if we have cached location data for this file
- const cachedLocation = locationDataRef.current.get(
- file.id,
- );
- const finalName =
- cachedLocation?.name || fileFileName(file);
- const finalCountry =
- cachedLocation?.country || "Unknown";
-
- photoData.push({
- lat: lat,
- lng: lng,
- name: finalName, // Use cached name if available, otherwise fallback to filename
- country: finalCountry,
- timestamp: new Date(
- file.metadata.creationTime / 1000,
- ).toISOString(),
- image: "", // Will be populated later for photos that need thumbnails
- fileId: file.id,
- });
- // Photo has no GPS data
- }
- } catch {
- // Silently ignore processing errors for individual files
- }
- }
-
- // Sort by timestamp
- photoData.sort(
- (a, b) =>
- new Date(a.timestamp).getTime() -
- new Date(b.timestamp).getTime(),
- );
-
- // Set journey data (location names will be fetched later)
- setJourneyData(photoData);
-
- // Mark initial load as complete
- setIsInitialLoad(false);
-
- // Set loading locations to true since we'll start fetching them
- if (photoData.length > 0) {
- setIsLoadingLocations(true);
- }
- };
-
- loadPhotosData();
- }, [files, journeyData.length]);
-
- // Load high quality cover image after initial data loads
- useEffect(() => {
- const loadCoverImage = async () => {
- if (journeyData.length === 0) return;
-
- let coverFile: EnteFile | undefined;
-
- // Check if there's a designated cover image in collection metadata
- const coverID = collection?.pubMagicMetadata?.data.coverID;
- if (coverID) {
- coverFile = files.find((f) => f.id === coverID);
- }
-
- // Fall back to first chronological photo if no cover is designated
- if (!coverFile) {
- const firstPhoto = journeyData[0];
- if (!firstPhoto) return;
- coverFile = files.find((f) => f.id === firstPhoto.fileId);
- }
-
- if (!coverFile) return;
-
- try {
- const sourceURLs =
- await downloadManager.renderableSourceURLs(coverFile);
- if (sourceURLs.type === "image") {
- setCoverImageUrl(sourceURLs.imageURL);
- }
- } catch {
- // Keep using thumbnail if high quality fails
- }
- };
-
- void loadCoverImage();
- }, [journeyData, files, collection]);
-
- // Fetch location names for clusters after they're created
- useEffect(() => {
- const fetchLocationNames = async () => {
- if (photoClusters.length === 0 || journeyData.length === 0) return;
-
- setIsLoadingLocations(true);
-
- // Create a map to track which photos have been updated
- const updatedPhotos = new Map<
- number,
- { name: string; country: string }
- >();
-
- // Get location names for each cluster center
- for (let i = 0; i < photoClusters.length; i++) {
- const cluster = photoClusters[i];
- if (!cluster || cluster.length === 0) continue;
-
- // 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;
-
- // Get location name for cluster center
- try {
- const locationInfo = await getLocationName(
- avgLat,
- avgLng,
- i + 1,
- );
-
- // Store the location info for all photos in this cluster
- cluster.forEach((photo) => {
- updatedPhotos.set(photo.fileId, {
- name: locationInfo.place,
- country: locationInfo.country,
- });
- // Also cache it in the ref for persistence
- locationDataRef.current.set(photo.fileId, {
- name: locationInfo.place,
- country: locationInfo.country,
- });
- });
- } catch {
- // Silently ignore processing errors for individual files
- }
- }
-
- // Update journey data with location names
- if (updatedPhotos.size > 0) {
- setJourneyData((prevData) =>
- prevData.map((photo) => {
- const update = updatedPhotos.get(photo.fileId);
- if (update) {
- return { ...photo, ...update };
- }
- return photo;
- }),
- );
- }
-
- setIsLoadingLocations(false);
- };
-
- void fetchLocationNames().catch(() => {
- setIsLoadingLocations(false);
- });
- // Only run when photoClusters changes, not journeyData to avoid infinite loop
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [photoClusters.length]);
-
- // Generate thumbnails only for photos that are actually used after clustering
- useEffect(() => {
- const generateNeededThumbnails = async () => {
- if (photoClusters.length === 0 || journeyData.length === 0) return;
-
- // Check if thumbnails have already been generated
- if (thumbnailsGeneratedRef.current) return;
-
- // Collect file IDs that need thumbnails
- const neededFileIds = new Set<number>();
-
- // First 3 photos of each cluster (covers map markers, super clusters, and timeline photo fans)
- photoClusters.forEach((cluster) => {
- cluster.slice(0, 3).forEach((photo) => {
- neededFileIds.add(photo.fileId);
- });
- });
-
- // Find the files that need thumbnails
- const filesToProcess = files.filter((file) =>
- neededFileIds.has(file.id),
- );
-
- // Generate thumbnails and update journey data while preserving location names
- const thumbnailUpdates = new Map<number, string>();
-
- for (const file of filesToProcess) {
- try {
- const thumbnailUrl =
- await downloadManager.renderableThumbnailURL(file);
- if (thumbnailUrl) {
- thumbnailUpdates.set(file.id, thumbnailUrl);
- }
- } catch {
- // Silently ignore thumbnail generation errors
- }
- }
-
- // Update journey data by preserving all existing data and only updating images
- if (thumbnailUpdates.size > 0) {
- setJourneyData((prevData) =>
- prevData.map((photo) => {
- const thumbnailUrl = thumbnailUpdates.get(photo.fileId);
- if (thumbnailUrl && !photo.image) {
- return { ...photo, image: thumbnailUrl };
- }
- return photo;
- }),
- );
- }
- thumbnailsGeneratedRef.current = true;
- };
-
- void generateNeededThumbnails().catch(() => {
- // Silently ignore thumbnail generation errors
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [photoClusters.length]);
-
- // Cleanup timeout on unmount
- useEffect(() => {
- return () => {
- if (clusterClickTimeoutRef.current) {
- clearTimeout(clusterClickTimeoutRef.current);
- clusterClickTimeoutRef.current = null;
- }
- };
- }, []);
-
- // Update location positions when layout changes
- const updateLocationPositions = useCallback(() => {
- if (locationRefs.current.length === 0) return;
-
- const positions = locationRefs.current.map((ref) => {
- if (!ref) return { top: 0, center: 0 };
- const rect = ref.getBoundingClientRect();
- const top = ref.offsetTop;
- const center = top + rect.height / 2;
- return { top, center };
- });
-
- // Use startTransition for lower-priority layout updates
- startTransition(() => {
- setLocationPositions(positions);
- });
}, []);
- // Calculate scroll progress based on timeline scroll position and update map center
- const handleTimelineScroll = useCallback(() => {
- if (
- !timelineRef.current ||
- photoClusters.length === 0 ||
- locationPositions.length === 0
- )
- return;
-
- const timelineContainer = timelineRef.current;
- const scrollHeight = timelineContainer.scrollHeight;
- const clientHeight = timelineContainer.clientHeight;
- const scrollTop = timelineContainer.scrollTop;
-
- // Calculate current progress based on scroll position
- const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
- let progress = 0;
- if (isAtBottom) {
- progress = 1;
- } else {
- const maxScrollableDistance = scrollHeight - clientHeight;
- if (maxScrollableDistance > 0) {
- progress = scrollTop / maxScrollableDistance;
- } else {
- progress = 0;
- }
- }
- const clampedProgress = Math.min(1, Math.max(0, progress));
-
- // Don't update progress during cluster click scrolling - keep the set value
- if (isClusterClickScrollingRef.current) {
- return;
- }
-
- // Normal scroll handling - mark that user has scrolled
- setHasUserScrolled(true);
- // Use startTransition for lower-priority scroll progress updates
- startTransition(() => {
- setScrollProgress(clampedProgress);
- });
+ // Use extracted data processing hooks
+ useDataProcessing({
+ files,
+ collection,
+ journeyData,
+ thumbnailsGeneratedRef,
+ filesCountRef,
+ locationDataRef,
+ setJourneyData,
+ setIsInitialLoad,
+ setIsLoadingLocations,
+ setCoverImageUrl,
+ });
+
+ useLocationFetching({
+ photoClusters,
+ journeyData,
+ locationDataRef,
+ setJourneyData,
+ setIsLoadingLocations,
+ });
- // Real-time map center update based on scroll progress
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
- if (mapRef && !isClusterClickScrollingRef.current) {
- 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 };
- });
-
- if (clusterCenters.length > 0) {
- let targetLat, targetLng;
-
- // Always start at first cluster (journey always starts at first location)
- const firstCenter = clusterCenters[0];
- const lastCenter = clusterCenters[clusterCenters.length - 1];
- if (!firstCenter || !lastCenter) return;
-
- if (clampedProgress <= 0) {
- // At the start, focus on first cluster
- targetLat = firstCenter.lat;
- targetLng = firstCenter.lng;
- } else if (clampedProgress === 1) {
- // At the end, focus on last cluster
- targetLat = lastCenter.lat;
- targetLng = lastCenter.lng;
- } else {
- // Interpolate between clusters based on progress
- const clusterProgress =
- clampedProgress * (clusterCenters.length - 1);
- const currentClusterIndex = Math.floor(clusterProgress);
- const nextClusterIndex = Math.min(
- currentClusterIndex + 1,
- clusterCenters.length - 1,
- );
- const lerpFactor = clusterProgress - currentClusterIndex;
-
- const currentCluster = clusterCenters[currentClusterIndex];
- const nextCluster = clusterCenters[nextClusterIndex];
-
- if (!currentCluster || !nextCluster) {
- targetLat = clusterCenters[0]?.lat || 0;
- targetLng = clusterCenters[0]?.lng || 0;
- } else {
- // Linear interpolation between clusters
- targetLat =
- currentCluster.lat +
- (nextCluster.lat - currentCluster.lat) * lerpFactor;
- targetLng =
- currentCluster.lng +
- (nextCluster.lng - currentCluster.lng) * lerpFactor;
- }
- }
-
- // Apply the offset for timeline positioning (same logic as getMapCenter)
- const isMobile = screenDimensions.width < 768;
- const timelineSizeRatio = isMobile ? 0.5 : 0.5;
-
- // Calculate the span and shift for centering in visible area
- 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 mapSizeRatio = 1 - timelineSizeRatio;
- const screenWidthInDegrees = paddedSpan / mapSizeRatio;
- const shiftAmount =
- screenWidthInDegrees * (timelineSizeRatio / 2);
-
- const adjustedLng = targetLng - shiftAmount;
-
- // Get current zoom level
- const currentMapZoom = mapRef.getZoom();
-
- // Always return to optimal zoom when scrolling timeline
- if (currentMapZoom !== optimalZoom) {
- // Zoom back to default/optimal zoom while panning
- mapRef.flyTo([targetLat, adjustedLng], optimalZoom, {
- animate: true,
- duration: 0.5,
- easeLinearity: 0.5,
- });
- } else {
- // Just pan when already at optimal zoom
- mapRef.panTo([targetLat, adjustedLng], {
- animate: true,
- duration: 0.3,
- easeLinearity: 0.8,
- });
- }
- }
- }
- }, [
+ useThumbnailGeneration({
+ photoClusters,
+ journeyData,
+ files,
+ thumbnailsGeneratedRef,
+ setJourneyData,
+ });
+
+ // Use extracted scroll handling hooks
+ const { markerClickHandler } = useScrollHandling({
timelineRef,
photoClusters,
locationPositions,
mapRef,
screenDimensions,
optimalZoom,
- ]);
-
- // Update positions when locations render
- useEffect(() => {
- if (
- locationRefs.current.length === photoClusters.length &&
- photoClusters.length > 0
- ) {
- // Small delay to ensure layout is complete
- const timer = setTimeout(updateLocationPositions, 100);
- return () => clearTimeout(timer);
- }
- return undefined;
- }, [photoClusters, updateLocationPositions]);
-
- // Throttled scroll handler for better performance
- const throttledTimelineScroll = useMemo(
- () => throttle(handleTimelineScroll, 16), // ~60fps
- [handleTimelineScroll],
- );
-
- // Add scroll event listener to timeline with throttling
- useEffect(() => {
- const timelineContainer = timelineRef.current;
- if (!timelineContainer) return;
-
- timelineContainer.addEventListener("scroll", throttledTimelineScroll);
-
- return () => {
- timelineContainer.removeEventListener(
- "scroll",
- throttledTimelineScroll,
- );
- };
- }, [throttledTimelineScroll, handleTimelineScroll]);
-
- // Function to scroll timeline to specific location
- const scrollTimelineToLocation = useCallback(
- (locationIndex: number) => {
- if (
- !timelineRef.current ||
- locationIndex < 0 ||
- locationIndex >= photoClusters.length ||
- locationPositions.length === 0
- )
- return;
-
- const timelineContainer = timelineRef.current;
- const scrollHeight = timelineContainer.scrollHeight;
- const clientHeight = timelineContainer.clientHeight;
- const maxScrollableDistance = scrollHeight - clientHeight;
-
- // Calculate what scroll position would give us progress to this location
- // We want progress = locationIndex / (totalLocations - 1)
- const targetProgress =
- locationIndex / Math.max(1, photoClusters.length - 1);
- const targetScrollTop = targetProgress * maxScrollableDistance;
-
- // Note: scroll progress is now set in the click handler before calling this function
- // to ensure immediate visual feedback
-
- // Smooth scroll to the calculated position
- timelineContainer.scrollTo({
- top: Math.max(
- 0,
- Math.min(targetScrollTop, maxScrollableDistance),
- ),
- behavior: "smooth",
- });
- },
- [photoClusters, timelineRef, locationPositions],
- );
-
- // Shared marker click handler to avoid duplication
- const handleMarkerClick = useCallback(
- (clusterIndex: number, clusterLat: number, clusterLng: number) => {
- // Calculate target progress for immediate update
- const targetProgress =
- clusterIndex / Math.max(1, photoClusters.length - 1);
-
- // Clear any existing timeout
- if (clusterClickTimeoutRef.current) {
- clearTimeout(clusterClickTimeoutRef.current);
- }
-
- // Block scroll handler during cluster click
- isClusterClickScrollingRef.current = true;
-
- // Immediately update scroll progress to show green state
- setScrollProgress(targetProgress);
-
- // Calculate positioning offset for timeline visibility
- const allClusterLngs = photoClusters.map(
- (cluster) =>
- cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length,
- );
- const minLng = Math.min(...allClusterLngs);
- const maxLng = Math.max(...allClusterLngs);
- const lngSpan = maxLng - minLng;
- const paddedSpan = Math.max(lngSpan * 1.4, 0.1);
-
- 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);
- const offsetLng = clusterLng - shiftAmount;
-
- if (mapRef) {
- const currentZoom = mapRef.getZoom();
- if (currentZoom > optimalZoom) {
- mapRef.flyTo([clusterLat, offsetLng], optimalZoom, {
- animate: true,
- duration: 1.2,
- easeLinearity: 0.25,
- });
- } else {
- mapRef.panTo([clusterLat, offsetLng], {
- animate: true,
- duration: 1.0,
- });
- }
- }
-
- // Start timeline scrolling and set timeout to re-enable handler
- setTimeout(() => {
- scrollTimelineToLocation(clusterIndex);
- }, 50);
-
- // Re-enable scroll handler after animation completes
- clusterClickTimeoutRef.current = setTimeout(() => {
- isClusterClickScrollingRef.current = false;
- clusterClickTimeoutRef.current = null;
- }, 1500);
- },
- [
- photoClusters,
- screenDimensions,
- mapRef,
- optimalZoom,
- scrollTimelineToLocation,
- ],
- );
+ locationRefs,
+ isClusterClickScrollingRef,
+ clusterClickTimeoutRef,
+ setLocationPositions,
+ setHasUserScrolled,
+ setScrollProgress,
+ });
// Only wait for client-side rendering (needed for maps), but show layout immediately
// Let individual components handle their own loading states
@@ -750,8 +233,20 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
<LoadingCoverImage>
<CoverGradientOverlay />
<CoverPlaceholderContent>
- <PlaceholderTextBox sx={{ height: '30px', width: '200px', mb: '2px' }} />
- <PlaceholderTextBox sx={{ height: '16px', width: '120px', margin: 0 }} />
+ <PlaceholderTextBox
+ sx={{
+ height: "30px",
+ width: "200px",
+ mb: "2px",
+ }}
+ />
+ <PlaceholderTextBox
+ sx={{
+ height: "16px",
+ width: "120px",
+ margin: 0,
+ }}
+ />
</CoverPlaceholderContent>
</LoadingCoverImage>
<LoadingSpinnerContainer>
@@ -819,7 +314,7 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
</div>
) : (
<NoPhotosContainer>
- <Box sx={{ color: 'text.muted' }}>
+ <Box sx={{ color: "text.muted" }}>
No photos with location data found.
</Box>
</NoPhotosContainer>
@@ -841,7 +336,7 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
setMapRef={setMapRef}
setCurrentZoom={setCurrentZoom}
setTargetZoom={setTargetZoom}
- onMarkerClick={handleMarkerClick}
+ onMarkerClick={markerClickHandler}
/>
{/* FileViewer for photo gallery */}
@@ -888,13 +383,9 @@ const TimelineSidebar = styled(Box)(({ theme }) => ({
borderRadius: "48px",
}));
-const TimelineContent = styled(Box)({
- padding: "32px",
-});
+const TimelineContent = styled(Box)({ padding: "32px" });
-const LoadingCoverPlaceholder = styled(Box)({
- marginBottom: "96px",
-});
+const LoadingCoverPlaceholder = styled(Box)({ marginBottom: "96px" });
const LoadingCoverImage = styled(Box)(({ theme }) => ({
aspectRatio: "16/8",
@@ -904,10 +395,7 @@ const LoadingCoverImage = styled(Box)(({ theme }) => ({
overflow: "hidden",
backgroundColor: theme.palette.grey[200],
animation: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
- "@keyframes pulse": {
- "0%, 100%": { opacity: 1 },
- "50%": { opacity: 0.5 },
- },
+ "@keyframes pulse": { "0%, 100%": { opacity: 1 }, "50%": { opacity: 0.5 } },
}));
const CoverGradientOverlay = styled(Box)({
@@ -966,10 +454,6 @@ const LocationsLoadingContainer = styled(Box)({
alignItems: "center",
});
-const TimelineContainer = styled(Box)({
- position: "relative",
-});
+const TimelineContainer = styled(Box)({ position: "relative" });
-const NoPhotosContainer = styled(Box)({
- textAlign: "center",
-});
+const NoPhotosContainer = styled(Box)({ textAlign: "center" });
diff --git a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
index 9223381640..b0d70b2c97 100644
--- a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
+++ b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
@@ -1,6 +1,6 @@
import L from "leaflet";
import type { JourneyPoint } from "./types";
-import { iconCache } from "./utils";
+import { iconCache } from "./utils/geocoding";
// Geographic clustering with responsive distance thresholds and day separation
export const clusterPhotosByProximity = (
diff --git a/web/apps/photos/src/components/TripTemplate/utils/dataProcessing.ts b/web/apps/photos/src/components/TripTemplate/utils/dataProcessing.ts
new file mode 100644
index 0000000000..5414ca2f25
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/utils/dataProcessing.ts
@@ -0,0 +1,191 @@
+import React from "react";
+import { downloadManager } from "ente-gallery/services/download";
+import { type EnteFile } from "ente-media/file";
+import { fileFileName } from "ente-media/file-metadata";
+
+import { getLocationName } from "./geocoding";
+import type { JourneyPoint } from "../types";
+
+export interface ProcessPhotosDataParams {
+ files: EnteFile[];
+ locationDataRef: React.MutableRefObject<Map<number, { name: string; country: string }>>;
+}
+
+export interface ProcessPhotosDataResult {
+ photoData: JourneyPoint[];
+ hasLocationData: boolean;
+}
+
+export const processPhotosData = ({
+ files,
+ locationDataRef,
+}: ProcessPhotosDataParams): ProcessPhotosDataResult => {
+ const photoData: JourneyPoint[] = [];
+
+ if (files.length === 0) {
+ return { photoData, hasLocationData: false };
+ }
+
+ for (const file of files) {
+ try {
+ const lat = file.metadata.latitude;
+ const lng = file.metadata.longitude;
+
+ if (lat && lng) {
+ const cachedLocation = locationDataRef.current.get(file.id);
+ const finalName = cachedLocation?.name || fileFileName(file);
+ const finalCountry = cachedLocation?.country || "Unknown";
+
+ photoData.push({
+ lat: lat,
+ lng: lng,
+ name: finalName,
+ country: finalCountry,
+ timestamp: new Date(file.metadata.creationTime / 1000).toISOString(),
+ image: "",
+ fileId: file.id,
+ });
+ }
+ } catch {
+ // Silently ignore processing errors for individual files
+ }
+ }
+
+ photoData.sort(
+ (a, b) =>
+ new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
+ );
+
+ return { photoData, hasLocationData: photoData.length > 0 };
+};
+
+export interface FetchLocationNamesParams {
+ photoClusters: JourneyPoint[][];
+ journeyData: JourneyPoint[];
+ locationDataRef: React.MutableRefObject<Map<number, { name: string; country: string }>>;
+}
+
+export interface FetchLocationNamesResult {
+ updatedPhotos: Map<number, { name: string; country: string }>;
+}
+
+export const fetchLocationNames = async ({
+ photoClusters,
+ locationDataRef,
+}: FetchLocationNamesParams): Promise<FetchLocationNamesResult> => {
+ const updatedPhotos = new Map<number, { name: string; country: string }>();
+
+ if (photoClusters.length === 0) {
+ return { updatedPhotos };
+ }
+
+ for (let i = 0; i < photoClusters.length; i++) {
+ const cluster = photoClusters[i];
+ if (!cluster || cluster.length === 0) continue;
+
+ const avgLat = cluster.reduce((sum, p) => sum + p.lat, 0) / cluster.length;
+ const avgLng = cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length;
+
+ try {
+ const locationInfo = await getLocationName(avgLat, avgLng, i + 1);
+
+ cluster.forEach((photo) => {
+ updatedPhotos.set(photo.fileId, {
+ name: locationInfo.place,
+ country: locationInfo.country,
+ });
+ locationDataRef.current.set(photo.fileId, {
+ name: locationInfo.place,
+ country: locationInfo.country,
+ });
+ });
+ } catch {
+ // Silently ignore processing errors for individual files
+ }
+ }
+
+ return { updatedPhotos };
+};
+
+export interface GenerateThumbnailsParams {
+ photoClusters: JourneyPoint[][];
+ files: EnteFile[];
+}
+
+export interface GenerateThumbnailsResult {
+ thumbnailUpdates: Map<number, string>;
+}
+
+export const generateNeededThumbnails = async ({
+ photoClusters,
+ files,
+}: GenerateThumbnailsParams): Promise<GenerateThumbnailsResult> => {
+ const thumbnailUpdates = new Map<number, string>();
+
+ if (photoClusters.length === 0) {
+ return { thumbnailUpdates };
+ }
+
+ const neededFileIds = new Set<number>();
+
+ photoClusters.forEach((cluster) => {
+ cluster.slice(0, 3).forEach((photo) => {
+ neededFileIds.add(photo.fileId);
+ });
+ });
+
+ const filesToProcess = files.filter((file) => neededFileIds.has(file.id));
+
+ for (const file of filesToProcess) {
+ try {
+ const thumbnailUrl = await downloadManager.renderableThumbnailURL(file);
+ if (thumbnailUrl) {
+ thumbnailUpdates.set(file.id, thumbnailUrl);
+ }
+ } catch {
+ // Silently ignore thumbnail generation errors
+ }
+ }
+
+ return { thumbnailUpdates };
+};
+
+export interface LoadCoverImageParams {
+ journeyData: JourneyPoint[];
+ files: EnteFile[];
+ collection?: { pubMagicMetadata?: { data: { coverID?: number } } };
+}
+
+export const loadCoverImage = async ({
+ journeyData,
+ files,
+ collection,
+}: LoadCoverImageParams): Promise<string | null> => {
+ if (journeyData.length === 0) return null;
+
+ let coverFile: EnteFile | undefined;
+
+ const coverID = collection?.pubMagicMetadata?.data.coverID;
+ if (coverID) {
+ coverFile = files.find((f) => f.id === coverID);
+ }
+
+ if (!coverFile) {
+ const firstPhoto = journeyData[0];
+ if (!firstPhoto) return null;
+ coverFile = files.find((f) => f.id === firstPhoto.fileId);
+ }
+
+ if (!coverFile) return null;
+
+ try {
+ const sourceURLs = await downloadManager.renderableSourceURLs(coverFile);
+ if (sourceURLs.type === "image") {
+ return sourceURLs.imageURL;
+ }
+ } catch {
+ // Keep using thumbnail if high quality fails
+ }
+
+ return null;
+};
\ 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/geocoding.ts
similarity index 100%
rename from web/apps/photos/src/components/TripTemplate/utils.ts
rename to web/apps/photos/src/components/TripTemplate/utils/geocoding.ts
diff --git a/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
new file mode 100644
index 0000000000..6498269130
--- /dev/null
+++ b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
@@ -0,0 +1,282 @@
+import L from "leaflet";
+import { startTransition } from "react";
+
+import type { JourneyPoint } from "../types";
+
+export interface PositionInfo {
+ top: number;
+ center: number;
+}
+
+export interface UpdateLocationPositionsParams {
+ locationRefs: (HTMLDivElement | null)[];
+ setLocationPositions: (positions: PositionInfo[]) => void;
+}
+
+export const updateLocationPositions = ({
+ locationRefs,
+ setLocationPositions,
+}: UpdateLocationPositionsParams) => {
+ if (locationRefs.length === 0) return;
+
+ const positions = locationRefs.map((ref) => {
+ if (!ref) return { top: 0, center: 0 };
+ const rect = ref.getBoundingClientRect();
+ const top = ref.offsetTop;
+ const center = top + rect.height / 2;
+ return { top, center };
+ });
+
+ startTransition(() => {
+ setLocationPositions(positions);
+ });
+};
+
+export interface HandleTimelineScrollParams {
+ timelineRef: React.RefObject<HTMLDivElement | null>;
+ photoClusters: JourneyPoint[][];
+ locationPositions: PositionInfo[];
+ mapRef: L.Map | null;
+ screenDimensions: { width: number; height: number };
+ optimalZoom: number;
+ isClusterClickScrollingRef: React.MutableRefObject<boolean>;
+ setHasUserScrolled: (scrolled: boolean) => void;
+ setScrollProgress: (progress: number) => void;
+}
+
+export const handleTimelineScroll = ({
+ timelineRef,
+ photoClusters,
+ locationPositions,
+ mapRef,
+ screenDimensions,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ setHasUserScrolled,
+ setScrollProgress,
+}: HandleTimelineScrollParams) => {
+ if (
+ !timelineRef.current ||
+ photoClusters.length === 0 ||
+ locationPositions.length === 0
+ )
+ return;
+
+ const timelineContainer = timelineRef.current;
+ const scrollHeight = timelineContainer.scrollHeight;
+ const clientHeight = timelineContainer.clientHeight;
+ const scrollTop = timelineContainer.scrollTop;
+
+ const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
+ let progress = 0;
+ if (isAtBottom) {
+ progress = 1;
+ } else {
+ const maxScrollableDistance = scrollHeight - clientHeight;
+ if (maxScrollableDistance > 0) {
+ progress = scrollTop / maxScrollableDistance;
+ } else {
+ progress = 0;
+ }
+ }
+ const clampedProgress = Math.min(1, Math.max(0, progress));
+
+ if (isClusterClickScrollingRef.current) {
+ return;
+ }
+
+ setHasUserScrolled(true);
+ startTransition(() => {
+ setScrollProgress(clampedProgress);
+ });
+
+ if (mapRef && !isClusterClickScrollingRef.current) {
+ 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 };
+ });
+
+ if (clusterCenters.length > 0) {
+ let targetLat, targetLng;
+
+ const firstCenter = clusterCenters[0];
+ const lastCenter = clusterCenters[clusterCenters.length - 1];
+ if (!firstCenter || !lastCenter) return;
+
+ if (clampedProgress <= 0) {
+ targetLat = firstCenter.lat;
+ targetLng = firstCenter.lng;
+ } else if (clampedProgress === 1) {
+ targetLat = lastCenter.lat;
+ targetLng = lastCenter.lng;
+ } else {
+ const clusterProgress = clampedProgress * (clusterCenters.length - 1);
+ const currentClusterIndex = Math.floor(clusterProgress);
+ const nextClusterIndex = Math.min(
+ currentClusterIndex + 1,
+ clusterCenters.length - 1,
+ );
+ const lerpFactor = clusterProgress - currentClusterIndex;
+
+ const currentCluster = clusterCenters[currentClusterIndex];
+ const nextCluster = clusterCenters[nextClusterIndex];
+
+ if (!currentCluster || !nextCluster) {
+ targetLat = clusterCenters[0]?.lat || 0;
+ targetLng = clusterCenters[0]?.lng || 0;
+ } else {
+ targetLat =
+ currentCluster.lat +
+ (nextCluster.lat - currentCluster.lat) * lerpFactor;
+ targetLng =
+ currentCluster.lng +
+ (nextCluster.lng - currentCluster.lng) * lerpFactor;
+ }
+ }
+
+ const isMobile = screenDimensions.width < 768;
+ const timelineSizeRatio = isMobile ? 0.5 : 0.5;
+
+ 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);
+
+ const mapSizeRatio = 1 - timelineSizeRatio;
+ const screenWidthInDegrees = paddedSpan / mapSizeRatio;
+ const shiftAmount = screenWidthInDegrees * (timelineSizeRatio / 2);
+
+ const adjustedLng = targetLng - shiftAmount;
+
+ const currentMapZoom = mapRef.getZoom();
+
+ if (currentMapZoom !== optimalZoom) {
+ mapRef.flyTo([targetLat, adjustedLng], optimalZoom, {
+ animate: true,
+ duration: 0.5,
+ easeLinearity: 0.5,
+ });
+ } else {
+ mapRef.panTo([targetLat, adjustedLng], {
+ animate: true,
+ duration: 0.3,
+ easeLinearity: 0.8,
+ });
+ }
+ }
+ }
+};
+
+export interface ScrollTimelineToLocationParams {
+ timelineRef: React.RefObject<HTMLDivElement | null>;
+ locationIndex: number;
+ photoClusters: JourneyPoint[][];
+ locationPositions: PositionInfo[];
+}
+
+export const scrollTimelineToLocation = ({
+ timelineRef,
+ locationIndex,
+ photoClusters,
+ locationPositions,
+}: ScrollTimelineToLocationParams) => {
+ if (
+ !timelineRef.current ||
+ locationIndex < 0 ||
+ locationIndex >= photoClusters.length ||
+ locationPositions.length === 0
+ )
+ return;
+
+ const timelineContainer = timelineRef.current;
+ const scrollHeight = timelineContainer.scrollHeight;
+ const clientHeight = timelineContainer.clientHeight;
+ const maxScrollableDistance = scrollHeight - clientHeight;
+
+ const targetProgress = locationIndex / Math.max(1, photoClusters.length - 1);
+ const targetScrollTop = targetProgress * maxScrollableDistance;
+
+ timelineContainer.scrollTo({
+ top: Math.max(0, Math.min(targetScrollTop, maxScrollableDistance)),
+ behavior: "smooth",
+ });
+};
+
+export interface HandleMarkerClickParams {
+ clusterIndex: number;
+ clusterLat: number;
+ clusterLng: number;
+ photoClusters: JourneyPoint[][];
+ screenDimensions: { width: number; height: number };
+ mapRef: L.Map | null;
+ optimalZoom: number;
+ isClusterClickScrollingRef: React.MutableRefObject<boolean>;
+ clusterClickTimeoutRef: React.MutableRefObject<NodeJS.Timeout | null>;
+ setScrollProgress: (progress: number) => void;
+ scrollTimelineToLocation: (locationIndex: number) => void;
+}
+
+export const handleMarkerClick = ({
+ clusterIndex,
+ clusterLat,
+ clusterLng,
+ photoClusters,
+ screenDimensions,
+ mapRef,
+ optimalZoom,
+ isClusterClickScrollingRef,
+ clusterClickTimeoutRef,
+ setScrollProgress,
+ scrollTimelineToLocation,
+}: HandleMarkerClickParams) => {
+ const targetProgress = clusterIndex / Math.max(1, photoClusters.length - 1);
+
+ if (clusterClickTimeoutRef.current) {
+ clearTimeout(clusterClickTimeoutRef.current);
+ }
+
+ isClusterClickScrollingRef.current = true;
+ setScrollProgress(targetProgress);
+
+ const allClusterLngs = photoClusters.map(
+ (cluster) => cluster.reduce((sum, p) => sum + p.lng, 0) / cluster.length,
+ );
+ const minLng = Math.min(...allClusterLngs);
+ const maxLng = Math.max(...allClusterLngs);
+ const lngSpan = maxLng - minLng;
+ const paddedSpan = Math.max(lngSpan * 1.4, 0.1);
+
+ 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);
+ const offsetLng = clusterLng - shiftAmount;
+
+ if (mapRef) {
+ const currentZoom = mapRef.getZoom();
+ if (currentZoom > optimalZoom) {
+ mapRef.flyTo([clusterLat, offsetLng], optimalZoom, {
+ animate: true,
+ duration: 1.2,
+ easeLinearity: 0.25,
+ });
+ } else {
+ mapRef.panTo([clusterLat, offsetLng], {
+ animate: true,
+ duration: 1.0,
+ });
+ }
+ }
+
+ setTimeout(() => {
+ scrollTimelineToLocation(clusterIndex);
+ }, 50);
+
+ clusterClickTimeoutRef.current = setTimeout(() => {
+ isClusterClickScrollingRef.current = false;
+ clusterClickTimeoutRef.current = null;
+ }, 1500);
+};
\ No newline at end of file