Skip to content

armgit / ente

Public Imported from GitHub
0

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

[web][photos] Add edit location dialog for selected files

Anand Baburajan0343a427159a
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index de12de1ddb..99d7b0954c 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -42,6 +42,7 @@ import {
masterKeyFromSession,
} from "ente-base/session";
import { savedAuthToken } from "ente-base/token";
+import type { Location } from "ente-base/types";
import { FullScreenDropZone } from "ente-gallery/components/FullScreenDropZone";
import { type UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
@@ -57,6 +58,7 @@ import {
CollectionSelector,
type CollectionSelectorAttributes,
} from "ente-new/photos/components/CollectionSelector";
+import { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";
import { Export } from "ente-new/photos/components/Export";
import { PlanSelector } from "ente-new/photos/components/PlanSelector";
import {
@@ -102,7 +104,10 @@ import {
PseudoCollectionID,
} from "ente-new/photos/services/collection-summary";
import exportService from "ente-new/photos/services/export";
-import { updateFilesVisibility } from "ente-new/photos/services/file";
+import {
+ updateFilesLocation,
+ updateFilesVisibility,
+} from "ente-new/photos/services/file";
import { addManualFileAssignmentsToPerson } from "ente-new/photos/services/ml";
import {
savedCollectionFiles,
@@ -258,6 +263,8 @@ const Page: React.FC = () => {
} = useModalVisibility();
const { show: showAlbumNameInput, props: albumNameInputVisibilityProps } =
useModalVisibility();
+ const { show: showEditLocation, props: editLocationVisibilityProps } =
+ useModalVisibility();
// Progress UI state for single-file add-to-album from the FileViewer
const [addToAlbumProgress, setAddToAlbumProgress] = useState<{
@@ -957,6 +964,25 @@ const Page: React.FC = () => {
[selected, filteredFiles, clearSelection],
);
+ const handleEditLocationConfirm = useCallback(
+ async (location: Location) => {
+ const selectedFiles = getSelectedFiles(selected, filteredFiles);
+ // Only update files owned by the user
+ const userFiles = selectedFiles.filter(
+ (f) => f.ownerID == user!.id,
+ );
+ if (userFiles.length > 0) {
+ await updateFilesLocation(
+ userFiles,
+ location.latitude,
+ location.longitude,
+ );
+ }
+ void remotePull({ silent: true });
+ },
+ [selected, filteredFiles, user, remotePull],
+ );
+
const handleSelectSearchOption = (
searchOption: SearchOption | undefined,
options?: { shouldExitSearchMode?: boolean },
@@ -1326,6 +1352,7 @@ const Page: React.FC = () => {
onAddPersonToSelectedFiles:
handleAddPersonToSelectedFiles,
}}
+ onEditLocation={showEditLocation}
/>
) : barMode == "hidden-albums" ? (
<HiddenSectionNavbarContents
@@ -1517,6 +1544,11 @@ const Page: React.FC = () => {
phase={addToAlbumProgress.phase}
albumName={addToAlbumProgress.albumName}
/>
+ <EditLocationDialog
+ {...editLocationVisibilityProps}
+ files={getSelectedFiles(selected, filteredFiles)}
+ onConfirm={handleEditLocationConfirm}
+ />
</FullScreenDropZone>
);
};
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index 99e2595602..1b9c2e9b8a 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -799,5 +799,8 @@
"continuous": "Continuous",
"trip": "Trip",
"album_layout": "Album layout",
- "maps_privacy_notice": "Approximate coordinates will be sent to privacy conscious third parties like OpenStreetMap to show the map and location."
+ "maps_privacy_notice": "Approximate coordinates will be sent to privacy conscious third parties like OpenStreetMap to show the map and location.",
+ "edit_location": "Edit location",
+ "save_location": "Save location",
+ "tap_to_select_location": "Click on the map to select a location"
}
diff --git a/web/packages/new/photos/components/EditLocationDialog.tsx b/web/packages/new/photos/components/EditLocationDialog.tsx
new file mode 100644
index 0000000000..8aa4fc2ad2
--- /dev/null
+++ b/web/packages/new/photos/components/EditLocationDialog.tsx
@@ -0,0 +1,408 @@
+import AddIcon from "@mui/icons-material/Add";
+import ArrowBackIcon from "@mui/icons-material/ArrowBack";
+import DoneIcon from "@mui/icons-material/Done";
+import RemoveIcon from "@mui/icons-material/Remove";
+import {
+ Box,
+ Button,
+ CircularProgress,
+ Dialog,
+ IconButton,
+ Stack,
+ styled,
+ Typography,
+ type DialogProps,
+} from "@mui/material";
+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
+import { haveWindow } from "ente-base/env";
+import type { Location } from "ente-base/types";
+import type { EnteFile } from "ente-media/file";
+import { fileLocation } from "ente-media/file-metadata";
+import { t } from "i18next";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+
+import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css";
+import "leaflet/dist/leaflet.css";
+// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unused-expressions
+haveWindow() && require("leaflet-defaulticon-compatibility");
+const leaflet = haveWindow()
+ ? // eslint-disable-next-line @typescript-eslint/no-require-imports
+ (require("leaflet") as typeof import("leaflet"))
+ : null;
+
+export interface EditLocationDialogProps extends ModalVisibilityProps {
+ /**
+ * The files whose location we want to edit.
+ */
+ files: EnteFile[];
+ /**
+ * Called when the user confirms the location update.
+ *
+ * @param location The new location to set for all selected files.
+ * @returns A promise that resolves when the update is complete.
+ */
+ onConfirm: (location: Location) => Promise<void>;
+}
+
+/**
+ * A full-screen dialog with an interactive map where users can drop a pin to
+ * set the location for one or more photos.
+ */
+export const EditLocationDialog: React.FC<EditLocationDialogProps> = ({
+ open,
+ onClose,
+ files,
+ onConfirm,
+}) => {
+ const [selectedLocation, setSelectedLocation] = useState<
+ Location | undefined
+ >(undefined);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSuccess, setIsSuccess] = useState(false);
+
+ // Get initial location only if a single file is selected
+ const initialLocation = useMemo(() => {
+ if (files.length !== 1) return undefined;
+ const file = files[0];
+ return file ? fileLocation(file) : undefined;
+ }, [files]);
+
+ // Reset selected location and states only when dialog opens
+ const prevOpenRef = useRef(false);
+ useEffect(() => {
+ if (open && !prevOpenRef.current) {
+ setSelectedLocation(initialLocation);
+ setIsLoading(false);
+ setIsSuccess(false);
+ }
+ prevOpenRef.current = open;
+ }, [open, initialLocation]);
+
+ const hasLocationChanged = useMemo(() => {
+ if (!selectedLocation) return false;
+ if (!initialLocation) return true;
+ return (
+ selectedLocation.latitude !== initialLocation.latitude ||
+ selectedLocation.longitude !== initialLocation.longitude
+ );
+ }, [selectedLocation, initialLocation]);
+
+ // Reset success state when user selects a new location
+ const prevSelectedLocationRef = useRef(selectedLocation);
+ useEffect(() => {
+ const prevLoc = prevSelectedLocationRef.current;
+ const currLoc = selectedLocation;
+ const locationChanged =
+ prevLoc?.latitude !== currLoc?.latitude ||
+ prevLoc?.longitude !== currLoc?.longitude;
+
+ if (isSuccess && locationChanged) {
+ setIsSuccess(false);
+ }
+ prevSelectedLocationRef.current = selectedLocation;
+ }, [isSuccess, selectedLocation]);
+
+ const handleConfirm = async () => {
+ if (selectedLocation && hasLocationChanged && !isLoading) {
+ setIsLoading(true);
+ setIsSuccess(false);
+ try {
+ await onConfirm(selectedLocation);
+ setIsSuccess(true);
+ } finally {
+ setIsLoading(false);
+ }
+ }
+ };
+
+ return (
+ <FullScreenDialog open={open} onClose={onClose}>
+ <Stack sx={{ height: "100%", width: "100%" }}>
+ <TitleBar
+ onBack={onClose}
+ onConfirm={handleConfirm}
+ canConfirm={hasLocationChanged}
+ isLoading={isLoading}
+ isSuccess={isSuccess}
+ />
+ <Box sx={{ flex: 1, position: "relative" }}>
+ <EditableMap
+ initialLocation={initialLocation}
+ selectedLocation={selectedLocation}
+ onLocationSelect={setSelectedLocation}
+ />
+ </Box>
+ </Stack>
+ </FullScreenDialog>
+ );
+};
+
+const FullScreenDialog = styled((props: DialogProps) => (
+ <Dialog fullScreen {...props} />
+))({
+ "& .MuiDialog-paper": {
+ backgroundColor: "var(--mui-palette-background-default)",
+ },
+});
+
+interface TitleBarProps {
+ onBack: () => void;
+ onConfirm: () => void;
+ canConfirm: boolean;
+ isLoading: boolean;
+ isSuccess: boolean;
+}
+
+const TitleBar: React.FC<TitleBarProps> = ({
+ onBack,
+ onConfirm,
+ canConfirm,
+ isLoading,
+ isSuccess,
+}) => (
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ gap: 1,
+ p: 1,
+ borderBottom: "1px solid",
+ borderColor: "divider",
+ }}
+ >
+ <IconButton onClick={onBack}>
+ <ArrowBackIcon />
+ </IconButton>
+ <Typography variant="h6" sx={{ flex: 1 }}>
+ {t("edit_location")}
+ </Typography>
+ {isLoading ? (
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ px: 2,
+ }}
+ >
+ <CircularProgress size={24} />
+ </Box>
+ ) : isSuccess ? (
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ px: 2,
+ color: "success.main",
+ }}
+ >
+ <DoneIcon />
+ </Box>
+ ) : (
+ <Button
+ onClick={onConfirm}
+ disabled={!canConfirm}
+ variant="contained"
+ color="accent"
+ >
+ {t("save_location")}
+ </Button>
+ )}
+ </Stack>
+);
+
+interface EditableMapProps {
+ initialLocation: Location | undefined;
+ selectedLocation: Location | undefined;
+ onLocationSelect: (location: Location) => void;
+}
+
+const EditableMap: React.FC<EditableMapProps> = ({
+ initialLocation,
+ selectedLocation,
+ onLocationSelect,
+}) => {
+ const mapContainerRef = useRef<HTMLDivElement>(null);
+ const mapRef = useRef<L.Map | null>(null);
+ const markerRef = useRef<L.Marker | null>(null);
+ // Capture initial location at mount time to avoid map reset on file updates
+ const initialLocationRef = useRef(initialLocation);
+
+ const urlTemplate = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
+ const attribution =
+ '&copy; <a target="_blank" rel="noopener" href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
+
+ useEffect(() => {
+ const mapContainer = mapContainerRef.current;
+ if (!mapContainer || !leaflet) return;
+
+ // Don't recreate map if it already exists
+ if (mapRef.current) return;
+
+ // Use the captured initial location from mount time
+ const initLoc = initialLocationRef.current;
+ const initialLat = initLoc?.latitude;
+ const initialLng = initLoc?.longitude;
+
+ // Determine initial view
+ const defaultCenter: L.LatLngTuple = [20, 0]; // World view
+ const defaultZoom = 3;
+
+ const hasInitialLocation =
+ initialLat !== undefined && initialLng !== undefined;
+ const center: L.LatLngTuple = hasInitialLocation
+ ? [initialLat, initialLng]
+ : defaultCenter;
+ const zoom = hasInitialLocation ? 6 : defaultZoom;
+
+ // Create map with zoom control disabled (we add custom controls)
+ const map = leaflet
+ .map(mapContainer, { zoomControl: false })
+ .setView(center, zoom);
+ leaflet.tileLayer(urlTemplate, { attribution }).addTo(map);
+ mapRef.current = map;
+
+ // Add initial marker if location exists
+ if (hasInitialLocation) {
+ const marker = leaflet
+ .marker([initialLat, initialLng], { draggable: true })
+ .addTo(map);
+ markerRef.current = marker;
+
+ marker.on("dragend", () => {
+ const pos = marker.getLatLng();
+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });
+ });
+ }
+
+ // Handle map clicks to place/move marker
+ map.on("click", (e: L.LeafletMouseEvent) => {
+ const { lat, lng } = e.latlng;
+ onLocationSelect({ latitude: lat, longitude: lng });
+
+ if (markerRef.current) {
+ markerRef.current.setLatLng([lat, lng]);
+ } else {
+ const marker = leaflet
+ .marker([lat, lng], { draggable: true })
+ .addTo(map);
+ markerRef.current = marker;
+
+ marker.on("dragend", () => {
+ const pos = marker.getLatLng();
+ onLocationSelect({ latitude: pos.lat, longitude: pos.lng });
+ });
+ }
+ });
+
+ return () => {
+ if (mapRef.current) {
+ mapRef.current.remove();
+ mapRef.current = null;
+ markerRef.current = null;
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Update marker position when selectedLocation changes externally
+ useEffect(() => {
+ if (
+ selectedLocation &&
+ markerRef.current &&
+ mapRef.current &&
+ leaflet
+ ) {
+ const currentPos = markerRef.current.getLatLng();
+ if (
+ currentPos.lat !== selectedLocation.latitude ||
+ currentPos.lng !== selectedLocation.longitude
+ ) {
+ markerRef.current.setLatLng([
+ selectedLocation.latitude,
+ selectedLocation.longitude,
+ ]);
+ }
+ }
+ }, [selectedLocation]);
+
+ const handleZoomIn = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ mapRef.current?.zoomIn();
+ };
+ const handleZoomOut = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ mapRef.current?.zoomOut();
+ };
+
+ return (
+ <MapWrapper>
+ <MapContainer ref={mapContainerRef} />
+ <MapOverlay>
+ {selectedLocation ? (
+ <Typography variant="body2" sx={{ color: "text.muted" }}>
+ {selectedLocation.latitude.toFixed(6)},{" "}
+ {selectedLocation.longitude.toFixed(6)}
+ </Typography>
+ ) : (
+ <Typography variant="body2" sx={{ color: "text.muted" }}>
+ {t("tap_to_select_location")}
+ </Typography>
+ )}
+ </MapOverlay>
+ <ZoomControls>
+ <ZoomButton onClick={handleZoomIn}>
+ <AddIcon />
+ </ZoomButton>
+ <ZoomButton onClick={handleZoomOut}>
+ <RemoveIcon />
+ </ZoomButton>
+ </ZoomControls>
+ </MapWrapper>
+ );
+};
+
+const MapWrapper = styled("div")({
+ height: "100%",
+ width: "100%",
+ position: "relative",
+});
+
+const MapContainer = styled("div")({
+ height: "100%",
+ width: "100%",
+});
+
+const MapOverlay = styled("div")(({ theme }) => ({
+ position: "absolute",
+ top: theme.spacing(2),
+ left: "50%",
+ transform: "translateX(-50%)",
+ zIndex: 1000,
+ backgroundColor: theme.vars.palette.background.paper,
+ padding: theme.spacing(1, 2),
+ borderRadius: "9999px",
+ boxShadow: theme.shadows[2],
+}));
+
+const ZoomControls = styled(Stack)(({ theme }) => ({
+ position: "absolute",
+ right: theme.spacing(3),
+ bottom: theme.spacing(6),
+ zIndex: 1000,
+ gap: theme.spacing(1),
+}));
+
+const ZoomButton = styled(IconButton)(({ theme }) => ({
+ backgroundColor: theme.vars.palette.background.paper,
+ boxShadow: theme.shadows[4],
+ width: 48,
+ height: 48,
+ borderRadius: 16,
+ transition: "transform 0.2s ease-out",
+ "&:hover": {
+ backgroundColor: theme.vars.palette.background.paper,
+ transform: "scale(1.05)",
+ },
+}));
diff --git a/web/packages/new/photos/components/SelectedFileOptions.tsx b/web/packages/new/photos/components/SelectedFileOptions.tsx
index 5503ab0d5f..4bd4472714 100644
--- a/web/packages/new/photos/components/SelectedFileOptions.tsx
+++ b/web/packages/new/photos/components/SelectedFileOptions.tsx
@@ -7,6 +7,7 @@ import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import CloseIcon from "@mui/icons-material/Close";
import DeleteIcon from "@mui/icons-material/Delete";
import DownloadIcon from "@mui/icons-material/Download";
+import LocationOnIcon from "@mui/icons-material/LocationOn";
import PersonAddIcon from "@mui/icons-material/PersonAdd";
import RemoveIcon from "@mui/icons-material/RemoveCircleOutline";
import RestoreIcon from "@mui/icons-material/Restore";
@@ -147,6 +148,12 @@ interface SelectedFileOptionsProps {
* person will be shown (when ML is enabled and there are named people).
*/
onAddPersonToSelectedFiles?: (personID: string) => Promise<void>;
+ /**
+ * Called when the user wants to edit the location of the selected files.
+ *
+ * Only shown when at least one owned file is selected.
+ */
+ onEditLocation?: () => void;
/**
* The total number of files available in the current view.
*/
@@ -175,6 +182,7 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
createOnSelectForCollectionOp,
createFileOpHandler,
onAddPersonToSelectedFiles,
+ onEditLocation,
totalFileCount,
onSelectAll,
}) => {
@@ -354,6 +362,9 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
<>
<FavoriteButton onClick={handleFavorite} />
<FixTimeButton onClick={handleFixTime} />
+ {onEditLocation && selectedOwnFileCount > 0 && (
+ <EditLocationButton onClick={onEditLocation} />
+ )}
<DownloadButton onClick={handleDownload} />
<AddToCollectionButton
onClick={handleAddToCollection}
@@ -424,6 +435,9 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
<FavoriteButton onClick={handleFavorite} />
)}
<FixTimeButton onClick={handleFixTime} />
+ {onEditLocation && selectedOwnFileCount > 0 && (
+ <EditLocationButton onClick={onEditLocation} />
+ )}
<DownloadButton onClick={handleDownload} />
<AddToCollectionButton
onClick={handleAddToCollection}
@@ -546,6 +560,14 @@ const FixTimeButton: React.FC<ButtonishProps> = ({ onClick }) => (
</Tooltip>
);
+const EditLocationButton: React.FC<ButtonishProps> = ({ onClick }) => (
+ <Tooltip title={t("edit_location")}>
+ <IconButton {...{ onClick }}>
+ <LocationOnIcon />
+ </IconButton>
+ </Tooltip>
+);
+
const AddToCollectionButton: React.FC<ButtonishProps> = ({ onClick }) => (
<Tooltip title={t("add")}>
<IconButton {...{ onClick }}>
diff --git a/web/packages/new/photos/services/file.ts b/web/packages/new/photos/services/file.ts
index 0f962f9eba..914c57b243 100644
--- a/web/packages/new/photos/services/file.ts
+++ b/web/packages/new/photos/services/file.ts
@@ -274,3 +274,23 @@ const putFilesPublicMagicMetadata = async (
body: JSON.stringify(updateRequest),
}),
);
+
+/**
+ * Update the location (latitude and longitude) for a list of files on remote.
+ *
+ * Remote only, does not modify local state.
+ *
+ * The location of an {@link EnteFile} is stored in its public magic metadata
+ * as the `lat` and `long` fields.
+ *
+ * @param files The list of files whose location we want to update.
+ *
+ * @param lat The new latitude.
+ *
+ * @param long The new longitude.
+ */
+export const updateFilesLocation = (
+ files: EnteFile[],
+ lat: number,
+ long: number,
+) => batched(files, (b) => updateFilesPublicMagicMetadata(b, { lat, long }));