Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune web comments

Manav Rathi9ee82cf71f6a
diff --git a/web/apps/albums/src/app/context/albums-app-context.ts b/web/apps/albums/src/app/context/albums-app-context.ts
index 35739da735..83e836ac0c 100644
--- a/web/apps/albums/src/app/context/albums-app-context.ts
+++ b/web/apps/albums/src/app/context/albums-app-context.ts
@@ -1,40 +1,15 @@
import type { NotificationAttributes } from "ente-base/components/Notification";
import { createContext, useContext } from "react";
-/**
- * The type of the React context available to all pages in the albums app.
- */
export interface AlbumsAppContextT {
- /**
- * Show the global activity indicator (a loading bar at the top of the
- * page).
- */
showLoadingBar: () => void;
- /**
- * Hide the global activity indicator bar.
- */
hideLoadingBar: () => void;
- /**
- * Show a {@link Notification}, customizing its contents and click
- * behaviour using the provided {@link NotificationAttributes}.
- */
showNotification: (attributes: NotificationAttributes) => void;
}
-/**
- * The React {@link Context} available to all nodes in the React tree of albums
- * app pages.
- */
export const AlbumsAppContext = createContext<AlbumsAppContextT | undefined>(
undefined,
);
-/**
- * Utility hook to get the albums app context.
- *
- * This context is provided at the top level _app component for the albums app,
- * and thus is available to all React components in the albums app's React
- * tree.
- */
export const useAlbumsAppContext = (): AlbumsAppContextT =>
useContext(AlbumsAppContext)!;
diff --git a/web/apps/albums/src/public-album/components/TripLayout/MobileCover.tsx b/web/apps/albums/src/public-album/components/TripLayout/MobileCover.tsx
index 1397e1952c..f38ec12e4a 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/MobileCover.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/MobileCover.tsx
@@ -27,7 +27,6 @@ export const MobileCover = memo<MobileCoverProps>(
year: "numeric",
});
- // Count unique locations based on unique name+country combinations
const uniqueLocations = new Set(
journeyData
.filter((point) => point.name && point.country)
diff --git a/web/apps/albums/src/public-album/components/TripLayout/MobileTimelineLocation.tsx b/web/apps/albums/src/public-album/components/TripLayout/MobileTimelineLocation.tsx
index da29dbc6d2..f79bff60f0 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/MobileTimelineLocation.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/MobileTimelineLocation.tsx
@@ -43,7 +43,6 @@ export const MobileTimelineLocation = memo<MobileTimelineLocationProps>(
id={`location-${index}`}
className="timeline-location"
>
- {/* Centered Photo Fan Container */}
<CenteredPhotoContainer>
<PhotoFanWrapper>
<PhotoFan
@@ -51,7 +50,6 @@ export const MobileTimelineLocation = memo<MobileTimelineLocationProps>(
onPhotoClick={onPhotoClick}
/>
- {/* Overlay text on top of main photo */}
<PhotoOverlay>
<DayBadge>
DAY {dayNumber} β€’{" "}
@@ -78,7 +76,6 @@ export const MobileTimelineLocation = memo<MobileTimelineLocationProps>(
},
);
-// Styled components
const MobileLocationContainer = styled(Box)({
position: "relative",
display: "flex",
diff --git a/web/apps/albums/src/public-album/components/TripLayout/MobileTripStarted.tsx b/web/apps/albums/src/public-album/components/TripLayout/MobileTripStarted.tsx
index 69d1b56b12..28f1e17ab3 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/MobileTripStarted.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/MobileTripStarted.tsx
@@ -9,7 +9,6 @@ interface MobileTripStartedProps {
export const MobileTripStarted = memo<MobileTripStartedProps>(
({ onRef, journeyData }) => {
- // Get the first photo's date
const sortedData = [...journeyData].sort(
(a, b) => a.timestamp - b.timestamp,
);
diff --git a/web/apps/albums/src/public-album/components/TripLayout/PhotoFan.tsx b/web/apps/albums/src/public-album/components/TripLayout/PhotoFan.tsx
index 290f9b860b..01e92f7d49 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/PhotoFan.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/PhotoFan.tsx
@@ -109,7 +109,6 @@ export const PhotoFan = memo<PhotoFanProps>(({ cluster, onPhotoClick }) => {
);
});
-// Styled components
const PhotoFanContainer = styled(Box)(({ theme }) => ({
position: "relative",
width: "180px",
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TimelineBaseLine.tsx b/web/apps/albums/src/public-album/components/TripLayout/TimelineBaseLine.tsx
index 9aed539515..d5a65da3ab 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TimelineBaseLine.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TimelineBaseLine.tsx
@@ -38,7 +38,6 @@ export const TimelineBaseLine = memo<TimelineBaseLineProps>(
},
);
-// Styled components
const BaseLine = styled(Box)(() => ({
position: "absolute",
left: "50%",
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TimelineLocation.tsx b/web/apps/albums/src/public-album/components/TripLayout/TimelineLocation.tsx
index 0503f5f810..b9c8ef5bdc 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TimelineLocation.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TimelineLocation.tsx
@@ -13,7 +13,6 @@ interface TimelineLocationProps {
onPhotoClick?: (cluster: JourneyPoint[], fileId: number) => void;
}
-// Component for timeline location item
export const TimelineLocation = memo<TimelineLocationProps>(
({
cluster,
@@ -48,7 +47,6 @@ export const TimelineLocation = memo<TimelineLocationProps>(
const diffTime = photoDateOnly.getTime() - firstDateOnly.getTime();
const dayNumber = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
- // Show green only for the active location
const currentLocationIndex = Math.round(
scrollProgress * Math.max(0, photoClusters.length - 1),
);
@@ -135,7 +133,6 @@ export const TimelineLocation = memo<TimelineLocationProps>(
},
);
-// Styled components
const LocationContainer = styled(Box)({
position: "relative",
display: "flex",
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TimelineProgressLine.tsx b/web/apps/albums/src/public-album/components/TripLayout/TimelineProgressLine.tsx
index 9e5c40a2c2..96889210d5 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TimelineProgressLine.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TimelineProgressLine.tsx
@@ -9,6 +9,5 @@ interface TimelineProgressLineProps {
}
export const TimelineProgressLine = memo<TimelineProgressLineProps>(() => {
- // No longer showing progressive green line - green indicators only for current location
return null;
});
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx b/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx
index 7be2e6f73e..7a4ab45afe 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TopNavButtons.tsx
@@ -88,7 +88,6 @@ export const TopNavButtons: React.FC<TopNavButtonsProps> = ({
);
};
-// Styled components
const ButtonContainer = styled(Box)({
position: "fixed",
top: "58px",
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TripCover.tsx b/web/apps/albums/src/public-album/components/TripLayout/TripCover.tsx
index b59effc2de..8b21cfb8d2 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TripCover.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TripCover.tsx
@@ -28,7 +28,6 @@ export const TripCover = memo<TripCoverProps>(
year: "numeric",
});
- // Count unique locations based on unique name+country combinations
const uniqueLocations = new Set(
journeyData
.filter((point) => point.name && point.country)
@@ -102,7 +101,6 @@ export const TripCover = memo<TripCoverProps>(
},
);
-// Styled components
const CoverContainer = styled(Box)({ marginBottom: "48px" });
const CoverImageContainer = styled(Box)(({ theme }) => ({
diff --git a/web/apps/albums/src/public-album/components/TripLayout/TripMap.tsx b/web/apps/albums/src/public-album/components/TripLayout/TripMap.tsx
index 438d5c770a..b78c561f9d 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/TripMap.tsx
+++ b/web/apps/albums/src/public-album/components/TripLayout/TripMap.tsx
@@ -40,9 +40,9 @@ export const TripMap: React.FC<TripMapProps> = ({
onMarkerClick,
}) => {
const theme = useTheme();
- const isMobileOrTablet = useMediaQuery(theme.breakpoints.down("md")); // 960px breakpoint for mobile and tablet
+ const isMobileOrTablet = useMediaQuery(theme.breakpoints.down("md"));
- // Load react-leaflet components client-side only to prevent SSR issues
+ // Leaflet must be loaded client-side.
const [mapComponents, setMapComponents] =
useState<MapComponentsType | null>(null);
@@ -60,28 +60,24 @@ export const TripMap: React.FC<TripMapProps> = ({
});
}, []);
- // Calculate current active location index based on scroll progress (same logic as in scrollUtils)
let currentActiveLocationIndex = -1;
if (photoClusters.length > 0) {
if (isMobileOrTablet) {
- // Mobile: Slower progression - stay on each location longer
+ // Mobile keeps each location active longer.
currentActiveLocationIndex = Math.floor(
scrollProgress * (photoClusters.length - 0.5),
);
} else {
- // Desktop: Use original logic
currentActiveLocationIndex = Math.round(
scrollProgress * Math.max(0, photoClusters.length - 1),
);
}
}
- // Super clusters disabled - show all clusters individually
const visibleClustersWithIndices = photoClusters.map(
(cluster, originalIndex) => ({ cluster, originalIndex }),
);
- // Return loading state if map components haven't loaded yet
if (!mapComponents) {
return <MapContainerWrapper hasPhotoData={false} />;
}
@@ -108,7 +104,6 @@ export const TripMap: React.FC<TripMapProps> = ({
setCurrentZoom={setCurrentZoom}
setTargetZoom={setTargetZoom}
/>
- {/* Stadia Alidade Satellite - includes both imagery and labels */}
<TileLayer
attribution={
isMobileOrTablet
@@ -121,7 +116,6 @@ export const TripMap: React.FC<TripMapProps> = ({
keepBuffer={isMobileOrTablet ? 3 : 1}
/>
- {/* Draw visible clusters */}
{visibleClustersWithIndices.map((item, index) => {
const { cluster, originalIndex } = item;
const firstPhoto = cluster[0];
@@ -133,9 +127,7 @@ export const TripMap: React.FC<TripMapProps> = ({
cluster.reduce((sum, p) => sum + p.lng, 0) /
cluster.length;
- // Use the preserved original index
const originalClusterIndex = originalIndex;
- // Show green only for active locations
const isActive =
originalClusterIndex === currentActiveLocationIndex;
@@ -155,7 +147,6 @@ export const TripMap: React.FC<TripMapProps> = ({
zIndexOffset={isActive ? 1000 : 0}
eventHandlers={{
click: () => {
- // Calculate cluster center
const avgLat =
cluster.reduce(
(sum, p) => sum + p.lat,
@@ -182,7 +173,6 @@ export const TripMap: React.FC<TripMapProps> = ({
);
};
-// Styled components
const MapContainerWrapper = styled(Box, {
shouldForwardProp: (prop) => prop !== "hasPhotoData",
})<{ hasPhotoData: boolean }>(({ hasPhotoData }) => ({
diff --git a/web/apps/albums/src/public-album/components/TripLayout/hooks/useDataProcessing.ts b/web/apps/albums/src/public-album/components/TripLayout/hooks/useDataProcessing.ts
index 810ead6bab..5b1b9c420e 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/hooks/useDataProcessing.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/hooks/useDataProcessing.ts
@@ -34,7 +34,6 @@ export const useDataProcessing = ({
setIsLoadingLocations,
setCoverImageUrl,
}: UseDataProcessingParams) => {
- // Process photos data when files change
useEffect(() => {
const hasFilesCountChanged = files.length !== filesCountRef.current;
filesCountRef.current = files.length;
@@ -67,7 +66,6 @@ export const useDataProcessing = ({
setIsLoadingLocations,
]);
- // Load cover image after data loads
useEffect(() => {
const loadCover = async () => {
const coverUrl = await loadCoverImage({
diff --git a/web/apps/albums/src/public-album/components/TripLayout/hooks/useFileViewer.ts b/web/apps/albums/src/public-album/components/TripLayout/hooks/useFileViewer.ts
index 30580e313d..38a521f870 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/hooks/useFileViewer.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/hooks/useFileViewer.ts
@@ -18,15 +18,12 @@ export const useFileViewer = ({
const handleOpenFileViewer = useCallback(
(cluster: JourneyPoint[], clickedFileId: number) => {
- // Get file IDs from the cluster
const clusterFileIds = cluster.map((point) => point.fileId);
- // Filter files to only include those from the cluster
const clusterFiles = files.filter((file) =>
clusterFileIds.includes(file.id),
);
- // Sort cluster files by the local photo creation date shown in the UI.
const sortTimeByFile = new Map<EnteFile, number>();
const sortTimeForFile = (file: EnteFile) => {
const cached = sortTimeByFile.get(file);
@@ -39,13 +36,11 @@ export const useFileViewer = ({
(a, b) => sortTimeForFile(a) - sortTimeForFile(b),
);
- // Find the index of the clicked photo in the cluster files
const clickedIndex = sortedClusterFiles.findIndex(
(f) => f.id === clickedFileId,
);
if (clickedIndex !== -1 && sortedClusterFiles.length > 0) {
- // Batch state updates to avoid multiple re-renders
setViewerFiles(sortedClusterFiles);
setCurrentFileIndex(clickedIndex);
setOpenFileViewer(true);
@@ -56,17 +51,14 @@ export const useFileViewer = ({
);
const handleCloseFileViewer = useCallback(() => {
- // Batch state updates
setOpenFileViewer(false);
onSetOpenFileViewer?.(false);
}, [onSetOpenFileViewer]);
return {
- // State
openFileViewer,
currentFileIndex,
viewerFiles,
- // Handlers
handleOpenFileViewer,
handleCloseFileViewer,
};
diff --git a/web/apps/albums/src/public-album/components/TripLayout/hooks/useLocationFetching.ts b/web/apps/albums/src/public-album/components/TripLayout/hooks/useLocationFetching.ts
index db2833e6d5..a2c17da45c 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/hooks/useLocationFetching.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/hooks/useLocationFetching.ts
@@ -24,14 +24,11 @@ export const useLocationFetching = ({
const processedPhotoIdsRef = useRef<Set<number>>(new Set());
const lastFetchedClustersRef = useRef<string>("");
- // Fetch location names for clusters
useEffect(() => {
- // Create a stable key for current clusters to prevent duplicate fetches
const clustersKey = photoClusters
.map((cluster) => cluster.map((p) => p.fileId).join(","))
.join("|");
- // Skip if we already fetched for these exact clusters
if (clustersKey === lastFetchedClustersRef.current) {
return;
}
@@ -39,12 +36,10 @@ export const useLocationFetching = ({
const fetchNames = async () => {
if (photoClusters.length === 0) return;
- // Get all current photo IDs
const currentPhotoIds = new Set(
photoClusters.flat().map((photo) => photo.fileId),
);
- // Check if any photos need location fetching
const needsFetching = photoClusters.some((cluster) =>
cluster.some(
(photo) => !locationDataRef.current.has(photo.fileId),
@@ -78,7 +73,6 @@ export const useLocationFetching = ({
);
}
- // Update processed photos set
processedPhotoIdsRef.current = currentPhotoIds;
} finally {
setIsLoadingLocations(false);
diff --git a/web/apps/albums/src/public-album/components/TripLayout/hooks/useScrollHandling.ts b/web/apps/albums/src/public-album/components/TripLayout/hooks/useScrollHandling.ts
index 2b1cdff5b0..865eb375b1 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/hooks/useScrollHandling.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/hooks/useScrollHandling.ts
@@ -41,7 +41,6 @@ export const useScrollHandling = ({
setTargetZoom,
isMobileOrTablet,
}: UseScrollHandlingParams) => {
- // Update location positions callback
const updatePositions = useCallback(() => {
updateLocationPositions({
locationRefs: locationRefs.current,
@@ -49,7 +48,6 @@ export const useScrollHandling = ({
});
}, [locationRefs, setLocationPositions]);
- // Timeline scroll handler
const timelineScrollHandler = useCallback(() => {
handleTimelineScroll({
timelineRef,
@@ -76,13 +74,11 @@ export const useScrollHandling = ({
setTargetZoom,
]);
- // Throttled scroll handler
const throttledTimelineScroll = useMemo(
() => throttle(timelineScrollHandler, 16),
[timelineScrollHandler],
);
- // Timeline scroll to location function
const scrollToLocation = useCallback(
(locationIndex: number) => {
scrollTimelineToLocation({
@@ -96,7 +92,6 @@ export const useScrollHandling = ({
[timelineRef, photoClusters, locationPositions, isMobileOrTablet],
);
- // Marker click handler
const markerClickHandler = useCallback(
(clusterIndex: number, clusterLat: number, clusterLng: number) => {
handleMarkerClick({
@@ -129,7 +124,6 @@ export const useScrollHandling = ({
],
);
- // Update positions when locations render
useEffect(() => {
if (
locationRefs.current.length === photoClusters.length &&
@@ -141,7 +135,6 @@ export const useScrollHandling = ({
return undefined;
}, [photoClusters, updatePositions, locationRefs]);
- // Add scroll event listener
useEffect(() => {
const timelineContainer = timelineRef.current;
if (!timelineContainer) return;
@@ -156,7 +149,6 @@ export const useScrollHandling = ({
};
}, [throttledTimelineScroll, timelineRef]);
- // Cleanup timeout on unmount
useEffect(() => {
return () => {
if (clusterClickTimeoutRef.current) {
diff --git a/web/apps/albums/src/public-album/components/TripLayout/hooks/useThumbnailGeneration.ts b/web/apps/albums/src/public-album/components/TripLayout/hooks/useThumbnailGeneration.ts
index 49991195c0..3c1190aac2 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/hooks/useThumbnailGeneration.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/hooks/useThumbnailGeneration.ts
@@ -22,17 +22,14 @@ export const useThumbnailGeneration = ({
}: UseThumbnailGenerationParams) => {
const processedPhotoIdsRef = useRef<Set<number>>(new Set());
- // Generate thumbnails for needed photos with progressive loading
useEffect(() => {
const generateThumbs = async () => {
if (photoClusters.length === 0) return;
- // Get all current photo IDs
const currentPhotoIds = new Set(
photoClusters.flat().map((photo) => photo.fileId),
);
- // Check if we have photos that need thumbnails
const photosNeedingThumbnails = photoClusters
.flat()
.filter(
@@ -61,7 +58,6 @@ export const useThumbnailGeneration = ({
);
}
- // Update processed photos set and mark as generated
processedPhotoIdsRef.current = new Set([
...processedPhotoIdsRef.current,
...currentPhotoIds,
diff --git a/web/apps/albums/src/public-album/components/TripLayout/types.ts b/web/apps/albums/src/public-album/components/TripLayout/types.ts
index 50f12d6de7..3b3adee824 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/types.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/types.ts
@@ -3,11 +3,7 @@ export interface JourneyPoint {
lng: number;
name: string;
country: string;
- /**
- * Millisecond sort/display key in the local photo timeline.
- *
- * This is not an absolute UTC timestamp.
- */
+ // Local timeline key, not an absolute UTC timestamp.
timestamp: number;
image: string;
fileId: number;
diff --git a/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts b/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts
index 4b0d1f5773..73c5d3e35d 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/utils/dataProcessing.ts
@@ -83,7 +83,6 @@ export const fetchLocationNames = async ({
return { updatedPhotos };
}
- // Create all geocoding promises at once for parallel execution
const geocodingPromises = photoClusters.map(async (cluster) => {
if (cluster.length === 0) return null;
@@ -102,10 +101,8 @@ export const fetchLocationNames = async ({
}
});
- // Execute all geocoding requests in parallel
const results = await Promise.all(geocodingPromises);
- // Process results and update maps
results.forEach((result) => {
if (!result) return; // Skip failed requests
@@ -155,12 +152,8 @@ export const generateNeededThumbnails = async ({
group.push(file);
};
- // Define priority groups with specific file collections
const priorityGroups: EnteFile[][] = [];
- // Priority 1: Cover image (handled separately in loadCoverImage, skip here)
-
- // Priority 2: First 3 locations photosfans (first 3 photos from each)
const firstLocationsFiles: EnteFile[] = [];
photoClusters.slice(0, 3).forEach((cluster) => {
cluster.slice(0, 3).forEach((photo) => {
@@ -171,7 +164,6 @@ export const generateNeededThumbnails = async ({
priorityGroups.push(firstLocationsFiles);
}
- // Priority 3: Map marker photos (first photo from each cluster for markers)
const mapMarkerFiles: EnteFile[] = [];
photoClusters.forEach((cluster) => {
if (cluster.length > 0 && cluster[0]) {
@@ -183,7 +175,6 @@ export const generateNeededThumbnails = async ({
priorityGroups.push(mapMarkerFiles);
}
- // Priority 4: Rest of locations photosfans (remaining locations, first 3 from each)
const remainingLocationFiles: EnteFile[] = [];
photoClusters.slice(3).forEach((cluster) => {
cluster.slice(0, 3).forEach((photo) => {
@@ -194,12 +185,10 @@ export const generateNeededThumbnails = async ({
priorityGroups.push(remainingLocationFiles);
}
- // Process priority groups sequentially with delays
for (let groupIndex = 0; groupIndex < priorityGroups.length; groupIndex++) {
const group = priorityGroups[groupIndex];
if (!group) continue;
- // Process files in parallel within each priority group
const groupPromises = group.map(async (file) => {
try {
const thumbnailUrl =
@@ -214,7 +203,7 @@ export const generateNeededThumbnails = async ({
await Promise.all(groupPromises);
- // Add small delay between priority groups to allow UI updates
+ // Yield so thumbnails from this priority group can render.
if (groupIndex < priorityGroups.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 50));
}
@@ -238,13 +227,11 @@ export const loadCoverImage = async ({
let coverFile: EnteFile | undefined;
- // Priority 1: Use explicit cover ID if set
const coverID = collection?.pubMagicMetadata?.data.coverID;
if (coverID) {
coverFile = files.find((f) => f.id === coverID);
}
- // Priority 2: Use first chronological photo as cover (highest priority)
if (!coverFile) {
const firstPhoto = journeyData[0];
if (!firstPhoto) return null;
@@ -254,7 +241,6 @@ export const loadCoverImage = async ({
if (!coverFile) return null;
try {
- // Load cover image at highest quality first (highest priority)
const sourceURLs =
await downloadManager.renderableSourceURLs(coverFile);
if (sourceURLs.type === "image") {
diff --git a/web/apps/albums/src/public-album/components/TripLayout/utils/geocoding.ts b/web/apps/albums/src/public-album/components/TripLayout/utils/geocoding.ts
index 557fe80e0a..33b476bded 100644
--- a/web/apps/albums/src/public-album/components/TripLayout/utils/geocoding.ts
+++ b/web/apps/albums/src/public-album/components/TripLayout/utils/geocoding.ts
@@ -19,10 +19,8 @@ export interface LocationInfo {
country: string;
}
-// Icon cache to avoid recreating identical icons
export const iconCache = new Map<string, import("leaflet").DivIcon>();
-// Throttle function for performance optimization
export const throttle = <T extends (...args: unknown[]) => void>(
func: T,
delay: number,
@@ -49,13 +47,12 @@ export const throttle = <T extends (...args: unknown[]) => void>(
};
};
-// Reverse geocoding function using Stadia Maps
export const getLocationName = async (
lat: number,
lng: number,
): Promise<LocationInfo> => {
try {
- // Round coordinates to 2 decimal place for better geocoding
+ // Keep reverse-geocoding requests at place-level precision.
const roundedLat = Math.round(lat * 100) / 100;
const roundedLng = Math.round(lng * 100) / 100;
@@ -69,26 +66,21 @@ export const getLocationName = async (
const data = (await response.json()) as StadiaMapsGeocodingResponse;
- // Extract location name from the response
const feature = data.features?.[0];
let result: LocationInfo;
if (feature?.properties) {
const props = feature.properties;
- // Build location name with city and state/region for better context
const city = props.locality || props.neighbourhood;
- // Get location name
const locationName =
city || props.county || props.region || props.name || "Unknown";
- // Get country info
const country = props.country || "Unknown";
result = { place: locationName, country };
} else {
- // Fallback if no location found
result = { place: "Unknown", country: "Unknown" };
}
diff --git a/web/apps/albums/src/shared/hooks/useBrowserBackClose.ts b/web/apps/albums/src/shared/hooks/useBrowserBackClose.ts
index c8296ee210..10b5649910 100644
--- a/web/apps/albums/src/shared/hooks/useBrowserBackClose.ts
+++ b/web/apps/albums/src/shared/hooks/useBrowserBackClose.ts
@@ -50,11 +50,7 @@ export interface UseBrowserBackCloseOptions {
enabled?: boolean;
}
-/**
- * Adds a transient history entry while an overlay is open, so mobile browser
- * back gestures close the overlay before navigating away or closing a parent
- * viewer.
- */
+// Push a transient entry so browser back closes the overlay first.
export const useBrowserBackClose = ({
open,
onClose,
diff --git a/web/apps/locker/src/services/remote-read.ts b/web/apps/locker/src/services/remote-read.ts
index d30abb0711..b3051f4af5 100644
--- a/web/apps/locker/src/services/remote-read.ts
+++ b/web/apps/locker/src/services/remote-read.ts
@@ -626,9 +626,8 @@ const decryptFileToLockerItem = async (
fileKey,
)) as Record<string, unknown> | undefined;
} catch {
- // Public metadata can be missing or unreadable for some older
- // files. We still want to surface the file row if basic
- // metadata decrypts successfully.
+ // Older files may have unreadable public metadata.
+ // Basic metadata is enough to keep the row.
}
}
diff --git a/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx b/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
index 60bea31ff1..69b86559c3 100644
--- a/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
+++ b/web/apps/paste/src/features/paste/components/PasteCreatePanel.tsx
@@ -267,7 +267,6 @@ export const PasteCreatePanel = ({
paddingTop: { xs: "12px", sm: "14px" },
paddingRight: { xs: "12px", sm: "14px" },
paddingLeft: { xs: "12px", sm: "14px" },
- // Keep only the minimum reserve needed for the footer row.
paddingBottom: { xs: "50px", sm: "56px" },
backdropFilter: "blur(9px) saturate(112%)",
WebkitBackdropFilter:
diff --git a/web/apps/photos/src/components/AlbumAddedNotification.tsx b/web/apps/photos/src/components/AlbumAddedNotification.tsx
index 3d7b4808e7..1b7ae80b7d 100644
--- a/web/apps/photos/src/components/AlbumAddedNotification.tsx
+++ b/web/apps/photos/src/components/AlbumAddedNotification.tsx
@@ -17,20 +17,15 @@ interface AlbumAddedNotificationProps {
open: boolean;
onClose: () => void;
phase: AddToAlbumPhase;
- /** The destination album name to show as subtitle (truncated). */
albumName?: string;
}
-/**
- * Success notification shown after files are added to an album.
- */
export const AlbumAddedNotification: React.FC<AlbumAddedNotificationProps> = ({
open,
onClose,
phase,
albumName,
}) => {
- // Only show the toast once the operation completes successfully.
const shouldShow = open && phase === "done";
return (
@@ -49,7 +44,6 @@ export const AlbumAddedNotification: React.FC<AlbumAddedNotificationProps> = ({
>
<Box>
<Typography variant="h3">
- {/* Intentionally using a simple title for clarity */}
{t("added_to_album")}
</Typography>
{albumName && (
diff --git a/web/apps/photos/src/components/AuthenticateUser.tsx b/web/apps/photos/src/components/AuthenticateUser.tsx
index bf3b3fbc58..eef702dc11 100644
--- a/web/apps/photos/src/components/AuthenticateUser.tsx
+++ b/web/apps/photos/src/components/AuthenticateUser.tsx
@@ -17,18 +17,9 @@ import { t } from "i18next";
import { useCallback, useEffect, useState } from "react";
type AuthenticateUserProps = ModalVisibilityProps & {
- /**
- * Called when the user successfully reauthenticates themselves.
- */
onAuthenticate: () => void;
};
-/**
- * A dialog for reauthenticating the logged in user by prompting them for their
- * password.
- *
- * This is used as precursor to performing various sensitive or locked actions.
- */
export const AuthenticateUser: React.FC<AuthenticateUserProps> = ({
open,
onClose,
@@ -44,11 +35,6 @@ export const AuthenticateUser: React.FC<AuthenticateUserProps> = ({
</TitledMiniDialog>
);
-/**
- * The contents of the {@link AuthenticateUser} dialog.
- *
- * See: [Note: MUI dialog state] for why this is a separate component.
- */
const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({
open,
onClose,
@@ -61,11 +47,7 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({
KeyAttributes | undefined
>(undefined);
- // This is a altered version of the check we do on the password verification
- // screen, except here it don't try to overwrite local state and instead
- // just request the user to login again if we detect that their password has
- // changed on a different device and they haven't unlocked even once since
- // then on this device.
+ // Reauthentication must not overwrite local state.
const validateSession = useCallback(async () => {
try {
const session = await checkSessionValidity();
@@ -76,8 +58,7 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({
);
}
} catch (e) {
- // Ignore errors since we shouldn't be logging the user out for
- // potentially transient issues.
+ // A transient validation failure must not log the user out.
log.warn("Ignoring error when determining session validity", e);
}
}, [logout, showMiniDialog, onClose]);
@@ -88,12 +69,9 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({
}, []);
useEffect(() => {
- // Do a non-blocking validation of the session whenever we show the
- // dialog to the user.
if (open) void validateSession();
}, [open, validateSession]);
- // They'll be read from disk shortly.
if (!user || !keyAttributes) return <></>;
return (
@@ -109,13 +87,6 @@ const AuthenticateUserDialogContents: React.FC<AuthenticateUserProps> = ({
);
};
-/**
- * Attributes for a dialog box that informs the user that their password was
- * changed on a different device, and they the need to login again to be able to
- * use the new one. Cancellable.
- *
- * @param onLogin Called if the user chooses the login option.
- */
const passwordChangedElsewhereDialogAttributes = (
onLogin: () => void,
): MiniDialogAttributes => ({
diff --git a/web/apps/photos/src/components/CollectionMappingChoice.tsx b/web/apps/photos/src/components/CollectionMappingChoice.tsx
index 45f5f08c1b..8a2c43661b 100644
--- a/web/apps/photos/src/components/CollectionMappingChoice.tsx
+++ b/web/apps/photos/src/components/CollectionMappingChoice.tsx
@@ -16,17 +16,9 @@ import { t } from "i18next";
import React from "react";
type CollectionMappingChoiceProps = ModalVisibilityProps & {
- /**
- * Callback invoked with the mapping choice selected by the user.
- *
- * The dialog is automatically closed before this callback is invoked.
- */
onSelect: (mapping: CollectionMapping) => void;
};
-/**
- * A {@link Dialog} that allow the user to choose a collection mapping.
- */
export const CollectionMappingChoice: React.FC<
CollectionMappingChoiceProps
> = ({ open, onClose, onSelect }) => (
diff --git a/web/apps/photos/src/components/Collections/AllAlbums.tsx b/web/apps/photos/src/components/Collections/AllAlbums.tsx
index ade23426ac..5b0197c891 100644
--- a/web/apps/photos/src/components/Collections/AllAlbums.tsx
+++ b/web/apps/photos/src/components/Collections/AllAlbums.tsx
@@ -62,9 +62,6 @@ interface AllAlbums {
onRemotePull: () => Promise<void>;
}
-/**
- * A modal showing the list of all the albums.
- */
export const AllAlbums: React.FC<AllAlbums> = ({
collectionSummaries,
open,
@@ -106,7 +103,6 @@ export const AllAlbums: React.FC<AllAlbums> = ({
: await createAlbum(albumName);
await onRemotePull();
- // Show custom toast with both buttons
setAlbumCreatedToast({
open: true,
albumId: newAlbum.id,
@@ -178,7 +174,6 @@ export const AllAlbums: React.FC<AllAlbums> = ({
submitButtonTitle={t("create")}
onSubmit={handleCreateAlbum}
/>
- {/* Custom toast for album created notification */}
<Snackbar
open={albumCreatedToast.open}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
@@ -405,11 +400,6 @@ interface ItemData {
onCreateAlbum: () => void;
}
-// This helper function memoizes incoming props,
-// To avoid causing unnecessary re-renders pure Row components.
-// This is only needed since we are passing multiple props with a wrapper object.
-// If we were only passing a single, stable value (e.g. items),
-// We could just pass the value directly.
const createItemData = memoize(
(
collectionRowList: (CollectionSummary | "create")[][],
@@ -418,10 +408,6 @@ const createItemData = memoize(
) => ({ collectionRowList, onCollectionClick, onCreateAlbum }),
);
-//If list items are expensive to render,
-// Consider using React.memo or shouldComponentUpdate to avoid unnecessary re-renders.
-// https://reactjs.org/docs/react-api.html#reactmemo
-// https://reactjs.org/docs/react-api.html#reactpurecomponent
const AlbumsRow = React.memo(
({
data,
@@ -495,7 +481,6 @@ const AllAlbumsContent: React.FC<AllAlbumsContentProps> = ({
const collectionRowList: (CollectionSummary | "create")[][] = [];
let index = 0;
- // Add create button as first item in first row if needed
if (showCreateButton) {
const firstRow: (CollectionSummary | "create")[] = ["create"];
for (
@@ -508,7 +493,6 @@ const AllAlbumsContent: React.FC<AllAlbumsContentProps> = ({
collectionRowList.push(firstRow);
}
- // Add remaining collections
while (index < collectionSummaries.length) {
const collectionRow: (CollectionSummary | "create")[] = [];
for (
@@ -530,16 +514,12 @@ const AllAlbumsContent: React.FC<AllAlbumsContentProps> = ({
main();
}, [collectionSummaries, columns, showCreateButton]);
- // Bundle additional data to list items using the "itemData" prop.
- // It will be accessible to item renderers as props.data.
- // Memoize this data to avoid bypassing shouldComponentUpdate().
const itemData = createItemData(
collectionRowList,
onCollectionClick,
onCreateAlbum,
);
- // Show "no results" message if there's a search query but no results
if (
hasSearchQuery &&
collectionSummaries.length === 0 &&
diff --git a/web/apps/photos/src/components/Collections/AllPeople.tsx b/web/apps/photos/src/components/Collections/AllPeople.tsx
index 2f907ec085..f33c787c11 100644
--- a/web/apps/photos/src/components/Collections/AllPeople.tsx
+++ b/web/apps/photos/src/components/Collections/AllPeople.tsx
@@ -131,11 +131,6 @@ export const AllPeople: React.FC<AllPeopleProps> = ({
const hasSearchQuery = !!searchTerm.trim();
- /**
- * Preparing the additional faces list when showing
- * more faces, excluding duplicates from the visible list
- * and excluding hidden cgroups
- */
const extraPeople = useMemo(() => {
const visiblePersonIDs = new Set(people.map(({ id }) => id));
const extra = allPeople.filter(
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index 832bef0d66..e76580cc53 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -99,10 +99,6 @@ export interface CollectionHeaderProps extends Pick<
mapFileSource?: FileListWithViewerProps["mapFileSource"];
setActiveCollectionID: (collectionID: number) => void;
isActiveCollectionDownloadInProgress: () => boolean;
- /**
- * Called when an operation (e.g. renaming a collection) completes and wants
- * to perform a full remote pull.
- */
onRemotePull: (opts?: RemotePullOpts) => Promise<void>;
onCollectionShare: () => void;
onCollectionManageLink: () => void;
@@ -110,17 +106,9 @@ export interface CollectionHeaderProps extends Pick<
canSetAlbumCover: boolean;
onSetAlbumCover: () => void;
hasActiveFileSelection: boolean;
- /**
- * A function that can be used to create a UI notification to track the
- * progress of user-initiated download, and to cancel it if needed.
- */
onAddSaveGroup: AddSaveGroup;
}
-/**
- * A header shown at the top of the list of photos in the gallery, when the
- * gallery is showing a collection.
- */
export const CollectionHeader: React.FC<CollectionHeaderProps> = (props) => {
const { collectionSummary } = props;
@@ -202,11 +190,6 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
activeCollection?.magicMetadata?.data.subType ==
CollectionSubType.quicklink;
- /**
- * Return a new function by wrapping an async function in an error handler,
- * showing the global loading bar when the function runs, and syncing with
- * remote on completion.
- */
const wrap = useCallback(
(f: () => Promise<void>) => {
const wrapped = async () => {
@@ -488,9 +471,7 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
}, [mapEnabled, onGenericError, showMapDialog]);
let menuOptions: React.ReactNode[] = [];
- // MUI doesn't let us use fragments to pass multiple menu items, so we need
- // to instead put them in an array. This also necessitates giving each a
- // unique key.
+ // MUI rejects fragments here, so return keyed arrays.
switch (collectionSummaryType) {
case "trash":
menuOptions = fileCount
@@ -503,7 +484,6 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
break;
case "uncategorized":
- // Quick options (download + clean) are shown instead of a menu
break;
case "hiddenItems":
@@ -530,7 +510,6 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
{t("map")}
</OverflowMenuOption>
),
- // Pin/Unpin for shared incoming collections
collectionSummary.attributes.has("shareePinned") ? (
<OverflowMenuOption
key="unpin"
@@ -825,7 +804,6 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
);
};
-/** Props for a generic option. */
interface OptionProps {
onClick: () => void;
}
@@ -1038,7 +1016,6 @@ const ShareIcon: React.FC = () => (
</svg>
);
-/** A smaller version of ShareIcon for use in the collection header summary. */
const SmallShareIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
<svg
width="15"
diff --git a/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx b/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
index 6f88db05fb..708562e9d3 100644
--- a/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
+++ b/web/apps/photos/src/components/Collections/GalleryBarAndListHeader.tsx
@@ -52,9 +52,6 @@ type GalleryBarAndListHeaderProps = Omit<
| "onShowAllAlbums"
| "onShowAllPeople"
> & {
- /**
- * When `true`, the bar is be hidden altogether.
- */
shouldHide: boolean;
barCollectionSummaries: CollectionSummaries;
allPeople: Person[];
@@ -86,24 +83,7 @@ type GalleryBarAndListHeaderProps = Omit<
"user" | "emailByUserID" | "shareSuggestionEmails" | "setBlockingLoad"
>;
-/**
- * The gallery bar, the header for the list items, and state for any associated
- * dialogs that might be triggered by actions on either the bar or the header..
- *
- * This component manages the sticky horizontally scrollable bar shown at the
- * top of the gallery, AND the (non-sticky) header shown below the bar, at the
- * top of the actual list of items.
- *
- * These are disparate views - indeed, the list header is not even a child of
- * this component but is instead proxied via {@link setFileListHeader}. Still,
- * having this intermediate wrapper component allows us to move some of the
- * common concerns shared by both the gallery bar and list header (e.g. some
- * dialogs that can be invoked from both places) into this file instead of
- * cluttering the already big gallery component.
- *
- * TODO: Once the gallery code is better responsibilitied out, consider moving
- * this code back inline into the gallery.
- */
+// TODO: Move this back into the gallery once its responsibilities are split.
export const GalleryBarAndListHeader: React.FC<
GalleryBarAndListHeaderProps
> = ({
@@ -205,8 +185,7 @@ export const GalleryBarAndListHeader: React.FC<
const collectionSummary = toShowCollectionSummaries.get(
activeCollectionID!,
);
- // Render the full CollectionHeader for pseudo-collections (e.g. trash)
- // so header actions/menus are available even without a real collection.
+ // Pseudo-collections need header actions despite having no Collection.
const shouldRenderCollectionHeader =
mode != "people" &&
collectionSummary &&
@@ -370,10 +349,6 @@ export const GalleryBarAndListHeader: React.FC<
);
};
-/**
- * A hook that maintains the collections sort order both as in-memory and local
- * storage state.
- */
const useCollectionsSortByLocalState = (initialValue: CollectionsSortBy) => {
const key = "collectionsSortBy";
diff --git a/web/apps/photos/src/components/Collections/PickCoverPhotoDialog.tsx b/web/apps/photos/src/components/Collections/PickCoverPhotoDialog.tsx
index a70f7131a6..7e08717ee5 100644
--- a/web/apps/photos/src/components/Collections/PickCoverPhotoDialog.tsx
+++ b/web/apps/photos/src/components/Collections/PickCoverPhotoDialog.tsx
@@ -37,9 +37,6 @@ interface PickCoverPhotoDialogProps {
type SubmittingAction = "use-selected-photo" | "reset-to-default";
-/**
- * Picker dialog for selecting a single file to use as an album cover.
- */
export const PickCoverPhotoDialog: React.FC<PickCoverPhotoDialogProps> = ({
open,
onClose,
diff --git a/web/apps/photos/src/components/CollectionsSortOptions.tsx b/web/apps/photos/src/components/CollectionsSortOptions.tsx
index 90576bec62..8a0713ccd3 100644
--- a/web/apps/photos/src/components/CollectionsSortOptions.tsx
+++ b/web/apps/photos/src/components/CollectionsSortOptions.tsx
@@ -17,55 +17,29 @@ import { t } from "i18next";
import React, { useRef, useState } from "react";
interface CollectionsSortOptionsProps {
- /**
- * The sorting scheme currently active.
- */
activeSortBy: CollectionsSortBy;
- /**
- * Change the scheme that should be used.
- */
onChangeSortBy: (by: CollectionsSortBy) => void;
- /**
- * Set this to true if we're being shown inside a dialog, to further
- * increase the elevation of the menu.
- */
nestedInDialog?: boolean;
- /**
- * Set this to true to disable the background for the icon button that
- * triggers the menu.
- */
transparentTriggerButtonBackground?: boolean;
- /**
- * Visual treatment for the surface in which the control is rendered.
- */
variant?: "default" | "v2";
}
-/** The three sort categories. */
type SortCategory = "name" | "creation-time" | "updation-time";
-/** Extract the category from a CollectionsSortBy value. */
const getSortCategory = (sortBy: CollectionsSortBy): SortCategory => {
if (sortBy.startsWith("name")) return "name";
if (sortBy.startsWith("creation-time")) return "creation-time";
return "updation-time";
};
-/** Check if the sort is ascending. */
const isAscending = (sortBy: CollectionsSortBy): boolean =>
sortBy.endsWith("-asc");
-/** Get the CollectionsSortBy value for a category and direction. */
const getSortBy = (
category: SortCategory,
ascending: boolean,
): CollectionsSortBy => `${category}-${ascending ? "asc" : "desc"}`;
-/**
- * A button that shows an overflow menu allowing the user to choose from amongst
- * the {@link CollectionsSortBy} values that should be used for sorting the
- * lists of collections.
- */
export const CollectionsSortOptions: React.FC<CollectionsSortOptionsProps> = ({
activeSortBy,
onChangeSortBy,
@@ -84,11 +58,10 @@ export const CollectionsSortOptions: React.FC<CollectionsSortOptionsProps> = ({
const handleCategoryClick = (category: SortCategory) => {
let nextSortBy: CollectionsSortBy;
if (category === activeCategory) {
- // Toggle direction if same category
nextSortBy = getSortBy(category, !activeAscending);
} else {
- // Select new category with default direction
- const defaultAscending = category === "name"; // Name defaults to A-Z (asc), dates to newest (desc)
+ // Names default to ascending; dates default to newest first.
+ const defaultAscending = category === "name";
nextSortBy = getSortBy(category, defaultAscending);
}
pendingSortByRef.current = nextSortBy;
diff --git a/web/apps/photos/src/components/DeleteAccount.tsx b/web/apps/photos/src/components/DeleteAccount.tsx
index bac4609f9a..8fb4d63bec 100644
--- a/web/apps/photos/src/components/DeleteAccount.tsx
+++ b/web/apps/photos/src/components/DeleteAccount.tsx
@@ -25,12 +25,6 @@ import React, { useState } from "react";
import { Trans } from "react-i18next";
type DeleteAccountProps = ModalVisibilityProps & {
- /**
- * Called when the user should be authenticated again.
- *
- * Account deletion only proceeds if the promise returned by this function
- * is fulfilled.
- */
onAuthenticateUser: () => Promise<void>;
};
@@ -44,11 +38,7 @@ export const DeleteAccount: React.FC<DeleteAccountProps> = ({
</TitledMiniDialog>
);
-/**
- * The contents of the {@link DeleteAccount} dialog.
- *
- * See: [Note: MUI dialog state] for why this is a separate component.
- */
+// Keep state in the dialog subtree so closing it resets the form.
const DeleteAccountDialogContents: React.FC<
Omit<DeleteAccountProps, "open">
> = ({ onClose, onAuthenticateUser }) => {
@@ -209,10 +199,7 @@ const DeleteAccountDialogContents: React.FC<
);
};
-/**
- * All of these must have a corresponding localized string nested under the
- * "delete_reason" key.
- */
+// Each value must have a delete_reason translation.
const deleteReasons = [
"missing_feature",
"behaviour",
diff --git a/web/apps/photos/src/components/DropdownInput.tsx b/web/apps/photos/src/components/DropdownInput.tsx
index 3e5c47a0bc..198d968b59 100644
--- a/web/apps/photos/src/components/DropdownInput.tsx
+++ b/web/apps/photos/src/components/DropdownInput.tsx
@@ -5,41 +5,18 @@ import {
Typography,
} from "@mui/material";
-/**
- * A label, and the associated value, shown in the {@link DropdownInput}.
- */
export interface DropdownOption<T> {
label: string;
value: T;
}
interface DropdownInputProps<T> {
- /**
- * The dropdown options.
- */
options: DropdownOption<T>[];
- /**
- * The currently selected value, if any.
- */
selected: T | undefined;
- /**
- * Callback invoked when the user changes the selected value.
- */
onSelect: (selectedValue: T) => void;
- /**
- * An optional placeholder shown when there is no selected value.
- */
placeholder?: string;
}
-/**
- * A custom MUI {@link Select} with a look as per our designs, and with an
- * narrower interface focused on picking from a static list of options.
- *
- * This behaves as a controlled component - the caller is expected to set the
- * {@link selected} prop. The caller will then be notified of changes by calls
- * to the {@link onSelect} function.
- */
export const DropdownInput = <T extends string>({
options,
selected,
@@ -54,10 +31,8 @@ export const DropdownInput = <T extends string>({
variant="outlined"
displayEmpty
renderValue={() => {
- // Return the value that is shown in the unexpanded state.
const label = options.find((o) => o.value == selected)?.label;
return label ? (
- // Wrap the label if doesn't fit.
<Typography sx={{ whiteSpace: "normal" }}>{label}</Typography>
) : (
<Typography sx={{ color: "text.muted" }}>
@@ -68,9 +43,7 @@ export const DropdownInput = <T extends string>({
MenuProps={{
slotProps: {
paper: {
- // Select component sets the min width of each element to
- // the width of the select input's width, so setting the
- // maxWidth to 0 forces element widths to equal minWidth.
+ // MUI's item min-width prevents wrapping unless max-width is reset.
sx: { maxWidth: 0 },
},
list: {
@@ -80,17 +53,13 @@ export const DropdownInput = <T extends string>({
color: "text.faint",
whiteSpace: "normal",
},
- // Make the selected item pop out by using color.
"&&& > .Mui-selected": { color: "text.base" },
},
},
},
}}
sx={{
- // Remove the border in the quiescent state.
".MuiOutlinedInput-notchedOutline": { borderColor: "transparent" },
- // Give the default appearance a background fill, similar to our
- // text inputs.
".MuiSelect-select": { backgroundColor: "fill.faint" },
}}
>
diff --git a/web/apps/photos/src/components/Export.tsx b/web/apps/photos/src/components/Export.tsx
index c7dfd3c713..bc339541ca 100644
--- a/web/apps/photos/src/components/Export.tsx
+++ b/web/apps/photos/src/components/Export.tsx
@@ -56,19 +56,9 @@ import {
} from "react-window";
type ExportProps = ModalVisibilityProps & {
- /**
- * A map from collection IDs to their user visible name.
- *
- * It will contain entries for all collections (both normal and hidden).
- */
collectionNameByID: Map<number, string>;
};
-/**
- * A dialog that allows the user to view and manage the export of their data.
- *
- * Available only in the desktop app (export requires direct disk access).
- */
export const Export: React.FC<ExportProps> = ({
open,
onClose,
@@ -85,7 +75,6 @@ export const Export: React.FC<ExportProps> = ({
failed: 0,
total: 0,
});
- // The list of EnteFiles that have not been exported yet.
const [pendingFiles, setPendingFiles] = useState<EnteFile[]>([]);
const [lastExportTime, setLastExportTime] = useState(0);
@@ -263,7 +252,7 @@ const ExportDirectory: React.FC<ExportDirectoryProps> = ({
exportStage === ExportStage.init ? (
<ChangeDirectoryOption onClick={onChangeExportDirectory} />
) : (
- // Prevent layout shift.
+ // Preserve the directory row width while its action is hidden.
<Box sx={{ width: "16px", height: "48px" }} />
)}
</>
@@ -283,9 +272,7 @@ const DirectoryPath: React.FC<DirectoryPathProps> = ({ path }) => (
<LinkButton onClick={() => void ensureElectron().openDirectory(path)}>
<Tooltip title={path}>
<EllipsizedTypography
- // Haven't found a way to get the path to ellipsize without
- // providing a maxWidth. Luckily, this is the context of the
- // desktop app where this width is should not be too off.
+ // Ellipsis needs a fixed maximum width.
sx={{ maxWidth: "262px" }}
>
{path}
@@ -303,14 +290,7 @@ const ChangeDirectoryOption: React.FC<ButtonishProps> = ({ onClick }) => (
);
interface ContinuousExportProps {
- /**
- * If `true`, then continuous export is shown as enabled.
- */
enabled: boolean;
- /**
- * Called when the user wants to toggle the current value of
- * {@link enabled}.
- */
onToggle: () => void;
}
@@ -559,7 +539,7 @@ const ExportPendingListDialog: React.FC<ExportPendingListDialogProps> = ({
collectionNameByID,
pendingFiles,
}) => {
- const itemSize = 56; /* px */
+ const itemSize = 56;
const itemCount = pendingFiles.length;
const listHeight = Math.min(itemCount * itemSize, 240);
@@ -617,14 +597,13 @@ const ExportPendingListItem: React.FC<
<Box sx={{ flexShrink: 0 }}>
<ItemCard
key={file.id}
- TileComponent={PreviewItemTile} /* 48 px */
+ TileComponent={PreviewItemTile}
coverFile={file}
/>
</Box>
<Stack
sx={{
- // We need to set overflow hidden on the containing
- // stack for the EllipsizedTypography to kick in.
+ // EllipsizedTypography needs overflow hidden on its container.
overflow: "hidden",
gap: "2px",
}}
diff --git a/web/apps/photos/src/components/FileContextMenu.tsx b/web/apps/photos/src/components/FileContextMenu.tsx
index 70a5660f1e..ea80ebfe9b 100644
--- a/web/apps/photos/src/components/FileContextMenu.tsx
+++ b/web/apps/photos/src/components/FileContextMenu.tsx
@@ -28,26 +28,17 @@ import {
import { t } from "i18next";
import React, { memo, useCallback, useMemo } from "react";
-/**
- * Position for anchoring the context menu.
- */
export interface ContextMenuPosition {
top: number;
left: number;
}
interface FileContextMenuProps {
- /** Whether the menu is open. */
open: boolean;
- /** The position to anchor the menu at. */
anchorPosition: ContextMenuPosition | undefined;
- /** Callback when the menu should close. */
onClose: () => void;
- /** The actions to display in the menu. */
actions: FileContextAction[];
- /** Callback when an action is selected. */
onAction: (action: FileContextAction) => void;
- /** Number of files currently selected. */
}
interface ActionConfig {
@@ -88,14 +79,6 @@ const actionConfigs: Record<FileContextAction, ActionConfig> = {
addPerson: { label: "add_a_person", Icon: hugeIcon(UserAdd02Icon) },
};
-/**
- * Context menu for file operations, displayed on right-click of file
- * thumbnails.
- *
- * This component renders a single Menu instance that is positioned based on
- * mouse coordinates. It should be rendered once at the FileList level, not per
- * thumbnail.
- */
export const FileContextMenu: React.FC<FileContextMenuProps> = memo(
({ open, anchorPosition, onClose, actions, onAction }) => {
const handleActionClick = useCallback(
@@ -106,7 +89,6 @@ export const FileContextMenu: React.FC<FileContextMenuProps> = memo(
[onClose, onAction],
);
- // Separate primary and destructive actions in a single pass
const [primaryActions, destructiveActions] = useMemo(() => {
const primary: FileContextAction[] = [];
const destructive: FileContextAction[] = [];
diff --git a/web/apps/photos/src/components/FixCreationTime.tsx b/web/apps/photos/src/components/FixCreationTime.tsx
index 2ec2b1519f..a096c75c17 100644
--- a/web/apps/photos/src/components/FixCreationTime.tsx
+++ b/web/apps/photos/src/components/FixCreationTime.tsx
@@ -32,20 +32,10 @@ import { t } from "i18next";
import React, { useEffect, useState } from "react";
type FixCreationTimeProps = ModalVisibilityProps & {
- /**
- * The {@link EnteFile}s whose creation time should be modified.
- */
files: EnteFile[];
- /**
- * Called after the creation times have been updated, to perform a full
- * remote pull.
- */
onRemotePull: () => Promise<void>;
};
-/**
- * A dialog allowing the user to modify the creation time of selected files.
- */
export const FixCreationTime: React.FC<FixCreationTimeProps> = ({
open,
onClose,
@@ -56,7 +46,6 @@ export const FixCreationTime: React.FC<FixCreationTimeProps> = ({
const [progress, setProgress] = useState({ completed: 0, total: 0 });
useEffect(() => {
- // Reset the step whenever the dialog is reopened.
if (open) setStep(undefined);
}, [open]);
@@ -105,7 +94,6 @@ export const FixCreationTime: React.FC<FixCreationTimeProps> = ({
);
};
-/** The current state of the fixing process. */
type Step = "running" | "completed" | "completed-with-errors";
type FixOption =
@@ -117,7 +105,6 @@ type FixOption =
interface FormValues {
option: FixOption;
- /* Only valid when {@link option} is "custom-time". */
customDate: ParsedMetadataDate | undefined;
}
@@ -320,24 +307,6 @@ const updateFiles = async (
return hadErrors;
};
-/**
- * Update the date associated with a given {@link EnteFile}.
- *
- * This is generally treated as the creation date of the underlying asset
- * (photo, video, live photo) that this file stores.
- *
- * - For images, this function allows us to update this date from the Exif and
- * other metadata embedded in the file.
- *
- * - For all types of files (including images), this function allows us to
- * update this date to an explicitly provided value.
- *
- * If an Exif-involving {@link fixOption} is passed for an non-image file, then
- * that file is just skipped over. Similarly, if an Exif-involving
- * {@link fixOption} is provided, but the given underlying image for the given
- * {@link file} does not have a corresponding Exif (or related) value, then that
- * file is skipped.
- */
const updateFileDate = async (
file: EnteFile,
fixOption: FixOption,
diff --git a/web/apps/photos/src/components/PeopleSortOptions.tsx b/web/apps/photos/src/components/PeopleSortOptions.tsx
index 37ab8d1d50..de836c38ae 100644
--- a/web/apps/photos/src/components/PeopleSortOptions.tsx
+++ b/web/apps/photos/src/components/PeopleSortOptions.tsx
@@ -40,20 +40,15 @@ export const PeopleSortOptions: React.FC<PeopleSortOptionsProps> = ({
nestedInDialog,
transparentTriggerButtonBackground,
}) => {
- // Tracks the button element the menu is anchored to; its presence also
- // determines whether the menu is open.
const [anchorEl, setAnchorEl] = useState<MenuProps["anchorEl"]>();
- // Holds the next sort choice until the menu close transition completes.
+ // Apply sort changes after the menu closes to avoid flicker.
const pendingSortByRef = useRef<PeopleSortBy | undefined>(undefined);
const ariaID = "people-sort";
- // Split the current sort into its category and direction for simpler menu logic.
const activeCategory = getPeopleSortCategory(activeSortBy);
const activeAscending = isPeopleSortAscending(activeSortBy);
- // Re-selecting the active category flips its direction; choosing a new
- // category applies that category's default direction.
const handleCategoryClick = (category: PeopleSortCategory) => {
let nextSortBy: PeopleSortBy;
if (category === activeCategory) {
@@ -65,8 +60,6 @@ export const PeopleSortOptions: React.FC<PeopleSortOptionsProps> = ({
setAnchorEl(undefined);
};
- // Optionally remove the trigger button background when this control is
- // rendered inside layouts that already provide their own styling.
const triggerButtonSxProps: IconButtonProps["sx"] = [
transparentTriggerButtonBackground
? {}
@@ -150,8 +143,6 @@ const PeopleSortCategoryOption: React.FC<PeopleSortCategoryOptionProps> = ({
label,
directionLabel,
}) => {
- // The selected option has a differnt color and arrow directions
- // and the below variables are for facilitating that.
const isSelected = category === activeCategory;
const arrowIcon = activeAscending ? ArrowUp02Icon : ArrowDown02Icon;
diff --git a/web/apps/photos/src/components/QuickLinkCreatedNotification.tsx b/web/apps/photos/src/components/QuickLinkCreatedNotification.tsx
index 0d89c260ec..9d7544a37d 100644
--- a/web/apps/photos/src/components/QuickLinkCreatedNotification.tsx
+++ b/web/apps/photos/src/components/QuickLinkCreatedNotification.tsx
@@ -20,8 +20,7 @@ export const QuickLinkCreatedNotification: React.FC<
useEffect(() => {
if (open) {
- // Reset only when opening so the check icon does not flicker back
- // to copy during the close animation.
+ // Reset on open, not during the close animation.
setCopied(false);
return;
}
diff --git a/web/apps/photos/src/components/SubscriptionCard.tsx b/web/apps/photos/src/components/SubscriptionCard.tsx
index d24bf8e672..fc48edb84a 100644
--- a/web/apps/photos/src/components/SubscriptionCard.tsx
+++ b/web/apps/photos/src/components/SubscriptionCard.tsx
@@ -22,21 +22,10 @@ import { t } from "i18next";
import type React from "react";
interface SubscriptionCardProps {
- /**
- * Details for the logged in user.
- *
- * Can be undefined if the fetch has not yet completed.
- */
userDetails: UserDetails | undefined;
- /**
- * Called when the user clicks on the card.
- */
onClick: () => void;
}
-/**
- * The card in the sidebar that shows a summary of the user's plan and usage.
- */
export const SubscriptionCard: React.FC<SubscriptionCardProps> = ({
userDetails,
onClick,
@@ -58,11 +47,7 @@ export const SubscriptionCard: React.FC<SubscriptionCardProps> = ({
const BackgroundOverlay: React.FC = () => (
<img
- style={{
- aspectRatio: "2/1",
- // Remove extra whitespace below the image.
- verticalAlign: "bottom",
- }}
+ style={{ aspectRatio: "2/1", verticalAlign: "bottom" }}
width="100%"
src="/images/subscription-card-background/1x.png"
srcSet="/images/subscription-card-background/2x.png 2x, /images/subscription-card-background/3x.png 3x"
@@ -75,31 +60,20 @@ const ClickOverlay: React.FC<ButtonishProps> = ({ onClick }) => (
</ClickOverlayButton>
);
-/**
- * The transparent button element offers activation of the subscription card.
- *
- * A mixin of {@link FocusVisibleUnstyledButton} and {@link Overlay}, plus
- * custom styling to place its contents (chevron) at the middle right.
- */
const ClickOverlayButton = styled(UnstyledButton)(
({ theme }) => `
- /* Overlay */
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
- /* Position the chevron at the middle right */
display: flex;
justify-content: flex-end;
align-items: center;
- /* Reset the button color */
color: inherit;
- /* FocusVisibleUnstyledButton, but customized to work button with the larger
- subscription card and its border radii. */
&:focus-visible {
outline: 1.5px solid ${theme.vars.palette.stroke.base};
outline-offset: 2px;
@@ -209,18 +183,7 @@ const IndividualUsageSection: React.FC<IndividualUsageSectionProps> = ({
storage,
fileCount,
}) => (
- // [Note: Fallback translation for languages with multiple plurals]
- //
- // Languages like Polish and Arabian have multiple plural forms, and
- // currently i18n falls back to the base language translation instead of the
- // "_other" form if all the plural forms are not listed out.
- //
- // As a workaround, name the _other form as the unprefixed name. That is,
- // instead of calling the most general plural form as foo_count_other, call
- // it foo_count (To keep our heads straight, we adopt the convention that
- // all such pluralizable strings use the _count suffix, but that's not a
- // requirement from the library).
-
+ // Use the unsuffixed key as the fallback for languages with more plural forms.
<Stack sx={{ gap: 1.5 }}>
<UsageBar>
<UsageBarSegment
@@ -246,14 +209,8 @@ const UsageBar = styled("div")`
background-color: rgba(255 255 255 / 0.2);
`;
-type UsageBarSegmentProps = UsageStorage & {
- /** A CSS color string representing the color that this segment */
- fillColor: string;
-};
+type UsageBarSegmentProps = UsageStorage & { fillColor: string };
-/**
- * A bar inside a UsageContainer.
- */
const UsageBarSegment: React.FC<UsageBarSegmentProps> = ({
usage,
storage,
diff --git a/web/apps/photos/src/components/UploadConfirmationDialog.tsx b/web/apps/photos/src/components/UploadConfirmationDialog.tsx
index bab7e10aef..714056a5e5 100644
--- a/web/apps/photos/src/components/UploadConfirmationDialog.tsx
+++ b/web/apps/photos/src/components/UploadConfirmationDialog.tsx
@@ -22,10 +22,6 @@ import type { ChangeEvent, ReactElement } from "react";
interface UploadConfirmationDialogProps {
open: boolean;
loading: boolean;
- /**
- * `true` if the items being uploaded were detected to be a Google Takeout
- * import (Takeout metadata JSONs were found amongst them).
- */
isTakeout: boolean;
fileCount: number;
albumCount: number;
@@ -258,7 +254,6 @@ function StatCard({
);
}
-/* primary/default in the design */
const green = "#08c225";
const paperSx = (theme: Theme) => ({
diff --git a/web/apps/photos/src/components/WatchFolder.tsx b/web/apps/photos/src/components/WatchFolder.tsx
index 6c0a50c44a..e9d1b7e72c 100644
--- a/web/apps/photos/src/components/WatchFolder.tsx
+++ b/web/apps/photos/src/components/WatchFolder.tsx
@@ -38,19 +38,11 @@ import type { CollectionMapping, FolderWatch } from "ente-base/types/ipc";
import { t } from "i18next";
import React, { useEffect, useRef, useState } from "react";
-/**
- * View the state of and manage folder watches.
- *
- * This is the screen that controls that "watch folder" feature in the app.
- */
export const WatchFolder: React.FC<ModalVisibilityProps> = ({
open,
onClose,
}) => {
- // The folders we are watching
const [watches, setWatches] = useState<FolderWatch[] | undefined>();
- // Temporarily stash the folder path while we show a choice dialog to the
- // user to select the collection mapping.
const [savedFolderPath, setSavedFolderPath] = useState<
string | undefined
>();
@@ -66,8 +58,7 @@ export const WatchFolder: React.FC<ModalVisibilityProps> = ({
void refreshWatches();
}, []);
- // Refresh watches when window gains focus while dialog is open.
- // This ensures the UI updates when a folder becomes accessible again.
+ // Recheck inaccessible folders when the window regains focus.
useEffect(() => {
if (!open) return;
@@ -246,7 +237,6 @@ const WatchEntry: React.FC<WatchEntryProps> = ({
const isAccessible = watch.isAccessible !== false;
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // Cleanup timer on unmount to avoid state update on unmounted component.
useEffect(() => {
return () => {
if (retryTimerRef.current) clearTimeout(retryTimerRef.current);
@@ -265,10 +255,10 @@ const WatchEntry: React.FC<WatchEntryProps> = ({
});
const handleRetry = async () => {
- if (isRetrying) return; // Prevent multiple rapid clicks.
+ if (isRetrying) return;
setIsRetrying(true);
await onRetry();
- // Keep spinner visible briefly so user sees feedback.
+ // Keep feedback visible long enough to notice.
retryTimerRef.current = setTimeout(() => setIsRetrying(false), 1000);
};
@@ -370,11 +360,5 @@ const EntryOptions: React.FC<EntryOptionsProps> = ({
</OverflowMenu>
);
-/**
- * Return true if all the paths in the given list are items that belong to the
- * same (arbitrary) directory.
- *
- * Empty list of paths is considered to be in the same directory.
- */
const areAllInSameDirectory = (paths: string[]) =>
new Set(paths.map(dirname)).size == 1;
diff --git a/web/apps/photos/src/components/WhatsNew.tsx b/web/apps/photos/src/components/WhatsNew.tsx
index efdb60942b..fab752a29c 100644
--- a/web/apps/photos/src/components/WhatsNew.tsx
+++ b/web/apps/photos/src/components/WhatsNew.tsx
@@ -19,16 +19,10 @@ import { SlideUpTransition } from "ente-new/photos/components/mui/SlideUpTransit
import React, { useEffect } from "react";
interface WhatsNewProps {
- /** If `true`, then the dialog is shown. */
open: boolean;
- /** Called when the dialog wants to be closed. */
onClose: () => void;
}
-/**
- * A dialog showing a short summary of interesting-for-the-user things since the
- * last time this dialog was shown.
- */
export const WhatsNew: React.FC<WhatsNewProps> = ({ open, onClose }) => {
const fullScreen = useIsSmallWidth();
@@ -73,8 +67,7 @@ export const WhatsNew: React.FC<WhatsNewProps> = ({ open, onClose }) => {
};
const ChangelogContent: React.FC = () => {
- // NOTE: Remember to update changelogVersion when changing the content
- // below.
+ // Update changelogVersion whenever this content changes.
return (
<Stack sx={{ gap: 2, mb: 1 }}>
@@ -93,8 +86,6 @@ const ChangelogContent: React.FC = () => {
};
const ButtonContents = styled("div")`
- /* Make the button text fill the entire space so the endIcon shows at the
- trailing edge of the button. */
width: 100%;
text-align: left;
`;
diff --git a/web/apps/photos/src/components/app-lock/AppLockReauthenticationDialog.tsx b/web/apps/photos/src/components/app-lock/AppLockReauthenticationDialog.tsx
index 6c1ea7b0fd..15d4e7d250 100644
--- a/web/apps/photos/src/components/app-lock/AppLockReauthenticationDialog.tsx
+++ b/web/apps/photos/src/components/app-lock/AppLockReauthenticationDialog.tsx
@@ -1,7 +1,3 @@
-/**
- * @file Reauthentication dialog for app-lock protected actions.
- */
-
import { Box, Modal } from "@mui/material";
import { useAppLockSnapshot } from "ente-new/photos/components/utils/use-snapshot";
import { t } from "i18next";
diff --git a/web/apps/photos/src/components/gallery/GalleryEmptyState.tsx b/web/apps/photos/src/components/gallery/GalleryEmptyState.tsx
index 0f73cfad13..43feff12b1 100644
--- a/web/apps/photos/src/components/gallery/GalleryEmptyState.tsx
+++ b/web/apps/photos/src/components/gallery/GalleryEmptyState.tsx
@@ -11,15 +11,7 @@ import React, { useEffect, useState } from "react";
import { Trans } from "react-i18next";
interface GalleryEmptyStateProps {
- /**
- * If `true`, then an upload is already in progress (the empty state will
- * then disable the prompts for uploads).
- */
isUploadInProgress: boolean;
- /**
- * Called when the user selects one of the upload buttons. It is passed the
- * "intent" of the user.
- */
onUpload: (intent: UploadTypeSelectorIntent) => void;
}
@@ -202,8 +194,7 @@ function MemoriesPreservedCount(): React.JSX.Element | null {
.catch(() => undefined);
};
- // The count is a fleet-wide number from Ente's production servers, so
- // it is only meaningful (and only shown) when connecting to them.
+ // Custom API origins cannot use this production-wide count.
let intervalID: number | undefined;
void customAPIOrigin().then((origin) => {
if (origin || abortController.signal.aborted) return;
@@ -373,10 +364,7 @@ const GalleryEmptyStateButton = styled(FocusVisibleButton)(({ theme }) => ({
"& .MuiButton-startIcon": { marginRight: 14, "& > svg": { fontSize: 20 } },
}));
-/**
- * Prevent the image from being selected _and_ dragged, since dragging it
- * triggers the our dropdown selector overlay.
- */
+// Draggable images trigger the upload overlay.
const NonDraggableImage = styled("img")(({ theme }) => ({
position: "absolute",
top: -96,
diff --git a/web/apps/photos/src/components/icons/ShapeIcon.tsx b/web/apps/photos/src/components/icons/ShapeIcon.tsx
index d9c6a25727..9e5f1d2590 100644
--- a/web/apps/photos/src/components/icons/ShapeIcon.tsx
+++ b/web/apps/photos/src/components/icons/ShapeIcon.tsx
@@ -1,7 +1,6 @@
import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";
import React from "react";
-// Custom icon because Shape01 is not available in Hugeicons.
export const ShapeIcon: React.FC<SvgIconProps> = (props) => (
<SvgIcon {...props} viewBox="0 0 24 24">
<path
diff --git a/web/apps/photos/src/components/icons/StarIcon.tsx b/web/apps/photos/src/components/icons/StarIcon.tsx
index 920405c01e..9f6799b2a7 100644
--- a/web/apps/photos/src/components/icons/StarIcon.tsx
+++ b/web/apps/photos/src/components/icons/StarIcon.tsx
@@ -1,22 +1,12 @@
import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";
import React from "react";
-/**
- * Custom star icon (filled).
- *
- * This is the app's custom star shape used for favorites.
- */
export const StarIcon: React.FC<SvgIconProps> = (props) => (
<SvgIcon {...props} viewBox="0 0 21 20">
<path d="M8.69381 1.56975C9.38617 0.609562 10.7995 0.609562 11.4919 1.56975L13.7114 4.64784C13.9253 4.9445 14.2255 5.16569 14.5699 5.28031L18.1427 6.46961C19.2572 6.84061 19.6939 8.20365 19.0073 9.16808L16.8062 12.2597C16.5941 12.5577 16.4794 12.9156 16.4783 13.2831L16.4669 17.0962C16.4634 18.2857 15.32 19.1281 14.2033 18.764L10.6234 17.5966C10.2784 17.4841 9.90729 17.4841 9.56228 17.5966L5.98245 18.764C4.86575 19.1281 3.72231 18.2857 3.71876 17.0962L3.70737 13.2831C3.70628 12.9156 3.5916 12.5577 3.37946 12.2597L1.17839 9.16808C0.491785 8.20365 0.928537 6.84061 2.04305 6.46961L5.61584 5.28031C5.96017 5.16569 6.26041 4.9445 6.47432 4.64784L8.69381 1.56975Z" />
</SvgIcon>
);
-/**
- * Custom star icon (outline).
- *
- * This is the app's custom star shape used for favorites (outline variant).
- */
export const StarBorderIcon: React.FC<SvgIconProps> = (props) => (
<SvgIcon {...props} viewBox="0 0 21 20">
<path
diff --git a/web/apps/photos/src/components/icons/StarOffIcon.tsx b/web/apps/photos/src/components/icons/StarOffIcon.tsx
index 16086e5cd1..54bb383710 100644
--- a/web/apps/photos/src/components/icons/StarOffIcon.tsx
+++ b/web/apps/photos/src/components/icons/StarOffIcon.tsx
@@ -1,11 +1,6 @@
import SvgIcon, { type SvgIconProps } from "@mui/material/SvgIcon";
import React from "react";
-/**
- * Custom star-off icon (unfavorite).
- *
- * This is the app's custom star with a strike-through used to remove favorites.
- */
export const StarOffIcon: React.FC<SvgIconProps> = (props) => (
<SvgIcon {...props} viewBox="0 0 21 20">
<svg
diff --git a/web/apps/photos/src/components/share/PublicLinkCreated.tsx b/web/apps/photos/src/components/share/PublicLinkCreated.tsx
index 240de38aad..a942ffc257 100644
--- a/web/apps/photos/src/components/share/PublicLinkCreated.tsx
+++ b/web/apps/photos/src/components/share/PublicLinkCreated.tsx
@@ -4,18 +4,8 @@ import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton"
import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
import { t } from "i18next";
-type PublicLinkCreatedProps = ModalVisibilityProps & {
- /**
- * Callback invoked when the user presses the button to copy the newly
- * created link. The dialog also closes when this happens.
- */
- onCopyLink: () => void;
-};
+type PublicLinkCreatedProps = ModalVisibilityProps & { onCopyLink: () => void };
-/**
- * A Dialog acknowledging the creation of a link to a public album, and offering
- * the user a choice to copy the newly created link.
- */
export const PublicLinkCreated: React.FC<PublicLinkCreatedProps> = ({
open,
onClose,
diff --git a/web/apps/photos/src/components/sidebar/MLSettings.tsx b/web/apps/photos/src/components/sidebar/MLSettings.tsx
index e3567730c6..8bd93d4a1c 100644
--- a/web/apps/photos/src/components/sidebar/MLSettings.tsx
+++ b/web/apps/photos/src/components/sidebar/MLSettings.tsx
@@ -46,7 +46,6 @@ export const MLSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
const handleConsent = useWrapAsyncOperation(async () => {
await enableML();
- // Close the FaceConsent drawer, come back to ourselves.
setOpenFaceConsent(false);
});
@@ -92,11 +91,7 @@ const Loading: React.FC = () => {
};
interface EnableMLProps {
- /** Called when the user enables ML. */
onEnable: () => void;
- /**
- * If true, a footnote describing the magic search feature will be shown.
- */
showMagicSearchHint?: boolean;
}
@@ -155,9 +150,7 @@ const FaceConsentDrawer: React.FC<FaceConsentDrawerProps> = ({
};
interface FaceConsentProps {
- /** Called when the user provides their consent. */
onConsent: () => void;
- /** Called when the user cancels out. */
onCancel: () => void;
}
@@ -223,9 +216,7 @@ export const FaceConsent: React.FC<FaceConsentProps> = ({
};
interface ManageMLProps {
- /** The {@link MLStatus}; a non-disabled one. */
mlStatus: Exclude<MLStatus, { phase: "disabled" }>;
- /** Called when the user wants to disable ML. */
onDisableML: () => void;
}
@@ -253,7 +244,6 @@ const ManageML: React.FC<ManageMLProps> = ({ mlStatus, onDisableML }) => {
break;
}
- // Show processed as percentages instead of potentially confusing counts.
const processed = `${nTotalFiles ? Math.round((100 * nSyncedFiles) / nTotalFiles) : 100}%`;
const confirmDisableML = () =>
diff --git a/web/apps/photos/src/components/sidebar/SessionsSettings.tsx b/web/apps/photos/src/components/sidebar/SessionsSettings.tsx
index 93bb060c61..432bf223e6 100644
--- a/web/apps/photos/src/components/sidebar/SessionsSettings.tsx
+++ b/web/apps/photos/src/components/sidebar/SessionsSettings.tsx
@@ -91,8 +91,7 @@ const SessionsSettingsContents: React.FC<SessionsSettingsContentsProps> = ({
} catch (e) {
log.error("Failed to fetch active sessions", e);
if (isHTTP401Error(e)) {
- // Use setTimeout to show the session expired dialog
- // after the current confirmation dialog closes
+ // Wait for the confirmation dialog to close.
setTimeout(() => {
showMiniDialog(sessionExpiredDialogAttributes(logout));
}, 0);
@@ -138,8 +137,7 @@ const SessionsSettingsContents: React.FC<SessionsSettingsContentsProps> = ({
} catch (e) {
log.error("Failed to terminate session", e);
if (isHTTP401Error(e)) {
- // Use setTimeout to show the session expired dialog
- // after the current confirmation dialog closes
+ // Wait for the confirmation dialog to close.
setTimeout(() => {
showMiniDialog(
sessionExpiredDialogAttributes(
diff --git a/web/apps/photos/src/components/utils/dialog-attributes.tsx b/web/apps/photos/src/components/utils/dialog-attributes.tsx
index 95d7532849..4b67f97cb5 100644
--- a/web/apps/photos/src/components/utils/dialog-attributes.tsx
+++ b/web/apps/photos/src/components/utils/dialog-attributes.tsx
@@ -1,10 +1,6 @@
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import { t } from "i18next";
-/**
- * Create attributes for a {@link MiniDialog} notifying the user that some of
- * the files were not processed because they belonged to other users.
- */
export const notifyOthersFilesDialogAttributes = () => ({
title: t("note"),
icon: <InfoOutlinedIcon />,
@@ -12,11 +8,6 @@ export const notifyOthersFilesDialogAttributes = () => ({
cancel: t("ok"),
});
-/**
- * Create attributes for a {@link MiniDialog} notifying the user that some
- * shared files could not be favorited because they do not have the metadata
- * needed to match them with a user-owned favorite copy.
- */
export const notifyUnsupportedSharedFavoritesDialogAttributes = () => ({
title: t("note"),
icon: <InfoOutlinedIcon />,
diff --git a/web/apps/photos/src/components/utils/use-app-lock-route.ts b/web/apps/photos/src/components/utils/use-app-lock-route.ts
index 8dd517783b..0bd6fb8414 100644
--- a/web/apps/photos/src/components/utils/use-app-lock-route.ts
+++ b/web/apps/photos/src/components/utils/use-app-lock-route.ts
@@ -11,21 +11,12 @@ interface DesktopAppLockRouteState {
shouldBlockAppLockRouteTransition: boolean;
}
-/**
- * Since the app lock has its own separate page, when navigating there,
- * we save the user's current location so they can return to the same
- * page on unlock.
- */
+// Save the current route before locking; consume it once after unlock.
const rememberAppLockReturnTo = (path: string) => {
if (path === APP_LOCK_ROUTE) return;
sessionStorage.setItem(APP_LOCK_RETURN_TO_KEY, path);
};
-/**
- * Once the user has unlocked the application, navigate them back to the page
- * they were previously on (i.e., the page that was saved when the app locked).
- */
-
const consumeAppLockReturnTo = (): string | null => {
const returnTo = sessionStorage.getItem(APP_LOCK_RETURN_TO_KEY);
sessionStorage.removeItem(APP_LOCK_RETURN_TO_KEY);
@@ -40,33 +31,18 @@ export const useDesktopAppLockRoute = (
const router = useRouter();
const showLockPage = isDesktop && isLocked && lockScreenMode === "lock";
- /**
- * This useEffect runs when you are not in the /lock route,
- * it saves the current route in sessionStorage
- * and redirects the app to the /lock page.
- */
useEffect(() => {
- /**
- * Since the app lock is currently available only on desktop,
- * ensure that it is ready before navigating to the lock page.
- */
if (!isDesktop || !isAppLockReady || !showLockPage) return;
- // if the current page is not of the applock then saving it before navigation.
if (router.asPath !== APP_LOCK_ROUTE) {
rememberAppLockReturnTo(router.asPath);
}
- // if the current page is not applock, then navgiating to the applock page.
if (router.pathname !== APP_LOCK_ROUTE) {
void router.replace(APP_LOCK_ROUTE);
}
}, [isAppLockReady, showLockPage, router, router.asPath, router.pathname]);
- /**
- * This useEffect is just returning you to the page in which you where before
- * the app lock happened.
- */
useEffect(() => {
if (
!isDesktop ||
diff --git a/web/apps/photos/src/components/utils/use-app-lock.ts b/web/apps/photos/src/components/utils/use-app-lock.ts
index 551f54330b..8c18a85aa5 100644
--- a/web/apps/photos/src/components/utils/use-app-lock.ts
+++ b/web/apps/photos/src/components/utils/use-app-lock.ts
@@ -17,13 +17,7 @@ import { useEffect, useRef, useState } from "react";
const hydrateSessionFromSafeStorageIfNeeded = async () => {
try {
- /**
- * The current session's master key might already exist in the OS's safe
- * storage, so if found then write it back into browser sessionStorage.
- *
- * Without this the user would need to re-enter the password on every
- * desktop launch.
- */
+ // Restore the master key before refreshing the lock state.
await updateSessionFromElectronSafeStorageIfNeeded();
} catch (e) {
log.warn(
@@ -44,11 +38,6 @@ const bootstrapAppLock = async () => {
await refreshAppLockStateFromSession();
};
-/**
- * Initialize app lock and return its bootstrap state and retry callback.
- *
- * This is meant to be called once from the top-level `_app.tsx`.
- */
export const useSetupAppLock = () => {
const [status, setStatus] = useState<"loading" | "ready" | "error">(
"loading",
@@ -85,20 +74,14 @@ export const useSetupAppLock = () => {
};
};
-/**
- * Start and clear auto-lock timers as the app moves between background and
- * foreground states.
- */
export const useAutoLockWhenBackgrounded = (
enabled: AppLockState["enabled"],
isLocked: AppLockState["isLocked"],
autoLockTimeMs: AppLockState["autoLockTimeMs"],
) => {
- // Holds the current timeout handle for a scheduled auto-lock.
const pendingAutoLockTimeoutRef = useRef<ReturnType<
typeof setTimeout
> | null>(null);
- // Stores the exact timestamp when auto-lock should happen.
const autoLockDueAtTimestampRef = useRef<number | null>(null);
useEffect(() => {
@@ -113,8 +96,6 @@ export const useAutoLockWhenBackgrounded = (
};
const lockIfDeadlineElapsed = () => {
- // Return early if the lock deadline has not been reached yet.
- // If the deadline has passed, clear timer state and lock now.
const deadline = autoLockDueAtTimestampRef.current;
if (deadline === null) return false;
if (Date.now() < deadline) return false;
@@ -124,8 +105,6 @@ export const useAutoLockWhenBackgrounded = (
return true;
};
- // Called when the app is backgrounded.
- // Starts auto-lock unless the app is already locked.
const startAutoLockTimer = () => {
if (isLocked) return;
if (shouldSuppressAutoLockOnBlur()) return;
@@ -151,15 +130,12 @@ export const useAutoLockWhenBackgrounded = (
}, autoLockTimeMs);
};
- // On foreground, lock immediately if the deadline passed; otherwise clear pending timer.
const handleAppForegrounded = () => {
clearAutoLockBlurSuppression();
if (lockIfDeadlineElapsed()) return;
clearAutoLockTimer();
};
- // Hidden means backgrounded, so start auto-lock countdown.
- // Visible means foregrounded, so re-check deadline and clear timer if needed.
const handleVisibilityChange = () => {
if (document.hidden) {
startAutoLockTimer();
@@ -185,7 +161,6 @@ export const useAutoLockWhenBackgrounded = (
document.addEventListener("visibilitychange", handleVisibilityChange);
window.addEventListener("focus", handleWindowFocus);
- // cleanup
return () => {
document.removeEventListener(
"visibilitychange",
diff --git a/web/apps/photos/src/components/utils/use-is-offline.ts b/web/apps/photos/src/components/utils/use-is-offline.ts
index c82a4e722c..80583c9949 100644
--- a/web/apps/photos/src/components/utils/use-is-offline.ts
+++ b/web/apps/photos/src/components/utils/use-is-offline.ts
@@ -1,11 +1,5 @@
import { useEffect, useState } from "react";
-/**
- * A hook that returns true if the browser is currently offline.
- *
- * This hook returns the (negated) value of the navigator.onLine property, and
- * also monitors for changes.
- */
export const useIsOffline = () => {
const [offline, setOffline] = useState(
typeof window != "undefined" && !window.navigator.onLine,
diff --git a/web/apps/photos/src/components/utils/use-wrap-async.ts b/web/apps/photos/src/components/utils/use-wrap-async.ts
index c91d7a84e5..c96b47867e 100644
--- a/web/apps/photos/src/components/utils/use-wrap-async.ts
+++ b/web/apps/photos/src/components/utils/use-wrap-async.ts
@@ -2,21 +2,6 @@ import { useBaseContext } from "ente-base/context";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { useCallback } from "react";
-/**
- * Wrap a function returning a promise in a loading bar and error handler.
- *
- * This function wraps asynchronous operations (e.g. API calls) in an global
- * activity indicator and error handler. The global activity indicator and error
- * alert triggering mechanism is obtained from the app context.
- *
- * Specifically, this function takes an async function. It starts the global
- * activity indicator (using {@link showLoadingBar}), performs the operation,
- * and stops the activity indicator on completion (using
- * {@link hideLoadingBar}).
- *
- * If the operation throws, it shows a generic error (using
- * {@link onGenericError}).
- */
export const useWrapAsyncOperation = <T extends unknown[]>(
f: (...args: T) => Promise<void>,
) => {
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index 1e1357c601..d80a146cb3 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -96,10 +96,6 @@ const App: React.FC<PhotosAppProps> = ({ Component, pageProps }) => {
const electron = globalThis.electron;
if (!electron) return undefined;
- // Attach various listeners for events sent to us by the Node.js layer.
- // This is for events that we should listen for always, not just when
- // the user is logged in.
-
const handleOpenEnteURL = (url: string) => {
if (url.startsWith("ente://app")) {
void router.push(url);
@@ -174,13 +170,6 @@ const App: React.FC<PhotosAppProps> = ({ Component, pageProps }) => {
{isDesktop && <WindowTitlebar>{title}</WindowTitlebar>}
<BaseContext value={baseContext}>
- {
- // The web and desktop components are rendered separately
- // because the desktop currently supports app-lock,
- // for which we have certain hooks and components.
- // We don't want this to load in the web as well, since there
- // is no particular purpose it would serve.
- }
<PhotosAppContext value={appContext}>
{!isI18nReady ? (
<LoadingIndicator />
@@ -259,12 +248,10 @@ const WindowTitlebar: React.FC<React.PropsWithChildren> = ({ children }) => (
</WindowTitlebarArea>
);
-// See: [Note: Customize the desktop title bar]
+// Electron uses this as a window drag region.
const WindowTitlebarArea = styled(CenteredRow)`
width: 100%;
- height: env(titlebar-area-height, 30px /* fallback */);
- /* LoadingIndicator is 100vh, so resist shrinking when shown with it. */
+ height: env(titlebar-area-height, 30px);
flex-shrink: 0;
- /* Allow using the titlebar to drag the window. */
app-region: drag;
`;
diff --git a/web/apps/photos/src/pages/large-files.tsx b/web/apps/photos/src/pages/large-files.tsx
index 58b8bdeae5..7a363382b9 100644
--- a/web/apps/photos/src/pages/large-files.tsx
+++ b/web/apps/photos/src/pages/large-files.tsx
@@ -65,7 +65,6 @@ const Page: React.FC = () => {
useRedirectIfNeedsCredentials("/large-files");
useEffect(() => {
- // Track if this effect is still current to prevent race conditions
let isCurrent = true;
dispatch({ type: "analyze" });
@@ -122,7 +121,6 @@ const Page: React.FC = () => {
setOpenFileViewer(false);
}, []);
- // Extract files for the FileViewer.
const files = useMemo(
() => state.largeFiles.map((item) => item.file),
[state.largeFiles],
@@ -136,7 +134,6 @@ const Page: React.FC = () => {
case "failed":
return <LoadFailed />;
case "completed":
- // Show empty state only if no files AND no deletion in progress
if (
state.largeFiles.length === 0 &&
state.deleteProgress === undefined
@@ -180,7 +177,7 @@ const Page: React.FC = () => {
files={files}
initialIndex={currentIndex}
onVisualFeedback={() => {
- // No-op: Large files viewer is read-only
+ // The large-files viewer is read-only.
}}
/>
</Stack>
@@ -375,7 +372,7 @@ const LargeFilesGrid: React.FC<LargeFilesGridProps> = ({
const columns = layoutParams.columns;
const dataRowCount = Math.ceil(largeFiles.length / columns);
- // Add an extra row for bottom padding (to account for the floating bar)
+ // Reserve a final row for the floating bar.
const rowCount = dataRowCount + 1;
const itemData: LargeFilesGridItemData = {
@@ -394,7 +391,7 @@ const LargeFilesGrid: React.FC<LargeFilesGridProps> = ({
const itemKey = (index: number) =>
index === dataRowCount ? "padding" : `row-${index}`;
- // Key based on width to force re-render when layout changes
+ // react-window must remount when the layout width changes.
const key = `${width}`;
return (
@@ -429,14 +426,12 @@ const GridRow: React.FC<ListChildComponentProps<LargeFilesGridItemData>> = memo(
dataRowCount,
} = data;
- // Padding row at the end - render empty space
if (rowIndex === dataRowCount) {
return <div style={style} />;
}
const columns = layoutParams.columns;
- // Calculate which items are in this row
const startIndex = rowIndex * columns;
const endIndex = Math.min(startIndex + columns, largeFiles.length);
const rowItems = largeFiles.slice(startIndex, endIndex);
@@ -479,7 +474,6 @@ const GridItem: React.FC<GridItemProps> = memo(({ item, onToggle, onOpen }) => {
onOpenRef.current = onOpen;
}, [onOpen]);
- // Memoize touch device detection to avoid media query on every render
const isTouchDevice = useMemo(
() =>
typeof window !== "undefined" &&
@@ -487,7 +481,6 @@ const GridItem: React.FC<GridItemProps> = memo(({ item, onToggle, onOpen }) => {
[],
);
- // Cleanup timer on unmount to prevent memory leaks
useEffect(() => {
return () => {
if (longPressTimer.current) {
@@ -528,7 +521,6 @@ const GridItem: React.FC<GridItemProps> = memo(({ item, onToggle, onOpen }) => {
const handleClick = () => {
if (isLongPress.current) return;
- // On mobile, tap to toggle selection; on desktop, tap to open
if (isTouchDevice) {
onToggle();
} else {
@@ -667,15 +659,12 @@ const DeleteButton: React.FC<DeleteButtonProps> = ({
fontSize: { xs: "0.85rem", sm: "0.9rem" },
"&.Mui-disabled": isDeleting
? {
- // Keep critical color during deletion
backgroundColor: "critical.main",
color: "critical.contrastText",
}
: {
- // Light mode default
backgroundColor: "rgba(0, 0, 0, 0.3)",
color: "rgba(0, 0, 0, 0.5)",
- // Dark mode override
...theme.applyStyles("dark", {
backgroundColor: "rgba(255, 255, 255, 0.3)",
color: "rgba(255, 255, 255, 0.5)",
@@ -711,8 +700,6 @@ const DeleteButton: React.FC<DeleteButtonProps> = ({
);
};
-// --- Styled Components ---
-
interface ItemGridProps {
layoutParams: ThumbnailGridLayoutParams;
style?: React.CSSProperties;
@@ -786,6 +773,7 @@ const SizeLabel = styled(Typography)`
}
`;
+// Safari requires block-level positioned pseudo-elements here.
const Check = styled("input")(
({ theme }) => `
appearance: none;
@@ -807,19 +795,19 @@ const Check = styled("input")(
&::before {
content: "";
- display: block; /* Critical for Safari */
+ display: block;
width: 19px;
height: 19px;
background-color: ${theme.vars.palette.grey[300]};
border-radius: 50%;
margin: 6px;
transition: background-color 0.3s ease, opacity 0.3s ease;
- position: relative; /* Important for Safari */
+ position: relative;
}
&::after {
content: "";
- display: block; /* Critical for Safari */
+ display: block;
position: absolute;
top: 50%;
left: 50%;
@@ -832,16 +820,13 @@ const Check = styled("input")(
transform-origin: center;
}
- /* Default state - hidden */
visibility: hidden;
- /* Hover state - show with reduced opacity */
&:hover {
visibility: visible;
opacity: 0.7;
}
- /* Checked state - fully visible and colored */
&:checked {
visibility: visible;
opacity: 1 !important;
diff --git a/web/apps/photos/src/services/avatar.ts b/web/apps/photos/src/services/avatar.ts
index 6c5395302e..8b06cb55c9 100644
--- a/web/apps/photos/src/services/avatar.ts
+++ b/web/apps/photos/src/services/avatar.ts
@@ -1,28 +1,8 @@
-/**
- * The CSS color for the uploader indicator on a file that was uploaded to a
- * public "collect" link that the user has created.
- *
- * Such files belong to the user, even if they were uploaded by someone on their
- * behalf, and are thus marked differently (in this case, colorlessly) than
- * other shared files.
- *
- * This is a hex string, suitable for being used in CSS.
- */
+// Collect-link uploads are owned by the user, so their marker stays neutral.
export const avatarBackgroundColorPublicCollectedFile = "#000000";
-/**
- * Foreground / text color for the avatars.
- *
- * All avatar background colors are chosen to work with this.
- */
export const avatarTextColor = "#fff";
-/**
- * The ordered list of CSS colors for the owner indicator avatar background on
- * files that the user does not own in shared albums.
- *
- * Each entry is a hex string, suitable for being used in CSS.
- */
const avatarBackgroundColors = [
"#76549A",
"#DF7861",
@@ -49,18 +29,5 @@ const avatarBackgroundColors = [
"#78B5A7",
];
-/**
- * Return the CSS color to use as the background of the avatar indicating the
- * owner of a shared file.
- *
- * @param ownerID The user ID of the user who owns that file.
- *
- * Note that for the files in shared albums uploaded via collect links, while we
- * do show an avatar / uploader indicator, but these should use
- * {@link avatarBackgroundColorPublicCollectedFile}.
- *
- * @returns A a hex string, suitable for being used in CSS as the color of the
- * owner avatar indicator atop item thumbnails.
- */
export const avatarBackgroundColor = (ownerID: number) =>
avatarBackgroundColors[ownerID % avatarBackgroundColors.length]!;
diff --git a/web/apps/photos/src/services/cast.ts b/web/apps/photos/src/services/cast.ts
index 6138c1a151..b327f32393 100644
--- a/web/apps/photos/src/services/cast.ts
+++ b/web/apps/photos/src/services/cast.ts
@@ -5,9 +5,6 @@ import { apiURL } from "ente-base/origins";
import type { Collection } from "ente-media/collection";
import { z } from "zod";
-/**
- * Revoke all existing outstanding cast tokens for the current user on remote.
- */
export const revokeAllCastTokens = async () =>
ensureOk(
await fetch(await apiURL("/cast/revoke-all-tokens"), {
@@ -16,11 +13,6 @@ export const revokeAllCastTokens = async () =>
}),
);
-/**
- * Fetch the public key (represented as a base64 string) associated with the
- * given device / pairing {@link code} from remote, or `undefined` if there is
- * no public key associated with the given code.
- */
const publicKeyForPairingCode = async (code: string) => {
const res = await fetch(await apiURL(`/cast/device-info/${code}`), {
headers: await authenticatedRequestHeaders(),
@@ -31,32 +23,18 @@ const publicKeyForPairingCode = async (code: string) => {
.publicKey;
};
+// AlbumCastDialog matches this exact message.
export const unknownDeviceCodeErrorMessage = "Unknown device code";
-/**
- * Publish encrypted payload for a cast session so that the paired device can
- * obtain the information it needs to cast a collection.
- *
- * If no device was found for the given {@link deviceCode}, then this function
- * will throw an error with the message
- * @param deviceCode The PIN / device code that the user entered to pair with
- * the casting end.
- *
- * @param collection The collection that the user wants to cast.
- */
export const publishCastPayload = async (
deviceCode: string,
collection: Collection,
) => {
- // Find out the public key associated with the given pairing code (if
- // indeed a device has published one).
const publicKey = await publicKeyForPairingCode(deviceCode);
if (!publicKey) throw new Error(unknownDeviceCodeErrorMessage);
- // Generate random id.
const castToken = newID("cast_");
- // Publish the payload so that the other end can use it.
const payload = JSON.stringify({
castToken,
collectionID: collection.id,
diff --git a/web/apps/photos/src/services/changelog.ts b/web/apps/photos/src/services/changelog.ts
index dbdecd3b11..2b2d3e95df 100644
--- a/web/apps/photos/src/services/changelog.ts
+++ b/web/apps/photos/src/services/changelog.ts
@@ -1,54 +1,17 @@
import type { Electron } from "ente-base/types/ipc";
-/**
- * The current changelog version.
- *
- * [Note: Conditions for showing "What's new"]
- *
- * We maintain a "changelog version". This version is an incrementing positive
- * integer, we increment it whenever we want to show this dialog again. Usually
- * we'd do this for each app update, but not necessarily.
- *
- * The "What's new" dialog is shown when the saved changelog version is less
- * than the current {@link changelogVersion}.
- *
- * The shown changelog version is saved on the Node.js layer since there we can
- * store it in the user preferences store, which is not cleared on logout.
- *
- * On app start, we read the last saved version:
- *
- * - If it is not present, we set it to the current version _without_ showing
- * the what's new dialog. This is to handle fresh installs.
- *
- * - If it is present and less than the current version, we show the what's new
- * dialog. Otherwise do nothing.
- *
- * The what's new dialog sets the saved version to the current one whenever it
- * is shown.
- */
const changelogVersion = 13;
-/**
- * Return true if we should show the {@link WhatsNew} dialog.
- *
- * It has the side affect of updating the persisted version (whilst returning
- * false) if there was no previous persisted changelog version version present.
- */
export const shouldShowWhatsNew = async (electron: Electron) => {
const lastShownVersion = await electron.lastShownChangelogVersion();
if (!lastShownVersion) {
- // On a fresh install, save the current version but don't show the
- // what's new dialog.
+ // A fresh install saves the version without showing the dialog.
await electron.setLastShownChangelogVersion(changelogVersion);
return false;
}
- // Show what's new if the saved version is older than the current one.
return lastShownVersion < changelogVersion;
};
-/**
- * Set the saved changelog version to the current changelog version.
- */
export const didShowWhatsNew = async (electron: Electron) =>
electron.setLastShownChangelogVersion(changelogVersion);
diff --git a/web/apps/photos/src/services/logout.ts b/web/apps/photos/src/services/logout.ts
index 79c002b26d..138f6ccdbd 100644
--- a/web/apps/photos/src/services/logout.ts
+++ b/web/apps/photos/src/services/logout.ts
@@ -17,34 +17,20 @@ import { logoutSettings } from "ente-new/photos/services/settings";
import { logoutUserDetails } from "ente-new/photos/services/user-details";
import { uploadManager } from "./upload-manager";
-/**
- * Logout sequence for the photos app.
- *
- * This function is guaranteed not to throw any errors.
- *
- * See: [Note: Do not throw during logout].
- */
+// Individual cleanup failures must not abort logout.
export const photosLogout = async () => {
const ignoreError = (label: string, e: unknown) =>
log.error(`Ignoring error during logout (${label})`, e);
- // - Workers
-
- // Terminate any workers that might access the DB before clearing persistent
- // state. See: [Note: Caching IDB instances in separate execution contexts].
-
+ // Stop workers before clearing databases they may still access.
try {
await terminateMLWorker();
} catch (e) {
ignoreError("ML/worker", e);
}
- // - Remote logout and clear state
-
await accountLogout();
- // - Photos specific logout
-
log.info("logout (photos)");
try {
@@ -107,8 +93,6 @@ export const photosLogout = async () => {
ignoreError("File viewer", e);
}
- // - Desktop
-
const electron = globalThis.electron;
if (electron) {
try {
@@ -136,9 +120,7 @@ export const photosLogout = async () => {
}
}
- // Clear the DB again to discard any in-flight completions that might've
- // happened since we started.
-
+ // Clear again after in-flight work has had a chance to finish.
await logoutClearStateAgain();
try {
@@ -147,10 +129,6 @@ export const photosLogout = async () => {
ignoreError("Files DB", e);
}
- // [Note: Full reload on logout]
- //
- // Do a full reload to discard any in-flight requests that might still
- // remain.
-
+ // Reload to discard any requests still in flight.
window.location.replace("/");
};
diff --git a/web/apps/photos/src/services/migration.ts b/web/apps/photos/src/services/migration.ts
index c03038edcb..c46fdcb011 100644
--- a/web/apps/photos/src/services/migration.ts
+++ b/web/apps/photos/src/services/migration.ts
@@ -1,41 +1,15 @@
import { getKVN, setKV } from "ente-base/kv";
import log from "ente-base/log";
-/**
- * App specific migrations.
- *
- * The app stores data in multiple places: local storage, IndexedDB, OPFS, and
- * not all of these support DB migrations. And even when they do, those are
- * rather heavy weight and complicated (e.g. IndexedDB).
- *
- * Further, there are various app level migrations, e.g. resetting the diff
- * fetch times, that don't correspond to DB migrations, these are just changes
- * we need to make to our locally persisted values and not the schemas
- * themselves.
- *
- * Thus we introduce the concept of app level migrations. This is some code
- * which runs early in the page load, and runs arbitrary blocks of code until it
- * reaches the last migration number.
- *
- * We can put all sorts of changes here: cleanup of legacy keys, re-triggers for
- * various fetches etc.
- *
- * This code usually runs fairly early on page load, but if you need specific
- * guarantees or have dependencies in the order of operations (beyond what is
- * captured by the sequential flow here), then this might not be appropriate.
- */
+// Runs cross-store migrations sequentially before normal app startup.
+// Do not add work here that depends on later initialization.
export const runMigrations = async () => {
const m = (await getKVN("migrationLevel")) ?? 0;
const latest = 5;
if (m < latest) {
log.info(`Running migrations ${m} => ${latest}`);
// Migration levels 1-5 (Aug 2024 - Feb 2025) were pruned.
- // New migrations should be 6+. e.g.,
- // if (m < 6) await m6();
+ // New migrations should be 6+.
await setKV("migrationLevel", latest);
}
};
-
-// const m6 = () => {
-// // See git history for other examples.
-// }
diff --git a/web/apps/photos/src/services/storage-bonus.ts b/web/apps/photos/src/services/storage-bonus.ts
index d75c6e30fb..183d9dca07 100644
--- a/web/apps/photos/src/services/storage-bonus.ts
+++ b/web/apps/photos/src/services/storage-bonus.ts
@@ -6,42 +6,27 @@ const ReferralView = z.object({
planInfo: z.object({ isEnabled: z.boolean(), storageInGB: z.number() }),
code: z.string(),
enableApplyCode: z.boolean(),
- /**
- * `true` iff the user is a non-admin family member; the referral owner is
- * then the family admin.
- */
+ // For non-admin family members, the family admin owns the referral.
isFamilyMember: z.boolean(),
- /**
- * Active REFERRAL + SIGN_UP bonus sum of the referral owner (in bytes).
- */
+ // Active referral and sign-up bonuses owned by the referral owner, in bytes.
claimedStorage: z.number(),
remainingCodeChangeAttempts: z.number().optional(),
});
-/**
- * Referral information for the currently logged in user.
- */
export type ReferralView = z.infer<typeof ReferralView>;
-// Remote also returns referralStats and bonuses arrays. They are not modelled
-// here; Zod strips the unknown keys.
+// Zod intentionally strips the remote referralStats and bonuses arrays.
const StorageBonusDetails = z.object({
refCount: z.number(),
refUpgradeCount: z.number(),
hasAppliedCode: z.boolean(),
});
-/**
- * Aggregate referral bonus details for the currently logged in user.
- */
export type StorageBonusDetails = z.infer<typeof StorageBonusDetails>;
export const normalizeReferralCode = (code: string) =>
code.trim().toUpperCase();
-/**
- * Fetch the referral view for the currently logged in user from remote.
- */
export const getReferralView = async (): Promise<ReferralView> => {
const res = await fetch(await apiURL("/storage-bonus/referral-view"), {
headers: await authenticatedRequestHeaders(),
@@ -50,10 +35,6 @@ export const getReferralView = async (): Promise<ReferralView> => {
return ReferralView.parse(await res.json());
};
-/**
- * Fetch aggregate storage bonus details for the currently logged in user from
- * remote.
- */
export const getStorageBonusDetails =
async (): Promise<StorageBonusDetails> => {
const res = await fetch(await apiURL("/storage-bonus/details"), {
@@ -63,9 +44,6 @@ export const getStorageBonusDetails =
return StorageBonusDetails.parse(await res.json());
};
-/**
- * Change the referral code for the currently logged in user.
- */
export const changeReferralCode = async (code: string): Promise<void> => {
ensureOk(
await fetch(await apiURL("/storage-bonus/change-code"), {
@@ -76,9 +54,6 @@ export const changeReferralCode = async (code: string): Promise<void> => {
);
};
-/**
- * Claim a referral code for the currently logged in user.
- */
export const claimReferralCode = async (code: string): Promise<void> => {
ensureOk(
await fetch(
diff --git a/web/apps/photos/src/utils/chromecast-sender.ts b/web/apps/photos/src/utils/chromecast-sender.ts
index 8b5f4e93df..6f6801fd02 100644
--- a/web/apps/photos/src/utils/chromecast-sender.ts
+++ b/web/apps/photos/src/utils/chromecast-sender.ts
@@ -1,14 +1,5 @@
/* eslint-disable @typescript-eslint/no-namespace */
-/**
- * The types for the sender are already available as
- * "@types/chromecast-caf-sender", however installing them breaks the types for
- * the cast receiver in apps/cast. Vice-versa, having those types for the
- * receiver ("@types/chromecast-caf-receiver") conflicts with the types that we
- * add for the sender.
- *
- * As a workaround, this file includes the handpicked interface from
- * "@types/chromecast-caf-sender" for only the parts that we use.
- */
+// Sender and receiver @types conflict, so declare only the sender APIs used here.
declare global {
interface Window {
@@ -18,18 +9,11 @@ declare global {
}
declare namespace chrome.cast {
- /**
- * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast#.AutoJoinPolicy
- */
export enum AutoJoinPolicy {
ORIGIN_SCOPED = "origin_scoped",
}
}
-/**
- * Cast Application Framework
- * @see https://developers.google.com/cast/docs/reference/chrome/cast.framework
- */
declare namespace cast.framework {
interface CastOptions {
autoJoinPolicy: chrome.cast.AutoJoinPolicy;
@@ -52,9 +36,6 @@ declare namespace cast.framework {
}
}
-/**
- * Load the Chromecast script, resolving with the global `cast` object.
- */
export const loadCast = (() => {
let promise: Promise<typeof cast> | undefined;
diff --git a/web/apps/photos/src/utils/file/index.ts b/web/apps/photos/src/utils/file/index.ts
index 857335b6ca..4bc1ca7fae 100644
--- a/web/apps/photos/src/utils/file/index.ts
+++ b/web/apps/photos/src/utils/file/index.ts
@@ -20,11 +20,7 @@ export interface SelectedState {
ownCount: number;
count: number;
collectionID: number | undefined;
- /**
- * The context in which the selection was made. Only set by newer code if
- * there is an active selection (older code continues to rely on the
- * {@link collectionID} logic).
- */
+ // New selection code sets context; legacy callers still use collectionID.
context: SelectionContext | undefined;
}
export type SetSelectedState = React.Dispatch<
diff --git a/web/apps/photos/src/utils/native-fs.ts b/web/apps/photos/src/utils/native-fs.ts
index 94e935a525..13773275db 100644
--- a/web/apps/photos/src/utils/native-fs.ts
+++ b/web/apps/photos/src/utils/native-fs.ts
@@ -1,10 +1,3 @@
-/**
- * @file Utilities for native file system access.
- *
- * While they don't have any direct dependencies to our desktop app, they were
- * written for use by the code that runs in our desktop app.
- */
-
import { joinPath, nameAndExtension } from "ente-base/file-name";
import {
exportMetadataDirectoryName,
@@ -12,27 +5,8 @@ import {
} from "ente-gallery/export-dirs";
import sanitize from "sanitize-filename";
-/**
- * Sanitize string for use as file or directory name.
- *
- * Return a string suitable for use as a file or directory name by replacing
- * directory separators and invalid characters in the input string {@link s}
- * with "_".
- */
const sanitizeFilename = (s: string) => sanitize(s, { replacement: "_" });
-/**
- * Return a new sanitized and unique directory name based on {@link name} that
- * is not the same as any existing item in the given {@link directoryPath}.
- *
- * We also ensure we don't return names which might collide with our own special
- * directories.
- *
- * @param exists A function to check if an item already exists at the given
- * path. Usually, you'd pass `fs.exists` from {@link Electron}.
- *
- * See also: {@link safeFileame}
- */
export const safeDirectoryName = async (
directoryPath: string,
name: string,
@@ -55,12 +29,6 @@ export const safeDirectoryName = async (
return result;
};
-/**
- * Return a new sanitized and unique file name based on {@link name} that is not
- * the same as any existing item in the given {@link directoryPath}.
- *
- * This is a sibling of {@link safeDirectoryName} for use with file names.
- */
export const safeFileName = async (
directoryPath: string,
name: string,
diff --git a/web/apps/photos/src/utils/photoFrame/index.ts b/web/apps/photos/src/utils/photoFrame/index.ts
index 6daa2161f7..d24038b3da 100644
--- a/web/apps/photos/src/utils/photoFrame/index.ts
+++ b/web/apps/photos/src/utils/photoFrame/index.ts
@@ -129,8 +129,6 @@ const createSelectedAndContext = (
};
}
} else if (!selected.context) {
- // Gallery will specify a mode, but a fresh selection starts off
- // without a context, so fill it in with the current context.
selected = {
...selected,
context:
@@ -139,9 +137,7 @@ const createSelectedAndContext = (
: { mode, collectionID: activeCollectionID },
};
} else {
- // Both mode and context are defined.
if (selected.context.mode != mode) {
- // Clear selection if mode has changed.
selected = {
ownCount: 0,
count: 0,
@@ -154,7 +150,6 @@ const createSelectedAndContext = (
} else {
if (selected.context.mode == "people") {
if (selected.context.personID != activePersonID) {
- // Clear selection if person has changed.
selected = {
ownCount: 0,
count: 0,
@@ -167,7 +162,6 @@ const createSelectedAndContext = (
}
} else {
if (selected.context.collectionID != activeCollectionID) {
- // Clear selection if collection has changed.
selected = {
ownCount: 0,
count: 0,
diff --git a/web/packages/accounts/services/join-album.ts b/web/packages/accounts/services/join-album.ts
index 8ea37e6a3a..e101edb52b 100644
--- a/web/packages/accounts/services/join-album.ts
+++ b/web/packages/accounts/services/join-album.ts
@@ -8,12 +8,7 @@ import {
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
-/**
- * The expected length in bytes for a collection key.
- *
- * This matches SecretBoxKeyBytes (crypto_secretbox_KEYBYTES) in libsodium,
- * which is 32 bytes (256 bits).
- */
+// libsodium secretbox keys are 32 bytes.
const collectionKeyBytes = 32;
const joinPublicAlbum = async (
@@ -57,12 +52,6 @@ const joinPublicAlbum = async (
}
};
-/**
- * Process the pending album join after authentication.
- * This should be called after successful sign-in/sign-up.
- *
- * @returns The collection ID if an album was successfully joined, null otherwise
- */
export const processPendingAlbumJoin = async (): Promise<number | null> => {
const context = getJoinAlbumContext();
@@ -73,7 +62,6 @@ export const processPendingAlbumJoin = async (): Promise<number | null> => {
try {
const collectionID = context.collectionID;
- // Get user's key attributes from local storage
const keyAttributes = savedKeyAttributes();
if (!keyAttributes) {
throw new Error(
@@ -83,9 +71,6 @@ export const processPendingAlbumJoin = async (): Promise<number | null> => {
const publicKey = keyAttributes.publicKey;
- // Validate the collection key is exactly 32 bytes (256 bits)
- // This matches SecretBoxKeyBytes on the server and prevents processing
- // malformed join album URLs
const collectionKeyBytes_ = await fromB64(context.collectionKey);
if (collectionKeyBytes_.length !== collectionKeyBytes) {
log.warn("Invalid collection key length in join album context");
@@ -93,12 +78,9 @@ export const processPendingAlbumJoin = async (): Promise<number | null> => {
return null;
}
- // Encrypt the collection key with user's public key
- // The collection key is already base64 encoded, and boxSeal expects base64
+ // boxSeal accepts the already-base64 collection key.
const encryptedKey = await boxSeal(context.collectionKey, publicKey);
- // Join the album (include JWT token if present for password-protected albums)
- // Server validates ownership and returns error if user is the album owner
await joinPublicAlbum(
context.accessToken,
collectionID,
@@ -106,12 +88,11 @@ export const processPendingAlbumJoin = async (): Promise<number | null> => {
context.accessTokenJWT,
);
- // Clear the context after successful join
clearJoinAlbumContext();
return collectionID;
} catch (error) {
- // Clear the context on failure to avoid repeated attempts
+ // Do not retry a failed join on every login.
clearJoinAlbumContext();
log.error("Failed to process pending album join", {
collectionID: context.collectionID,
diff --git a/web/packages/base/assert.ts b/web/packages/base/assert.ts
index 6f4743e7db..a29e0f70b0 100644
--- a/web/packages/base/assert.ts
+++ b/web/packages/base/assert.ts
@@ -1,13 +1,6 @@
import { isDevBuild } from "./env";
import log from "./log";
-/**
- * If running in a dev build, throw an exception with the given message.
- * Otherwise log it as a warning.
- *
- * @param message An optional message to use for the failure. If not provided,
- * then a generic one is used.
- */
export const assertionFailed = (message?: string) => {
message = message ?? "Assertion failed";
if (isDevBuild) throw new Error(message);
diff --git a/web/packages/base/bytes.ts b/web/packages/base/bytes.ts
index a701b2f62f..75118b9297 100644
--- a/web/packages/base/bytes.ts
+++ b/web/packages/base/bytes.ts
@@ -2,10 +2,6 @@ export const isArrayBufferBacked = (
bytes: Uint8Array,
): bytes is Uint8Array<ArrayBuffer> => bytes.buffer instanceof ArrayBuffer;
-/**
- * Return {@link bytes} when it is backed by an {@link ArrayBuffer}; otherwise
- * copy it into a new {@link Uint8Array} with an {@link ArrayBuffer} backing.
- */
export const ensureArrayBufferBacked = (
bytes: Uint8Array,
): Uint8Array<ArrayBuffer> =>
diff --git a/web/packages/base/components/EnteLogo.tsx b/web/packages/base/components/EnteLogo.tsx
index c3cd69e1d0..a1e573691c 100644
--- a/web/packages/base/components/EnteLogo.tsx
+++ b/web/packages/base/components/EnteLogo.tsx
@@ -3,26 +3,9 @@ import React from "react";
import { enteWordmarkPaths, enteWordmarkViewBox } from "./ente-wordmark";
interface EnteLogoProps {
- /**
- * The height of the logo image, in pixels.
- *
- * Default: 18px
- */
height?: number;
}
-/**
- * The Ente wordmark, as an inline SVG.
- *
- * Having it as an inline SVG has two advantages:
- *
- * - It does not rely on a corresponding asset in the public folder
- * - It can be styled using CSS.
- *
- * The default height of the SVG element is 18px. The size can be customized by
- * providing a {@link height} prop: the SVG will preserve its aspect ratio when
- * fitting inside the provided viewport.
- */
export const EnteLogo: React.FC<EnteLogoProps> = ({ height }) => (
<svg
height={height ?? 18}
@@ -35,16 +18,7 @@ export const EnteLogo: React.FC<EnteLogoProps> = ({ height }) => (
</svg>
);
-/**
- * A container for {@link EnteLogo} that resets the line height to vertically
- * center the logo within the surrounding context.
- *
- * By default, the line height causes the SVG to have an extra space at the
- * bottom. Removing it allows the SVG contents to be centered using its inherent
- * sizing. This is a convenience container that resets the line height, and also
- * takes the {@link sx} prop to allow for easy tweaking of other styling of the
- * container without touching the SVG.
- */
+// Remove the inline SVG's baseline gap.
export const EnteLogoBox = styled("div")`
line-height: 0;
`;
diff --git a/web/packages/base/components/EnteSwitch.tsx b/web/packages/base/components/EnteSwitch.tsx
index b339fafecb..6611cde5f2 100644
--- a/web/packages/base/components/EnteSwitch.tsx
+++ b/web/packages/base/components/EnteSwitch.tsx
@@ -1,9 +1,6 @@
import { Switch, styled, type SwitchProps } from "@mui/material";
import React from "react";
-/**
- * A custom variant of the MUI {@link Switch}, styled per our designs.
- */
export const EnteSwitch: React.FC<SwitchProps> = styled((props) => (
<Switch disableRipple {...props} />
))(({ theme }) => ({
@@ -41,13 +38,10 @@ export const EnteSwitch: React.FC<SwitchProps> = styled((props) => (
duration: 500,
}),
},
- // Use an alternative affordance to indicate focusVisible as the ripple
- // effect is disabled.
".MuiSwitch-switchBase.Mui-focusVisible + .MuiSwitch-track": {
outline: `2px solid ${theme.vars.palette.stroke.muted}`,
outlineOffset: "-2px",
},
- // Same for when the switch is active.
".MuiSwitch-switchBase:active + .MuiSwitch-track": {
outline: `1px solid ${theme.vars.palette.stroke.faint}`,
outlineOffset: "-1px",
diff --git a/web/packages/base/components/ErrorIndicator.tsx b/web/packages/base/components/ErrorIndicator.tsx
index 1548dd57c3..0a50d58d2a 100644
--- a/web/packages/base/components/ErrorIndicator.tsx
+++ b/web/packages/base/components/ErrorIndicator.tsx
@@ -3,13 +3,6 @@ import { Stack, Typography } from "@mui/material";
import { t } from "i18next";
import type React from "react";
-/**
- * An error message indicator, styled to complement {@link ActivityIndicator}.
- *
- * If a child is provided, it is used as the error message to show (after being
- * wrapped in a suitable {@link Typography}). Otherwise the default generic
- * error message is shown.
- */
export const ActivityErrorIndicator: React.FC<React.PropsWithChildren> = ({
children,
}) => (
@@ -21,14 +14,6 @@ export const ActivityErrorIndicator: React.FC<React.PropsWithChildren> = ({
</Stack>
);
-/**
- * An smaller error message indicator suitable for being shown above or below
- * text fields.
- *
- * If a child is provided, it is used as the error message to show (after being
- * wrapped in a suitable {@link Typography}). Otherwise the default generic
- * error message is shown.
- */
export const InlineErrorIndicator: React.FC<React.PropsWithChildren> = ({
children,
}) => (
diff --git a/web/packages/base/components/LinkButton.tsx b/web/packages/base/components/LinkButton.tsx
index cd7be3fd57..57002f2a7f 100644
--- a/web/packages/base/components/LinkButton.tsx
+++ b/web/packages/base/components/LinkButton.tsx
@@ -1,12 +1,6 @@
import { Link, type ButtonProps } from "@mui/material";
import React from "react";
-/**
- * A button that looks like a link.
- *
- * The use of this component is not encouraged. It is only useful in uncommon
- * cases where we do not have sufficient space to include a proper button.
- */
export const LinkButton: React.FC<
React.PropsWithChildren<Pick<ButtonProps, "onClick">>
> = ({ onClick, children }) => (
@@ -15,8 +9,7 @@ export const LinkButton: React.FC<
sx={(theme) => ({
color: "text.base",
textDecoration: "underline",
- // The shortcut "text.faint" does not work with textDecorationColor
- // (as of MUI v6).
+ // Palette shorthand does not resolve for textDecorationColor.
textDecorationColor: theme.vars.palette.text.faint,
"&:hover": {
color: "accent.main",
@@ -30,12 +23,6 @@ export const LinkButton: React.FC<
</Link>
);
-/**
- * A variant of {@link LinkButton} that does not show an underline, and instead
- * uses a bolder font weight to indicate clickability.
- *
- * Similar caveats as {@link LinkButton} apply.
- */
export const LinkButtonUndecorated: React.FC<
React.PropsWithChildren<Pick<ButtonProps, "onClick">>
> = ({ onClick, children }) => (
diff --git a/web/packages/base/components/SingleInputDialog.tsx b/web/packages/base/components/SingleInputDialog.tsx
index 124ef8b43b..8031dd721d 100644
--- a/web/packages/base/components/SingleInputDialog.tsx
+++ b/web/packages/base/components/SingleInputDialog.tsx
@@ -15,20 +15,8 @@ import React, { useCallback } from "react";
import { SingleInputForm, type SingleInputFormProps } from "./SingleInputForm";
type SingleInputDialogProps = ModalVisibilityProps &
- Omit<SingleInputFormProps, "onCancel"> & {
- /** Title of the dialog. */
- title: string;
- };
+ Omit<SingleInputFormProps, "onCancel"> & { title: string };
-/**
- * A dialog that can be used to ask for a single text input using a
- * {@link SingleInputForm}.
- *
- * The dialog closes when the promise returned by the {@link onSubmit} callback
- * fulfills.
- *
- * See also: {@link CollectionNamer}, its older sibling.
- */
export const SingleInputDialog: React.FC<SingleInputDialogProps> = ({
open,
onClose,
diff --git a/web/packages/base/components/ThemedLoadingBar.tsx b/web/packages/base/components/ThemedLoadingBar.tsx
index 6e6df7853d..a185b4a1b7 100644
--- a/web/packages/base/components/ThemedLoadingBar.tsx
+++ b/web/packages/base/components/ThemedLoadingBar.tsx
@@ -7,10 +7,6 @@ interface ThemedLoadingBarProps {
ref: React.Ref<LoadingBarController>;
}
-/**
- * A wrapper over the {@link LoadingBar} library component that sets it to use
- * the main accent color from the theme.
- */
export const ThemedLoadingBar: React.FC<ThemedLoadingBarProps> = ({ ref }) => {
const theme = useTheme();
diff --git a/web/packages/base/components/Typography.tsx b/web/packages/base/components/Typography.tsx
index 9fa71e7b73..fe234ae4fd 100644
--- a/web/packages/base/components/Typography.tsx
+++ b/web/packages/base/components/Typography.tsx
@@ -1,36 +1,16 @@
import { styled, Typography } from "@mui/material";
-/**
- * A variant of {@link Typography} that inserts ellipsis instead of wrapping the
- * text over multiple lines, or letting it overflow.
- *
- * Refs:
- * - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text/Wrapping_breaking_text
- * - https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
- */
export const EllipsizedTypography = styled(Typography)`
- /* Initial value of overflow is visible. Set overflow (the handling of
- content that is too small for the container in the inline direction) to
- hidden instead. */
overflow: hidden;
- /* Specify handling of text when it overflows, asking the browser to insert
- ellipsis instead of clipping.
-
- Note that both overflow and text-overflow are required.
- */
text-overflow: ellipsis;
- /* Don't automatically wrap the text by inserting line breaks. */
white-space: nowrap;
`;
-/**
- * A variant of {@link EllipsizedTypography} that takes up to 2 lines.
- */
export const Ellipsized2LineTypography = styled(Typography)`
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
- -webkit-line-clamp: 2; /* number of lines to show */
+ -webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
word-break: break-word;
diff --git a/web/packages/base/components/ente-wordmark.ts b/web/packages/base/components/ente-wordmark.ts
index 061f740761..5f140ad67d 100644
--- a/web/packages/base/components/ente-wordmark.ts
+++ b/web/packages/base/components/ente-wordmark.ts
@@ -1,6 +1,3 @@
-/**
- * Shared geometry for the Ente wordmark across React and non-React surfaces.
- */
export const enteWordmarkViewBox = "0 0 844 264";
export const enteWordmarkPaths = [
diff --git a/web/packages/base/components/loaders.tsx b/web/packages/base/components/loaders.tsx
index c0a24bec2a..3d06dc7e1b 100644
--- a/web/packages/base/components/loaders.tsx
+++ b/web/packages/base/components/loaders.tsx
@@ -4,31 +4,16 @@ import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
import { t } from "i18next";
import React from "react";
-/**
- * A centered activity indicator shown in a container that fills up the entire
- * width and height of the viewport.
- *
- * This is meant as a root component of a page, e.g., during initial load.
- */
export const LoadingIndicator: React.FC = () => (
<Stack100vhCenter>
<ActivityIndicator />
</Stack100vhCenter>
);
-/**
- * An translucent overlay that covers the entire viewport and shows an activity
- * indicator in its center.
- *
- * Used as a overlay during blocking actions. The use of this component is not
- * recommended for new code.
- */
+// Prefer localized activity indicators in new code.
export const TranslucentLoadingOverlay: React.FC = () => (
<Backdrop
- // Specifying open here causes us to lose animations. This is not
- // optimal, but fine for now since this the use of this is limited to a
- // few interstitial overlays, and if refactoring consider replacing this
- // entirely with a more localized activity indicator.
+ // A Backdrop mounted already open has no entrance transition.
open={true}
slotProps={{
root: {
@@ -41,8 +26,6 @@ export const TranslucentLoadingOverlay: React.FC = () => (
sx={{
backgroundColor: "var(--mui-palette-backdrop-muted)",
backdropFilter: "blur(30px) opacity(95%)",
- /* Above the highest possible MUI z-index, that of the MUI tooltip
- See: https://mui.com/material-ui/customization/default-theme/ */
zIndex: "calc(var(--mui-zIndex-tooltip) + 1)",
}}
>
diff --git a/web/packages/base/components/mui/ActivityIndicator.tsx b/web/packages/base/components/mui/ActivityIndicator.tsx
index bd9e7620c2..7b2bb818fd 100644
--- a/web/packages/base/components/mui/ActivityIndicator.tsx
+++ b/web/packages/base/components/mui/ActivityIndicator.tsx
@@ -6,16 +6,6 @@ import {
} from "@mui/material";
import type React from "react";
-/**
- * A standard {@link CircularProgress} for use in our code.
- *
- * If a child is specified, it is wrapped in a Typography and shown as a caption
- * below the {@link CircularProgress}.
- *
- * While it does take and forward props to the the underlying
- * {@link CircularProgress}, if you find yourself needing to customize it too
- * much, consider directly using a {@link CircularProgress} instead.
- */
export const ActivityIndicator: React.FC<
React.PropsWithChildren<CircularProgressProps>
> = ({ children, ...rest }) =>
diff --git a/web/packages/base/components/mui/DialogCloseIconButton.tsx b/web/packages/base/components/mui/DialogCloseIconButton.tsx
index 6b8fc24856..0329e6f8a1 100644
--- a/web/packages/base/components/mui/DialogCloseIconButton.tsx
+++ b/web/packages/base/components/mui/DialogCloseIconButton.tsx
@@ -6,13 +6,6 @@ import React from "react";
type DialogCloseIconButtonProps = Omit<ModalVisibilityProps, "open">;
-/**
- * A convenience {@link IconButton} commonly needed on {@link Dialog}s, at the
- * top right, to allow the user to close the dialog.
- *
- * Note that an explicit "Cancel" button is a better approach whenever possible,
- * so use this sparingly.
- */
export const DialogCloseIconButton: React.FC<DialogCloseIconButtonProps> = ({
onClose,
}) => (
diff --git a/web/packages/base/components/mui/FocusVisibleButton.tsx b/web/packages/base/components/mui/FocusVisibleButton.tsx
index 3fdc016783..a048eda98d 100644
--- a/web/packages/base/components/mui/FocusVisibleButton.tsx
+++ b/web/packages/base/components/mui/FocusVisibleButton.tsx
@@ -6,10 +6,6 @@ export const RippleDisabledButton: React.FC<ButtonProps> = (props) => (
<Button disableRipple {...props} />
);
-/**
- * A MUI {@link Button} that shows a keyboard focus indicator (e.g. when the
- * user tabs to it) and also an affordance to indicate when it is activated.
- */
export const FocusVisibleButton = styled(RippleDisabledButton)(
({ theme }) => `
&.Mui-focusVisible {
diff --git a/web/packages/base/components/mui/LoadingButton.tsx b/web/packages/base/components/mui/LoadingButton.tsx
index 84ae32a907..6298e25c9a 100644
--- a/web/packages/base/components/mui/LoadingButton.tsx
+++ b/web/packages/base/components/mui/LoadingButton.tsx
@@ -3,12 +3,6 @@ import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton"
import { isSxArray } from "ente-base/components/utils/sx";
import React from "react";
-/**
- * A button that shows a indeterminate progress indicator if the {@link loading}
- * prop is set.
- *
- * The button is also disabled when in the loading state.
- */
export const LoadingButton: React.FC<ButtonProps & { loading?: boolean }> = ({
loading,
disabled,
diff --git a/web/packages/base/components/mui/PasswordInputAdornment.tsx b/web/packages/base/components/mui/PasswordInputAdornment.tsx
index 08c4771bc6..4397634b35 100644
--- a/web/packages/base/components/mui/PasswordInputAdornment.tsx
+++ b/web/packages/base/components/mui/PasswordInputAdornment.tsx
@@ -5,28 +5,14 @@ import { t } from "i18next";
import React from "react";
interface ShowHidePasswordInputAdornmentProps {
- /**
- * When `true`, the password is being shown.
- */
showPassword: boolean;
- /**
- * Called when the user wants to toggle the state of {@link showPassword}.
- */
onToggle: () => void;
}
-/**
- * A MUI {@link InputAdornment} that can be used at the trailing edge of a
- * password input field to allow the user to toggle the visibility of the
- * password.
- */
export const ShowHidePasswordInputAdornment: React.FC<
ShowHidePasswordInputAdornmentProps
> = ({ showPassword, onToggle: onToggle }) => {
- // Prevent password field from losing focus when the input adornment is
- // clicked by ignoring both the mouse up and down events. This is the
- // approach mentioned in the MUI docs.
- // https://mui.com/material-ui/react-text-field/#input-adornments
+ // Prevent the visibility button from blurring the password field.
const preventDefault = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
};
diff --git a/web/packages/base/components/mui/index.tsx b/web/packages/base/components/mui/index.tsx
index a440a90964..1bfe205710 100644
--- a/web/packages/base/components/mui/index.tsx
+++ b/web/packages/base/components/mui/index.tsx
@@ -1,15 +1,9 @@
import { IconButton, styled } from "@mui/material";
-/**
- * Convenience typed props for a component that acts like a push button.
- */
export interface ButtonishProps {
onClick: () => void;
}
-/**
- * A MUI {@link IconButton} filled in with a faint background.
- */
export const FilledIconButton = styled(IconButton)(({ theme }) => ({
backgroundColor: theme.vars.palette.fill.faint,
}));
diff --git a/web/packages/base/components/pages/404.tsx b/web/packages/base/components/pages/404.tsx
index 66a30fc533..24d6a5f7cf 100644
--- a/web/packages/base/components/pages/404.tsx
+++ b/web/packages/base/components/pages/404.tsx
@@ -1,25 +1,9 @@
import { useRouter } from "next/router";
import React, { useEffect } from "react";
-/**
- * A reusable 404 page.
- */
const Page: React.FC = () => {
- // [Note: 404 back to home]
- //
- // In the desktop app, if the user presses the refresh button when the URL
- // has an attached query parameter, e.g. "/gallery?collectionId=xxx", then
- // the code in next-electron-server blindly appends the html extension to
- // this URL, resulting in it trying to open "gallery?collectionId=xxx.html"
- // instead of "gallery.html". It doesn't find such a file, causing it open
- // "404.html" (the static file generated from this file).
- //
- // One way around is to patch the package, e.g.
- // https://github.com/ente/next-electron-server/pull/1/files
- //
- // However, redirecting back to the root is arguably a better fallback in
- // all cases (even when running on our website), since our app is a SPA.
-
+ // next-electron-server serves 404.html when a refreshed URL has a query.
+ // Return to the SPA root instead of leaving desktop stranded here.
const router = useRouter();
useEffect(() => {
diff --git a/web/packages/base/components/utils/dialog.tsx b/web/packages/base/components/utils/dialog.tsx
index bf8041d99d..1c765e6316 100644
--- a/web/packages/base/components/utils/dialog.tsx
+++ b/web/packages/base/components/utils/dialog.tsx
@@ -3,11 +3,6 @@ import { t } from "i18next";
import { useCallback, useState } from "react";
import type { MiniDialogAttributes } from "../MiniDialog";
-/**
- * A React hook for simplifying the provisioning of a {@link showMiniDialog}
- * function to inject in app contexts, and of the other props that are needed to
- * be passed to the {@link AttributedMiniDialog}.
- */
export const useAttributedMiniDialog = () => {
const [attributes, setAttributes] = useState<
MiniDialogAttributes | undefined
@@ -33,17 +28,6 @@ export const useAttributedMiniDialog = () => {
};
};
-/**
- * A convenience function to construct {@link MiniDialogAttributes} for showing
- * error dialogs.
- *
- * It takes one or two arguments.
- *
- * - If both are provided, then the first one is taken as the title and the
- * second one as the message.
- *
- * - Otherwise it sets a default title and use the only argument as the message.
- */
export const errorDialogAttributes = (
messageOrTitle: string,
optionalMessage?: string,
diff --git a/web/packages/base/components/utils/hooks-app.ts b/web/packages/base/components/utils/hooks-app.ts
index 34f7b93f39..55497e0121 100644
--- a/web/packages/base/components/utils/hooks-app.ts
+++ b/web/packages/base/components/utils/hooks-app.ts
@@ -5,15 +5,6 @@ import { logUnhandledErrorsAndRejections } from "ente-base/log-web";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
-/**
- * A hook that initializes the localization library that we use.
- *
- * This is only meant to be called from the top level `_app.tsx`, as this
- * initialization is intended to happen only once for the lifetime of the app.
- *
- * @returns a boolean which will be set to true when the localized strings have
- * been loaded.
- */
export const useSetupI18n = () => {
const [isI18nReady, setIsI18nReady] = useState(false);
@@ -25,18 +16,9 @@ export const useSetupI18n = () => {
};
interface SetupLoggingOptions {
- /** If true, then the logs will not be saved to local storage. */
disableDiskLogs?: boolean;
}
-/**
- * A hook that initializes the logging subsystem.
- *
- * This is only meant to be called from the top level `_app.tsx`, as this
- * initialization is intended to happen only once for the lifetime of the app.
- *
- * @param opts Optional {@link SetupLoggingOptions} to customize the setup.
- */
export const useSetupLogs = (opts?: SetupLoggingOptions) => {
useEffect(() => {
if (opts?.disableDiskLogs) disableDiskLogs();
@@ -45,12 +27,6 @@ export const useSetupLogs = (opts?: SetupLoggingOptions) => {
}, []);
};
-/**
- * A hook that keeps track of whether or not we are in the middle of a Next.js
- * route change.
- *
- * The top level app component uses this to show a loading indicator.
- */
export const useIsRouteChangeInProgress = () => {
const router = useRouter();
const [loading, setLoading] = useState(false);
@@ -79,11 +55,6 @@ export const useIsRouteChangeInProgress = () => {
return loading;
};
-/**
- * A React hook for simplifying the provisioning of a {@link showNotification}
- * function to inject in app contexts, and of the other props that are needed to
- * be passed to the {@link Notification}.
- */
export const useNotification = () => {
const [attributes, setAttributes] = useState<
NotificationAttributes | undefined
diff --git a/web/packages/base/components/utils/hooks.ts b/web/packages/base/components/utils/hooks.ts
index 21c4c87d66..b256cea924 100644
--- a/web/packages/base/components/utils/hooks.ts
+++ b/web/packages/base/components/utils/hooks.ts
@@ -1,41 +1,13 @@
import { useMediaQuery, useTheme } from "@mui/material";
import { useCallback, useEffect, useEffectEvent, useState } from "react";
-/**
- * Return true if the screen width is classified as a small size. This is often
- * treated as an (rather arbitrary) cutoff for "mobile" sized screens.
- *
- * We use the MUI "sm" (small, 600px) breakpoint as the cutoff. This hook will
- * return true if the size of the window's width is less than 600px.
- */
export const useIsSmallWidth = () =>
useMediaQuery(useTheme().breakpoints.down("sm"));
-/**
- * Heuristic "isMobileOrTablet"-ish check using a pointer media query.
- *
- * The absence of fine-resolution pointing device can be taken a quick and proxy
- * for detecting if the user is using a mobile or tablet.
- *
- * This is of course not going to work in all scenarios (e.g. someone connecting
- * their mice to their tablet), but ad-hoc user agent checks are not problem
- * free either. This media query should be accurate enough for cases where false
- * positives will degrade gracefully.
- *
- * See: https://github.com/mui/mui-x/issues/10039
- */
+// Only use this touchscreen heuristic where misclassification degrades gracefully.
export const useIsTouchscreen = () =>
useMediaQuery("(hover: none) and (pointer: coarse)", { noSsr: true });
-/**
- * A hook that manages a transient "copied" state.
- *
- * @param text The text to copy.
- *
- * @returns a tuple containing a boolean {@link copied} indicating if a copy has
- * just successfully happened, and a function {@link onCopy} to trigger the
- * copy.
- */
export const useClipboardCopy = (
text: string,
): [copied: boolean, onCopy: () => void] => {
@@ -51,12 +23,6 @@ export const useClipboardCopy = (
return [copied, handleCopyLink];
};
-/**
- * A hook that runs a callback at a specified interval.
- *
- * @param callback The function to call on each interval tick.
- * @param delay The interval in milliseconds, or null to pause the interval.
- */
export const useInterval = (
callback: () => void,
delay: number | null,
diff --git a/web/packages/base/components/utils/modal.ts b/web/packages/base/components/utils/modal.ts
index 0b40c9d786..c31219a189 100644
--- a/web/packages/base/components/utils/modal.ts
+++ b/web/packages/base/components/utils/modal.ts
@@ -1,23 +1,10 @@
import { useCallback, useState } from "react";
-/**
- * Common props that control the display of a modal (e.g. dialog, drawer)
- * component.
- */
export interface ModalVisibilityProps {
- /** If `true`, the component is shown. */
open: boolean;
- /** Callback fired when the component requests to be closed. */
onClose: () => void;
}
-/**
- * A convenience hook for keeping the state for opening and closing a modal, and
- * exposing a function to close the modal whose identity is stable.
- *
- * These props can be passed verbatim to our components that expect
- * {@link ModalVisibilityProps}.
- */
export const useModalVisibility = () => {
const [open, setOpen] = useState(false);
diff --git a/web/packages/base/components/utils/sx.ts b/web/packages/base/components/utils/sx.ts
index ea837681b5..ed37d517f4 100644
--- a/web/packages/base/components/utils/sx.ts
+++ b/web/packages/base/components/utils/sx.ts
@@ -1,21 +1,7 @@
import type { SxProps, Theme } from "@mui/material";
import type { SystemStyleObject } from "@mui/system";
-/**
- * Wrapper over Array.isArray that retains the TypeScript type for SxProps when
- * trying to spread them.
- *
- * The recommended pattern to use sx props in our own component (whilst
- * forwarding them to the underlying MUI component) is to:
- *
- * ...(Array.isArray(sx) ? sx : [sx])
- *
- * However, currently (as of MUI v6), this runs afoul of the
- * 'no-unsafe-assignment' eslint rule. This function provides a workaround, and
- * can be used as a drop-in replacement of Array.isArray in the above pattern.
- *
- * Ref: https://github.com/mui/material-ui/issues/37730
- */
+// Array.isArray does not preserve MUI's SxProps array type.
export const isSxArray = (
sx: SxProps<Theme>,
): sx is readonly (
diff --git a/web/packages/base/components/utils/use-loading-bar.ts b/web/packages/base/components/utils/use-loading-bar.ts
index 0f3a7c61f4..b202e50d36 100644
--- a/web/packages/base/components/utils/use-loading-bar.ts
+++ b/web/packages/base/components/utils/use-loading-bar.ts
@@ -5,16 +5,6 @@ export interface LoadingBarController {
complete: () => void;
}
-/**
- * A convenience hook for returning stable functions tied to a
- * {@link LoadingBar} ref.
- *
- * The {@link LoadingBar} component comes from the "react-top-loading-bar"
- * library. To control it, we keep a ref. We want to allow components in our
- * React tree to be able to also control the loading bar, but instead of
- * exposing the ref directly, we export wrapper functions to start and stop the
- * loading bar. This hook returns these functions (and the ref).
- */
export const useLoadingBar = () => {
const loadingBarRef = useRef<LoadingBarController | null>(null);
diff --git a/web/packages/base/crypto/worker.ts b/web/packages/base/crypto/worker.ts
index 29e4e30991..6d3749640e 100644
--- a/web/packages/base/crypto/worker.ts
+++ b/web/packages/base/crypto/worker.ts
@@ -2,13 +2,7 @@ import { expose } from "comlink";
import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";
import * as libsodium from "./libsodium";
-/**
- * A web worker that exposes the functions defined by libsodium.ts.
- *
- * See: [Note: Crypto code hierarchy].
- *
- * Note: Keep these methods logic free. They are meant to be trivial proxies.
- */
+// Keep these as direct proxies; crypto logic belongs in libsodium.ts.
export class CryptoWorker {
toB64 = libsodium.toB64;
fromB64 = libsodium.fromB64;
diff --git a/web/packages/base/date.ts b/web/packages/base/date.ts
index ec9d0e4b8c..6706ced325 100644
--- a/web/packages/base/date.ts
+++ b/web/packages/base/date.ts
@@ -1,8 +1,5 @@
import i18n, { t } from "i18next";
-/**
- * Return `true` if both the given dates have the same day.
- */
export const isSameDay = (first: Date, second: Date) =>
first.getFullYear() === second.getFullYear() &&
first.getMonth() === second.getMonth() &&
@@ -19,11 +16,6 @@ const translatedRelativeTime = (
: translated;
};
-/**
- * Format a server timestamp in microseconds using the same thresholds as the
- * comments sidebar: relative labels for recent comments, locale dates for older
- * ones.
- */
export const formatTimeAgo = (timestampMicros: number): string => {
const timestampMs = Math.floor(timestampMicros / 1000);
const now = Date.now();
diff --git a/web/packages/base/electron.ts b/web/packages/base/electron.ts
index 1bc6634445..12382128df 100644
--- a/web/packages/base/electron.ts
+++ b/web/packages/base/electron.ts
@@ -1,21 +1,5 @@
import type { Electron } from "./types/ipc";
-/**
- * A wrapper over a non-null assertion of `globalThis.electron`.
- *
- * This is useful where we have previously verified that the code path in which
- * we're running only executes when we're in electron (usually by directly
- * checking that `globalThis.electron` is defined somewhere up the chain).
- *
- * Generally, this should not be required - the check and the use should be
- * colocated, or the unwrapped non-null value saved somewhere. But sometimes
- * doing so requires code refactoring, so as an escape hatch we provide this
- * convenience function.
- *
- * It will throw if `globalThis.electron` is undefined.
- *
- * @see `global-electron.d.ts`.
- */
export const ensureElectron = (): Electron => {
const et = globalThis.electron;
if (et) return et;
@@ -27,13 +11,7 @@ export const ensureElectron = (): Electron => {
const defaultTrustedWindowBlurSuppressionMs = 5 * 1e3;
let suppressMainWindowBlurUntil = 0;
-/**
- * Temporarily suppress blur handling for trusted app-initiated native prompts.
- *
- * Native OS dialogs can blur the window without indicating user backgrounding
- * intent (for example, directory pickers). Consumers can gate blur-driven
- * actions during this short window.
- */
+// Native prompts blur the window without meaning the app was backgrounded.
export const suppressMainWindowBlurForTrustedPrompt = (
durationMs = defaultTrustedWindowBlurSuppressionMs,
) => {
@@ -54,6 +32,7 @@ export const clearMainWindowBlurSuppression = () => {
type MainWindowFocusListener = () => void;
type MainWindowBlurListener = () => void;
+// Electron exposes one callback per event; multiplex local subscribers here.
const mainWindowFocusListeners = new Set<MainWindowFocusListener>();
let hasAttachedMainWindowFocusBridge = false;
const mainWindowBlurListeners = new Set<MainWindowBlurListener>();
@@ -88,12 +67,6 @@ const detachMainWindowFocusBridgeIfNeeded = () => {
hasAttachedMainWindowFocusBridge = false;
};
-/**
- * Subscribe to main window focus events on Electron.
- *
- * This helper multiplexes listeners over Electron's single-callback API,
- * allowing multiple consumers to listen concurrently.
- */
export const subscribeMainWindowFocus = (
listener: MainWindowFocusListener,
): (() => void) => {
@@ -132,12 +105,6 @@ const detachMainWindowBlurBridgeIfNeeded = () => {
hasAttachedMainWindowBlurBridge = false;
};
-/**
- * Subscribe to main window blur events on Electron.
- *
- * This helper multiplexes listeners over Electron's single-callback API,
- * allowing multiple consumers to listen concurrently.
- */
export const subscribeMainWindowBlur = (
listener: MainWindowBlurListener,
): (() => void) => {
diff --git a/web/packages/base/env.ts b/web/packages/base/env.ts
index 4122482101..0474258006 100644
--- a/web/packages/base/env.ts
+++ b/web/packages/base/env.ts
@@ -1,6 +1,4 @@
-/**
- * Build-time `process.env.*` replacements available to our browser bundles.
- */
+// Replaced at build time.
declare const process: {
readonly env: {
readonly NODE_ENV: "development" | "production" | "test";
@@ -13,17 +11,6 @@ declare const process: {
};
};
-/**
- * A build is considered as a development build if either the NODE_ENV is
- * environment variable is set to 'development'.
- *
- * NODE_ENV is automatically set to 'development' when we run `npm run dev`. From
- * Next.js docs:
- *
- * > If the environment variable NODE_ENV is unassigned, Next.js automatically
- * assigns development when running the `next dev` command, or production for
- * all other commands.
- */
export const isDevBuild = process.env.NODE_ENV == "development";
export const buildEnvIsProductionBuild = process.env.NODE_ENV == "production";
@@ -35,27 +22,7 @@ export const buildEnvIsDesktop = process.env.isDesktop == "1";
export const buildEnvDesktopAppVersion = process.env.desktopAppVersion;
export const buildEnvGitSHA = process.env.gitSHA;
-/**
- * `true` if we're running in the default global context (aka the main thread)
- * of a web browser.
- *
- * In particular, this is `false` when we're running in a web worker,
- * irrespective of whether the worker is running in a Node.js context or a web
- * browser context.
- *
- * > We can be running in a browser context either if the user has the page open
- * in a web browser, or if we're the renderer process of an Electron app.
- *
- * Note that this cannot be a constant, otherwise it'll get inlined during SSR
- * with the wrong value.
- */
+// Keep these as functions; SSR would inline constants with the server value.
export const haveWindow = () => typeof window != "undefined";
-/**
- * Return true if we are running in a [Web
- * Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
- *
- * Note that this cannot be a constant, otherwise it'll get inlined during SSR
- * with the wrong value.
- */
export const inWorker = () => typeof importScripts == "function";
diff --git a/web/packages/base/file-download.ts b/web/packages/base/file-download.ts
index 2cf7589ae4..3c59df2a3e 100644
--- a/web/packages/base/file-download.ts
+++ b/web/packages/base/file-download.ts
@@ -53,7 +53,7 @@ export const fetchFile = async (fileID: number, kind: FileKind) => {
return response;
}
- // migration : 3 aug 2026
+ // TODO: Remove this legacy endpoint after the v3 migration window.
const token = await ensureAuthToken();
return fetch(
await apiURL(`/files/${legacyFilePath(kind)}/${fileID}`, { token }),
diff --git a/web/packages/base/global-electron.d.ts b/web/packages/base/global-electron.d.ts
index c5de87ea12..38a0cb3575 100644
--- a/web/packages/base/global-electron.d.ts
+++ b/web/packages/base/global-electron.d.ts
@@ -1,18 +1,6 @@
import type { Electron } from "./types/ipc";
-/**
- * Extend the global object's (`globalThis`) interface to state that it can
- * potentially hold a property called `electron`. It will be injected by our
- * preload.js script when we're running in the context of our desktop app.
- */
declare global {
- /**
- * Extra, desktop specific, APIs provided by our Node.js layer.
- *
- * This property will defined only when we're running inside our desktop
- * (Electron) app. It will expose a bunch of functions (see
- * {@link Electron}) that allow us to communicate with the Node.js layer of
- * our desktop app.
- */
+ // Preload injects this only in Electron renderers.
declare var electron: Electron | undefined;
}
diff --git a/web/packages/base/globals.d.ts b/web/packages/base/globals.d.ts
index 6dc68bbf07..5e02f5ab87 100644
--- a/web/packages/base/globals.d.ts
+++ b/web/packages/base/globals.d.ts
@@ -1,6 +1,3 @@
interface ErrorConstructor {
- /**
- * V8 stack trace hook available in Chromium-derived browsers and Electron.
- */
captureStackTrace?(targetObject: object, constructorOpt?: unknown): void;
}
diff --git a/web/packages/base/id-worker.ts b/web/packages/base/id-worker.ts
index 593e2d236e..8e83118e42 100644
--- a/web/packages/base/id-worker.ts
+++ b/web/packages/base/id-worker.ts
@@ -3,15 +3,4 @@ import { alphabet } from "./id";
const nanoid = customAlphabet(alphabet, 22);
-/**
- * This is a variant of the regular {@link newID} that can be used in web
- * workers.
- *
- * Web workers don't have access to a secure random generator, so we need to use
- * the non-secure variant.
- * https://github.com/ai/nanoid?tab=readme-ov-file#web-workers
- *
- * For many of our use cases, where we're not using these IDs for cryptographic
- * operations, this is okay. We also have an increased alphabet length.
- */
export const newNonSecureID = (prefix: string) => prefix + nanoid();
diff --git a/web/packages/base/id.ts b/web/packages/base/id.ts
index 025d4344e0..4e8c5c0785 100644
--- a/web/packages/base/id.ts
+++ b/web/packages/base/id.ts
@@ -1,24 +1,10 @@
import { customAlphabet } from "nanoid";
-/**
- * Remove _ and - from the default set to have better looking IDs that can also
- * be selected in the editor quickly ("-" prevents this), and which we can
- * prefix unambiguously ("_" is used for that).
- *
- * To compensate, increase length from the default of 21 to 22.
- *
- * To play around with these, use https://zelark.github.io/nano-id-cc/
- */
+// Exclude "-" for editor selection and "_" so prefixes remain unambiguous.
export const alphabet =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+// The extra character compensates for the smaller alphabet.
const nanoid = customAlphabet(alphabet, 22);
-/**
- * Generate a new random identifier with the given prefix.
- *
- * Internally this uses [nanoids](https://github.com/ai/nanoid).
- *
- * See {@link newNonSecureID} for a variant that can be used in web workers.
- */
export const newID = (prefix: string) => prefix + nanoid();
diff --git a/web/packages/base/join-album.ts b/web/packages/base/join-album.ts
index 2ee1c0bd76..20b7dacd0c 100644
--- a/web/packages/base/join-album.ts
+++ b/web/packages/base/join-album.ts
@@ -2,16 +2,14 @@ export const JOIN_ALBUM_CONTEXT_KEY = "ente_join_album_context";
export interface JoinAlbumContext {
accessToken: string;
- collectionKey: string; // Base64 encoded collection key for API calls
- collectionKeyHash: string; // Original hash value from URL (base58 or hex)
+ // Base64-encoded collection key used by the API.
+ collectionKey: string;
+ // Unmodified base58 or hex value from the URL.
+ collectionKeyHash: string;
collectionID: number;
- accessTokenJWT?: string; // JWT token for password-protected albums
+ accessTokenJWT?: string;
}
-/**
- * Retrieve stored album context after authentication.
- * Checks sessionStorage for the stored context.
- */
export const getJoinAlbumContext = (): JoinAlbumContext | null => {
const stored = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);
if (!stored) {
@@ -25,16 +23,10 @@ export const getJoinAlbumContext = (): JoinAlbumContext | null => {
}
};
-/**
- * Clear the stored album context after successful join or timeout.
- */
export const clearJoinAlbumContext = () => {
sessionStorage.removeItem(JOIN_ALBUM_CONTEXT_KEY);
};
-/**
- * Check if there's a pending album to join.
- */
export const hasPendingAlbumToJoin = (): boolean => {
return getJoinAlbumContext() !== null;
};
diff --git a/web/packages/base/local-storage.ts b/web/packages/base/local-storage.ts
index 52794a5381..a82467edb2 100644
--- a/web/packages/base/local-storage.ts
+++ b/web/packages/base/local-storage.ts
@@ -1,10 +1,6 @@
import { nullToUndefined } from "ente-utils/transform";
-/**
- * Clear local storage on logout.
- *
- * This function clears everything from local storage except the app's logs.
- */
+// Preserve logs across logout.
export const clearLocalStorage = () => {
const existingLogs = nullToUndefined(localStorage.getItem("logs"));
localStorage.clear();
diff --git a/web/packages/base/public-memory.ts b/web/packages/base/public-memory.ts
index a42a350ef6..d87029e80f 100644
--- a/web/packages/base/public-memory.ts
+++ b/web/packages/base/public-memory.ts
@@ -1,21 +1,9 @@
import { publicRequestHeaders } from "ente-base/http";
-/**
- * Credentials needed to make public memory share related API requests.
- */
export interface PublicMemoryCredentials {
- /**
- * The access token for the public memory share.
- *
- * This is obtained from the "t" query parameter of the share URL.
- * It both identifies the share and authenticates the request.
- */
accessToken: string;
}
-/**
- * Return headers for public memory share API requests.
- */
export const authenticatedPublicMemoryRequestHeaders = ({
accessToken,
}: PublicMemoryCredentials) => ({
diff --git a/web/packages/base/token.ts b/web/packages/base/token.ts
index 109322b339..b34450d9b1 100644
--- a/web/packages/base/token.ts
+++ b/web/packages/base/token.ts
@@ -1,42 +1,13 @@
import { getKVS, removeKV, setKV } from "./kv";
-/**
- * Return the user's auth token, or throw an error.
- *
- * The user's auth token can be retrieved using {@link savedAuthToken}. This
- * function is a wrapper which throws an error if the token is not found (which
- * should only happen if the user is not logged in).
- */
export const ensureAuthToken = async () => {
const token = await savedAuthToken();
if (!token) throw new Error("Not logged in");
return token;
};
-/**
- * Return the user's auth token, if available.
- *
- * The user's auth token is stored in KV DB using {@link saveAuthToken} during
- * the login / signup flow. This function returns that saved auth token.
- *
- * The underlying data is stored in IndexedDB, and can be accessed from web
- * workers.
- *
- * If your code is running in a context where the user is already expected to be
- * logged in, use {@link ensureAuthToken} instead.
- */
export const savedAuthToken = () => getKVS("token");
-/**
- * Save the user's auth token in KV DB.
- *
- * This is the setter corresponding to {@link savedAuthToken}.
- */
export const saveAuthToken = (token: string) => setKV("token", token);
-/**
- * Remove the user's auth token from KV DB.
- *
- * See {@link saveAuthToken}.
- */
export const removeAuthToken = () => removeKV("token");
diff --git a/web/packages/base/types/index.ts b/web/packages/base/types/index.ts
index 10dc83fa67..7c18e1cd39 100644
--- a/web/packages/base/types/index.ts
+++ b/web/packages/base/types/index.ts
@@ -1,6 +1,3 @@
-/**
- * A location, represented as a (latitude, longitude) pair.
- */
export interface Location {
latitude: number;
longitude: number;
diff --git a/web/packages/base/utils/web.ts b/web/packages/base/utils/web.ts
index f0120f4a35..6148cb0385 100644
--- a/web/packages/base/utils/web.ts
+++ b/web/packages/base/utils/web.ts
@@ -1,14 +1,3 @@
-/**
- * Download the asset at the given {@link url} to a file on the user's download
- * folder by appending a temporary <a> element to the DOM.
- *
- * @param url The URL that we want to download. The URL is revoked after
- * initiating the download.
- *
- * @param fileName The name of downloaded file.
- *
- * See also {@link saveStringAsFile}.
- */
export const saveAsFileAndRevokeObjectURL = (url: string, fileName: string) => {
const a = document.createElement("a");
a.style.display = "none";
@@ -20,13 +9,6 @@ export const saveAsFileAndRevokeObjectURL = (url: string, fileName: string) => {
a.remove();
};
-/**
- * Save the given string {@link s} as a file in the user's download folder.
- *
- * @param s The string to save.
- *
- * @param fileName The name of the file that gets saved.
- */
export const saveStringAsFile = (s: string, fileName: string) => {
const file = new Blob([s], { type: "text/plain" });
const fileURL = URL.createObjectURL(file);
diff --git a/web/packages/base/worker/worker-bridge.ts b/web/packages/base/worker/worker-bridge.ts
index eaf3028ea4..b1e0166de2 100644
--- a/web/packages/base/worker/worker-bridge.ts
+++ b/web/packages/base/worker/worker-bridge.ts
@@ -2,14 +2,7 @@ import { wrap } from "comlink";
import { inWorker } from "../env";
import type { WorkerBridge } from "./comlink-worker";
-/**
- * The web worker side handle to the {@link WorkerBridge} exposed by the main
- * thread.
- *
- * This file is meant to be run inside a worker. Accessing the properties of
- * this object will be transparently (but asynchrorously) relayed to the
- * implementation of the {@link WorkerBridge} in `comlink-worker.ts`.
- */
+// Calls are relayed asynchronously to workerBridge exposed by the main thread.
export const workerBridge = inWorker()
? wrap<WorkerBridge>(globalThis)
: undefined;
diff --git a/web/packages/gallery/components/FileInfoComponents.tsx b/web/packages/gallery/components/FileInfoComponents.tsx
index f6d1d05efb..87cc9e3133 100644
--- a/web/packages/gallery/components/FileInfoComponents.tsx
+++ b/web/packages/gallery/components/FileInfoComponents.tsx
@@ -5,13 +5,7 @@ import { useClipboardCopy } from "ente-base/components/utils/hooks";
import { t } from "i18next";
interface CopyButtonProps {
- /**
- * The text to copy when the button is clicked.
- */
text: string;
- /**
- * The size of the icon.
- */
size?: SvgIconProps["fontSize"];
}
diff --git a/web/packages/gallery/components/FullScreenDropZone.tsx b/web/packages/gallery/components/FullScreenDropZone.tsx
index 458444f5ad..c01a6537e9 100644
--- a/web/packages/gallery/components/FullScreenDropZone.tsx
+++ b/web/packages/gallery/components/FullScreenDropZone.tsx
@@ -22,56 +22,21 @@ const hasDraggedFiles = (
};
export interface FullScreenDropZoneProps {
- /**
- * Optional override to the message show to the user when a drag is in
- * progress.
- *
- * Default: t("upload_dropzone_hint")
- */
message?: string;
- /**
- * If `true`, then drag and drop functionality is disabled.
- */
disabled?: boolean;
- /**
- * Callback invoked when the user drags and drops files.
- *
- * It will only be called if there is at least one file in {@link files}.
- */
onDrop: (files: FileWithPath[]) => void;
}
-/**
- * A full screen container that accepts drag and drop of files, and also shows a
- * visual overlay to the user while a drag is in progress.
- *
- * It can serves as the root component of the gallery pages as the container
- * itself is a stack with flex 1, and so will fill all the height (and width)
- * available to it. The other contents of the screen can then be placed as its
- * children.
- *
- * It is meant to be used in tandem with "react-dropzone"; specifically, it
- * requires the `getRootProps` function returned by a call to
- * {@link useDropzone}.
- */
export const FullScreenDropZone: React.FC<
React.PropsWithChildren<FullScreenDropZoneProps>
> = ({ message, disabled, onDrop, children }) => {
- const {
- // A function to call to get the props we should apply to the container,
- getRootProps,
- // ... the props we should apply to the <input> element,
- getInputProps,
- } = useDropzone({
+ const { getRootProps, getInputProps } = useDropzone({
noClick: true,
noKeyboard: true,
disabled,
onDrop(acceptedFiles) {
setIsDropPending(false);
- // Invoked the `onDrop` callback only if there is at least 1 file.
if (acceptedFiles.length) {
- // Create a regular array from the readonly array returned by
- // dropzone.
onDrop([...acceptedFiles]);
}
},
@@ -163,8 +128,6 @@ const DropZoneOverlay = styled(Stack)(
border-color: ${theme.vars.palette.accent.light};
background-color: ${theme.vars.palette.backdrop.base};
backdrop-filter: blur(10px);
- /* Above the highest possible MUI z-index, that of the MUI tooltip
- See: https://mui.com/material-ui/customization/default-theme/ */
z-index: calc(var(--mui-zIndex-tooltip) + 1);
`,
);
diff --git a/web/packages/gallery/components/Upload.tsx b/web/packages/gallery/components/Upload.tsx
index 5333f212d0..944f49f037 100644
--- a/web/packages/gallery/components/Upload.tsx
+++ b/web/packages/gallery/components/Upload.tsx
@@ -1,7 +1,2 @@
-/**
- * The upload can be triggered by different buttons and flows in the UI, each of
- * which is referred to as an "intent".
- *
- * The "intent" does not change the eventual upload outcome, only the UX flow.
- */
+// Changes the upload flow, not the uploaded result.
export type UploadTypeSelectorIntent = "upload" | "import";
diff --git a/web/packages/gallery/components/upload-progress/UploadProgress.tsx b/web/packages/gallery/components/upload-progress/UploadProgress.tsx
index ab3d367ade..a5ffad4007 100644
--- a/web/packages/gallery/components/upload-progress/UploadProgress.tsx
+++ b/web/packages/gallery/components/upload-progress/UploadProgress.tsx
@@ -49,16 +49,6 @@ function UploadProgressBody({
preUploadSkippedFiles = emptyPreUploadSkippedFiles,
cancelUploads,
}: UploadProgressProps) {
- /**
- * expanded: This variable decides whether the full upload progress
- * modal should be shown or just the compact one is fine.
- *
- * dragPosition: For facilitating the drag of the compact upload widget
- * across the screen.
- *
- * showStopConfirmation: If the user tries to close the upload, we show
- * a confirmation modal, and this variable is the decider for that.
- */
const [expanded, setExpanded] = useState(false);
const [dragPosition, setDragPosition] = useState<DragPosition>();
const [showStopConfirmation, setShowStopConfirmation] = useState(false);
diff --git a/web/packages/gallery/components/upload-progress/context.ts b/web/packages/gallery/components/upload-progress/context.ts
index 6c57a207fd..7bd2b4e2e6 100644
--- a/web/packages/gallery/components/upload-progress/context.ts
+++ b/web/packages/gallery/components/upload-progress/context.ts
@@ -8,18 +8,11 @@ import type {
UploadFileNames,
} from "../uploadProgressStats";
-/**
- * Coordinates for positioning the draggable minimized upload progress widget.
- */
export interface DragPosition {
x: number;
y: number;
}
-/**
- * This the main prop type facilitating the variour actions
- * which are currently available to the UploadProgress UI
- */
export interface UploadProgressContextT {
onClose: () => void;
uploadCounter: UploadCounter;
diff --git a/web/packages/gallery/components/upload-progress/helpers.ts b/web/packages/gallery/components/upload-progress/helpers.ts
index 3653fae25d..3b26b96b15 100644
--- a/web/packages/gallery/components/upload-progress/helpers.ts
+++ b/web/packages/gallery/components/upload-progress/helpers.ts
@@ -121,10 +121,5 @@ export const uploadCountsText = ({
: uploadStatusText(uploadPhase);
};
-/**
- *
- * @param value The upload percent which has decimal places
- * @returns The value with the decimal places rounded.
- */
export const normalizePercent = (value: number) =>
Math.min(100, Math.max(0, Math.round(value || 0)));
diff --git a/web/packages/gallery/components/upload-progress/useMinimizedUploadDrag.ts b/web/packages/gallery/components/upload-progress/useMinimizedUploadDrag.ts
index 2347df3674..51072d190b 100644
--- a/web/packages/gallery/components/upload-progress/useMinimizedUploadDrag.ts
+++ b/web/packages/gallery/components/upload-progress/useMinimizedUploadDrag.ts
@@ -1,13 +1,6 @@
import { useRef, type PointerEvent, type RefObject } from "react";
import { useUploadProgressContext } from "./context";
-/**
- * Returns pointer handlers that move `dragSurfaceRef` from a dedicated drag
- * handle. Expand and close actions remain in `MinimizedUploadProgress`.
- *
- * This file currently only has the functions and the interface which are
- * required for the drag implementation.
- */
export function useMinimizedUploadDrag(
dragSurfaceRef: RefObject<HTMLDivElement | null>,
) {
diff --git a/web/packages/gallery/components/uploadProgressStats.ts b/web/packages/gallery/components/uploadProgressStats.ts
index ea4e3d23e2..2c65e85c9d 100644
--- a/web/packages/gallery/components/uploadProgressStats.ts
+++ b/web/packages/gallery/components/uploadProgressStats.ts
@@ -17,15 +17,12 @@ export type SegregatedFinishedUploads = Map<FinishedUploadType, number[]>;
export type UploadFileNames = Map<number, string>;
-// The below types are considered as completed because the files are grouped
-// to either of these after it was tried to upload the file.
+// These are terminal outcomes, including skipped and failed attempts.
export const finishedStatKinds = ["completed", "skipped", "failed"] as const;
export type FinishedStatKind = (typeof finishedStatKinds)[number];
-// The inProgress here is more kind of a remaining value. When a bunch of files
-// are uploaded all of them before the pre-upload stage are put under this
-// inProgress state.
+// "inProgress" includes every file until it reaches pre-upload.
export type UploadStatKind = "inProgress" | FinishedStatKind;
export const uploadStatColors: Record<FinishedStatKind, string> = {
@@ -34,15 +31,7 @@ export const uploadStatColors: Record<FinishedStatKind, string> = {
failed: "#ff8a1f",
};
-/**
- * There are a total of 11 probable stats which is retruned after each
- * file upload and we are grouping them based on this, so that they
- * can be shown under the corresponding tab in the UI.
- *
- * The herustics for failed is there is a probablity that the files
- * can be uploaded whereas for the skipped it's sure that the files
- * can't be uploaded.
- */
+// "failed" may be retryable; "skipped" cannot be uploaded.
export const statFinishedTypes: Record<FinishedStatKind, FinishedUploadType[]> =
{
completed: ["uploaded", "uploadedWithStaticThumbnail"],
diff --git a/web/packages/gallery/components/viewer/LikeAlbumSelectorModal.tsx b/web/packages/gallery/components/viewer/LikeAlbumSelectorModal.tsx
index 264e8310c8..094615dd9f 100644
--- a/web/packages/gallery/components/viewer/LikeAlbumSelectorModal.tsx
+++ b/web/packages/gallery/components/viewer/LikeAlbumSelectorModal.tsx
@@ -4,10 +4,6 @@ import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
import { t } from "i18next";
import React from "react";
-// =============================================================================
-// Icons
-// =============================================================================
-
const HeartFilledIcon: React.FC<{ size?: number; color?: string }> = ({
size = 18,
color = "#08C225",
@@ -116,10 +112,6 @@ const LikePhotoIllustration: React.FC = () => (
</svg>
);
-// =============================================================================
-// Types
-// =============================================================================
-
interface Album {
id: number;
name: string;
@@ -127,31 +119,12 @@ interface Album {
}
export interface LikeAlbumSelectorModalProps extends ModalVisibilityProps {
- /**
- * List of albums containing this file that user can like in.
- */
albums: Album[];
- /**
- * Set of album IDs where the photo is currently liked.
- */
likedAlbumIDs: Set<number>;
- /**
- * Called when user clicks on an album to toggle like status.
- * @param albumId The album ID
- * @param isCurrentlyLiked Whether the album is currently liked
- */
onToggleAlbum: (albumId: number, isCurrentlyLiked: boolean) => void;
- /**
- * Called when user clicks "Like all" to like in all albums.
- */
onLikeAll: () => void;
}
-/**
- * Modal dialog for selecting which album to like a photo in.
- * Shown when the like button is clicked and the photo was opened from
- * gallery view (not from a specific collection).
- */
export const LikeAlbumSelectorModal: React.FC<LikeAlbumSelectorModalProps> = ({
open,
onClose,
@@ -247,10 +220,6 @@ export const LikeAlbumSelectorModal: React.FC<LikeAlbumSelectorModalProps> = ({
);
};
-// =============================================================================
-// Styled Components
-// =============================================================================
-
const StyledDialog = styled(Dialog)(({ theme }) => ({
"& .MuiDialog-paper": {
width: 381,
diff --git a/web/packages/gallery/export-dirs.ts b/web/packages/gallery/export-dirs.ts
index 40229741ed..8d5bb3c4e7 100644
--- a/web/packages/gallery/export-dirs.ts
+++ b/web/packages/gallery/export-dirs.ts
@@ -1,11 +1,3 @@
-/**
- * Name of the directory in which we put our metadata when exporting to the file
- * system.
- */
export const exportMetadataDirectoryName = "metadata";
-/**
- * Name of the directory in which we keep trash items when deleting files that
- * have been exported to the local disk previously.
- */
export const exportTrashDirectoryName = "Trash";
diff --git a/web/packages/gallery/services/convert.ts b/web/packages/gallery/services/convert.ts
index e11a7a762b..44f91b1d0d 100644
--- a/web/packages/gallery/services/convert.ts
+++ b/web/packages/gallery/services/convert.ts
@@ -26,8 +26,7 @@ const nativeConvertToJPEG = async (imageBlob: Blob) => {
const startTime = Date.now();
const imageData = new Uint8Array(await imageBlob.arrayBuffer());
const electron = globalThis.electron;
- // If we're running in a worker, reroute the request back to the main
- // thread since workers don't have access to window.electron.
+ // Workers route through the main thread because they cannot access electron.
const jpegData = electron
? await electron.convertToJPEG(imageData)
: await workerBridge!.convertToJPEG(imageData);
diff --git a/web/packages/gallery/services/share.ts b/web/packages/gallery/services/share.ts
index 3f37ff4bbd..c496477d2b 100644
--- a/web/packages/gallery/services/share.ts
+++ b/web/packages/gallery/services/share.ts
@@ -1,23 +1,6 @@
import bs58 from "bs58";
import { fromB64, fromHex, toB64 } from "ente-base/crypto";
-/**
- * Add the collection key as the hash to the given URL.
- *
- * The hash fragment is a client side component and is not accessible to remote
- * servers. The collection key is base-58 encoded and set as the hash in public
- * URLs of shared albums.
- *
- * Use {@link extractCollectionKeyFromShareURL} to get back the collection key.
-
- * @param url The base URL for the public album.
-
- * @param collectionKey The base-64 encoded string representation of the
- * collection key for the public album.
- *
- * @returns A URL that includes the base-58 encoded collection key as the hash
- * fragment.
- */
export const appendCollectionKeyToShareURL = async (
url: string,
collectionKey: string,
@@ -29,17 +12,6 @@ export const appendCollectionKeyToShareURL = async (
return sharableURL.href;
};
-/**
- * Extract the collection key from a public URL.
- *
- * This is the inverse of {@link appendCollectionKeyToShareURL}, returning the
- * base64 string representation of the collection key.
- *
- * collection key (bytes)
- * => appendCollectionKeytoShareURL (base 64 => base 58)
- * => URL hash => extractCollectionKeyBytesFromShareURL (base 58 => base 64)
- * => collection key (bytes).
- */
export const extractCollectionKeyFromShareURL = async (url: URL) => {
const ck = url.hash.slice(1);
return ck.length < 50 ? await toB64(bs58.decode(ck)) : await fromHex(ck);
diff --git a/web/packages/gallery/services/upload/md5.ts b/web/packages/gallery/services/upload/md5.ts
index 4e4770b6e1..01e041b43d 100644
--- a/web/packages/gallery/services/upload/md5.ts
+++ b/web/packages/gallery/services/upload/md5.ts
@@ -1,9 +1,4 @@
-/**
- * Minimal MD5 implementation tailored for computing a base64 encoded checksum
- * of Uint8Array inputs.
- *
- * The implementation follows RFC 1321.
- */
+// RFC 1321 MD5, returning the checksum as base64.
const shifts = new Uint8Array([
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5,
@@ -45,9 +40,8 @@ const bytesToBase64 = (bytes: Uint8Array) => {
export const computeMd5Base64 = (data: Uint8Array): string => {
const originalLengthBits = data.length * 8;
- const paddedLength =
- (((data.length + 8) >>> 6) << 4) +
- 16; /* (n + 64) rounded up to multiple of 64 bytes, expressed in 32-bit words */
+ // Round MD5's padded input to 64-byte blocks, measured in 32-bit words.
+ const paddedLength = (((data.length + 8) >>> 6) << 4) + 16;
const words = new Uint32Array(paddedLength);
for (const [i, value] of data.entries()) {
diff --git a/web/packages/gallery/utils/avatar-colors.ts b/web/packages/gallery/utils/avatar-colors.ts
index a8d672e931..5efe5ca178 100644
--- a/web/packages/gallery/utils/avatar-colors.ts
+++ b/web/packages/gallery/utils/avatar-colors.ts
@@ -1,44 +1,30 @@
-/**
- * Avatar colors matching the mobile app's contact colors.
- *
- * These colors are used to give users a consistent colored avatar
- * based on their identifier (email or user ID).
- */
+// Keep this palette and length-based selection in sync with mobile.
export const avatarColors = [
- "#76549A", // Purple
- "#DF7861", // Coral
- "#94B49F", // Sage green
- "#87A2FB", // Periwinkle blue
- "#C689C6", // Orchid
- "#937DC2", // Soft purple
- "#325288", // Deep blue
- "#85B4E0", // Sky blue
- "#C1A3A3", // Dusty rose
- "#E1A059", // Amber
- "#426165", // Teal
- "#6B77B2", // Slate blue
- "#957FEF", // Violet
- "#DD9DE2", // Pink
- "#82AB8B", // Forest green
- "#9BBBE8", // Light blue
- "#8FBEBE", // Seafoam
- "#8AC3A1", // Mint
- "#A8B0F2", // Lavender
- "#B0C695", // Lime green
- "#E99AAD", // Rose
- "#D18484", // Salmon
- "#78B5A7", // Cyan
+ "#76549A",
+ "#DF7861",
+ "#94B49F",
+ "#87A2FB",
+ "#C689C6",
+ "#937DC2",
+ "#325288",
+ "#85B4E0",
+ "#C1A3A3",
+ "#E1A059",
+ "#426165",
+ "#6B77B2",
+ "#957FEF",
+ "#DD9DE2",
+ "#82AB8B",
+ "#9BBBE8",
+ "#8FBEBE",
+ "#8AC3A1",
+ "#A8B0F2",
+ "#B0C695",
+ "#E99AAD",
+ "#D18484",
+ "#78B5A7",
];
-/**
- * Get a consistent avatar color for a user based on their email or userName.
- *
- * Uses the same algorithm as the mobile app: the string length modulo the
- * number of available colors determines the color index.
- *
- * @param identifier - The user's email or userName (any string)
- * @returns A hex color string from the avatar colors palette
- */
export const getAvatarColor = (identifier: string): string => {
return avatarColors[identifier.length % avatarColors.length]!;
};
diff --git a/web/packages/gallery/utils/native-worker.ts b/web/packages/gallery/utils/native-worker.ts
index e168ac4bbe..86e82cc793 100644
--- a/web/packages/gallery/utils/native-worker.ts
+++ b/web/packages/gallery/utils/native-worker.ts
@@ -1,24 +1,15 @@
import type { Electron, UtilityProcessType } from "ente-base/types/ipc";
-/**
- * Obtain a port from the Node.js layer that can be used to communicate with the
- * native utility process of type {@link type}.
- */
export const createUtilityProcess = (
electron: Electron,
type: UtilityProcessType,
): Promise<MessagePort> => {
- // The main process will do its thing, and send back the port it created to
- // us by sending an message on the "utilityProcessPort/<type>" channel via
- // the postMessage API. This roundabout way is needed because MessagePorts
- // cannot be transferred via the usual send/invoke pattern.
-
+ // MessagePorts cannot travel through Electron's usual send/invoke IPC.
const portEvent = `utilityProcessPort/${type}`;
const port = new Promise<MessagePort>((resolve) => {
const l = ({ source, data, ports }: MessageEvent) => {
- // The source check verifies that the message is coming from our own
- // preload script. The data is the message that was posted.
+ // Accept only messages relayed by this window's preload.
if (source == window && data == portEvent) {
window.removeEventListener("message", l);
resolve(ports[0]!);
diff --git a/web/packages/gallery/utils/quick-link.ts b/web/packages/gallery/utils/quick-link.ts
index 307ceb8541..7e8743a1bd 100644
--- a/web/packages/gallery/utils/quick-link.ts
+++ b/web/packages/gallery/utils/quick-link.ts
@@ -18,9 +18,7 @@ const shortMonths = [
"Dec",
];
-/**
- * Date-range formatting used by quick-link naming (kept in mobile parity).
- */
+// Keep date formatting in sync with mobile.
export const quickLinkDateRangeForCreationTimes = (
firstCreationTime: number,
secondCreationTime: number,
diff --git a/web/packages/new/photos/components/AssignPersonDialog.tsx b/web/packages/new/photos/components/AssignPersonDialog.tsx
index 1f0a22993a..d38243ce98 100644
--- a/web/packages/new/photos/components/AssignPersonDialog.tsx
+++ b/web/packages/new/photos/components/AssignPersonDialog.tsx
@@ -20,24 +20,11 @@ import React, { useState } from "react";
import { ItemCard, LargeTileButton, LargeTileTextOverlay } from "./Tiles";
export type AssignPersonDialogProps = ModalVisibilityProps & {
- /**
- * Existing named people that can be selected.
- */
people: Person[];
- /**
- * Title to show on the dialog.
- */
title: string;
- /**
- * Called when the user selects a person.
- */
onSelectPerson: (personID: string) => void;
};
-/**
- * A dialog that allows selecting an existing person (cgroup) to associate
- * something (e.g. file(s)) with.
- */
export const AssignPersonDialog: React.FC<AssignPersonDialogProps> = ({
open,
onClose,
diff --git a/web/packages/new/photos/components/EditLocationDialog.tsx b/web/packages/new/photos/components/EditLocationDialog.tsx
index d4cf58fd34..ef945f2a4b 100644
--- a/web/packages/new/photos/components/EditLocationDialog.tsx
+++ b/web/packages/new/photos/components/EditLocationDialog.tsx
@@ -35,23 +35,10 @@ const leaflet = haveWindow()
: 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,
@@ -65,24 +52,21 @@ export const EditLocationDialog: React.FC<EditLocationDialogProps> = ({
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]);
- // Capture whether we're adding (vs editing) when dialog opens
const [isAddingLocation, setIsAddingLocation] = useState(false);
- // Reset selected location and states only when dialog opens
+ // File updates while open must not reset the user's edits.
const prevOpenRef = useRef(false);
useEffect(() => {
if (open && !prevOpenRef.current) {
setSelectedLocation(initialLocation);
setIsLoading(false);
setIsSuccess(false);
- // Determine add vs edit based on whether any file has location at open time
setIsAddingLocation(!files.some((file) => fileLocation(file)));
}
prevOpenRef.current = open;
@@ -97,7 +81,6 @@ export const EditLocationDialog: React.FC<EditLocationDialogProps> = ({
);
}, [selectedLocation, initialLocation]);
- // Reset success state when user selects a new location
const prevSelectedLocationRef = useRef(selectedLocation);
useEffect(() => {
const prevLoc = prevSelectedLocationRef.current;
@@ -263,10 +246,9 @@ const EditableMap: React.FC<EditableMapProps> = ({
const mapRef = useRef<L.Map | null>(null);
const markerRef = useRef<L.Marker | null>(null);
const prevOpenRef = useRef(open);
- // Capture initial location at mount time to avoid map reset on file updates
+ // File updates must not reset the map.
const initialLocationRef = useRef(initialLocation);
- // Search state
const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState<NominatimResult[]>([]);
const [showResults, setShowResults] = useState(false);
@@ -275,11 +257,9 @@ const EditableMap: React.FC<EditableMapProps> = ({
const searchRequestIdRef = useRef(0);
const searchAbortRef = useRef<AbortController | null>(null);
- // Manual coordinate input state
const [manualLat, setManualLat] = useState<string | null>(null);
const [manualLon, setManualLon] = useState<string | null>(null);
- // Reset manual inputs when dialog opens or selectedLocation changes
useEffect(() => {
setManualLat(null);
setManualLon(null);
@@ -361,11 +341,9 @@ const EditableMap: React.FC<EditableMapProps> = ({
const lng = parseFloat(result.lon);
onLocationSelect({ latitude: lat, longitude: lng });
- // Update map view
if (mapRef.current) {
mapRef.current.setView([lat, lng], 12);
- // Update or create marker
if (markerRef.current) {
markerRef.current.setLatLng([lat, lng]);
} else if (leaflet) {
@@ -443,16 +421,13 @@ const EditableMap: React.FC<EditableMapProps> = ({
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 defaultCenter: L.LatLngTuple = [20, 0];
const defaultZoom = 2;
const hasInitialLocation =
@@ -462,14 +437,12 @@ const EditableMap: React.FC<EditableMapProps> = ({
: 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 })
@@ -482,7 +455,6 @@ const EditableMap: React.FC<EditableMapProps> = ({
});
}
- // Handle map clicks to place/move marker
map.on("click", (e: L.LeafletMouseEvent) => {
const { lat, lng } = e.latlng;
onLocationSelect({ latitude: lat, longitude: lng });
diff --git a/web/packages/new/photos/components/PlaceholderThumbnails.tsx b/web/packages/new/photos/components/PlaceholderThumbnails.tsx
index 95a4684fd9..f4859f6f87 100644
--- a/web/packages/new/photos/components/PlaceholderThumbnails.tsx
+++ b/web/packages/new/photos/components/PlaceholderThumbnails.tsx
@@ -5,26 +5,14 @@ import { Overlay } from "ente-base/components/containers";
import { FileType } from "ente-media/file-type";
import React from "react";
-/**
- * A thumbnail shown when we're loading the thumbnail for a file.
- * @returns
- */
export const LoadingThumbnail = () => (
<Overlay sx={{ backgroundColor: "fill.faint", borderRadius: "4px" }} />
);
interface StaticThumbnailProps {
- /**
- * The type of the file for which we're showing the placeholder thumbnail.
- *
- * Expected to be one of {@link FileType}.
- */
fileType: number;
}
-/**
- * A thumbnail shown when a file does not have a thumbnail.
- */
export const StaticThumbnail: React.FC<StaticThumbnailProps> = ({
fileType,
}) => (
diff --git a/web/packages/new/photos/components/UnstyledButton.tsx b/web/packages/new/photos/components/UnstyledButton.tsx
index d3d5d6f590..c3812e9ae2 100644
--- a/web/packages/new/photos/components/UnstyledButton.tsx
+++ b/web/packages/new/photos/components/UnstyledButton.tsx
@@ -1,34 +1,16 @@
import { styled } from "@mui/material";
-/**
- * An "unstyled" button.
- *
- * There are cases where we semantically (and functionally) want a button, but
- * don't want the browser's default styling. This component is meant to act as a
- * base for such cases.
- *
- * Contrary to its name, it does add a bit of styling, to make these buttons fit
- * in with the rest of our theme.
- */
export const UnstyledButton = styled("button")`
- /* Reset some button defaults that are affecting us */
background: transparent;
border: 0;
padding: 0;
font: inherit;
- /* We customized the letter spacing in the theme. Need to tell the button to
- inherit that customization also. */
letter-spacing: inherit;
- /* Default cursor on mouse over of a button is not a hand pointer */
cursor: pointer;
`;
-/**
- * A variant of {@link UnstyledButton} that modifying the keyboard focus and
- * activation states to match the styling of {@link FocusVisibleButton}.
- */
export const FocusVisibleUnstyledButton = styled(UnstyledButton)(
({ theme }) => `
&:focus-visible {
diff --git a/web/packages/new/photos/components/gallery/ListHeader.tsx b/web/packages/new/photos/components/gallery/ListHeader.tsx
index 1979ff5fe5..bce71a4456 100644
--- a/web/packages/new/photos/components/gallery/ListHeader.tsx
+++ b/web/packages/new/photos/components/gallery/ListHeader.tsx
@@ -9,38 +9,14 @@ import { t } from "i18next";
import React from "react";
interface GalleryItemsSummaryProps {
- /**
- * The name / title for the items that are being shown.
- */
name: string;
- /**
- * Optional extra props to pass to the {@link Typography} component that
- * shows {@link name}
- */
nameProps?: TypographyProps;
- /**
- * The number of items being shown.
- */
fileCount: number;
- /**
- * An optional element, usually an icon, placed after the file count.
- */
endIcon?: React.ReactNode;
- /**
- * An optional click handler for the name.
- *
- * Note: Do not use this as the primary / only mechanism for the
- * corresponding functionality to be invoked, since this click handler will
- * be accessible only to sighted mouse users. However, it is fine to use it
- * as an alternate means of invoking some function.
- */
+ // This cannot be the only way to invoke the action; it is mouse-only.
onNameClick?: () => void;
}
-/**
- * A component suitable for being used as a summary displayed on top of the of a
- * list of photos (or other items) shown in the gallery.
- */
export const GalleryItemsSummary: React.FC<GalleryItemsSummaryProps> = ({
name,
nameProps,
@@ -57,7 +33,7 @@ export const GalleryItemsSummary: React.FC<GalleryItemsSummaryProps> = ({
direction="row"
sx={{
gap: 1.5,
- // Keep height the same even when there is no endIcon
+ // Keep the header height stable without an end icon.
minHeight: "24px",
}}
>
@@ -73,15 +49,6 @@ export const GalleryItemsSummary: React.FC<GalleryItemsSummaryProps> = ({
</div>
);
-/**
- * A component suitable for wrapping a component which is acting like a gallery
- * items header so that it fills the entire width (and acts like a "header")
- * when it is displayed in the gallery view.
- *
- * The header view (e.g. a {@link GalleryItemsSummary}) is displayed as part of
- * the gallery items list itself so that it scrolls alongwith the items. This
- * wrapper makes it take the full width of the "row" that it occupies.
- */
export const GalleryItemsHeaderAdapter = styled("div")`
width: 100%;
margin-bottom: 12px;
diff --git a/web/packages/new/photos/components/mui/SlideUpTransition.tsx b/web/packages/new/photos/components/mui/SlideUpTransition.tsx
index ffe461ffb2..8396fdde5e 100644
--- a/web/packages/new/photos/components/mui/SlideUpTransition.tsx
+++ b/web/packages/new/photos/components/mui/SlideUpTransition.tsx
@@ -2,11 +2,6 @@ import Slide from "@mui/material/Slide";
import type { TransitionProps } from "@mui/material/transitions";
import React, { forwardRef } from "react";
-/**
- * A React component that can be passed as the {@link slots.transition} prop to
- * a MUI {@link Dialog} to get it to use a slide transition (by default, the
- * dialog does a fade transition).
- */
export const SlideUpTransition = forwardRef(function Transition(
props: TransitionProps & { children: React.ReactElement },
ref: React.Ref<unknown>,
diff --git a/web/packages/new/photos/components/utils/thumbnail-grid-layout.ts b/web/packages/new/photos/components/utils/thumbnail-grid-layout.ts
index 5ab7f7935e..997ccb1d4f 100644
--- a/web/packages/new/photos/components/utils/thumbnail-grid-layout.ts
+++ b/web/packages/new/photos/components/utils/thumbnail-grid-layout.ts
@@ -4,49 +4,15 @@ export const thumbnailMaxWidth = 180;
export const thumbnailLayoutMinColumns = 4;
export interface ThumbnailGridLayoutParams {
- /**
- * The overall width available to us.
- *
- * This is the height that is the input to the computation, stashed here so
- * that other parts of the code downstream can also get at it if needed.
- */
containerWidth: number;
- /**
- * `true` if the container width is classified as a smaller screen for the
- * purpose of the thumbnail grid, and some dimensions are reduced to account
- * for the lesser space available to us.
- */
isSmallerLayout: boolean;
- /**
- * The inline padding (px) of the thumbnail grid.
- */
paddingInline: number;
- /**
- * The number of columns in the thumbnail grid.
- */
columns: number;
- /**
- * The width (px) of each item.
- */
itemWidth: number;
- /**
- * The height (px) of each item.
- */
itemHeight: number;
- /**
- * The gap (px) between each grid item.
- */
gap: number;
}
-/**
- * Determine the layout parameters for a grid of thumbnails that would best fit
- * the given width under various constraints.
- *
- * @param containerWidth The width available to the container. In our case,
- * since the thumbnail grids span the entire available width, this is the width
- * of the page itself.
- */
export const computeThumbnailGridLayoutParams = (
containerWidth: number,
): ThumbnailGridLayoutParams => {
diff --git a/web/packages/new/photos/components/utils/use-snapshot.ts b/web/packages/new/photos/components/utils/use-snapshot.ts
index 0b76c01b3a..69e639dcbf 100644
--- a/web/packages/new/photos/components/utils/use-snapshot.ts
+++ b/web/packages/new/photos/components/utils/use-snapshot.ts
@@ -16,45 +16,21 @@ import {
userDetailsSubscribe,
} from "../../services/user-details";
-/**
- * A convenience hook that returns {@link appLockSnapshot}, and also subscribes
- * to updates.
- */
export const useAppLockSnapshot = () =>
useSyncExternalStore(appLockSubscribe, appLockSnapshot, appLockSnapshot);
-/**
- * A convenience hook that returns {@link settingsSnapshot}, and also
- * subscribes to updates.
- */
export const useSettingsSnapshot = () =>
useSyncExternalStore(settingsSubscribe, settingsSnapshot);
-/**
- * A convenience hook that returns {@link userDetailsSnapshot}, and also
- * subscribes to updates.
- */
export const useUserDetailsSnapshot = () =>
useSyncExternalStore(userDetailsSubscribe, userDetailsSnapshot);
-/**
- * A convenience hook that returns {@link mlStatusSnapshot}, and also subscribes
- * to updates.
- */
export const useMLStatusSnapshot = () =>
useSyncExternalStore(mlStatusSubscribe, mlStatusSnapshot);
-/**
- * A convenience hook that returns {@link peopleStateSnapshot}, and also
- * subscribes to updates.
- */
export const usePeopleStateSnapshot = () =>
useSyncExternalStore(peopleStateSubscribe, peopleStateSnapshot);
-/**
- * A convenience hook that returns {@link hlsGenerationStatusSnapshot}, and also
- * subscribes to updates.
- */
export const useHLSGenerationStatusSnapshot = () =>
useSyncExternalStore(
hlsGenerationStatusSubscribe,
diff --git a/web/packages/new/photos/services/comment.ts b/web/packages/new/photos/services/comment.ts
index e6a182acb2..7596f5fbb4 100644
--- a/web/packages/new/photos/services/comment.ts
+++ b/web/packages/new/photos/services/comment.ts
@@ -3,35 +3,21 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { z } from "zod";
-/**
- * A decrypted comment.
- */
export interface Comment {
id: string;
collectionID: number;
fileID?: number;
parentCommentID?: string;
- /** User ID of the parent comment's author (only in feed responses). */
+ // Only present in feed responses.
parentCommentUserID?: number;
userID: number;
anonUserID?: string;
- /** The decrypted comment text. */
text: string;
isDeleted: boolean;
createdAt: number;
updatedAt: number;
}
-/**
- * Add a comment to a file in a collection.
- *
- * @param collectionID The ID of the collection containing the file.
- * @param fileID The ID of the file to comment on.
- * @param text The comment text to encrypt.
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @param parentCommentID Optional parent comment ID for replies.
- * @returns The ID of the created comment.
- */
export const addComment = async (
collectionID: number,
fileID: number,
@@ -63,11 +49,6 @@ export const addComment = async (
return id;
};
-/**
- * Delete a comment by its ID.
- *
- * @param commentID The ID of the comment to delete.
- */
export const deleteComment = async (commentID: string): Promise<void> => {
const res = await fetch(await apiURL(`/comments/${commentID}`), {
method: "DELETE",
diff --git a/web/packages/new/photos/services/ml/index-flags.ts b/web/packages/new/photos/services/ml/index-flags.ts
index b07ec6cbea..d108b37947 100644
--- a/web/packages/new/photos/services/ml/index-flags.ts
+++ b/web/packages/new/photos/services/ml/index-flags.ts
@@ -1,14 +1,8 @@
-/**
- * Bits for the `flags` bitmask stored on remote face and CLIP indexes.
- *
- * These values are part of the cross-client wire format and must stay aligned
- * with `ml_versions.dart`. Once shipped, a bit's meaning is immutable.
- */
+// Cross-client wire bits; keep aligned with ml_versions.dart and never reuse them.
const mlIndexFlagRuntimeRust = 1 << 0;
const mlIndexFlagCoreML = 1 << 1;
const mlIndexFlagWebGPU = 1 << 2;
-/** Flags describing the runtime that produced a Rust analysis result. */
export const mlIndexFlagsForRustResult = ({
usedCoreml,
usedWebgpu,
diff --git a/web/packages/new/photos/services/ml/kvdb.ts b/web/packages/new/photos/services/ml/kvdb.ts
index 9792514d7f..6fd0673da1 100644
--- a/web/packages/new/photos/services/ml/kvdb.ts
+++ b/web/packages/new/photos/services/ml/kvdb.ts
@@ -1,55 +1,22 @@
import { getKV, setKV } from "ente-base/kv";
import { z } from "zod";
-/**
- * Zod schema for {@link ClusterIDsByCGroupID}.
- */
const ClusterIDsByCGroupID = z.record(z.string(), z.array(z.string()));
-/**
- * cgroupID -> clusterIDs
- *
- * A record containing an array of clusters (represented by their IDs), keyed by
- * the corresponding cgroup ID.
- */
export type ClusterIDsByCGroupID = z.infer<typeof ClusterIDsByCGroupID>;
-/**
- * Return the locally persisted record of clusters per cgroup that the user has
- * rejected as not belonging to that cgroup.
- *
- * [Note: Persistent KV pairs related to ML]
- *
- * Conceptually, these could be part of ML DB. Practically, that'd would require
- * us to create a "kv" store within the ML DB, which seems both unnecessary, and
- * also potentially problematic since we'll have to introduce a version
- * migration (IndexedDB is finicky, and we've had better luck not poking it when
- * possible. See [Note: Avoiding IndexedDB flakiness by avoiding indexes]).
- */
+// Keep this in KV to avoid an IndexedDB migration.
export const savedRejectedClusters = async (): Promise<ClusterIDsByCGroupID> =>
ClusterIDsByCGroupID.parse((await getKV("rejectedClusters")) ?? {});
-/**
- * Update the locally persisted record of rejected clusters.
- *
- * Sibling of {@link savedRejectedClusters}.
- */
export const saveRejectedClusters = (entries: ClusterIDsByCGroupID) =>
setKV("rejectedClusters", entries);
-/**
- * Return the list of locally persisted clusters that the user has rejected as
- * not belonging to a particular cgroup (as identified by its {@link cgroupID}).
- */
export const savedRejectedClustersForCGroup = async (
cgroupID: string,
): Promise<string[]> =>
savedRejectedClusters().then((cs) => cs[cgroupID] ?? []);
-/**
- * Update the locally persisted record of rejected clusters for the given cgroup
- * (as identified by its {@link cgroupID}).
- */
export const saveRejectedClustersForCGroup = async (
cgroupID: string,
clusterIDs: string[],
diff --git a/web/packages/new/photos/services/reaction.ts b/web/packages/new/photos/services/reaction.ts
index b39b769762..1287b17b66 100644
--- a/web/packages/new/photos/services/reaction.ts
+++ b/web/packages/new/photos/services/reaction.ts
@@ -3,29 +3,12 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { z } from "zod";
-/**
- * Fixed length for padded reaction types.
- * All reactions are padded to this length before encryption to prevent
- * length-based analysis of the ciphertext.
- * Max emoji name is ~70 chars, so 100 provides a safe buffer.
- */
+// Hide reaction length in ciphertext; emoji names are currently at most ~70 characters.
const paddedReactionLength = 100;
-/**
- * Pad a reaction type to a fixed length using null bytes.
- */
const padReaction = (reactionType: string): string =>
reactionType.padEnd(paddedReactionLength, "\0");
-/**
- * Add a reaction to a file in a collection.
- *
- * @param collectionID The ID of the collection containing the file.
- * @param fileID The ID of the file to react to.
- * @param reactionType The type of reaction (e.g., "green_heart").
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @returns The ID of the created reaction.
- */
export const addReaction = async (
collectionID: number,
fileID: number,
@@ -50,16 +33,7 @@ export const addReaction = async (
return id;
};
-/**
- * Add a reaction to a comment in a collection.
- *
- * @param collectionID The ID of the collection containing the comment.
- * @param commentID The ID of the comment to react to.
- * @param reactionType The type of reaction (e.g., "green_heart").
- * @param collectionKey The decrypted collection key (base64 encoded).
- * @param fileID Optional file ID, required for file-scoped comments.
- * @returns The ID of the created reaction.
- */
+// fileID is required for file-scoped comments.
export const addCommentReaction = async (
collectionID: number,
commentID: string,
@@ -93,11 +67,6 @@ export const addCommentReaction = async (
const UpsertReactionResponse = z.object({ id: z.string() });
-/**
- * Delete a reaction by its ID.
- *
- * @param reactionID The ID of the reaction to delete.
- */
export const deleteReaction = async (reactionID: string): Promise<void> => {
const res = await fetch(await apiURL(`/reactions/${reactionID}`), {
method: "DELETE",
diff --git a/web/packages/new/photos/services/remote-store.ts b/web/packages/new/photos/services/remote-store.ts
index 8bbe80c08e..ad22666c1d 100644
--- a/web/packages/new/photos/services/remote-store.ts
+++ b/web/packages/new/photos/services/remote-store.ts
@@ -2,30 +2,7 @@ import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";
import { apiURL } from "ente-base/origins";
import { z } from "zod";
-/**
- * [Note: Remote store]
- *
- * The remote store provides a unified interface for persisting varied "remote
- * flags":
- *
- * - User preferences like "mapEnabled"
- *
- * - Feature flags like "isInternalUser"
- *
- * There are two APIs to get the current state from remote:
- *
- * 1. GET /remote-store/feature-flags fetches the combined state (nb: even
- * though the name of the endpoint has the word feature-flags, it also
- * includes user preferences).
- *
- * 2. GET /remote-store fetches individual values.
- *
- * Usually 1 is what we use, since it gets us everything in a single go, and
- * which we can also easily cache in local storage by saving the entire response
- * JSON blob.
- *
- * There is a single API (/remote-store/update) to update the state on remote.
- */
+// Despite its name, this endpoint returns preferences as well as feature flags.
export const fetchFeatureFlags = async () => {
const res = await fetch(await apiURL("/remote-store/feature-flags"), {
headers: await authenticatedRequestHeaders(),
@@ -34,11 +11,6 @@ export const fetchFeatureFlags = async () => {
return res;
};
-/**
- * Fetch the value for the given {@link key} from remote store.
- *
- * If the key is not present in the remote store, return {@link defaultValue}.
- */
export const getRemoteValue = async (key: string, defaultValue: string) => {
const res = await fetch(
await apiURL("/remote-store", { key, defaultValue }),
@@ -50,15 +22,9 @@ export const getRemoteValue = async (key: string, defaultValue: string) => {
const GetRemoteStoreResponse = z.object({ value: z.string() }).nullable();
-/**
- * Convenience wrapper over {@link getRemoteValue} that returns booleans.
- */
export const getRemoteFlag = async (key: string) =>
(await getRemoteValue(key, "false")) == "true";
-/**
- * Update or insert {@link value} for the given {@link key} into remote store.
- */
export const updateRemoteValue = async (key: string, value: string) =>
ensureOk(
await fetch(await apiURL("/remote-store/update"), {
@@ -68,8 +34,5 @@ export const updateRemoteValue = async (key: string, value: string) =>
}),
);
-/**
- * Convenience wrapper over {@link updateRemoteValue} that sets booleans.
- */
export const updateRemoteFlag = (key: string, value: boolean) =>
updateRemoteValue(key, JSON.stringify(value));
diff --git a/web/packages/new/photos/services/user-entity/db.ts b/web/packages/new/photos/services/user-entity/db.ts
index 1b2e37a7cb..ad3d957d74 100644
--- a/web/packages/new/photos/services/user-entity/db.ts
+++ b/web/packages/new/photos/services/user-entity/db.ts
@@ -3,34 +3,13 @@ import { z } from "zod";
import type { EntityType } from ".";
import { RemoteUserEntityKey } from "./remote";
-// Our DB footprint---
-//
-// All these are stored in the kv db.
-
const entitiesKey = (type: EntityType) => `entity/${type}`;
const entityKeyKey = (type: EntityType) => `entity/${type}/key`;
const latestUpdatedAtKey = (type: EntityType) => `entity/${type}/time`;
-// ^---
-
-/**
- * A locally persisted user entity.
- */
export interface LocalUserEntity {
- /**
- * The UUID or nanoid of the entity.
- */
id: string;
- /**
- * Arbitrary (decrypted) data associated with the entity. The format of this
- * data is specific to each entity type, but it is guaranteed to be JSON
- * serializable.
- */
data: unknown;
- /**
- * Epoch microseconds denoting when this entity was last changed (created or
- * updated).
- */
updatedAt: number;
}
@@ -41,33 +20,19 @@ const LocalUserEntity = z.object({
updatedAt: z.number(),
});
-/**
- * Update the list of locally persisted user entities of the given {@link type}.
- */
export const saveEntities = (type: EntityType, items: LocalUserEntity[]) =>
setKV(entitiesKey(type), items);
-/**
- * Return the list of locally persisted user entities of the given {@link type}.
- */
export const savedEntities = async (
type: EntityType,
): Promise<LocalUserEntity[]> =>
LocalUserEntity.array().parse((await getKV(entitiesKey(type))) ?? []);
-/**
- * Save the {@link entityKey} for the given user entity {@link type} to our
- * local database.
- */
export const saveRemoteUserEntityKey = (
type: EntityType,
entityKey: RemoteUserEntityKey,
) => setKV(entityKeyKey(type), entityKey);
-/**
- * Return the locally persisted {@link RemoteUserEntityKey}, if any,
- * corresponding the given user entity {@link type}.
- */
export const savedRemoteUserEntityKey = (
type: EntityType,
): Promise<RemoteUserEntityKey | undefined> =>
@@ -75,19 +40,9 @@ export const savedRemoteUserEntityKey = (
s ? RemoteUserEntityKey.parse(s) : undefined,
);
-/**
- * Save the latest `updatedAt` {@link value} for the given user entity
- * {@link type} to our local database.
- */
export const saveLatestUpdatedAt = (type: EntityType, value: number) =>
setKV(latestUpdatedAtKey(type), value);
-/**
- * Return the locally persisted value for the latest `updatedAt` time for the
- * given user entity {@link type}.
- *
- * This is used to checkpoint diffs, so that we can resume fetching from the
- * last time we did a fetch.
- */
+// Diff checkpoint; resume pulls from this timestamp.
export const savedLatestUpdatedAt = (type: EntityType) =>
getKVN(latestUpdatedAtKey(type));
diff --git a/web/packages/new/photos/types/context.ts b/web/packages/new/photos/types/context.ts
index 27b5ab1954..dbc51544ac 100644
--- a/web/packages/new/photos/types/context.ts
+++ b/web/packages/new/photos/types/context.ts
@@ -1,41 +1,17 @@
import type { NotificationAttributes } from "ente-base/components/Notification";
import { createContext, useContext } from "react";
-/**
- * The type of the React context available to all pages in the photos app.
- */
export interface PhotosAppContextT {
- /**
- * Show the global activity indicator (a loading bar at the top of the
- * page).
- */
showLoadingBar: () => void;
- /**
- * Hide the global activity indicator bar.
- */
hideLoadingBar: () => void;
- /**
- * Show a {@link Notification}, customizing its contents and click behaviour
- * using the provided {@link NotificationAttributes}.
- */
showNotification: (attributes: NotificationAttributes) => void;
watchFolderView: boolean;
setWatchFolderView: (isOpen: boolean) => void;
}
-/**
- * The React {@link Context} available to all nodes in the React tree of photos
- * app pages.
- */
export const PhotosAppContext = createContext<PhotosAppContextT | undefined>(
undefined,
);
-/**
- * Utility hook to get the photos {@link PhotosAppContextT}.
- *
- * This context is provided at the top level _app component for the photos app,
- * and thus is available to all React components in the Photos app's React tree.
- */
export const usePhotosAppContext = (): PhotosAppContextT =>
useContext(PhotosAppContext)!;
diff --git a/web/packages/new/photos/utils/gzip.ts b/web/packages/new/photos/utils/gzip.ts
index c9446ce4f2..9adafff20b 100644
--- a/web/packages/new/photos/utils/gzip.ts
+++ b/web/packages/new/photos/utils/gzip.ts
@@ -1,40 +1,19 @@
-/**
- * Compress the given {@link string} using "gzip" and return the resultant
- * bytes. See {@link gunzip} for the reverse operation.
- *
- * This is syntactic sugar to deal with the string/blob/stream/bytes
- * conversions, but it should not be taken as an abstraction layer. If your code
- * can directly use a ReadableStream, then then data -> stream -> data round
- * trip is unnecessary.
- */
export const gzip = async (
string: string,
): Promise<Uint8Array<ArrayBuffer>> => {
const compressedStream = new Blob([string])
.stream()
- // This code only runs on the desktop app currently, so we can rely on
- // the existence of new web features the CompressionStream APIs.
.pipeThrough(new CompressionStream("gzip"));
return new Uint8Array(await new Response(compressedStream).arrayBuffer());
};
-/**
- * Decompress the given "gzip" compressed {@link data} and return the resultant
- * string. See {@link gzip} for the reverse operation.
- */
export const gunzip = async (data: Uint8Array<ArrayBuffer>) => {
const decompressedStream = new Blob([data])
.stream()
- // This code only runs on the desktop app currently, so we can rely on
- // the existence of new web features the CompressionStream APIs.
.pipeThrough(new DecompressionStream("gzip"));
return new Response(decompressedStream).text();
};
-/**
- * Decompress the given "gzip" compressed {@link data}, rejecting it if the
- * decompressed output exceeds {@link maxOutputBytes}.
- */
export const gunzipWithLimit = async (
data: Uint8Array<ArrayBuffer>,
maxOutputBytes: number,
diff --git a/web/packages/new/photos/utils/web.ts b/web/packages/new/photos/utils/web.ts
index 7236cab798..e979aaee87 100644
--- a/web/packages/new/photos/utils/web.ts
+++ b/web/packages/new/photos/utils/web.ts
@@ -1,8 +1,3 @@
-/**
- * Open the given {@link url} in a new browser tab.
- *
- * @param url The URL to open.
- */
export const openURL = (url: string) => {
const a = document.createElement("a");
a.href = url;
@@ -11,10 +6,6 @@ export const openURL = (url: string) => {
a.click();
};
-/**
- * Open the system configured email client, initiating a new email to the given
- * {@link email} address.
- */
export const initiateEmail = (email: string) => {
const a = document.createElement("a");
a.href = "mailto:" + email;