Skip to content

armgit / ente

Public Imported from GitHub
0

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

fix: better interaction for multi country trips

anandbaburajand1b095d383b0
diff --git a/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts b/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts
index f0d026c144..ddb1d98f07 100644
--- a/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts
+++ b/web/apps/photos/src/components/TripTemplate/hooks/useScrollHandling.ts
@@ -15,10 +15,10 @@ export interface UseScrollHandlingParams {
photoClusters: JourneyPoint[][];
locationPositions: PositionInfo[];
mapRef: L.Map | null;
- optimalZoom: number;
locationRefs: React.RefObject<(HTMLDivElement | null)[]>;
isClusterClickScrollingRef: React.RefObject<boolean>;
clusterClickTimeoutRef: React.RefObject<NodeJS.Timeout | null>;
+ previousActiveLocationRef: React.RefObject<number>;
setLocationPositions: (positions: PositionInfo[]) => void;
setHasUserScrolled: (scrolled: boolean) => void;
setScrollProgress: (progress: number) => void;
@@ -29,10 +29,10 @@ export const useScrollHandling = ({
photoClusters,
locationPositions,
mapRef,
- optimalZoom,
locationRefs,
isClusterClickScrollingRef,
clusterClickTimeoutRef,
+ previousActiveLocationRef,
setLocationPositions,
setHasUserScrolled,
setScrollProgress,
@@ -52,20 +52,20 @@ export const useScrollHandling = ({
photoClusters,
locationPositions,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
setHasUserScrolled,
setScrollProgress,
+ previousActiveLocationRef,
});
}, [
timelineRef,
photoClusters,
locationPositions,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
setHasUserScrolled,
setScrollProgress,
+ previousActiveLocationRef,
]);
// Throttled scroll handler
@@ -96,7 +96,6 @@ export const useScrollHandling = ({
clusterLng,
photoClusters,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
clusterClickTimeoutRef,
setScrollProgress,
@@ -107,7 +106,6 @@ export const useScrollHandling = ({
[
photoClusters,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
clusterClickTimeoutRef,
setScrollProgress,
diff --git a/web/apps/photos/src/components/TripTemplate/index.tsx b/web/apps/photos/src/components/TripTemplate/index.tsx
index 8e45b71063..0173a13116 100644
--- a/web/apps/photos/src/components/TripTemplate/index.tsx
+++ b/web/apps/photos/src/components/TripTemplate/index.tsx
@@ -89,10 +89,6 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
const [targetZoom, setTargetZoom] = useState<number | null>(null);
const [scrollProgress, setScrollProgress] = useState(0); // 0 to 1 representing scroll progress
const [hasUserScrolled, setHasUserScrolled] = useState(false); // Track if user has actually scrolled
- const [screenDimensions, setScreenDimensions] = useState<{
- width: number;
- height: number;
- }>({ width: 1400, height: 800 });
const [locationPositions, setLocationPositions] = useState<PositionInfo[]>(
[],
);
@@ -105,28 +101,8 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
Map<number, { name: string; country: string }>
>(new Map()); // Track location data to prevent resets
const filesCountRef = useRef<number>(0); // Track files count to detect real changes
+ const previousActiveLocationRef = useRef<number>(-1); // Track previous active location for discrete panning
- // Track screen dimensions for responsive zoom calculation
- useEffect(() => {
- const updateScreenDimensions = () => {
- if (typeof window !== "undefined") {
- setScreenDimensions({
- width: window.innerWidth,
- height: window.innerHeight,
- });
- }
- };
-
- // Set initial dimensions
- updateScreenDimensions();
-
- // Listen for window resize
- window.addEventListener("resize", updateScreenDimensions);
-
- return () => {
- window.removeEventListener("resize", updateScreenDimensions);
- };
- }, []);
const photoClusters = useMemo(() => {
const clusters = clusterPhotosByProximity(journeyData);
@@ -145,8 +121,8 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
// Calculate optimal zoom level based on cluster spread
const optimalZoom = useMemo(() => {
- return calculateOptimalZoom(photoClusters, screenDimensions);
- }, [photoClusters, screenDimensions]);
+ return calculateOptimalZoom();
+ }, []);
// Update currentZoom when optimalZoom changes and there's no mapRef yet
useEffect(() => {
@@ -196,10 +172,10 @@ export const TripTemplate: React.FC<TripTemplateProps> = ({
photoClusters,
locationPositions,
mapRef,
- optimalZoom,
locationRefs,
isClusterClickScrollingRef,
clusterClickTimeoutRef,
+ previousActiveLocationRef,
setLocationPositions,
setHasUserScrolled,
setScrollProgress,
diff --git a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
index d0046166b7..1a787ab1aa 100644
--- a/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
+++ b/web/apps/photos/src/components/TripTemplate/mapHelpers.ts
@@ -2,6 +2,26 @@ import L from "leaflet";
import type { JourneyPoint } from "./types";
import { iconCache } from "./utils/geocoding";
+// Calculate distance between two points using Haversine formula (returns distance in km)
+export const calculateDistance = (
+ lat1: number,
+ lng1: number,
+ lat2: number,
+ lng2: number,
+): number => {
+ const R = 6371; // Radius of Earth in kilometers
+ const dLat = (lat2 - lat1) * (Math.PI / 180);
+ const dLng = (lng2 - lng1) * (Math.PI / 180);
+ const a =
+ Math.sin(dLat / 2) * Math.sin(dLat / 2) +
+ Math.cos(lat1 * (Math.PI / 180)) *
+ Math.cos(lat2 * (Math.PI / 180)) *
+ Math.sin(dLng / 2) *
+ Math.sin(dLng / 2);
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+ return R * c;
+};
+
// Geographic clustering with responsive distance thresholds and day separation
export const clusterPhotosByProximity = (photos: JourneyPoint[]) => {
if (photos.length === 0) return [];
@@ -54,96 +74,10 @@ export const clusterPhotosByProximity = (photos: JourneyPoint[]) => {
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
- const timelineSizeRatio = 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 fixed zoom level of 10 for consistent positioning
+export const calculateOptimalZoom = (): number => {
+ // Return fixed zoom of 10 as per new requirements
+ return 10;
};
// Function to create icon with specific image and progress styling
@@ -496,7 +430,7 @@ export const detectScreenCollisions = (
return { superClusters, visibleClusters };
};
-// Calculate map center - start at first location to match timeline initial state
+// Calculate map center with first location positioned at 20% from right edge
export const getMapCenter = (
photoClusters: JourneyPoint[][],
journeyData: JourneyPoint[],
@@ -508,7 +442,7 @@ export const getMapCenter = (
return [firstPoint.lat, firstPoint.lng];
}
- // Start at first cluster center to match the timeline starting position
+ // Start at first cluster center
const firstCluster = photoClusters[0];
if (!firstCluster || firstCluster.length === 0) return [0, 0]; // Fallback, but map won't render anyway
@@ -517,29 +451,32 @@ export const getMapCenter = (
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 timelineSizeRatio = 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;
+ // Position first location at 20% from right edge (80% from left)
+ // At zoom level 10, each pixel represents approximately 152.87 meters
+ // Timeline takes up 50% of screen width, so visible map area is 50%
+ // We want the first location to be at 20% from right of the visible map area
+ // This means 80% from left of visible map, or 40% from left of total screen
+
+ const timelineWidthRatio = 0.5; // Timeline takes up 50% of screen
+
+ // At zoom 10, approximately 0.35 degrees per 1000px at equator
+ // For positioning, we need to shift the longitude to place marker at desired position
+ const degreesPerPixelAtZoom10 = 0.35 / 1000; // rough approximation
+ const pixelsToShiftFor20Percent = (window.innerWidth || 1400) * timelineWidthRatio * 0.3; // 30% of visible map width
+ const lngShift = pixelsToShiftFor20Percent * degreesPerPixelAtZoom10;
+
+ const adjustedLng = firstLng - lngShift;
return [firstLat, adjustedLng];
};
+
+// Calculate position for a location to be at 20% from right edge of visible map
+export const getLocationPosition = (lat: number, lng: number): [number, number] => {
+ // Position location at 20% from right edge (80% from left) of visible map area
+ const timelineWidthRatio = 0.5; // Timeline takes up 50% of screen
+ const degreesPerPixelAtZoom10 = 0.35 / 1000; // rough approximation at zoom 10
+ const pixelsToShiftFor20Percent = (window.innerWidth || 1400) * timelineWidthRatio * 0.3; // 30% of visible map width
+ const lngShift = pixelsToShiftFor20Percent * degreesPerPixelAtZoom10;
+
+ return [lat, lng - lngShift];
+};
diff --git a/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
index b00a883262..1cab564798 100644
--- a/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
+++ b/web/apps/photos/src/components/TripTemplate/utils/scrollUtils.ts
@@ -1,6 +1,7 @@
import L from "leaflet";
import { startTransition } from "react";
+import { calculateDistance, getLocationPosition } from "../mapHelpers";
import type { JourneyPoint } from "../types";
export interface PositionInfo {
@@ -37,10 +38,10 @@ export interface HandleTimelineScrollParams {
photoClusters: JourneyPoint[][];
locationPositions: PositionInfo[];
mapRef: L.Map | null;
- optimalZoom: number;
isClusterClickScrollingRef: React.RefObject<boolean>;
setHasUserScrolled: (scrolled: boolean) => void;
setScrollProgress: (progress: number) => void;
+ previousActiveLocationRef: React.RefObject<number>;
}
export const handleTimelineScroll = ({
@@ -48,10 +49,10 @@ export const handleTimelineScroll = ({
photoClusters,
locationPositions,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
setHasUserScrolled,
setScrollProgress,
+ previousActiveLocationRef,
}: HandleTimelineScrollParams) => {
if (
!timelineRef.current ||
@@ -65,6 +66,7 @@ export const handleTimelineScroll = ({
const clientHeight = timelineContainer.clientHeight;
const scrollTop = timelineContainer.scrollTop;
+ // Calculate scroll progress (0 to 1)
const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
let progress = 0;
if (isAtBottom) {
@@ -88,81 +90,72 @@ export const handleTimelineScroll = ({
setScrollProgress(clampedProgress);
});
- if (mapRef) {
+ // Calculate current active location index based on scroll progress
+ const currentActiveLocationIndex = Math.round(clampedProgress * Math.max(0, photoClusters.length - 1));
+ const previousActiveLocationIndex = previousActiveLocationRef.current;
+
+ // Only pan map when active location changes (discrete panning)
+ if (mapRef && currentActiveLocationIndex !== previousActiveLocationIndex) {
+ previousActiveLocationRef.current = currentActiveLocationIndex;
+
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;
+ 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 targetCluster = clusterCenters[currentActiveLocationIndex];
+ if (!targetCluster) return;
+
+ // Position active location at 20% from right edge
+ const [positionedLat, positionedLng] = getLocationPosition(targetCluster.lat, targetCluster.lng);
+
+ // Check if this is a distant location (>500km from previous)
+ let isDistantLocation = false;
+ if (previousActiveLocationIndex !== -1 && previousActiveLocationIndex !== currentActiveLocationIndex) {
+ const previousCluster = clusterCenters[previousActiveLocationIndex];
+ if (previousCluster) {
+ const distance = calculateDistance(
+ previousCluster.lat,
+ previousCluster.lng,
+ targetCluster.lat,
+ targetCluster.lng
);
- 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;
- }
+ isDistantLocation = distance > 500; // 500km threshold
}
+ }
- const timelineSizeRatio = 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 targetZoom = 10; // Fixed zoom level
+ if (isDistantLocation) {
+ // For distant locations: zoom out β†’ pan β†’ zoom in
+ mapRef.flyTo([positionedLat, positionedLng], 4, {
+ animate: true,
+ duration: 0.8,
+ easeLinearity: 0.3,
+ });
+
+ setTimeout(() => {
+ mapRef.flyTo([positionedLat, positionedLng], targetZoom, {
+ animate: true,
+ duration: 0.6,
+ easeLinearity: 0.3,
+ });
+ }, 900);
+ } else {
+ // For nearby locations: simple pan to target location
const currentMapZoom = mapRef.getZoom();
-
- if (currentMapZoom !== optimalZoom) {
- mapRef.flyTo([targetLat, adjustedLng], optimalZoom, {
+ if (Math.abs(currentMapZoom - targetZoom) > 0.5) {
+ mapRef.flyTo([positionedLat, positionedLng], targetZoom, {
animate: true,
- duration: 0.5,
- easeLinearity: 0.5,
+ duration: 0.8,
+ easeLinearity: 0.3,
});
} else {
- mapRef.panTo([targetLat, adjustedLng], {
+ mapRef.panTo([positionedLat, positionedLng], {
animate: true,
- duration: 0.3,
- easeLinearity: 0.8,
+ duration: 0.8,
+ easeLinearity: 0.3,
});
}
}
@@ -211,7 +204,6 @@ export interface HandleMarkerClickParams {
clusterLng: number;
photoClusters: JourneyPoint[][];
mapRef: L.Map | null;
- optimalZoom: number;
isClusterClickScrollingRef: React.RefObject<boolean>;
clusterClickTimeoutRef: React.RefObject<NodeJS.Timeout | null>;
setScrollProgress: (progress: number) => void;
@@ -225,7 +217,6 @@ export const handleMarkerClick = ({
clusterLng,
photoClusters,
mapRef,
- optimalZoom,
isClusterClickScrollingRef,
clusterClickTimeoutRef,
setScrollProgress,
@@ -242,35 +233,16 @@ export const handleMarkerClick = ({
setScrollProgress(targetProgress);
setHasUserScrolled(true);
- 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 timelineSizeRatio = 0.5;
- const mapSizeRatio = 1 - timelineSizeRatio;
- const screenWidthInDegrees = paddedSpan / mapSizeRatio;
- const shiftAmount = screenWidthInDegrees * (timelineSizeRatio / 2);
- const offsetLng = clusterLng - shiftAmount;
+ // Position clicked location at 20% from right edge
+ const [positionedLat, positionedLng] = getLocationPosition(clusterLat, clusterLng);
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,
- });
- }
+ const targetZoom = 10; // Fixed zoom level
+ mapRef.flyTo([positionedLat, positionedLng], targetZoom, {
+ animate: true,
+ duration: 1.0,
+ easeLinearity: 0.3,
+ });
}
setTimeout(() => {