Skip to content

armgit / ente

Public Imported from GitHub
0

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

[photos][web] Update gallery code architecture (#14283)

Aswin Asok59e5be221634
diff --git a/web/apps/photos/src/components/FileList.tsx b/web/apps/photos/src/components/FileList.tsx
index 91b2eedf43..70a0401c31 100644
--- a/web/apps/photos/src/components/FileList.tsx
+++ b/web/apps/photos/src/components/FileList.tsx
@@ -3,8 +3,8 @@ import {
FileContextMenu,
type ContextMenuPosition,
} from "@/components/FileContextMenu";
-import { AlbumEmptyState } from "@/components/gallery/AlbumEmptyState";
import type { GalleryBarMode } from "@/components/gallery/reducer";
+import { AlbumEmptyState } from "@/components/gallery/sections/albums/AlbumEmptyState";
import {
selectedFavoriteCount as countSelectedFavorites,
type SelectedState,
@@ -115,7 +115,7 @@ export interface FileListProps {
selected: SelectedState | ((selected: SelectedState) => SelectedState),
) => void;
selected: SelectedState;
- activeCollectionID: number;
+ activeCollectionID: number | undefined;
activePersonID?: string | undefined;
favoriteFileIDs?: Set<number>;
emailByUserID?: Map<number, string>;
@@ -992,7 +992,7 @@ type FileThumbnailProps = {
isRangeSelectActive: boolean;
selectOnClick: boolean;
isInSelectRange: boolean;
- activeCollectionID: number;
+ activeCollectionID: number | undefined;
showPlaceholder: boolean;
isFav: boolean;
onClick: () => void;
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index 1f91bff9c4..ca13189411 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -1,5 +1,5 @@
import type { RemotePullOpts } from "@/components/gallery";
-import { usePhotosNavigation } from "@/components/gallery/PhotosNavigationContext";
+import { usePhotosNavigation } from "@/components/gallery/navigation/PhotosNavigationContext";
import { downloadAndSaveFiles } from "@/services/save";
import { uploadManager } from "@/services/upload-manager";
import { fileTimelineDateString } from "@/utils/file";
@@ -7,7 +7,6 @@ import { styled } from "@mui/material";
import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";
import {
FileViewer,
- type FileViewerInitialSidebar,
type FileViewerProps,
} from "ente-gallery/components/viewer/FileViewer";
import type { Collection } from "ente-media/collection";
@@ -34,10 +33,6 @@ export type FileListWithViewerProps = {
onSetOpenFileViewer?: (open: boolean) => void;
onRemotePull: (opts?: RemotePullOpts) => Promise<void>;
activeCollectionSummary?: CollectionSummary;
- pendingFileIndex?: number;
- pendingFileSidebar?: FileViewerInitialSidebar;
- pendingHighlightCommentID?: string;
- onPendingNavigationConsumed?: () => void;
onAddSaveGroup: AddSaveGroup;
onAddFileToCollection?: (
@@ -133,10 +128,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
onAddFileToCollection,
onScroll,
onVisibleDateChange,
- pendingFileIndex,
- pendingFileSidebar,
- pendingHighlightCommentID,
- onPendingNavigationConsumed,
}) => {
const {
selectCollectionFromViewer: onSelectCollection,
@@ -144,12 +135,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
} = usePhotosNavigation();
const [openFileViewer, setOpenFileViewer] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
- const [initialSidebar, setInitialSidebar] = useState<
- FileViewerInitialSidebar | undefined
- >(undefined);
- const [highlightCommentID, setHighlightCommentID] = useState<
- string | undefined
- >(undefined);
const { showNotification, setIsFileViewerOpen } = usePhotosAppContext();
const updateOpenFileViewer = useCallback(
(open: boolean) => {
@@ -162,25 +147,7 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
useEffect(() => () => setIsFileViewerOpen?.(false), [setIsFileViewerOpen]);
- useEffect(() => {
- if (pendingFileIndex !== undefined) {
- setCurrentIndex(pendingFileIndex);
- setInitialSidebar(pendingFileSidebar);
- setHighlightCommentID(pendingHighlightCommentID);
- updateOpenFileViewer(true);
- onPendingNavigationConsumed?.();
- }
- }, [
- pendingFileIndex,
- pendingFileSidebar,
- pendingHighlightCommentID,
- updateOpenFileViewer,
- onPendingNavigationConsumed,
- ]);
-
const handleCloseFileViewerInternal = useCallback(() => {
- setInitialSidebar(undefined);
- setHighlightCommentID(undefined);
updateOpenFileViewer(false);
}, [updateOpenFileViewer]);
@@ -280,8 +247,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
open={openFileViewer}
onClose={handleCloseFileViewerInternal}
initialIndex={currentIndex}
- initialSidebar={initialSidebar}
- highlightCommentID={highlightCommentID}
disableDownload={!enableDownload}
isInTrashSection={
activeCollectionID == PseudoCollectionID.trash
diff --git a/web/apps/photos/src/components/SearchBar.tsx b/web/apps/photos/src/components/SearchBar.tsx
index 663fbf13a0..8fd0c61d64 100644
--- a/web/apps/photos/src/components/SearchBar.tsx
+++ b/web/apps/photos/src/components/SearchBar.tsx
@@ -1,4 +1,4 @@
-import { usePhotosNavigation } from "@/components/gallery/PhotosNavigationContext";
+import { usePhotosNavigation } from "@/components/gallery/navigation/PhotosNavigationContext";
import { sidebarTheme } from "@/components/sidebar/theme";
import {
groupSearchOptions,
diff --git a/web/apps/photos/src/components/SelectedFileOptions.tsx b/web/apps/photos/src/components/SelectedFileOptions.tsx
index e112a42302..de0e2fc57b 100644
--- a/web/apps/photos/src/components/SelectedFileOptions.tsx
+++ b/web/apps/photos/src/components/SelectedFileOptions.tsx
@@ -298,9 +298,9 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
};
return (
- <>
- <SpacedRow sx={{ flex: 1, gap: 1, flexWrap: "wrap" }}>
- <IconButton onClick={onClearSelection}>
+ <SpacedRow sx={{ flex: 1, minWidth: 0, gap: 1, flexWrap: "wrap" }}>
+ <SpacedRow sx={{ gap: 1, flexShrink: 0 }}>
+ <IconButton onClick={onClearSelection} aria-label={t("close")}>
<CloseIcon />
</IconButton>
<Typography>
@@ -315,12 +315,27 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
isAllSelected={isAllSelected}
onClick={isAllSelected ? onClearSelection : onSelectAll}
/>
-
- <Box sx={{ mr: "auto" }} />
-
- {toolbarActions.map(renderActionButton)}
</SpacedRow>
- </>
+ <Box
+ sx={{
+ display: "flex",
+ flex: "1 1 320px",
+ minWidth: 0,
+ overflowX: "auto",
+ }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ flexShrink: 0,
+ ml: "auto",
+ "& .MuiIconButton-root": { p: 1 },
+ }}
+ >
+ {toolbarActions.map(renderActionButton)}
+ </Box>
+ </Box>
+ </SpacedRow>
);
};
diff --git a/web/apps/photos/src/components/collections/GalleryBarAndListHeader.tsx b/web/apps/photos/src/components/collections/AlbumContentHeader.tsx
similarity index 87%
rename from web/apps/photos/src/components/collections/GalleryBarAndListHeader.tsx
rename to web/apps/photos/src/components/collections/AlbumContentHeader.tsx
index b9c61bb3f2..aa2b1d4cad 100644
--- a/web/apps/photos/src/components/collections/GalleryBarAndListHeader.tsx
+++ b/web/apps/photos/src/components/collections/AlbumContentHeader.tsx
@@ -8,9 +8,7 @@ import type { FileListHeaderOrFooter } from "@/components/FileList";
import {
AlbumsHeader,
albumsHeaderHeight,
-} from "@/components/gallery/AlbumsHeader";
-import { PeopleHeader } from "@/components/gallery/PeopleHeader";
-import type { GalleryBarMode } from "@/components/gallery/reducer";
+} from "@/components/gallery/sections/albums/AlbumsHeader";
import { Box } from "@mui/material";
import { useModalVisibility } from "ente-base/components/utils/modal";
import type { Collection } from "ente-media/collection";
@@ -22,7 +20,6 @@ import {
PseudoCollectionID,
type CollectionSummary,
} from "ente-new/photos/services/collection-summary";
-import type { Person } from "ente-new/photos/services/ml/people";
import { t } from "i18next";
import React, { useCallback, useEffect, useState } from "react";
import { AlbumCastDialog } from "./AlbumCastDialog";
@@ -31,14 +28,10 @@ import {
type CollectionHeaderProps,
} from "./CollectionHeader";
-type GalleryBarAndListHeaderProps = {
- mode: GalleryBarMode;
- shouldHide: boolean;
+type AlbumContentHeaderProps = {
collectionSummary: CollectionSummary | undefined;
albums: CollectionSummary[];
activeCollection: Collection | undefined;
- activePerson: Person | undefined;
- people: Person[];
setFileListHeader: (header: FileListHeaderOrFooter) => void;
hasActiveFileSelection: boolean;
} & Pick<
@@ -55,20 +48,14 @@ type GalleryBarAndListHeaderProps = {
"user" | "emailByUserID" | "shareSuggestionEmails" | "setBlockingLoad"
>;
-export const GalleryBarAndListHeader: React.FC<
- GalleryBarAndListHeaderProps
-> = ({
- shouldHide,
- mode,
+export const AlbumContentHeader: React.FC<AlbumContentHeaderProps> = ({
user,
collectionSummary,
albums,
activeCollection,
setBlockingLoad,
- people,
isActiveCollectionDownloadInProgress,
hasActiveFileSelection,
- activePerson,
emailByUserID,
shareSuggestionEmails,
onRemotePull,
@@ -105,11 +92,8 @@ export const GalleryBarAndListHeader: React.FC<
const [descriptionHeight, setDescriptionHeight] = useState(0);
useEffect(() => {
- if (shouldHide || mode == "links") return;
-
// Pseudo-collections need header actions despite having no Collection.
const shouldRenderCollectionHeader =
- mode != "people" &&
collectionSummary &&
(activeCollection ||
collectionSummary.id <= PseudoCollectionID.all);
@@ -149,15 +133,13 @@ export const GalleryBarAndListHeader: React.FC<
onDescriptionHeightChange={setDescriptionHeight}
/>
</Box>
- ) : mode != "people" && collectionSummary ? (
+ ) : collectionSummary ? (
<GalleryItemsHeaderAdapter>
<GalleryItemsSummary
name={collectionSummary.name}
fileCount={collectionSummary.fileCount}
/>
</GalleryItemsHeaderAdapter>
- ) : activePerson ? (
- <PeopleHeader person={activePerson} people={people} />
) : (
<></>
),
@@ -168,13 +150,10 @@ export const GalleryBarAndListHeader: React.FC<
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
- shouldHide,
- mode,
collectionSummary,
albums,
activeCollection,
isActiveCollectionDownloadInProgress,
- activePerson,
showCollectionShare,
openCollectionShare,
openCollectionManageLink,
@@ -187,15 +166,8 @@ export const GalleryBarAndListHeader: React.FC<
onEditAlbumDetails,
albumDescription,
descriptionHeight,
- // TODO: Cluster
- // This causes a loop since it is an array dep
- // people,
]);
- if (shouldHide) {
- return <></>;
- }
-
return (
<>
{activeCollection && (
diff --git a/web/apps/photos/src/components/collections/CollectionHeader.tsx b/web/apps/photos/src/components/collections/CollectionHeader.tsx
index 7ac3026fee..fee5b0088f 100644
--- a/web/apps/photos/src/components/collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/collections/CollectionHeader.tsx
@@ -1,5 +1,5 @@
import type { RemotePullOpts } from "@/components/gallery";
-import { usePhotosNavigation } from "@/components/gallery/PhotosNavigationContext";
+import { usePhotosNavigation } from "@/components/gallery/navigation/PhotosNavigationContext";
import { downloadAndSaveCollectionFiles } from "@/services/save";
import {
CleanIcon,
diff --git a/web/apps/photos/src/components/collections/CollectionMap.tsx b/web/apps/photos/src/components/collections/CollectionMap.tsx
index 6e7a0a838b..2cbdbc53a2 100644
--- a/web/apps/photos/src/components/collections/CollectionMap.tsx
+++ b/web/apps/photos/src/components/collections/CollectionMap.tsx
@@ -1,5 +1,5 @@
import type { RemotePullOpts } from "@/components/gallery";
-import type { PlaceSelection } from "@/components/gallery/PlacesList";
+import type { PlaceSelection } from "@/components/gallery/sections/places/PlacesList";
import type { SelectedState } from "@/utils/file";
import AddIcon from "@mui/icons-material/Add";
import LocationOnIcon from "@mui/icons-material/LocationOn";
diff --git a/web/apps/photos/src/components/gallery/BarImpl.tsx b/web/apps/photos/src/components/gallery/BarImpl.tsx
deleted file mode 100644
index 88afd0a735..0000000000
--- a/web/apps/photos/src/components/gallery/BarImpl.tsx
+++ /dev/null
@@ -1,1093 +0,0 @@
-import { CollectionsSortOptions } from "@/components/CollectionsSortOptions";
-import { PeopleSortOptions } from "@/components/PeopleSortOptions";
-import {
- matchesAlbumFilter,
- type AlbumFilter,
- type albumFilters,
-} from "@/utils/album-filters";
-import type { PeopleSortBy } from "@/utils/people-sort";
-import {
- ArrowDown01Icon,
- Link05Icon,
- PinIcon,
- StarIcon,
-} from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
-import AddIcon from "@mui/icons-material/Add";
-import ArchiveIcon from "@mui/icons-material/Archive";
-import CloseIcon from "@mui/icons-material/Close";
-import PeopleIcon from "@mui/icons-material/People";
-import SearchIcon from "@mui/icons-material/Search";
-import {
- Box,
- ButtonBase,
- Divider,
- Drawer,
- IconButton,
- InputBase,
- Stack,
- Tooltip,
- Typography,
- styled,
- useMediaQuery,
- useTheme,
-} from "@mui/material";
-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
-import type { EnteFile } from "ente-media/file";
-import { ItemCard } from "ente-new/photos/components/Tiles";
-import {
- PseudoCollectionID,
- type CollectionSummary,
- type CollectionSummaryAttribute,
- type CollectionsSortBy,
-} from "ente-new/photos/services/collection-summary";
-import type { Person } from "ente-new/photos/services/ml/people";
-import { wait } from "ente-utils/promise";
-import { t } from "i18next";
-import React, {
- memo,
- useCallback,
- useEffect,
- useId,
- useMemo,
- useRef,
- useState,
-} from "react";
-import AutoSizer from "react-virtualized-auto-sizer";
-import {
- FixedSizeList,
- VariableSizeList,
- areEqual,
- type ListChildComponentProps,
-} from "react-window";
-import { usePhotosNavigation } from "./PhotosNavigationContext";
-import { PlacesList, type PlaceSelection } from "./PlacesList";
-import type { GalleryBarMode } from "./reducer";
-
-export interface GalleryBarPresentationProps {
- collapsed: boolean;
- mobileDrawerProps: ModalVisibilityProps;
-}
-
-export interface GalleryBarImplProps extends GalleryBarPresentationProps {
- mode: GalleryBarMode;
- placesFiles?: EnteFile[];
- selectedPlace?: PlaceSelection;
- albumFilter: AlbumFilter;
- albumSearchQuery: string;
- onAlbumSearchQueryChange: (query: string) => void;
- collectionSummaries: CollectionSummary[];
- visibleAlbumFilters: typeof albumFilters;
- uncategorizedCollectionSummaryID: number;
- activeCollectionID: number | undefined;
- onCreateAlbum: () => void;
- collectionsSortBy: CollectionsSortBy;
- onChangeCollectionsSortBy: (by: CollectionsSortBy) => void;
- peopleSortBy: PeopleSortBy;
- onChangePeopleSortBy: (by: PeopleSortBy) => void;
- people: Person[];
- activePerson: Person | undefined;
-}
-
-export const GalleryBarImpl: React.FC<GalleryBarImplProps> = ({
- mode,
- placesFiles,
- selectedPlace,
- albumFilter,
- albumSearchQuery,
- onAlbumSearchQueryChange,
- collectionSummaries,
- visibleAlbumFilters,
- uncategorizedCollectionSummaryID,
- activeCollectionID,
- onCreateAlbum,
- collectionsSortBy,
- onChangeCollectionsSortBy,
- peopleSortBy,
- onChangePeopleSortBy,
- people,
- activePerson,
- collapsed,
- mobileDrawerProps,
-}) => {
- const {
- selectCollection,
- selectPerson,
- selectPlace,
- showAlbumOverview: onShowAlbumOverview,
- showPeople: onShowPeopleOverview,
- showLinksOverview: onShowLinksOverview,
- showCollectionSummary: onShowCollectionSummary,
- } = usePhotosNavigation();
- const { onClose: closeMobileNavigation } = mobileDrawerProps;
- const onSelectCollectionID = useCallback(
- (id: number) => {
- selectCollection(id);
- closeMobileNavigation();
- },
- [selectCollection, closeMobileNavigation],
- );
- const onSelectPerson = useCallback(
- (id: string) => {
- selectPerson(id);
- closeMobileNavigation();
- },
- [selectPerson, closeMobileNavigation],
- );
- const onSelectPlace = useCallback(
- (place: PlaceSelection | undefined) => {
- selectPlace(place);
- closeMobileNavigation();
- },
- [selectPlace, closeMobileNavigation],
- );
- const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
- const titleID = useId();
- const listRef = useRef<FixedSizeList | null>(null);
- const albumListRef = useRef<VariableSizeList | null>(null);
- const searchInputRef = useRef<HTMLInputElement>(null);
- const [placesSearchQuery, setPlacesSearchQuery] = useState("");
- const [peopleSearchQuery, setPeopleSearchQuery] = useState("");
- const [groupExpanded, setGroupExpanded] = useState(true);
- const searchQuery = placesFiles
- ? placesSearchQuery
- : mode == "people"
- ? peopleSearchQuery
- : albumSearchQuery;
- const setSearchQuery = placesFiles
- ? setPlacesSearchQuery
- : mode == "people"
- ? setPeopleSearchQuery
- : onAlbumSearchQueryChange;
- const normalizedSearchQuery = searchQuery.trim().toLowerCase();
- const isSearching = !!normalizedSearchQuery;
- const matchingPeople = useMemo(
- () =>
- mode == "people" && isSearching
- ? people.filter((person) =>
- person.name
- ?.toLowerCase()
- .includes(normalizedSearchQuery),
- )
- : people,
- [mode, people, isSearching, normalizedSearchQuery],
- );
- const [viewportHeight, setViewportHeight] = useState(0);
- const [expandedAlbumFilter, setExpandedAlbumFilter] = useState<
- AlbumFilter | undefined
- >(albumFilter);
- const lastAlbumFilter = useRef(albumFilter);
- const displayedAlbumFilter =
- isSearching &&
- expandedAlbumFilter !== undefined &&
- !visibleAlbumFilters.some(({ value }) => value == expandedAlbumFilter)
- ? visibleAlbumFilters[0]?.value
- : expandedAlbumFilter;
- const displayedCollectionSummaries = useMemo(
- () =>
- mode == "albums"
- ? collectionSummaries.filter(
- (cs) =>
- displayedAlbumFilter !== undefined &&
- matchesAlbumFilter(cs, displayedAlbumFilter),
- )
- : collectionSummaries,
- [mode, collectionSummaries, displayedAlbumFilter],
- );
-
- useEffect(() => {
- // Heading clicks already set expansion; sync other group navigation.
- if (lastAlbumFilter.current == albumFilter) return;
- lastAlbumFilter.current = albumFilter;
- setExpandedAlbumFilter(albumFilter);
- }, [albumFilter]);
- useEffect(() => {
- setPeopleSearchQuery("");
- setGroupExpanded(true);
- }, [mode]);
-
- useEffect(() => {
- if (
- mode == "people" &&
- (mobile ? !mobileDrawerProps.open : collapsed)
- ) {
- setPeopleSearchQuery("");
- }
- }, [mode, mobile, mobileDrawerProps.open, collapsed]);
-
- const isPlacesView = !!placesFiles;
- useEffect(() => {
- if (!isPlacesView) setPlacesSearchQuery("");
- }, [isPlacesView]);
-
- useEffect(() => {
- if (isSearching) {
- listRef.current?.scrollTo(0);
- albumListRef.current?.scrollTo(0);
- }
- }, [searchQuery, isSearching]);
-
- const itemData = useMemo<ItemData>(
- () =>
- mode == "albums" ||
- mode == "hidden-albums" ||
- mode == "archive-albums" ||
- mode == "links"
- ? {
- type: "collections",
- collectionSummaries: displayedCollectionSummaries,
- indented:
- mode == "albums" ||
- mode == "links" ||
- mode == "hidden-albums",
- activeCollectionID: activeCollectionID!,
- onSelectCollectionID,
- }
- : {
- type: "people" as const,
- people: matchingPeople,
- activePerson,
- onSelectPerson,
- },
- [
- mode,
- displayedCollectionSummaries,
- activeCollectionID,
- onSelectCollectionID,
- matchingPeople,
- activePerson,
- onSelectPerson,
- ],
- );
-
- const title = placesFiles
- ? t("search_places")
- : mode == "people"
- ? t("people")
- : mode == "links"
- ? t("links")
- : mode == "hidden-albums"
- ? t("hidden_albums")
- : mode == "archive-albums"
- ? t("section_archive")
- : t("albums");
-
- const albumShortcuts = [
- {
- id: uncategorizedCollectionSummaryID,
- label: t("section_uncategorized"),
- active: activeCollectionID == uncategorizedCollectionSummaryID,
- },
- {
- id: PseudoCollectionID.hiddenItems,
- label: t("section_hidden"),
- active: mode == "hidden-albums",
- },
- {
- id: PseudoCollectionID.archiveItems,
- label: t("section_archive"),
- active: mode == "archive-albums",
- },
- {
- id: PseudoCollectionID.trash,
- label: t("section_trash"),
- active: activeCollectionID == PseudoCollectionID.trash,
- },
- ].filter(({ label }) =>
- label.toLowerCase().includes(normalizedSearchQuery),
- );
-
- const items = (
- <Box sx={{ flex: 1, minHeight: 0, minWidth: 0 }}>
- <AutoSizer onResize={({ height }) => setViewportHeight(height)}>
- {({ width, height }) => (
- <FixedSizeList
- ref={listRef}
- width={width}
- height={height}
- itemData={itemData}
- itemKey={getItemKey}
- itemCount={getItemCount(itemData)}
- itemSize={mobile ? 46 : 50}
- style={{ overflowX: "hidden" }}
- >
- {ListItem}
- </FixedSizeList>
- )}
- </AutoSizer>
- </Box>
- );
-
- const searchEmptyState = (
- <Stack
- role="status"
- sx={{
- flex: 1,
- minHeight: 0,
- alignItems: "center",
- justifyContent: "safe center",
- gap: "12px",
- px: "16px",
- py: "24px",
- textAlign: "center",
- overflowY: "auto",
- }}
- >
- <Box
- component="img"
- src="/images/empty-state/no-matches.svg"
- alt=""
- draggable={false}
- sx={{ width: 112, height: "auto", flexShrink: 0 }}
- />
- <Typography
- sx={{
- color: "text.base",
- fontFamily: '"Outfit Variable", sans-serif',
- fontSize: 18,
- fontWeight: 600,
- lineHeight: "26px",
- }}
- >
- {t("no_results")}
- </Typography>
- </Stack>
- );
-
- const rowHeight = mobile ? 46 : 50;
- const albumNavigationRows: AlbumNavigationRow[] = [];
- for (const filter of visibleAlbumFilters) {
- albumNavigationRows.push({
- key: `filter-${filter.value}`,
- height: rowHeight,
- content: (
- <BarCard
- aria-label={filter.title()}
- aria-current={
- activeCollectionID === undefined &&
- albumFilter == filter.value
- ? "page"
- : undefined
- }
- aria-expanded={displayedAlbumFilter == filter.value}
- onClick={() => {
- lastAlbumFilter.current = filter.value;
- setExpandedAlbumFilter(
- displayedAlbumFilter == filter.value
- ? undefined
- : filter.value,
- );
- onShowAlbumOverview(filter.value);
- mobileDrawerProps.onClose();
- }}
- sx={{ flexShrink: 0 }}
- >
- <CardText>{filter.label()}</CardText>
- <Box
- component={HugeiconsIcon}
- icon={ArrowDown01Icon}
- size={16}
- strokeWidth={1.8}
- sx={{
- color: "text.muted",
- transform:
- displayedAlbumFilter == filter.value
- ? undefined
- : "rotate(-90deg)",
- }}
- />
- </BarCard>
- ),
- });
- if (displayedAlbumFilter == filter.value) {
- for (const collectionSummary of displayedCollectionSummaries) {
- albumNavigationRows.push({
- key: `collection-${collectionSummary.id}`,
- height: rowHeight,
- content: (
- <CollectionBarCard
- key={`${collectionSummary.id}-${collectionSummary.coverFile?.id}`}
- collectionSummary={collectionSummary}
- activeCollectionID={activeCollectionID!}
- onSelectCollectionID={onSelectCollectionID}
- indented={
- !collectionSummary.attributes.has("system")
- }
- />
- ),
- });
- }
- }
- }
- if (visibleAlbumFilters.length && albumShortcuts.length) {
- albumNavigationRows.push({
- key: "shortcut-divider",
- height: 18,
- content: (
- <Divider
- sx={{
- mt: "8px",
- height: "2px",
- border: 0,
- bgcolor: "divider",
- opacity: 0.5,
- }}
- />
- ),
- });
- }
- for (const { id, label, active } of albumShortcuts) {
- albumNavigationRows.push({
- key: `shortcut-${id}`,
- height: rowHeight,
- content: (
- <BarCard
- aria-label={label}
- aria-current={active ? "true" : undefined}
- onClick={() => {
- void onShowCollectionSummary(
- id,
- id == PseudoCollectionID.hiddenItems,
- ).then(async (success) => {
- if (!success || !mobile) return;
- if (id == PseudoCollectionID.hiddenItems)
- await wait(10);
- mobileDrawerProps.onClose();
- });
- }}
- sx={{ flexShrink: 0 }}
- >
- <CardText>{label}</CardText>
- </BarCard>
- ),
- });
- }
-
- const albumRowSizes = albumNavigationRows
- .map(({ height }) => height)
- .join(",");
- const activeAlbumRowIndex = albumNavigationRows.findIndex(
- ({ key }) => key == `collection-${activeCollectionID}`,
- );
- useEffect(() => {
- albumListRef.current?.resetAfterIndex(0);
- }, [albumRowSizes]);
-
- useEffect(() => {
- if (isSearching) return;
- if (mode == "albums") {
- if (activeAlbumRowIndex != -1)
- albumListRef.current?.scrollToItem(
- activeAlbumRowIndex,
- "smart",
- );
- return;
- }
- if (!listRef.current) return;
- let i = -1;
- switch (mode) {
- case "hidden-albums":
- case "archive-albums":
- case "links":
- i = displayedCollectionSummaries.findIndex(
- ({ id }) => id == activeCollectionID,
- );
- break;
- case "people":
- i = matchingPeople.findIndex(
- ({ id }) => id == activePerson?.id,
- );
- break;
- }
- if (i != -1) listRef.current.scrollToItem(i, "smart");
- }, [
- mode,
- activeAlbumRowIndex,
- displayedCollectionSummaries,
- activeCollectionID,
- matchingPeople,
- activePerson,
- collapsed,
- mobile,
- mobileDrawerProps.open,
- viewportHeight,
- isSearching,
- ]);
-
- const isGroupOverview =
- mode == "links"
- ? activeCollectionID === undefined
- : activeCollectionID == PseudoCollectionID.hiddenItems;
-
- const navigation = (
- <Stack
- component="nav"
- aria-labelledby={titleID}
- onKeyDown={(event) => {
- if (event.key == "Escape" && searchQuery) {
- event.stopPropagation();
- setSearchQuery("");
- }
- }}
- sx={(theme) => ({
- "--gallery-navigation-surface": "#FFFFFF",
- "--gallery-navigation-hover":
- "color-mix(in srgb, var(--mui-palette-text-base) 8%, var(--gallery-navigation-surface))",
- flexShrink: 0,
- width: "100%",
- height: "100%",
- minHeight: 0,
- px: mobile ? "12px" : "16px",
- py: mobile ? "14px" : 0,
- borderLeft: mobile ? 0 : "2px solid",
- borderColor: "rgba(224, 224, 224, 0.5)",
- gap: "16px",
- letterSpacing: 0,
- ...theme.applyStyles("dark", {
- "--gallery-navigation-surface": "#212121",
- borderColor: "rgba(62, 62, 62, 0.5)",
- }),
- })}
- >
- <Stack
- direction="row"
- sx={{
- alignItems: "center",
- flexShrink: 0,
- height: 38,
- gap: 0.5,
- "& .MuiIconButton-root": {
- width: 38,
- height: 38,
- borderRadius: "12px",
- bgcolor: "var(--gallery-navigation-surface)",
- "&:hover": {
- bgcolor: "var(--gallery-navigation-hover)",
- },
- },
- }}
- >
- <Typography
- component="h2"
- id={titleID}
- sx={{
- flex: 1,
- minWidth: 0,
- fontFamily: '"Outfit Variable", Outfit, sans-serif',
- fontSize: mobile ? 20 : 24,
- fontWeight: 600,
- lineHeight: mobile ? "26px" : "32px",
- }}
- >
- {mode == "people" && !placesFiles ? (
- <ButtonBase
- onClick={() => {
- setPeopleSearchQuery("");
- onShowPeopleOverview();
- mobileDrawerProps.onClose();
- }}
- sx={{
- font: "inherit",
- justifyContent: "flex-start",
- borderRadius: 1,
- "&:hover": { color: "text.muted" },
- "&.Mui-focusVisible": {
- outline: "2px solid",
- outlineColor: "primary.main",
- outlineOffset: 2,
- },
- }}
- >
- {title}
- </ButtonBase>
- ) : (
- title
- )}
- </Typography>
- {!placesFiles &&
- (mode != "people" ? (
- <CollectionsSortOptions
- variant="v2"
- activeSortBy={collectionsSortBy}
- onChangeSortBy={onChangeCollectionsSortBy}
- />
- ) : (
- <PeopleSortOptions
- variant="v2"
- activeSortBy={peopleSortBy}
- onChangeSortBy={onChangePeopleSortBy}
- />
- ))}
- {!placesFiles &&
- (mode == "albums" || mode == "hidden-albums") && (
- <Tooltip title={t("new_album")}>
- <IconButton
- aria-label={t("new_album")}
- aria-haspopup="dialog"
- onClick={() => {
- mobileDrawerProps.onClose();
- onCreateAlbum();
- }}
- >
- <AddIcon sx={{ fontSize: 20 }} />
- </IconButton>
- </Tooltip>
- )}
- {mobile && (
- <IconButton
- aria-label={t("close")}
- onClick={mobileDrawerProps.onClose}
- >
- <CloseIcon sx={{ fontSize: 20 }} />
- </IconButton>
- )}
- </Stack>
- <Stack
- direction="row"
- sx={{
- alignItems: "center",
- flexShrink: 0,
- display: "flex",
- height: 52,
- gap: "10px",
- px: "16px",
- borderRadius: "12px",
- bgcolor: "var(--gallery-navigation-surface)",
- border: "1px solid",
- borderColor: "stroke.faint",
- "&:focus-within": {
- outline: "1px solid",
- outlineColor: "stroke.muted",
- outlineOffset: -1,
- },
- }}
- >
- <SearchIcon sx={{ fontSize: 18, color: "text.muted" }} />
- <InputBase
- inputRef={searchInputRef}
- fullWidth
- placeholder={t(
- placesFiles
- ? "search_in_places"
- : mode == "people"
- ? "people_search_hint"
- : mode == "links"
- ? "search_links"
- : "search_in_albums",
- )}
- inputProps={{
- "aria-label": t(
- placesFiles
- ? "search_in_places"
- : mode == "people"
- ? "people_search_hint"
- : mode == "links"
- ? "search_links"
- : "search_in_albums",
- ),
- }}
- value={searchQuery}
- onChange={(event) => setSearchQuery(event.target.value)}
- sx={{
- fontSize: mobile ? 13 : 14,
- fontWeight: 500,
- color: "text.base",
- "& input::placeholder": {
- color: "text.muted",
- opacity: 1,
- },
- }}
- />
- {searchQuery && (
- <IconButton
- aria-label={t("clear_search")}
- onClick={() => {
- setSearchQuery("");
- searchInputRef.current?.focus();
- }}
- size="small"
- >
- <CloseIcon sx={{ fontSize: 18 }} />
- </IconButton>
- )}
- </Stack>
- {placesFiles ? (
- <PlacesList
- files={placesFiles}
- searchQuery={placesSearchQuery}
- selectedPlace={selectedPlace}
- onSelectPlace={onSelectPlace}
- />
- ) : isSearching &&
- (mode == "albums"
- ? !visibleAlbumFilters.length && !albumShortcuts.length
- : !getItemCount(itemData)) ? (
- searchEmptyState
- ) : mode == "albums" ? (
- <Box
- role="group"
- aria-label={t("filter_albums")}
- sx={{ flex: 1, minHeight: 0, minWidth: 0 }}
- >
- <AutoSizer
- onResize={({ height }) => setViewportHeight(height)}
- >
- {({ width, height }) => (
- <VariableSizeList
- ref={albumListRef}
- width={width}
- height={height}
- itemData={albumNavigationRows}
- itemCount={albumNavigationRows.length}
- itemKey={(index, rows) => rows[index]!.key}
- itemSize={(index) =>
- albumNavigationRows[index]!.height
- }
- style={{ overflowX: "hidden" }}
- >
- {AlbumNavigationItem}
- </VariableSizeList>
- )}
- </AutoSizer>
- </Box>
- ) : mode == "links" || mode == "hidden-albums" ? (
- <Stack
- role="group"
- aria-label={t(mode == "links" ? "links" : "section_hidden")}
- sx={{ flex: 1, minHeight: 0, minWidth: 0 }}
- >
- <BarCard
- aria-current={isGroupOverview ? "page" : undefined}
- aria-expanded={isSearching || groupExpanded}
- onClick={() => {
- setGroupExpanded(
- !isGroupOverview || !groupExpanded,
- );
- if (mode == "links") onShowLinksOverview();
- else
- onSelectCollectionID(
- PseudoCollectionID.hiddenItems,
- );
- mobileDrawerProps.onClose();
- }}
- sx={{ flexShrink: 0, height: rowHeight }}
- >
- <CardText>
- {t(mode == "links" ? "links" : "section_hidden")}
- </CardText>
- <Box
- component={HugeiconsIcon}
- icon={ArrowDown01Icon}
- size={16}
- strokeWidth={1.8}
- sx={{
- color: "text.muted",
- transform:
- isSearching || groupExpanded
- ? undefined
- : "rotate(-90deg)",
- }}
- />
- </BarCard>
- {(isSearching || groupExpanded) && items}
- </Stack>
- ) : (
- items
- )}
- </Stack>
- );
-
- return mobile ? (
- <Drawer
- {...mobileDrawerProps}
- anchor="left"
- slotProps={{
- backdrop: { sx: { bgcolor: "rgba(0,0,0,0.4)" } },
- paper: {
- role: "dialog",
- "aria-modal": true,
- "aria-labelledby": titleID,
- inert: !mobileDrawerProps.open,
- sx: (theme) => ({
- width: "100%",
- borderRadius: 0,
- boxShadow: "none",
- bgcolor: "#F4F4F4",
- ...theme.applyStyles("dark", { bgcolor: "#161616" }),
- }),
- },
- }}
- >
- {navigation}
- </Drawer>
- ) : (
- navigation
- );
-};
-
-interface AlbumNavigationRow {
- key: string;
- height: number;
- content: React.ReactNode;
-}
-
-const AlbumNavigationItem = memo(
- ({ data, index, style }: ListChildComponentProps<AlbumNavigationRow[]>) => (
- <div style={style}>{data[index]!.content}</div>
- ),
- areEqual,
-);
-
-type ItemData =
- | {
- type: "collections";
- collectionSummaries: CollectionSummary[];
- indented: boolean;
- activeCollectionID: number;
- onSelectCollectionID: (id: number) => void;
- }
- | {
- type: "people";
- people: Person[];
- activePerson: Person | undefined;
- onSelectPerson: (personID: string) => void;
- };
-
-const getItemCount = (data: ItemData) => {
- switch (data.type) {
- case "collections": {
- return data.collectionSummaries.length;
- }
- case "people": {
- return data.people.length;
- }
- }
-};
-
-const getItemKey = (index: number, data: ItemData) => {
- switch (data.type) {
- case "collections": {
- const collectionSummary = data.collectionSummaries[index]!;
- return `${data.type}-${collectionSummary.id}-${collectionSummary.coverFile?.id}`;
- }
- case "people": {
- const person = data.people[index]!;
- return `${data.type}-${person.id}-${person.displayFaceID}`;
- }
- }
-};
-
-const ListItem = memo((props: ListChildComponentProps<ItemData>) => {
- const { data, index, style } = props;
-
- let card: React.ReactNode;
-
- switch (data.type) {
- case "collections": {
- const {
- collectionSummaries,
- activeCollectionID,
- onSelectCollectionID,
- } = data;
- const collectionSummary = collectionSummaries[index]!;
- card = (
- <CollectionBarCard
- key={collectionSummary.id}
- {...{
- collectionSummary,
- activeCollectionID,
- onSelectCollectionID,
- }}
- indented={
- data.indented &&
- !collectionSummary.attributes.has("system")
- }
- />
- );
- break;
- }
-
- case "people": {
- const { people, activePerson, onSelectPerson } = data;
- const person = people[index]!;
- card = (
- <PersonCard
- key={person.id}
- {...{ person, activePerson, onSelectPerson }}
- />
- );
- break;
- }
- }
-
- return <div style={style}>{card}</div>;
-}, areEqual);
-
-interface CollectionBarCardProps {
- collectionSummary: CollectionSummary;
- indented: boolean;
- activeCollectionID: number;
- onSelectCollectionID: (collectionID: number) => void;
-}
-
-const CollectionBarCard: React.FC<CollectionBarCardProps> = ({
- collectionSummary,
- indented,
- activeCollectionID,
- onSelectCollectionID,
-}: CollectionBarCardProps) => (
- <BarCard
- aria-label={collectionSummary.name}
- aria-current={
- activeCollectionID === collectionSummary.id ? "true" : undefined
- }
- title={collectionSummary.name}
- onClick={() => onSelectCollectionID(collectionSummary.id)}
- sx={
- indented
- ? { marginInlineStart: "20px", width: "calc(100% - 20px)" }
- : undefined
- }
- >
- <Box aria-hidden sx={{ flexShrink: 0 }}>
- <ItemCard
- TileComponent={BarThumbnail}
- coverFile={collectionSummary.coverFile}
- />
- </Box>
- <CardText>{collectionSummary.name}</CardText>
- <CollectionBarCardIcon attributes={collectionSummary.attributes} />
- </BarCard>
-);
-
-const CardText: React.FC<React.PropsWithChildren> = ({ children }) => (
- <Typography
- noWrap
- sx={(theme) => ({
- flex: 1,
- minWidth: 0,
- fontFamily: '"Inter Variable", Inter, sans-serif',
- fontSize: 14,
- fontWeight: 500,
- lineHeight: "20px",
- [theme.breakpoints.down("md")]: { fontSize: 13 },
- })}
- >
- {children}
- </Typography>
-);
-
-interface CollectionBarCardIconProps {
- attributes: Set<CollectionSummaryAttribute>;
-}
-
-const CollectionBarCardIcon: React.FC<CollectionBarCardIconProps> = ({
- attributes,
-}) => (
- // A collection can show all four status icons at once.
- <CollectionBarCardIcon_ aria-hidden>
- {attributes.has("userFavorites") && (
- <HugeiconsIcon
- icon={StarIcon}
- size={16}
- fill="currentColor"
- aria-hidden
- />
- )}
- {(attributes.has("pinned") || attributes.has("shareePinned")) && (
- <HugeiconsIcon icon={PinIcon} size={14} />
- )}
- {attributes.has("shared") && !attributes.has("sharedOnlyViaLink") && (
- <PeopleIcon />
- )}
- {attributes.has("sharedViaLink") && (
- <HugeiconsIcon icon={Link05Icon} size={16} />
- )}
- {attributes.has("archived") && <ArchiveIcon sx={{ opacity: 0.48 }} />}
- </CollectionBarCardIcon_>
-);
-
-const CollectionBarCardIcon_ = styled("span")`
- display: flex;
- flex-shrink: 0;
- margin-inline-start: auto;
- align-items: center;
- gap: 4px;
- color: #969696;
- & > .MuiSvgIcon-root {
- font-size: 16px;
- }
-`;
-
-const BarCard = styled(ButtonBase)(({ theme }) => ({
- display: "flex",
- justifyContent: "flex-start",
- gap: "12px",
- width: "100%",
- height: 48,
- paddingInline: "16px 12px",
- borderRadius: "12px",
- color: theme.vars.palette.text.base,
- textAlign: "left",
- '&[aria-current="true"], &[aria-current="page"]': {
- backgroundColor: "var(--gallery-navigation-surface)",
- },
- "&:hover": { backgroundColor: "var(--gallery-navigation-hover)" },
- "&.Mui-focusVisible": {
- outline: "2px solid",
- outlineColor: theme.vars.palette.stroke.base,
- outlineOffset: -2,
- },
- [theme.breakpoints.down("md")]: { height: 44 },
-}));
-
-const BarThumbnail = styled("div")({
- width: 24,
- height: 24,
- position: "relative",
- overflow: "hidden",
- borderRadius: "6px",
- "& > img": {
- width: "100%",
- height: "100%",
- objectFit: "cover",
- display: "block",
- },
- "& .MuiSvgIcon-root": { fontSize: 18 },
-});
-
-interface PersonCardProps {
- person: Person;
- activePerson: Person | undefined;
- onSelectPerson: (personID: string) => void;
-}
-
-const PersonCard: React.FC<PersonCardProps> = ({
- person,
- activePerson,
- onSelectPerson,
-}) => (
- <BarCard
- aria-label={person.name || t("unnamed_person")}
- aria-current={activePerson?.id === person.id ? "true" : undefined}
- title={person.name || t("unnamed_person")}
- onClick={() => onSelectPerson(person.id)}
- >
- <Box
- aria-hidden
- sx={{ flexShrink: 0, borderRadius: "50%", overflow: "hidden" }}
- >
- <ItemCard
- TileComponent={BarThumbnail}
- coverFile={person.displayFaceFile}
- coverFaceID={person.displayFaceID}
- />
- </Box>
- <CardText>{person.name || t("unnamed_person")}</CardText>
- {person.isPinned && (
- <CollectionBarCardIcon_ aria-hidden>
- <HugeiconsIcon icon={PinIcon} size={14} />
- </CollectionBarCardIcon_>
- )}
- </BarCard>
-);
diff --git a/web/apps/photos/src/components/gallery/hooks/use-collections-sort-by.ts b/web/apps/photos/src/components/gallery/hooks/use-collections-sort-by.ts
new file mode 100644
index 0000000000..a474924a89
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/hooks/use-collections-sort-by.ts
@@ -0,0 +1,27 @@
+import {
+ collectionsSortBy as supportedCollectionsSortBy,
+ type CollectionsSortBy,
+} from "ente-new/photos/services/collection-summary";
+import { includes } from "ente-utils/type-guards";
+import { useCallback, useEffect, useState } from "react";
+
+export const useCollectionsSortBy = () => {
+ const [collectionsSortBy, setCollectionsSortBy] =
+ useState<CollectionsSortBy>("updation-time-desc");
+
+ useEffect(() => {
+ const value = localStorage.getItem("collectionsSortBy");
+ if (value && includes(supportedCollectionsSortBy, value))
+ setCollectionsSortBy(value);
+ }, []);
+
+ const onChangeCollectionsSortBy = useCallback(
+ (value: CollectionsSortBy) => {
+ localStorage.setItem("collectionsSortBy", value);
+ setCollectionsSortBy(value);
+ },
+ [],
+ );
+
+ return { collectionsSortBy, onChangeCollectionsSortBy };
+};
diff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts b/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts
new file mode 100644
index 0000000000..d5ea03048b
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/hooks/use-gallery-library.ts
@@ -0,0 +1,277 @@
+import type { RemotePullOpts } from "@/components/gallery";
+import { useSubscriptionCompletionRedirect } from "@/components/gallery/hooks/use-subscription-completion-redirect";
+import { useGalleryReducer } from "@/components/gallery/reducer";
+import exportService from "@/services/export";
+import { processPendingAlbumJoin } from "@/services/join-album";
+import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
+import {
+ getAndClearIsFirstLogin,
+ savedJustSignedUp,
+} from "ente-accounts/services/accounts-db";
+import { stashRedirect } from "ente-accounts/services/redirect";
+import { isSessionInvalid } from "ente-accounts/services/session";
+import { ensureLocalUser } from "ente-accounts/services/user";
+import { useBaseContext } from "ente-base/context";
+import { subscribeMainWindowFocus } from "ente-base/electron";
+import { isNamedError } from "ente-base/error";
+import { hasPendingAlbumToJoin } from "ente-base/join-album";
+import log from "ente-base/log";
+import {
+ clearSessionStorage,
+ haveMasterKeyInSession,
+} from "ente-base/session-storage";
+import { savedAuthToken } from "ente-base/token";
+import { initContacts, pullContacts } from "ente-contacts";
+import {
+ usePeopleStateSnapshot,
+ useUserDetailsSnapshot,
+} from "ente-new/photos/components/utils/use-snapshot";
+import { masterKeyFromSession } from "ente-new/photos/services/account-keys";
+import { contactsGetDiff, contactsGetProfilePicture } from "ente-photos-wasm";
+
+import { ensureAuthenticatedSession } from "@/services/authenticated-session";
+import { postPullFiles, prePullFiles, pullFiles } from "@/services/pull";
+import watcher from "@/services/watch";
+import {
+ savedCollectionFiles,
+ savedCollections,
+ savedTrashItems,
+} from "ente-new/photos/services/photos-fdb";
+import { updateSearchCollectionsAndFiles } from "ente-new/photos/services/search";
+import { initSettings } from "ente-new/photos/services/settings";
+import { savedUserDetailsOrTriggerPull } from "ente-new/photos/services/user-details";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { PromiseQueue } from "ente-utils/promise";
+import { t } from "i18next";
+import { useRouter } from "next/router";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export const useGalleryLibrary = () => {
+ const [joinedCollectionID, setJoinedCollectionID] = useState<number>();
+ const { logout, showMiniDialog, onGenericError } = useBaseContext();
+ const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();
+ const router = useRouter();
+ const [state, dispatch] = useGalleryReducer();
+
+ const [searchIndexRevision, setSearchIndexRevision] = useState(0);
+ const [isFirstLoad, setIsFirstLoad] = useState(false);
+ // Pull pipelines mutate the same local DB and reducer state.
+ const remoteFilesPullQueue = useRef(new PromiseQueue<void>());
+ const remotePullQueue = useRef(new PromiseQueue<void>());
+
+ const userDetails = useUserDetailsSnapshot();
+ const peopleState = usePeopleStateSnapshot();
+ const showSessionExpiredDialog = useCallback(
+ () => showMiniDialog(sessionExpiredDialogAttributes(logout)),
+ [showMiniDialog, logout],
+ );
+
+ // Use this for collection/file/trash-only effects; a full pull costs more.
+ const remoteFilesPull = useCallback(
+ () =>
+ remoteFilesPullQueue.current.add(() =>
+ pullFiles({
+ onSetCollections: (collections) =>
+ dispatch({ type: "setCollections", collections }),
+ onSetCollectionFiles: (collectionFiles) =>
+ dispatch({
+ type: "setCollectionFiles",
+ collectionFiles,
+ }),
+ onSetTrashedItems: (trashItems) =>
+ dispatch({ type: "setTrashItems", trashItems }),
+ onDidUpdateCollectionFiles: () =>
+ exportService.onLocalFilesUpdated(),
+ }),
+ ),
+ [],
+ );
+
+ const remotePull = useCallback(
+ async (opts?: RemotePullOpts) =>
+ remotePullQueue.current.add(async () => {
+ const { silent, source, strict } = opts ?? {};
+
+ if (!navigator.onLine) {
+ if (strict) throw new Error("Remote pull failed: offline");
+ return;
+ }
+ if (await isSessionInvalid()) {
+ showSessionExpiredDialog();
+ if (strict)
+ throw new Error("Remote pull failed: invalid session");
+ return;
+ }
+ if (!(await masterKeyFromSession())) {
+ clearSessionStorage();
+ void router.push("/credentials");
+ if (strict)
+ throw new Error(
+ "Remote pull failed: missing master key",
+ );
+ return;
+ }
+
+ try {
+ if (!silent) showLoadingBar();
+ await prePullFiles();
+ await remoteFilesPull();
+ await postPullFiles(source);
+ } catch (e) {
+ // A later pull retries transient failures after remote mutations.
+ log.error("Remote pull failed", e);
+ if (strict) throw e;
+ } finally {
+ dispatch({ type: "clearUnsyncedState" });
+ if (!silent) hideLoadingBar();
+ }
+ }),
+ [
+ showLoadingBar,
+ hideLoadingBar,
+ router,
+ showSessionExpiredDialog,
+ remoteFilesPull,
+ ],
+ );
+
+ useEffect(() => {
+ const electron = globalThis.electron;
+ let syncIntervalID: ReturnType<typeof setInterval> | undefined;
+ let unsubscribeMainWindowFocus: (() => void) | undefined;
+
+ void (async () => {
+ const authToken = await savedAuthToken();
+ if (!haveMasterKeyInSession() || !authToken) {
+ stashRedirect("/gallery");
+ void router.push("/");
+ return;
+ }
+
+ if (savedJustSignedUp()) {
+ void router.replace("/plan");
+ return;
+ }
+
+ try {
+ await ensureAuthenticatedSession();
+ } catch (e) {
+ if (isNamedError(e, "missing_recovery_key")) {
+ showMiniDialog(sessionExpiredDialogAttributes(logout));
+ } else {
+ onGenericError(e);
+ }
+ return;
+ }
+
+ initSettings();
+
+ setIsFirstLoad(getAndClearIsFirstLogin());
+
+ const user = ensureLocalUser();
+ void initContacts(
+ user.id,
+ ensureAuthenticatedSession,
+ contactsGetDiff,
+ contactsGetProfilePicture,
+ )
+ .then(pullContacts)
+ .catch((error: unknown) => {
+ log.warn(
+ "[gallery] Failed to warm contacts display cache",
+ error,
+ );
+ });
+ const userDetails = await savedUserDetailsOrTriggerPull();
+ dispatch({
+ type: "mount",
+ user,
+ familyData: userDetails?.familyData,
+ collections: await savedCollections(),
+ collectionFiles: await savedCollectionFiles(),
+ trashItems: await savedTrashItems(),
+ });
+
+ // Join first so the initial pull includes the new album.
+ let joinedAlbumId: number | null = null;
+
+ if (hasPendingAlbumToJoin()) {
+ try {
+ const joinedCollectionId = await processPendingAlbumJoin();
+ if (joinedCollectionId) {
+ joinedAlbumId = joinedCollectionId;
+ }
+ } catch (error) {
+ log.error("Failed to join album", error);
+ showMiniDialog({
+ title: t("error"),
+ message: t("album_join_failed"),
+ });
+ }
+ }
+
+ await remotePull({ source: "gallery-mount" });
+
+ if (joinedAlbumId) {
+ setJoinedCollectionID(joinedAlbumId);
+ }
+
+ setIsFirstLoad(false);
+
+ syncIntervalID = setInterval(
+ () => remotePull({ silent: true, source: "gallery-periodic" }),
+ 5 * 60 * 1000,
+ );
+
+ if (electron) {
+ unsubscribeMainWindowFocus = subscribeMainWindowFocus(() => {
+ void remotePull({ silent: true, source: "desktop-focus" });
+ void watcher.checkAccessibility();
+ });
+ }
+ })();
+
+ return () => {
+ clearInterval(syncIntervalID);
+ unsubscribeMainWindowFocus?.();
+ };
+ }, []);
+
+ useEffect(() => {
+ if (state.user && userDetails) {
+ dispatch({ type: "setUserDetails", userDetails });
+ }
+ }, [state.user, userDetails]);
+
+ useEffect(() => {
+ updateSearchCollectionsAndFiles(
+ state.collections,
+ state.collectionFiles,
+ state.hiddenCollectionIDs,
+ state.hiddenFileIDs,
+ );
+ setSearchIndexRevision((revision) => revision + 1);
+ }, [
+ state.collections,
+ state.collectionFiles,
+ state.hiddenCollectionIDs,
+ state.hiddenFileIDs,
+ ]);
+
+ useEffect(() => {
+ dispatch({ type: "setPeopleState", peopleState });
+ }, [peopleState]);
+
+ useSubscriptionCompletionRedirect();
+ return {
+ joinedCollectionID,
+ state,
+ dispatch,
+ isFirstLoad,
+ searchIndexRevision,
+ peopleState,
+ remotePull,
+ remoteFilesPull,
+ showSessionExpiredDialog,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-operations.ts b/web/apps/photos/src/components/gallery/hooks/use-gallery-operations.ts
new file mode 100644
index 0000000000..fc16662f2f
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/hooks/use-gallery-operations.ts
@@ -0,0 +1,147 @@
+import type { useGalleryLibrary } from "@/components/gallery/hooks/use-gallery-library";
+import { useGalleryUploads } from "@/components/gallery/hooks/use-gallery-uploads";
+import { useFileMutations } from "@/components/gallery/media/use-file-mutations";
+import type { GalleryBarMode } from "@/components/gallery/reducer";
+import type { GallerySectionOperations } from "@/components/gallery/sections/types";
+import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
+import { ItemVisibility } from "ente-media/file-metadata";
+import { haveOnlySystemCollections } from "ente-new/photos/services/collection-summary";
+import type { SidebarActionID } from "ente-new/photos/services/search/types";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { useCallback, useState } from "react";
+import { useCollectionDialogs } from "../media/use-collection-dialogs";
+import type { GalleryNavigationState } from "../navigation/navigation-state";
+export const useGalleryOperations = (
+ libraryOwner: ReturnType<typeof useGalleryLibrary>,
+ navigation: GalleryNavigationState,
+ authenticateOpen: boolean,
+ showSettings: (action?: SidebarActionID) => void,
+) => {
+ const {
+ state,
+ dispatch,
+ peopleState,
+ remotePull,
+ remoteFilesPull,
+ showSessionExpiredDialog,
+ } = libraryOwner;
+ const { user, normalCollectionSummaries } = state;
+ const barMode: GalleryBarMode =
+ navigation.destination.albumMode ?? "albums";
+ const activeCollection =
+ navigation.destination.section === "albums" ||
+ navigation.destination.section === "places"
+ ? state.collections.find(
+ (collection) =>
+ collection.id === navigation.destination.collectionID,
+ )
+ : undefined;
+ const isCleanupViewOpen =
+ navigation.overlay?.section === "duplicates" ||
+ navigation.overlay?.section === "large-files";
+ const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();
+ const [sectionActivity, setSectionActivity] = useState({
+ selection: false,
+ drop: false,
+ });
+ const [blockingLoad, setBlockingLoad] = useState(false);
+ const { saveGroups, onAddSaveGroup, onRemoveSaveGroup } = useSaveGroups();
+ const quickLinkVisibility =
+ barMode == "hidden-albums"
+ ? ItemVisibility.hidden
+ : ItemVisibility.visible;
+ const {
+ publicLinkToast,
+ setPublicLinkToast,
+ handleFavoriteFileOp,
+ onSendLinkError,
+ handleFileViewerToggleFavorite,
+ handleFileViewerFileVisibilityUpdate,
+ handleFileViewerSendLink,
+ handleMarkTempDeleted,
+ } = useFileMutations({ state, dispatch, remotePull, quickLinkVisibility });
+ const handleVisualFeedback = useCallback(() => {
+ showLoadingBar();
+ setTimeout(hideLoadingBar, 0);
+ }, [showLoadingBar, hideLoadingBar]);
+ const {
+ openCollectionSelector,
+ albumNameInputVisibilityProps,
+ showCreateAlbum,
+ handleOpenCollectionSelector,
+ handleCloseCollectionSelector,
+ handleAddSingleFileToCollection,
+ collectionSelectorProps,
+ albumNameInputProps,
+ } = useCollectionDialogs({ state, remotePull });
+ const { openUploader, uploadTypeSelectorView, uploadProps, dropzoneProps } =
+ useGalleryUploads({
+ user,
+ activeCollection,
+ isFirstUpload: haveOnlySystemCollections(normalCollectionSummaries),
+ isInHiddenSection: barMode == "hidden-albums",
+ onUploadFile: (file) => dispatch({ type: "uploadFile", file }),
+ onShowSubscription: () => showSettings("subscription"),
+ onRemotePull: remotePull,
+ onRemoteFilesPull: remoteFilesPull,
+ onOpenCollectionSelector: handleOpenCollectionSelector,
+ onCloseCollectionSelector: handleCloseCollectionSelector,
+ onShowSessionExpiredDialog: showSessionExpiredDialog,
+ setLoading: setBlockingLoad,
+ });
+ const sectionOperations: GallerySectionOperations = {
+ dispatch,
+ peopleState,
+ mutations: {
+ setPublicLinkToast,
+ handleFavoriteFileOp,
+ onSendLinkError,
+ handleMarkTempDeleted,
+ },
+ selectionDisabled:
+ uploadTypeSelectorView ||
+ openCollectionSelector ||
+ albumNameInputVisibilityProps.open ||
+ authenticateOpen ||
+ sectionActivity.selection,
+ onAddSaveGroup,
+ onToggleFavorite: handleFileViewerToggleFavorite,
+ onFileVisibilityUpdate: handleFileViewerFileVisibilityUpdate,
+ onSendLink: handleFileViewerSendLink,
+ onMarkTempDeleted: handleMarkTempDeleted,
+ onRemotePull: remotePull,
+ onRemoteFilesPull: remoteFilesPull,
+ onVisualFeedback: handleVisualFeedback,
+ onAddFileToCollection: handleAddSingleFileToCollection,
+ setBlockingLoad,
+ onUpload: openUploader,
+ onCreateAlbum: () => showCreateAlbum(),
+ saveGroups,
+ setSectionActivity,
+ };
+
+ return {
+ operations: sectionOperations,
+ dropzoneProps: {
+ ...dropzoneProps,
+ disabled:
+ dropzoneProps.disabled ||
+ sectionActivity.drop ||
+ isCleanupViewOpen,
+ },
+ blockingLoad,
+ collectionSelectorProps,
+ albumNameInputProps,
+ downloadNotificationsProps: { saveGroups, onRemoveSaveGroup },
+ uploadProps,
+ quickLinkNotificationProps: {
+ open: publicLinkToast.open,
+ onCopy: () => {
+ if (publicLinkToast.url)
+ void navigator.clipboard.writeText(publicLinkToast.url);
+ },
+ onClose: () =>
+ setPublicLinkToast((prev) => ({ ...prev, open: false })),
+ },
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-preferences.ts b/web/apps/photos/src/components/gallery/hooks/use-gallery-preferences.ts
new file mode 100644
index 0000000000..f88b9901c7
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/hooks/use-gallery-preferences.ts
@@ -0,0 +1,73 @@
+import { useCollectionsSortBy } from "@/components/gallery/hooks/use-collections-sort-by";
+import type { GalleryBarMode } from "@/components/gallery/reducer";
+import type { AlbumFilter } from "@/utils/album-filters";
+import type { PeopleSortBy } from "@/utils/people-sort";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+
+import { useEffect, useRef, useState } from "react";
+
+export const useGalleryPreferences = ({
+ barMode,
+ activeCollectionID,
+ navigationAvailable,
+}: {
+ barMode: GalleryBarMode;
+ activeCollectionID: number | undefined;
+ navigationAvailable: boolean;
+}) => {
+ const [albumFilter, setAlbumFilter] = useState<AlbumFilter>("ente");
+ const [albumSearchQuery, setAlbumSearchQuery] = useState("");
+ const [searchSortAsc, setSearchSortAsc] = useState<boolean>();
+ const [albumOpenedFromOverview, setAlbumOpenedFromOverview] = useState<{
+ collectionID: number;
+ filter: AlbumFilter;
+ searchQuery: string;
+ }>();
+ const [peopleSortBy, setPeopleSortBy] =
+ useState<PeopleSortBy>("count-desc");
+ const { collectionsSortBy, onChangeCollectionsSortBy } =
+ useCollectionsSortBy();
+ const [expandedAlbumFilter, setExpandedAlbumFilter] = useState<
+ AlbumFilter | undefined
+ >("ente");
+ const lastAlbumFilter = useRef(albumFilter);
+ useEffect(() => {
+ if (lastAlbumFilter.current != albumFilter || !navigationAvailable) {
+ lastAlbumFilter.current = albumFilter;
+ setExpandedAlbumFilter(albumFilter);
+ }
+ }, [albumFilter, navigationAvailable]);
+ useEffect(() => {
+ setAlbumSearchQuery("");
+ }, [barMode]);
+
+ useEffect(() => {
+ if (barMode == "albums" && activeCollectionID == PseudoCollectionID.all)
+ setAlbumSearchQuery("");
+ }, [barMode, activeCollectionID]);
+
+ return {
+ searchSortAsc,
+ setSearchSortAsc,
+ albumFilter,
+ setAlbumFilter,
+ albumSearchQuery,
+ setAlbumSearchQuery,
+ albumOpenedFromOverview,
+ setAlbumOpenedFromOverview,
+ peopleSortBy,
+ setPeopleSortBy,
+ collectionsSortBy,
+ onChangeCollectionsSortBy,
+ albumExpansion: {
+ value: expandedAlbumFilter,
+ onChange: (
+ value: AlbumFilter | undefined,
+ selectedFilter?: AlbumFilter,
+ ) => {
+ if (selectedFilter) lastAlbumFilter.current = selectedFilter;
+ setExpandedAlbumFilter(value);
+ },
+ },
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-uploads.ts b/web/apps/photos/src/components/gallery/hooks/use-gallery-uploads.ts
new file mode 100644
index 0000000000..b8a7cc4354
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/hooks/use-gallery-uploads.ts
@@ -0,0 +1,80 @@
+import type { Upload } from "@/components/Upload";
+import { uploadManager } from "@/services/upload-manager";
+import type { UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import type { ComponentProps } from "react";
+import { useState } from "react";
+import type { FileWithPath } from "react-dropzone";
+type UploadInputs = Pick<
+ ComponentProps<typeof Upload>,
+ | "activeCollection"
+ | "isFirstUpload"
+ | "isInHiddenSection"
+ | "onUploadFile"
+ | "onShowSubscription"
+ | "onRemotePull"
+ | "onRemoteFilesPull"
+ | "onOpenCollectionSelector"
+ | "onCloseCollectionSelector"
+ | "onShowSessionExpiredDialog"
+ | "setLoading"
+> & { user: ComponentProps<typeof Upload>["user"] | undefined };
+export const useGalleryUploads = ({
+ user,
+ activeCollection,
+ isFirstUpload,
+ isInHiddenSection,
+ onUploadFile,
+ onShowSubscription,
+ onRemotePull: remotePull,
+ onRemoteFilesPull: remoteFilesPull,
+ onOpenCollectionSelector: handleOpenCollectionSelector,
+ onCloseCollectionSelector: handleCloseCollectionSelector,
+ onShowSessionExpiredDialog: showSessionExpiredDialog,
+ setLoading: setBlockingLoad,
+}: UploadInputs) => {
+ const { watchFolderView } = usePhotosAppContext();
+ const [shouldDisableDropzone, setShouldDisableDropzone] = useState(false);
+ const [dragAndDropFiles, setDragAndDropFiles] = useState<FileWithPath[]>(
+ [],
+ );
+ const [uploadTypeSelectorView, setUploadTypeSelectorView] = useState(false);
+ const [uploadTypeSelectorIntent, setUploadTypeSelectorIntent] =
+ useState<UploadTypeSelectorIntent>("upload");
+ const openUploader = (intent?: UploadTypeSelectorIntent) => {
+ if (uploadManager.isUploadInProgress()) return;
+ setUploadTypeSelectorView(true);
+ setUploadTypeSelectorIntent(intent ?? "upload");
+ };
+ const uploadProps: ComponentProps<typeof Upload> | undefined = user
+ ? {
+ user,
+ dragAndDropFiles,
+ uploadTypeSelectorIntent,
+ uploadTypeSelectorView,
+ isFirstUpload,
+ activeCollection,
+ closeUploadTypeSelector: setUploadTypeSelectorView.bind(
+ null,
+ false,
+ ),
+ setLoading: setBlockingLoad,
+ setShouldDisableDropzone,
+ onRemotePull: remotePull,
+ onRemoteFilesPull: remoteFilesPull,
+ onOpenCollectionSelector: handleOpenCollectionSelector,
+ onCloseCollectionSelector: handleCloseCollectionSelector,
+ onUploadFile,
+ onShowSubscription,
+ onShowSessionExpiredDialog: showSessionExpiredDialog,
+ isInHiddenSection,
+ }
+ : undefined;
+ const dropzoneProps = {
+ message: watchFolderView ? t("watch_folder_dropzone_hint") : undefined,
+ disabled: shouldDisableDropzone,
+ onDrop: setDragAndDropFiles,
+ };
+ return { openUploader, uploadTypeSelectorView, uploadProps, dropzoneProps };
+};
diff --git a/web/apps/photos/src/components/gallery/index.tsx b/web/apps/photos/src/components/gallery/index.tsx
index 56c5a46e21..1c3767892e 100644
--- a/web/apps/photos/src/components/gallery/index.tsx
+++ b/web/apps/photos/src/components/gallery/index.tsx
@@ -35,7 +35,7 @@ import type { SearchSuggestion } from "ente-new/photos/services/search/types";
import { t } from "i18next";
import React, { useRef, useState } from "react";
-export { GalleryEmptyState } from "./GalleryEmptyState";
+export { GalleryEmptyState } from "./sections/albums/GalleryEmptyState";
export interface RemotePullOpts {
silent?: boolean;
@@ -45,7 +45,7 @@ export interface RemotePullOpts {
export type SelectionContext =
| {
mode: "albums" | "hidden-albums" | "archive-albums";
- collectionID: number;
+ collectionID: number | undefined;
}
| { mode: "people"; personID: string };
diff --git a/web/apps/photos/src/components/gallery/media/GalleryDownloadNotifications.tsx b/web/apps/photos/src/components/gallery/media/GalleryDownloadNotifications.tsx
new file mode 100644
index 0000000000..8c281eea47
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/GalleryDownloadNotifications.tsx
@@ -0,0 +1,20 @@
+import { DownloadStatusNotifications } from "ente-gallery/components/DownloadStatusNotifications";
+import type { ComponentProps } from "react";
+import { usePhotosNavigation } from "../navigation/PhotosNavigationContext";
+
+export const GalleryDownloadNotifications = (
+ props: Omit<
+ ComponentProps<typeof DownloadStatusNotifications>,
+ "onShowCollectionSummary"
+ >,
+) => {
+ const { showCollectionSummary } = usePhotosNavigation();
+ return (
+ <DownloadStatusNotifications
+ {...props}
+ onShowCollectionSummary={(id, isHidden) => {
+ void showCollectionSummary(id, isHidden);
+ }}
+ />
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx b/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx
new file mode 100644
index 0000000000..70716a014d
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/GalleryMedia.tsx
@@ -0,0 +1,280 @@
+import { CollectionSelector } from "@/components/CollectionSelector";
+import type { FileListHeaderOrFooter } from "@/components/FileList";
+import { FileListWithViewer } from "@/components/FileListWithViewer";
+import { FixCreationTime } from "@/components/FixCreationTime";
+import { SelectedFileOptions } from "@/components/SelectedFileOptions";
+import { externalLink } from "@/utils/link";
+import { Box, Typography } from "@mui/material";
+import { SingleInputDialog } from "ente-base/components/SingleInputDialog";
+import { ItemVisibility } from "ente-media/file-metadata";
+import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
+import { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";
+import { t } from "i18next";
+import type { GalleryMediaSource } from "../sections/types";
+import { useCollectionOperations } from "./use-collection-operations";
+import { useFileContextActions } from "./use-file-context-actions";
+import { useGallerySelection } from "./use-gallery-selection";
+import { useSelectedFileOperations } from "./use-selected-file-operations";
+import { useSelectionShortcuts } from "./use-selection-shortcuts";
+
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { Trans } from "react-i18next";
+
+import type { GallerySectionProps } from "../sections/types";
+type GalleryMediaProps = Pick<
+ GallerySectionProps,
+ "library" | "operations" | "navigation"
+> & {
+ source: GalleryMediaSource;
+ header?: FileListHeaderOrFooter;
+ children?: (hasSelection: boolean) => ReactNode;
+};
+
+export const GalleryMedia = (props: GalleryMediaProps) => {
+ const { source, navigation } = props;
+ const scope = JSON.stringify([
+ source.mode,
+ source.modePlus,
+ source.activeCollectionID,
+ source.activePersonID,
+ navigation.overlay?.suggestion?.type,
+ navigation.overlay?.suggestion?.label,
+ navigation.overlay?.searchRevision,
+ ]);
+ return <GalleryMediaContent key={scope} {...props} />;
+};
+
+const GalleryMediaContent = ({
+ library,
+ operations,
+ navigation,
+ source,
+ header,
+ children,
+}: GalleryMediaProps) => {
+ const { selected, setSelected, clearSelection } = useGallerySelection(
+ source.files,
+ library.user?.id,
+ );
+ const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);
+ const [isFileViewerOpen, setIsFileViewerOpen] = useState(false);
+ const viewerOpen = useRef(false);
+ const onSetOpenFileViewer = useCallback((open: boolean) => {
+ viewerOpen.current = open;
+ setIsFileViewerOpen(open);
+ }, []);
+ useEffect(
+ () => () => {
+ if (viewerOpen.current && document.fullscreenElement)
+ void document.exitFullscreen();
+ },
+ [],
+ );
+ const collectionActions = useCollectionOperations({
+ state: library,
+ selected,
+ filteredFiles: source.files,
+ barMode: source.mode ?? "albums",
+ clearSelection,
+ remotePull: operations.onRemotePull,
+ });
+ const fileActions = useSelectedFileOperations({
+ state: library,
+ dispatch: operations.dispatch,
+ peopleState: operations.peopleState,
+ selected,
+ filteredFiles: source.files,
+ quickLinkVisibility:
+ source.mode === "hidden-albums"
+ ? ItemVisibility.hidden
+ : ItemVisibility.visible,
+ clearSelection,
+ onAddSaveGroup: operations.onAddSaveGroup,
+ remotePull: operations.onRemotePull,
+ mutations: operations.mutations,
+ });
+ const isSearch = source.modePlus === "search";
+ const onContextMenuAction = useFileContextActions({
+ collectionOperations: collectionActions,
+ selectedOperations: fileActions,
+ activeCollection: isSearch ? undefined : source.activeCollection,
+ activeCollectionSummary: isSearch
+ ? undefined
+ : source.activeCollectionSummary,
+ barMode: source.mode ?? "albums",
+ });
+ const selectAll = useSelectionShortcuts({
+ source,
+ userID: library.user?.id,
+ setSelected,
+ clearSelection,
+ disabled: operations.selectionDisabled || isFileViewerOpen,
+ });
+ const showSelectionBar =
+ selected.count > 0 &&
+ !fileActions.suppressContextSelectionBar &&
+ !(isContextMenuOpen && selected.count === 1);
+ const fileCollectionIDs = useMemo(
+ () =>
+ library.collectionFiles.reduce((result, file) => {
+ const collectionIDs = result.get(file.id);
+ if (collectionIDs) {
+ if (!collectionIDs.includes(file.collectionID)) {
+ collectionIDs.push(file.collectionID);
+ }
+ } else {
+ result.set(file.id, [file.collectionID]);
+ }
+ return result;
+ }, new Map<number, number[]>()),
+ [library.collectionFiles],
+ );
+
+ const showAppDownloadFooter =
+ library.collectionFiles.length < 30 &&
+ navigation.overlay?.section !== "search";
+ const footer = useMemo(
+ () => (showAppDownloadFooter ? createAppDownloadFooter() : undefined),
+ [showAppDownloadFooter],
+ );
+ return (
+ <>
+ {showSelectionBar && (
+ <Box
+ role="toolbar"
+ aria-label={t("selected_count", {
+ selected: selected.count,
+ })}
+ sx={{
+ flexShrink: 0,
+ display: "flex",
+ mx: { xs: 1, md: 2 },
+ pb: 1.5,
+ mb: 1.5,
+ borderBottom: 1,
+ borderColor: "divider",
+ }}
+ >
+ <SelectedFileOptions
+ barMode={source.mode}
+ isInSearchMode={isSearch}
+ collection={
+ isSearch ? undefined : source.activeCollection
+ }
+ collectionSummary={
+ isSearch
+ ? undefined
+ : source.activeCollectionSummary
+ }
+ selectedFileCount={selected.count}
+ selectedOwnFileCount={selected.ownCount}
+ selectedFavoriteCount={
+ fileActions.selectedFavoriteCount
+ }
+ onClearSelection={clearSelection}
+ onDelete={() => fileActions.handleDeleteFiles()}
+ onRemoveFilesFromCollection={
+ collectionActions.handleRemoveFilesFromCollection
+ }
+ onOpenCollectionSelector={
+ collectionActions.handleOpenCollectionSelector
+ }
+ createOnCreateForCollectionOp={
+ collectionActions.createOnCreateForCollectionOp
+ }
+ createOnSelectForCollectionOp={
+ collectionActions.createOnSelectForCollectionOp
+ }
+ createFileOpHandler={fileActions.createFileOpHandler}
+ onShowAssignPersonDialog={
+ fileActions.showAddPersonAction
+ ? fileActions.showContextMenuAssignPerson
+ : undefined
+ }
+ onEditLocation={fileActions.showEditLocation}
+ onSelectAll={selectAll}
+ isAllSelected={
+ source.files.length > 0 &&
+ selected.count === source.files.length
+ }
+ />
+ </Box>
+ )}
+ {children?.(selected.count > 0)}
+ <FileListWithViewer
+ {...operations}
+ {...source}
+ selected={selected}
+ setSelected={setSelected}
+ onContextMenuAction={onContextMenuAction}
+ onContextMenuOpenChange={setIsContextMenuOpen}
+ suppressSelectionUI={fileActions.suppressContextSelectionBar}
+ showAddPersonAction={fileActions.showAddPersonAction}
+ onSetOpenFileViewer={onSetOpenFileViewer}
+ onAddFileToCollection={
+ collectionActions.handleAddSingleFileToCollection
+ }
+ user={library.user}
+ header={header}
+ footer={footer}
+ enableDownload
+ enableSelect
+ isInIncomingSharedCollection={source.activeCollectionSummary?.attributes.has(
+ "sharedIncoming",
+ )}
+ isInHiddenSection={source.mode == "hidden-albums"}
+ showEditLocationAction={selected.ownCount > 0}
+ favoriteFileIDs={library.favoriteFileIDs}
+ collectionNameByID={library.collectionNameByID}
+ fileNormalCollectionIDs={library.fileNormalCollectionIDs}
+ fileCollectionIDs={fileCollectionIDs}
+ hiddenCollectionIDs={library.hiddenCollectionIDs}
+ pendingFavoriteUpdates={library.pendingFavoriteUpdates}
+ pendingVisibilityUpdates={library.pendingVisibilityUpdates}
+ collectionSummaries={library.normalCollectionSummaries}
+ emailByUserID={library.emailByUserID}
+ />
+ <CollectionSelector
+ {...collectionActions.collectionSelectorProps}
+ />
+ <SingleInputDialog {...collectionActions.albumNameInputProps} />
+ <FixCreationTime {...fileActions.fixCreationTimeProps} />
+ <AssignPersonDialog {...fileActions.assignPersonDialogProps} />
+ <EditLocationDialog {...fileActions.editLocationDialogProps} />
+ </>
+ );
+};
+const createAppDownloadFooter = (): FileListHeaderOrFooter => ({
+ component: (
+ <Typography
+ variant="small"
+ sx={{
+ alignSelf: "flex-end",
+ marginInline: "auto",
+ marginBlock: 0.75,
+ textAlign: "center",
+ color: "text.faint",
+ }}
+ >
+ <Trans
+ i18nKey="install_mobile_app"
+ components={{
+ a: externalLink(
+ "https://play.google.com/store/apps/details?id=io.ente.photos",
+ ),
+ b: externalLink(
+ "https://apps.apple.com/in/app/ente-photos/id1542026904",
+ ),
+ }}
+ />
+ </Typography>
+ ),
+ height: 90,
+});
diff --git a/web/apps/photos/src/components/gallery/media/file-selection.ts b/web/apps/photos/src/components/gallery/media/file-selection.ts
new file mode 100644
index 0000000000..2df7e26fa6
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/file-selection.ts
@@ -0,0 +1,31 @@
+import type { SelectedState } from "@/utils/file";
+import type { EnteFile } from "ente-media/file";
+
+export const emptySelection: SelectedState = {
+ ownCount: 0,
+ count: 0,
+ collectionID: undefined,
+ context: undefined,
+};
+
+export const retainVisibleSelection = (
+ selected: SelectedState,
+ files: EnteFile[],
+ userID: number | undefined,
+): SelectedState => {
+ if (!selected.count) return selected;
+ const next: SelectedState = {
+ ...emptySelection,
+ collectionID: selected.collectionID,
+ context: selected.context,
+ };
+ for (const file of files) {
+ if (!selected[file.id] || next[file.id]) continue;
+ next[file.id] = true;
+ next.count++;
+ if (file.ownerID === userID) next.ownCount++;
+ }
+ return next.count === selected.count && next.ownCount === selected.ownCount
+ ? selected
+ : next;
+};
diff --git a/web/apps/photos/src/components/gallery/media/media-files.ts b/web/apps/photos/src/components/gallery/media/media-files.ts
new file mode 100644
index 0000000000..6cfc356b4c
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/media-files.ts
@@ -0,0 +1,29 @@
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import { metadataHash } from "ente-media/file-metadata";
+export const suppressSharedFilesSavedByUser = (
+ files: EnteFile[],
+ currentUserID: number | undefined,
+ activeCollection: Collection | undefined,
+) => {
+ if (!currentUserID || activeCollection) return files;
+
+ const ownedFileKeys = new Set<string>();
+ for (const file of files) {
+ if (file.ownerID != currentUserID) continue;
+ const hash = metadataHash(file.metadata);
+ if (!hash) continue;
+ ownedFileKeys.add(`${hash}:${file.metadata.fileType}`);
+ }
+
+ if (!ownedFileKeys.size) return files;
+
+ return files.filter((file) => {
+ if (file.ownerID == currentUserID) return true;
+
+ const hash = metadataHash(file.metadata);
+ if (!hash) return true;
+
+ return !ownedFileKeys.has(`${hash}:${file.metadata.fileType}`);
+ });
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-collection-dialogs.ts b/web/apps/photos/src/components/gallery/media/use-collection-dialogs.ts
new file mode 100644
index 0000000000..66a88ea1fc
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-collection-dialogs.ts
@@ -0,0 +1,174 @@
+import type {
+ CollectionSelector,
+ CollectionSelectorAttributes,
+} from "@/components/CollectionSelector";
+import {
+ findCollectionCreatingIfNeeded,
+ performCollectionOp,
+} from "@/components/gallery/helpers";
+import type { SingleInputDialog } from "ente-base/components/SingleInputDialog";
+import { useModalVisibility } from "ente-base/components/utils/modal";
+import { useBaseContext } from "ente-base/context";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import {
+ createAlbum,
+ createHiddenAlbum,
+ renameCollection,
+} from "ente-new/photos/services/collection";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import { useCallback, useState, type ComponentProps } from "react";
+import type { RemotePullOpts } from "..";
+import type { GalleryState } from "../reducer";
+
+export const useCollectionDialogs = ({
+ state,
+ remotePull,
+}: {
+ state: GalleryState;
+ remotePull: (opts?: RemotePullOpts) => Promise<void>;
+}) => {
+ const { onGenericError } = useBaseContext();
+ const { showLoadingBar, hideLoadingBar, showNotification } =
+ usePhotosAppContext();
+ const [openCollectionSelector, setOpenCollectionSelector] = useState(false);
+ const [attributes, setAttributes] =
+ useState<CollectionSelectorAttributes>();
+ const [creation, setCreation] = useState<{
+ getOrCreate: (name: string) => Promise<Collection>;
+ onCreate?: (collection: Collection) => void | Promise<void>;
+ }>();
+ const { show, props: albumNameInputVisibilityProps } = useModalVisibility();
+ const showCreateAlbum = useCallback(
+ (
+ hidden = false,
+ onCreate?: (collection: Collection) => void | Promise<void>,
+ ) => {
+ let collection: Collection | undefined;
+ setCreation({
+ getOrCreate: async (name) => {
+ if (!collection) {
+ collection = hidden
+ ? await createHiddenAlbum(name)
+ : await createAlbum(name);
+ } else if (collection.name !== name) {
+ await renameCollection(collection, name);
+ collection = { ...collection, name };
+ }
+ return collection;
+ },
+ onCreate,
+ });
+ show();
+ },
+ [show],
+ );
+ const handleOpenCollectionSelector = useCallback(
+ (next: CollectionSelectorAttributes) => {
+ setAttributes(next);
+ setOpenCollectionSelector(true);
+ },
+ [],
+ );
+ const handleCloseCollectionSelector = useCallback(
+ () => setOpenCollectionSelector(false),
+ [],
+ );
+ const handleAlbumNameSubmit = async (name: string) => {
+ const request = creation;
+ if (!request) return;
+ const collection = await request.getOrCreate(name);
+ if (request.onCreate) await request.onCreate(collection);
+ else {
+ await remotePull();
+ showNotification({ color: "primary", title: t("album_created") });
+ }
+ setCreation((previous) =>
+ previous === request ? undefined : previous,
+ );
+ };
+ const handleAddSingleFileToCollection = useCallback(
+ (file: EnteFile, sourceCollectionSummaryID?: number) => {
+ let addedCollectionID: number | undefined;
+ const add = async (collection: Collection) => {
+ showLoadingBar();
+ try {
+ if (addedCollectionID !== collection.id) {
+ await performCollectionOp(
+ "add",
+ collection,
+ [file],
+ sourceCollectionSummaryID,
+ );
+ addedCollectionID = collection.id;
+ }
+ await remotePull({
+ silent: true,
+ source: "single-file-add-to-album",
+ });
+ showNotification({
+ color: "primary",
+ title: t("added_to_album"),
+ caption: collection.name,
+ });
+ } finally {
+ hideLoadingBar();
+ }
+ };
+ handleOpenCollectionSelector({
+ action: "add",
+ sourceCollectionSummaryID,
+ onSelectCollection: (collection) =>
+ void add(collection).catch(onGenericError),
+ onCreateCollection: () =>
+ showCreateAlbum(false, async (collection) => {
+ await add(collection);
+ handleCloseCollectionSelector();
+ }),
+ });
+ },
+ [
+ handleOpenCollectionSelector,
+ handleCloseCollectionSelector,
+ showCreateAlbum,
+ showLoadingBar,
+ hideLoadingBar,
+ remotePull,
+ showNotification,
+ onGenericError,
+ ],
+ );
+ const collectionSelectorProps: ComponentProps<typeof CollectionSelector> = {
+ open: openCollectionSelector,
+ onClose: handleCloseCollectionSelector,
+ onExited: () => setAttributes(undefined),
+ attributes,
+ collectionSummaries: attributes?.showHiddenCollections
+ ? state.hiddenCollectionSummaries
+ : state.normalCollectionSummaries,
+ collectionForCollectionSummaryID: (id) =>
+ findCollectionCreatingIfNeeded(state.collections, id),
+ };
+ const albumNameInputProps: ComponentProps<typeof SingleInputDialog> = {
+ ...albumNameInputVisibilityProps,
+ title: t("new_album"),
+ label: t("album_name"),
+ submitButtonTitle: t("create"),
+ onClose: () => {
+ setCreation(undefined);
+ albumNameInputVisibilityProps.onClose();
+ },
+ onSubmit: handleAlbumNameSubmit,
+ };
+ return {
+ openCollectionSelector,
+ albumNameInputVisibilityProps,
+ showCreateAlbum,
+ handleOpenCollectionSelector,
+ handleCloseCollectionSelector,
+ handleAddSingleFileToCollection,
+ collectionSelectorProps,
+ albumNameInputProps,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-collection-operations.tsx b/web/apps/photos/src/components/gallery/media/use-collection-operations.tsx
new file mode 100644
index 0000000000..53704291cd
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-collection-operations.tsx
@@ -0,0 +1,164 @@
+import type { CollectionOp } from "@/components/SelectedFileOptions";
+import { performCollectionOp } from "@/components/gallery/helpers";
+import type {
+ GalleryBarMode,
+ GalleryState,
+} from "@/components/gallery/reducer";
+import { notifyOthersFilesDialogAttributes } from "@/components/utils/dialog-attributes";
+import { getSelectedFiles, type SelectedState } from "@/utils/file";
+import { useBaseContext } from "ente-base/context";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import {
+ canAddFilesToCollection,
+ removeFromCollection,
+} from "ente-new/photos/services/collection";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import { useCallback } from "react";
+import type { RemotePullOpts } from "..";
+import { useCollectionDialogs } from "./use-collection-dialogs";
+export const useCollectionOperations = ({
+ state,
+ selected,
+ filteredFiles,
+ barMode,
+ clearSelection,
+ remotePull,
+}: {
+ state: GalleryState;
+ selected: SelectedState;
+ filteredFiles: EnteFile[];
+ barMode: GalleryBarMode;
+ clearSelection: () => void;
+ remotePull: (opts?: RemotePullOpts) => Promise<void>;
+}) => {
+ const { user } = state;
+ const { showMiniDialog, onGenericError } = useBaseContext();
+ const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();
+ const dialogs = useCollectionDialogs({ state, remotePull });
+ const { handleCloseCollectionSelector } = dialogs;
+ const handleRemoveFilesFromCollection = (collection: Collection) => {
+ void (async () => {
+ showLoadingBar();
+ let notifyOthersFiles = false;
+ try {
+ handleCloseCollectionSelector();
+ const selectedFiles = getSelectedFiles(selected, filteredFiles);
+ const processedCount = await removeFromCollection(
+ collection,
+ selectedFiles,
+ );
+ notifyOthersFiles = processedCount != selectedFiles.length;
+ clearSelection();
+ await remotePull({
+ silent: true,
+ source: "remove-from-collection",
+ });
+ } catch (e) {
+ onGenericError(e);
+ } finally {
+ hideLoadingBar();
+ }
+
+ if (notifyOthersFiles) {
+ showMiniDialog(notifyOthersFilesDialogAttributes());
+ }
+ })();
+ };
+ const createOnSelectForCollectionOp = useCallback(
+ (op: CollectionOp) => (selectedCollection: Collection) => {
+ const selectedFiles = getSelectedFiles(selected, filteredFiles);
+ const userFiles = selectedFiles.filter(
+ (f) => f.ownerID == user!.id,
+ );
+ const sourceCollectionID = selected.collectionID;
+
+ const performSelectedCollectionOp = async (
+ op: CollectionOp,
+ filesToProcess: EnteFile[],
+ notifySkippedFiles = false,
+ ) => {
+ showLoadingBar();
+ try {
+ handleCloseCollectionSelector();
+ if (filesToProcess.length > 0) {
+ await performCollectionOp(
+ op,
+ selectedCollection,
+ filesToProcess,
+ sourceCollectionID,
+ );
+ }
+ if (notifySkippedFiles) {
+ showMiniDialog(notifyOthersFilesDialogAttributes());
+ }
+ clearSelection();
+ await remotePull({
+ silent: true,
+ source: `collection-op:${op}`,
+ });
+ } finally {
+ hideLoadingBar();
+ }
+ };
+
+ const shouldAddInsteadOfMove =
+ op == "move" &&
+ selectedCollection.owner.id != user!.id &&
+ canAddFilesToCollection(selectedCollection);
+
+ if (shouldAddInsteadOfMove) {
+ showMiniDialog({
+ title: t("cannot_move_to_shared_albums"),
+ message: t("cannot_move_to_shared_albums_message"),
+ continue: {
+ text: t("add"),
+ action: () =>
+ performSelectedCollectionOp("add", selectedFiles),
+ },
+ cancel: t("cancel"),
+ });
+ return;
+ }
+
+ return (async () => {
+ try {
+ const filesToProcess =
+ op == "add" ? selectedFiles : userFiles;
+ await performSelectedCollectionOp(
+ op,
+ filesToProcess,
+ op != "add" && userFiles.length != selectedFiles.length,
+ );
+ } catch (e) {
+ onGenericError(e);
+ }
+ })();
+ },
+ [
+ selected,
+ filteredFiles,
+ user,
+ showLoadingBar,
+ showMiniDialog,
+ clearSelection,
+ remotePull,
+ hideLoadingBar,
+ onGenericError,
+ handleCloseCollectionSelector,
+ ],
+ );
+ const createOnCreateForCollectionOp = (op: CollectionOp) => {
+ const onCreate = createOnSelectForCollectionOp(op);
+ const hidden =
+ (op === "add" || op === "move") && barMode === "hidden-albums";
+ return () => dialogs.showCreateAlbum(hidden, onCreate);
+ };
+ return {
+ ...dialogs,
+ handleRemoveFilesFromCollection,
+ createOnSelectForCollectionOp,
+ createOnCreateForCollectionOp,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-file-context-actions.ts b/web/apps/photos/src/components/gallery/media/use-file-context-actions.ts
new file mode 100644
index 0000000000..0fb774b903
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-file-context-actions.ts
@@ -0,0 +1,223 @@
+import { useCollectionOperations } from "@/components/gallery/media/use-collection-operations";
+import { useSelectedFileOperations } from "@/components/gallery/media/use-selected-file-operations";
+import type { GalleryBarMode } from "@/components/gallery/reducer";
+import type { FileContextAction } from "@/utils/file-actions";
+import { useBaseContext } from "ente-base/context";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
+import { t } from "i18next";
+import { useCallback } from "react";
+export const useFileContextActions = ({
+ collectionOperations,
+ selectedOperations,
+ activeCollection,
+ activeCollectionSummary,
+ barMode,
+}: {
+ collectionOperations: Pick<
+ ReturnType<typeof useCollectionOperations>,
+ | "createOnCreateForCollectionOp"
+ | "createOnSelectForCollectionOp"
+ | "handleOpenCollectionSelector"
+ | "handleRemoveFilesFromCollection"
+ >;
+ selectedOperations: Pick<
+ ReturnType<typeof useSelectedFileOperations>,
+ | "createFileOpHandler"
+ | "handleDeleteFiles"
+ | "showContextMenuAssignPerson"
+ | "showEditLocation"
+ | "selectedCount"
+ | "selectedOwnCount"
+ >;
+ activeCollection: Collection | undefined;
+ activeCollectionSummary: CollectionSummary | undefined;
+ barMode: GalleryBarMode;
+}) => {
+ const {
+ createOnCreateForCollectionOp,
+ createOnSelectForCollectionOp,
+ handleOpenCollectionSelector,
+ handleRemoveFilesFromCollection,
+ } = collectionOperations;
+ const {
+ createFileOpHandler,
+ handleDeleteFiles,
+ showContextMenuAssignPerson,
+ showEditLocation,
+ selectedCount,
+ selectedOwnCount,
+ } = selectedOperations;
+ const { showMiniDialog } = useBaseContext();
+ const handleContextMenuAction = useCallback(
+ (
+ action: FileContextAction,
+ _targetFile?: EnteFile,
+ meta?: { isEphemeralSingleSelection: boolean },
+ ) => {
+ const suppressSelectionBar = !!meta?.isEphemeralSingleSelection;
+ switch (action) {
+ case "sendLink":
+ case "download":
+ case "favorite":
+ case "unfavorite":
+ case "archive":
+ case "unarchive":
+ case "hide":
+ case "fixTime":
+ void createFileOpHandler(action, {
+ suppressSelectionBar,
+ })();
+ break;
+ case "trash":
+ handleDeleteFiles(suppressSelectionBar);
+ break;
+ case "deletePermanently":
+ showMiniDialog({
+ title: t("delete_files_title"),
+ kind: "warning",
+ message: t("delete_files_message"),
+ continue: {
+ text: t("delete"),
+ color: "critical",
+ action: createFileOpHandler("deletePermanently", {
+ suppressSelectionBar,
+ }),
+ },
+ });
+ break;
+ case "restore":
+ handleOpenCollectionSelector({
+ action: "restore",
+ onCreateCollection:
+ createOnCreateForCollectionOp("restore"),
+ onSelectCollection: (collection) =>
+ void createOnSelectForCollectionOp("restore")(
+ collection,
+ ),
+ });
+ break;
+ case "addToAlbum":
+ handleOpenCollectionSelector({
+ action: "add",
+ sourceCollectionSummaryID: activeCollectionSummary?.id,
+ showHiddenCollections: barMode == "hidden-albums",
+ onCreateCollection:
+ createOnCreateForCollectionOp("add"),
+ onSelectCollection: (collection) =>
+ void createOnSelectForCollectionOp("add")(
+ collection,
+ ),
+ });
+ break;
+ case "moveToAlbum":
+ handleOpenCollectionSelector({
+ action: "move",
+ sourceCollectionSummaryID: activeCollectionSummary?.id,
+ showHiddenCollections: barMode == "hidden-albums",
+ onCreateCollection:
+ createOnCreateForCollectionOp("move"),
+ onSelectCollection: (collection) =>
+ void createOnSelectForCollectionOp("move")(
+ collection,
+ ),
+ });
+ break;
+ case "removeFromAlbum": {
+ if (!activeCollection) break;
+ const isSharedIncoming =
+ activeCollectionSummary?.attributes.has(
+ "sharedIncoming",
+ );
+ const isSharedOutgoing =
+ activeCollectionSummary?.attributes.has(
+ "sharedOutgoing",
+ );
+ const isRemovingOthers = selectedCount != selectedOwnCount;
+ const remove = () =>
+ handleRemoveFilesFromCollection(activeCollection);
+
+ if (isSharedIncoming) {
+ if (isRemovingOthers) {
+ showMiniDialog({
+ title: t("remove_from_album"),
+ message: t("remove_from_album_others_message"),
+ continue: {
+ text: t("remove"),
+ color: "critical",
+ action: remove,
+ },
+ cancel: t("cancel"),
+ });
+ } else {
+ remove();
+ }
+ break;
+ }
+
+ if (isSharedOutgoing && isRemovingOthers) {
+ showMiniDialog({
+ title: t("remove_from_album"),
+ message: t("remove_from_album_others_message"),
+ continue: {
+ text: t("remove"),
+ color: "critical",
+ action: remove,
+ },
+ });
+ break;
+ }
+
+ const onlyUserFiles = !isRemovingOthers;
+ showMiniDialog({
+ title: t("remove_from_album"),
+ message: onlyUserFiles
+ ? t("confirm_remove_message")
+ : t("confirm_remove_incl_others_message"),
+ continue: {
+ text: t("yes_remove"),
+ color: onlyUserFiles ? "primary" : "critical",
+ action: remove,
+ },
+ });
+ break;
+ }
+ case "unhide":
+ handleOpenCollectionSelector({
+ action: "unhide",
+ onCreateCollection:
+ createOnCreateForCollectionOp("unhide"),
+ onSelectCollection: (collection) =>
+ void createOnSelectForCollectionOp("unhide")(
+ collection,
+ ),
+ });
+ break;
+ case "addPerson":
+ showContextMenuAssignPerson();
+ break;
+ case "editLocation":
+ showEditLocation();
+ break;
+ }
+ },
+ [
+ createFileOpHandler,
+ createOnCreateForCollectionOp,
+ createOnSelectForCollectionOp,
+ handleOpenCollectionSelector,
+ handleRemoveFilesFromCollection,
+ handleDeleteFiles,
+ showMiniDialog,
+ showContextMenuAssignPerson,
+ showEditLocation,
+ activeCollectionSummary,
+ activeCollection,
+ barMode,
+ selectedCount,
+ selectedOwnCount,
+ ],
+ );
+ return handleContextMenuAction;
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-file-mutations.ts b/web/apps/photos/src/components/gallery/media/use-file-mutations.ts
new file mode 100644
index 0000000000..d52fd94304
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-file-mutations.ts
@@ -0,0 +1,219 @@
+import type { FileOp } from "@/components/SelectedFileOptions";
+import { errorDialogAttributes } from "ente-base/components/utils/dialog";
+import { useBaseContext } from "ente-base/context";
+import { isHTTPErrorWithStatus } from "ente-base/http";
+import log from "ente-base/log";
+import {
+ quickLinkNameForFiles,
+ resolveQuickLinkURL,
+} from "ente-gallery/utils/quick-link";
+import type { EnteFile } from "ente-media/file";
+import { ItemVisibility, metadataHash } from "ente-media/file-metadata";
+import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";
+import {
+ addToCollection,
+ addToFavoritesCollection,
+ createPublicURL,
+ createQuickLinkCollection,
+ removeFromFavoritesCollection,
+} from "ente-new/photos/services/collection";
+import { updateFilesVisibility } from "ente-new/photos/services/file";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import type { Dispatch } from "react";
+import { useCallback, useState } from "react";
+import type { RemotePullOpts } from "..";
+import type { GalleryAction, GalleryState } from "../reducer";
+export const useFileMutations = ({
+ state,
+ dispatch,
+ remotePull,
+ quickLinkVisibility,
+}: {
+ state: GalleryState;
+ dispatch: Dispatch<GalleryAction>;
+ remotePull: (opts?: RemotePullOpts) => Promise<void>;
+ quickLinkVisibility: ItemVisibility;
+}) => {
+ const { user, favoriteFileIDs } = state;
+ const { customDomain } = useSettingsSnapshot();
+ const { showMiniDialog, onGenericError } = useBaseContext();
+ const { showLoadingBar, hideLoadingBar } = usePhotosAppContext();
+ const [publicLinkToast, setPublicLinkToast] = useState<{
+ open: boolean;
+ url?: string;
+ }>({ open: false });
+ const handleFavoriteFileOp = async (
+ op: Extract<FileOp, "favorite" | "unfavorite">,
+ selectedFiles: EnteFile[],
+ ) => {
+ const filesToProcess: EnteFile[] = [];
+ let skippedUnsupportedSharedFile = false;
+
+ // Shared copies need a metadata hash to find their owned equivalent.
+ for (const file of selectedFiles) {
+ if (file.ownerID == user!.id || metadataHash(file.metadata)) {
+ filesToProcess.push(file);
+ } else {
+ skippedUnsupportedSharedFile = true;
+ }
+ }
+
+ if (!filesToProcess.length) {
+ return { processed: false, skippedUnsupportedSharedFile };
+ }
+
+ const isFavorite = op == "favorite";
+ const previousFavoriteByFileID = new Map(
+ filesToProcess.map((file) => [
+ file.id,
+ favoriteFileIDs.has(file.id),
+ ]),
+ );
+
+ for (const file of filesToProcess) {
+ dispatch({ type: "addPendingFavoriteUpdate", fileID: file.id });
+ dispatch({ type: "unsyncedFavoriteUpdate", file, isFavorite });
+ }
+
+ try {
+ const action = isFavorite
+ ? addToFavoritesCollection
+ : removeFromFavoritesCollection;
+ await action(filesToProcess);
+ return { processed: true, skippedUnsupportedSharedFile };
+ } catch (e) {
+ for (const file of filesToProcess) {
+ dispatch({
+ type: "unsyncedFavoriteUpdate",
+ file,
+ isFavorite: previousFavoriteByFileID.get(file.id)!,
+ });
+ }
+ throw e;
+ } finally {
+ for (const file of filesToProcess) {
+ dispatch({
+ type: "removePendingFavoriteUpdate",
+ fileID: file.id,
+ });
+ }
+ }
+ };
+ const onSendLinkError = useCallback(
+ (e: unknown) => {
+ if (isHTTPErrorWithStatus(e, 402)) {
+ log.error("Could not create share link", e);
+ showMiniDialog(
+ errorDialogAttributes(
+ t("share_link_subscription_required"),
+ ),
+ );
+ } else {
+ onGenericError(e);
+ }
+ },
+ [showMiniDialog, onGenericError],
+ );
+ const handleFileViewerToggleFavorite = useCallback(
+ async (file: EnteFile) => {
+ const fileID = file.id;
+ const isFavorite = favoriteFileIDs.has(fileID);
+
+ dispatch({ type: "addPendingFavoriteUpdate", fileID });
+ dispatch({
+ type: "unsyncedFavoriteUpdate",
+ file,
+ isFavorite: !isFavorite,
+ });
+ try {
+ const action = isFavorite
+ ? removeFromFavoritesCollection
+ : addToFavoritesCollection;
+ await action([file]);
+ } catch (e) {
+ dispatch({ type: "unsyncedFavoriteUpdate", file, isFavorite });
+ throw e;
+ } finally {
+ dispatch({ type: "removePendingFavoriteUpdate", fileID });
+ }
+ },
+ [favoriteFileIDs],
+ );
+ const handleFileViewerFileVisibilityUpdate = useCallback(
+ async (file: EnteFile, visibility: ItemVisibility) => {
+ const fileID = file.id;
+ dispatch({ type: "addPendingVisibilityUpdate", fileID });
+ try {
+ await updateFilesVisibility([file], visibility);
+ // Keep the UI ahead of the background pull.
+ // TODO: Replace with files pull?
+ dispatch({
+ type: "unsyncedPrivateMagicMetadataUpdate",
+ fileID,
+ privateMagicMetadata: {
+ ...file.magicMetadata,
+ count: file.magicMetadata?.count ?? 0,
+ version: (file.magicMetadata?.version ?? 0) + 1,
+ data: { ...file.magicMetadata?.data, visibility },
+ },
+ });
+ } finally {
+ dispatch({ type: "removePendingVisibilityUpdate", fileID });
+ }
+ },
+ [],
+ );
+ const handleFileViewerSendLink = useCallback(
+ async (file: EnteFile) => {
+ if (file.ownerID != user?.id) return;
+
+ showLoadingBar();
+ try {
+ const quickLinkCollection = await createQuickLinkCollection(
+ quickLinkNameForFiles([file]),
+ quickLinkVisibility,
+ );
+ await addToCollection(quickLinkCollection, [file]);
+ const publicURL = await createPublicURL(
+ quickLinkCollection.id,
+ { enableJoin: false },
+ );
+ const resolvedURL = await resolveQuickLinkURL(
+ publicURL.url,
+ quickLinkCollection.key,
+ customDomain,
+ );
+ setPublicLinkToast({ open: true, url: resolvedURL });
+ await remotePull({ silent: true, source: "viewer-send-link" });
+ } catch (e) {
+ onSendLinkError(e);
+ } finally {
+ hideLoadingBar();
+ }
+ },
+ [
+ user?.id,
+ showLoadingBar,
+ hideLoadingBar,
+ customDomain,
+ quickLinkVisibility,
+ remotePull,
+ onSendLinkError,
+ ],
+ );
+ const handleMarkTempDeleted = useCallback(
+ (files: EnteFile[]) => dispatch({ type: "markTempDeleted", files }),
+ [],
+ );
+ return {
+ publicLinkToast,
+ setPublicLinkToast,
+ handleFavoriteFileOp,
+ onSendLinkError,
+ handleFileViewerToggleFavorite,
+ handleFileViewerFileVisibilityUpdate,
+ handleFileViewerSendLink,
+ handleMarkTempDeleted,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-gallery-selection.ts b/web/apps/photos/src/components/gallery/media/use-gallery-selection.ts
new file mode 100644
index 0000000000..fdb29299d1
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-gallery-selection.ts
@@ -0,0 +1,36 @@
+import type { SetSelectedState } from "@/utils/file";
+import type { EnteFile } from "ente-media/file";
+import { useCallback, useMemo, useState } from "react";
+import { emptySelection, retainVisibleSelection } from "./file-selection";
+
+export const useGallerySelection = (
+ files: EnteFile[],
+ userID: number | undefined,
+) => {
+ const [stored, setStored] = useState({
+ value: emptySelection,
+ revision: 0,
+ });
+ const selected = useMemo(
+ () => retainVisibleSelection(stored.value, files, userID),
+ [stored.value, files, userID],
+ );
+ if (selected !== stored.value) setStored({ ...stored, value: selected });
+ const setSelected = useCallback<SetSelectedState>((update) => {
+ setStored((previous) => ({
+ value:
+ typeof update === "function" ? update(previous.value) : update,
+ revision: previous.revision + 1,
+ }));
+ }, []);
+ const revision = stored.revision;
+ const clearSelection = useCallback(() => {
+ // Data refreshes retain the revision; newer user selections do not.
+ setStored((previous) =>
+ previous.revision === revision
+ ? { value: emptySelection, revision: revision + 1 }
+ : previous,
+ );
+ }, [revision]);
+ return { selected, setSelected, clearSelection };
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-selected-file-operations.ts b/web/apps/photos/src/components/gallery/media/use-selected-file-operations.ts
new file mode 100644
index 0000000000..9937aa2542
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-selected-file-operations.ts
@@ -0,0 +1,379 @@
+import type { FixCreationTime } from "@/components/FixCreationTime";
+import type { FileOp } from "@/components/SelectedFileOptions";
+import { useFileMutations } from "@/components/gallery/media/use-file-mutations";
+import {
+ notifyOthersFilesDialogAttributes,
+ notifyUnsupportedSharedFavoritesDialogAttributes,
+ trashFilesDialogAttributes,
+} from "@/components/utils/dialog-attributes";
+import {
+ selectedFavoriteCount as countSelectedFavorites,
+ getSelectedFiles,
+ performFileOp,
+ type SelectedState,
+} from "@/utils/file";
+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";
+import { useModalVisibility } from "ente-base/components/utils/modal";
+import { useBaseContext } from "ente-base/context";
+import type { Location } from "ente-base/types";
+import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
+import {
+ quickLinkNameForFiles,
+ resolveQuickLinkURL,
+} from "ente-gallery/utils/quick-link";
+import type { EnteFile } from "ente-media/file";
+import { ItemVisibility } from "ente-media/file-metadata";
+import type { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
+import type { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";
+import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";
+import {
+ addToCollection,
+ createPublicURL,
+ createQuickLinkCollection,
+} from "ente-new/photos/services/collection";
+import { updateFilesLocation } from "ente-new/photos/services/file";
+import {
+ addManualFileAssignmentsToPerson,
+ isMLEnabled,
+} from "ente-new/photos/services/ml";
+import type { PeopleState } from "ente-new/photos/services/ml/people";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+import type { ComponentProps, Dispatch } from "react";
+import { useCallback, useMemo, useState } from "react";
+import type { RemotePullOpts } from "..";
+import type { GalleryAction, GalleryState } from "../reducer";
+export const useSelectedFileOperations = ({
+ state,
+ dispatch,
+ peopleState,
+ selected,
+ filteredFiles,
+ quickLinkVisibility,
+ clearSelection,
+ onAddSaveGroup,
+ remotePull,
+ mutations,
+}: {
+ state: GalleryState;
+ dispatch: Dispatch<GalleryAction>;
+ peopleState: PeopleState | undefined;
+ selected: SelectedState;
+ filteredFiles: EnteFile[];
+ quickLinkVisibility: ItemVisibility;
+ clearSelection: () => void;
+ onAddSaveGroup: ReturnType<typeof useSaveGroups>["onAddSaveGroup"];
+ remotePull: (opts?: RemotePullOpts) => Promise<void>;
+ mutations: Pick<
+ ReturnType<typeof useFileMutations>,
+ | "setPublicLinkToast"
+ | "handleFavoriteFileOp"
+ | "onSendLinkError"
+ | "handleMarkTempDeleted"
+ >;
+}) => {
+ const { user, favoriteFileIDs } = state;
+ const { customDomain } = useSettingsSnapshot();
+ const { showMiniDialog, onGenericError } = useBaseContext();
+ const { showLoadingBar, hideLoadingBar, showNotification } =
+ usePhotosAppContext();
+ const {
+ setPublicLinkToast,
+ handleFavoriteFileOp,
+ onSendLinkError,
+ handleMarkTempDeleted,
+ } = mutations;
+ const selectedFilesInView = useMemo(
+ () => getSelectedFiles(selected, filteredFiles),
+ [selected, filteredFiles],
+ );
+ const [suppressContextSelectionBar, setSuppressContextSelectionBar] =
+ useState(false);
+ const [fixCreationTimeFiles, setFixCreationTimeFiles] = useState<
+ EnteFile[]
+ >([]);
+ const { show: openAssignPerson, props: contextMenuAssignPersonProps } =
+ useModalVisibility();
+ const namedPeople = useMemo(
+ () =>
+ (peopleState?.visiblePeople ?? []).filter(
+ (p) => p.type == "cgroup" && !!p.name,
+ ),
+ [peopleState],
+ );
+ const showAddPersonAction = useMemo(
+ () => isMLEnabled() && namedPeople.length > 0,
+ [namedPeople],
+ );
+ const { show: showFixCreationTime, props: fixCreationTimeVisibilityProps } =
+ useModalVisibility();
+ const { show: openEditLocation, props: editLocationVisibilityProps } =
+ useModalVisibility();
+ const [personSelection, setPersonSelection] = useState<{
+ files: EnteFile[];
+ clear: () => void;
+ }>();
+ const [editLocationFiles, setEditLocationFiles] = useState<EnteFile[]>([]);
+ const showContextMenuAssignPerson = useCallback(() => {
+ setPersonSelection({
+ files: selectedFilesInView,
+ clear: clearSelection,
+ });
+ openAssignPerson();
+ }, [selectedFilesInView, clearSelection, openAssignPerson]);
+ const showEditLocation = useCallback(() => {
+ setEditLocationFiles(selectedFilesInView);
+ openEditLocation();
+ }, [selectedFilesInView, openEditLocation]);
+ const createFileOpHandler = useCallback(
+ (op: FileOp, options?: { suppressSelectionBar?: boolean }) => () => {
+ return (async () => {
+ if (options?.suppressSelectionBar) {
+ setSuppressContextSelectionBar(true);
+ }
+ showLoadingBar();
+ try {
+ if (op == "sendLink") {
+ const selectedFiles = getSelectedFiles(
+ selected,
+ filteredFiles,
+ );
+ const ownedSelectedFiles = selectedFiles.filter(
+ (file) => file.ownerID == user!.id,
+ );
+ if (!ownedSelectedFiles.length) return;
+ if (ownedSelectedFiles.length != selectedFiles.length) {
+ showMiniDialog(notifyOthersFilesDialogAttributes());
+ }
+
+ const quickLinkCollection =
+ await createQuickLinkCollection(
+ quickLinkNameForFiles(ownedSelectedFiles),
+ quickLinkVisibility,
+ );
+ await addToCollection(
+ quickLinkCollection,
+ ownedSelectedFiles,
+ );
+ const publicURL = await createPublicURL(
+ quickLinkCollection.id,
+ { enableJoin: false },
+ );
+ const resolvedURL = await resolveQuickLinkURL(
+ publicURL.url,
+ quickLinkCollection.key,
+ customDomain,
+ );
+ setPublicLinkToast({ open: true, url: resolvedURL });
+
+ clearSelection();
+ await remotePull({
+ silent: true,
+ source: "selected-files-quick-link",
+ });
+ return;
+ }
+
+ // Hide every non-hidden copy, including copies outside this view.
+ const opFiles =
+ op == "hide"
+ ? state.collectionFiles.filter(
+ (f) => !state.hiddenFileIDs.has(f.id),
+ )
+ : filteredFiles;
+ const selectedFiles = getSelectedFiles(selected, opFiles);
+ if (op == "favorite" || op == "unfavorite") {
+ const { processed, skippedUnsupportedSharedFile } =
+ await handleFavoriteFileOp(op, selectedFiles);
+ clearSelection();
+ if (processed) {
+ await remotePull({
+ silent: true,
+ source: `file-op:${op}`,
+ });
+ }
+ if (skippedUnsupportedSharedFile) {
+ showMiniDialog(
+ notifyUnsupportedSharedFavoritesDialogAttributes(),
+ );
+ }
+ return;
+ }
+
+ const ownedSelectedFiles =
+ op == "download"
+ ? selectedFiles
+ : selectedFiles.filter(
+ (file) => file.ownerID == user!.id,
+ );
+ if (ownedSelectedFiles.length > 0) {
+ await performFileOp(
+ op,
+ ownedSelectedFiles,
+ onAddSaveGroup,
+ handleMarkTempDeleted,
+ () => dispatch({ type: "clearTempDeleted" }),
+ (files) =>
+ dispatch({ type: "markTempHidden", files }),
+ () => dispatch({ type: "clearTempHidden" }),
+ (files) => {
+ setFixCreationTimeFiles(files);
+ showFixCreationTime();
+ },
+ );
+ }
+
+ if (
+ op != "download" &&
+ ownedSelectedFiles.length != selectedFiles.length
+ ) {
+ showMiniDialog(notifyOthersFilesDialogAttributes());
+ }
+ clearSelection();
+ await remotePull({ silent: true, source: `file-op:${op}` });
+ } catch (e) {
+ if (op == "trash") {
+ throw e;
+ } else if (op == "sendLink") {
+ onSendLinkError(e);
+ } else {
+ onGenericError(e);
+ }
+ } finally {
+ if (options?.suppressSelectionBar) {
+ setSuppressContextSelectionBar(false);
+ }
+ hideLoadingBar();
+ }
+ })();
+ },
+ [
+ selected,
+ filteredFiles,
+ quickLinkVisibility,
+ user,
+ showMiniDialog,
+ showLoadingBar,
+ hideLoadingBar,
+ customDomain,
+ setPublicLinkToast,
+ clearSelection,
+ remotePull,
+ state.collectionFiles,
+ state.hiddenFileIDs,
+ handleFavoriteFileOp,
+ onAddSaveGroup,
+ handleMarkTempDeleted,
+ dispatch,
+ showFixCreationTime,
+ onSendLinkError,
+ onGenericError,
+ ],
+ );
+ const handleAddPersonToSelectedFiles = useCallback(
+ async (personID: string) => {
+ showLoadingBar();
+ try {
+ const selectedFiles = personSelection?.files ?? [];
+ await addManualFileAssignmentsToPerson(
+ personID,
+ selectedFiles.map((f) => f.id),
+ );
+ personSelection?.clear();
+ const personName = namedPeople.find(
+ (p) => p.id === personID,
+ )?.name;
+ showNotification({
+ color: "secondary",
+ startIcon: CheckmarkCircle02Icon,
+ title: t("added_to_person"),
+ caption: personName,
+ });
+ } catch (e) {
+ onGenericError(e);
+ } finally {
+ hideLoadingBar();
+ }
+ },
+ [
+ personSelection,
+ showNotification,
+ namedPeople,
+ showLoadingBar,
+ hideLoadingBar,
+ onGenericError,
+ ],
+ );
+ const handleContextMenuSelectPerson = useCallback(
+ (personID: string) => {
+ contextMenuAssignPersonProps.onClose();
+ void handleAddPersonToSelectedFiles(personID);
+ },
+ [contextMenuAssignPersonProps, handleAddPersonToSelectedFiles],
+ );
+ const handleEditLocationConfirm = useCallback(
+ async (location: Location) => {
+ const userFiles = editLocationFiles.filter(
+ (f) => f.ownerID == user!.id,
+ );
+ if (userFiles.length > 0) {
+ await updateFilesLocation(
+ userFiles,
+ location.latitude,
+ location.longitude,
+ );
+ }
+ void remotePull({ silent: true, source: "edit-location" });
+ },
+ [editLocationFiles, user, remotePull],
+ );
+ const selectedCount = selected.count;
+ const selectedOwnCount = selected.ownCount;
+ const handleDeleteFiles = useCallback(
+ (suppressSelectionBar = false) => {
+ if (selectedOwnCount === 0) return;
+ showMiniDialog(
+ trashFilesDialogAttributes(
+ selectedOwnCount,
+ createFileOpHandler("trash", { suppressSelectionBar }),
+ ),
+ );
+ },
+ [selectedOwnCount, createFileOpHandler, showMiniDialog],
+ );
+ const selectedFavoriteCount = useMemo(
+ () => countSelectedFavorites(selected, favoriteFileIDs),
+ [favoriteFileIDs, selected],
+ );
+ const fixCreationTimeProps: ComponentProps<typeof FixCreationTime> = {
+ ...fixCreationTimeVisibilityProps,
+ files: fixCreationTimeFiles,
+ onRemotePull: remotePull,
+ };
+ const assignPersonDialogProps: ComponentProps<typeof AssignPersonDialog> = {
+ ...contextMenuAssignPersonProps,
+ people: namedPeople,
+ title: t("add_a_person"),
+ onSelectPerson: handleContextMenuSelectPerson,
+ };
+ const editLocationDialogProps: ComponentProps<typeof EditLocationDialog> = {
+ ...editLocationVisibilityProps,
+ files: editLocationFiles,
+ onConfirm: handleEditLocationConfirm,
+ };
+ return {
+ suppressContextSelectionBar,
+ showAddPersonAction,
+ fixCreationTimeVisibilityProps,
+ showEditLocation,
+ showContextMenuAssignPerson,
+ createFileOpHandler,
+ handleDeleteFiles,
+ selectedFavoriteCount,
+ selectedCount,
+ selectedOwnCount,
+ fixCreationTimeProps,
+ assignPersonDialogProps,
+ editLocationDialogProps,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/media/use-selection-shortcuts.ts b/web/apps/photos/src/components/gallery/media/use-selection-shortcuts.ts
new file mode 100644
index 0000000000..500d8030f9
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/media/use-selection-shortcuts.ts
@@ -0,0 +1,77 @@
+import type { SelectedState } from "@/utils/file";
+import { useCallback, useEffect, useEffectEvent } from "react";
+import type { GalleryMediaSource } from "../sections/types";
+
+export const useSelectionShortcuts = ({
+ source,
+ userID,
+ setSelected,
+ clearSelection,
+ disabled,
+}: {
+ source: GalleryMediaSource;
+ userID: number | undefined;
+ setSelected: React.Dispatch<React.SetStateAction<SelectedState>>;
+ clearSelection: () => void;
+ disabled: boolean;
+}) => {
+ const { files, mode, activeCollectionID, activePersonID } = source;
+ const selectAll = useCallback(() => {
+ if (userID === undefined || !files.length) return;
+ const selected: SelectedState = {
+ count: 0,
+ ownCount: 0,
+ collectionID: activeCollectionID,
+ context:
+ mode === "people" && activePersonID
+ ? { mode: "people", personID: activePersonID }
+ : {
+ mode: mode as
+ "albums" | "hidden-albums" | "archive-albums",
+ collectionID: activeCollectionID!,
+ },
+ };
+ for (const file of files) {
+ if (selected[file.id]) continue;
+ selected[file.id] = true;
+ selected.count++;
+ if (file.ownerID === userID) selected.ownCount++;
+ }
+ setSelected(selected);
+ }, [files, mode, activeCollectionID, activePersonID, userID, setSelected]);
+ const handleKey = useEffectEvent((event: KeyboardEvent) => {
+ if (
+ disabled ||
+ event.defaultPrevented ||
+ (event.target instanceof Element &&
+ event.target.closest(
+ 'input, textarea, [contenteditable="true"]',
+ )) ||
+ Array.from(
+ document.querySelectorAll<HTMLElement>(
+ '[role="dialog"], [role="alertdialog"], [role="menu"]',
+ ),
+ ).some(
+ (element) =>
+ element.getClientRects().length > 0 &&
+ !element.closest('[aria-hidden="true"]') &&
+ getComputedStyle(element).visibility !== "hidden",
+ )
+ )
+ return;
+ if (event.key === "Escape") clearSelection();
+ else if (
+ event.key.toLowerCase() === "a" &&
+ (event.ctrlKey || event.metaKey)
+ ) {
+ event.preventDefault();
+ selectAll();
+ }
+ });
+ useEffect(() => {
+ const handler = (event: KeyboardEvent) => handleKey(event);
+ document.addEventListener("keydown", handler);
+ return () => document.removeEventListener("keydown", handler);
+ }, []);
+ return selectAll;
+};
diff --git a/web/apps/photos/src/components/gallery/navigation/GallerySectionLayout.tsx b/web/apps/photos/src/components/gallery/navigation/GallerySectionLayout.tsx
new file mode 100644
index 0000000000..dd0a60e7f1
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/navigation/GallerySectionLayout.tsx
@@ -0,0 +1,135 @@
+import CloudOffIcon from "@mui/icons-material/CloudOff";
+import { CircularProgress, Stack, Typography } from "@mui/material";
+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
+import { thumbnailGridPadding } from "ente-new/photos/components/utils/thumbnail-grid-layout";
+import { t } from "i18next";
+import type { ReactNode } from "react";
+import { NavigationSlide } from "./NavigationSlide";
+import { useNavigationContentMotion } from "./use-navigation-content-motion";
+
+export interface GallerySectionPresentation {
+ collapsed: boolean;
+ mobile: boolean;
+ mobileDrawerProps: ModalVisibilityProps;
+ reduceMotion: boolean;
+ isFirstLoad: boolean;
+ isOffline: boolean;
+}
+
+export const GallerySectionLayout = ({
+ presentation,
+ navigation,
+ fullBleed = false,
+ children,
+}: {
+ presentation: GallerySectionPresentation;
+ navigation?: ReactNode;
+ fullBleed?: boolean;
+ children: ReactNode;
+}) => {
+ const { collapsed, mobile, reduceMotion, isFirstLoad, isOffline } =
+ presentation;
+ const panelOpen = !!navigation && !collapsed;
+ const contentRef = useNavigationContentMotion(
+ `${mobile}-${panelOpen}`,
+ reduceMotion,
+ );
+
+ return (
+ <Stack
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ minHeight: 0,
+ flexDirection: { xs: "column", md: "row" },
+ }}
+ >
+ {navigation && (
+ <NavigationSlide
+ open={panelOpen}
+ width={328}
+ reduceMotion={reduceMotion}
+ disabled={mobile}
+ >
+ {navigation}
+ </NavigationSlide>
+ )}
+ <Stack
+ ref={contentRef}
+ sx={{ flex: 1, minWidth: 0, minHeight: 0, gap: "8px" }}
+ >
+ <Stack
+ sx={(theme) => ({
+ flex: 1,
+ minWidth: 0,
+ minHeight: 0,
+ pt: fullBleed
+ ? 0
+ : { xs: `${thumbnailGridPadding}px`, md: "36px" },
+ px: fullBleed ? 0 : { xs: 0, md: "12px" },
+ "--mui-palette-background-default": "#FFFFFF",
+ bgcolor: "background.default",
+ borderRadius: "20px",
+ overflow: "hidden",
+ ...theme.applyStyles("dark", {
+ "--mui-palette-background-default": "#212121",
+ }),
+ })}
+ >
+ {children}
+ </Stack>
+ {isFirstLoad && (
+ <GalleryStatusMessage
+ icon={
+ <CircularProgress
+ size={12}
+ thickness={5}
+ color="inherit"
+ aria-hidden
+ />
+ }
+ >
+ {t("initial_load_delay_warning")}
+ </GalleryStatusMessage>
+ )}
+ {isOffline && (
+ <GalleryStatusMessage
+ icon={
+ <CloudOffIcon sx={{ fontSize: 16 }} aria-hidden />
+ }
+ >
+ {t("offline_message")}
+ </GalleryStatusMessage>
+ )}
+ </Stack>
+ </Stack>
+ );
+};
+
+const GalleryStatusMessage = ({
+ icon,
+ children,
+}: {
+ icon: ReactNode;
+ children: ReactNode;
+}) => (
+ <Stack
+ direction="row"
+ role="status"
+ sx={{
+ flexShrink: 0,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 1.25,
+ px: 1,
+ py: 1.25,
+ color: "text.muted",
+ opacity: 0.65,
+ }}
+ >
+ {icon}
+ <Typography variant="small" sx={{ textAlign: "center" }}>
+ {children}
+ </Typography>
+ </Stack>
+);
diff --git a/web/apps/photos/src/components/gallery/navigation/NavigationPrimitives.tsx b/web/apps/photos/src/components/gallery/navigation/NavigationPrimitives.tsx
new file mode 100644
index 0000000000..75e85ad917
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/navigation/NavigationPrimitives.tsx
@@ -0,0 +1,377 @@
+import { Link05Icon, PinIcon, StarIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import ArchiveIcon from "@mui/icons-material/Archive";
+import CloseIcon from "@mui/icons-material/Close";
+import PeopleIcon from "@mui/icons-material/People";
+import SearchIcon from "@mui/icons-material/Search";
+import {
+ Box,
+ ButtonBase,
+ Drawer,
+ IconButton,
+ InputBase,
+ Stack,
+ Typography,
+ styled,
+ useMediaQuery,
+ useTheme,
+} from "@mui/material";
+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
+import { ItemCard } from "ente-new/photos/components/Tiles";
+import type {
+ CollectionSummary,
+ CollectionSummaryAttribute,
+} from "ente-new/photos/services/collection-summary";
+import { t } from "i18next";
+import React, { useId, useRef, type ReactNode } from "react";
+
+export interface GalleryBarPresentationProps {
+ collapsed: boolean;
+ mobileDrawerProps: ModalVisibilityProps;
+}
+
+interface NavigationFrameProps {
+ title: ReactNode;
+ actions: ReactNode;
+ searchPlaceholder: string;
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ mobileDrawerProps: ModalVisibilityProps;
+ children: ReactNode;
+}
+
+export const NavigationFrame = ({
+ title,
+ actions,
+ searchPlaceholder,
+ searchQuery,
+ setSearchQuery,
+ mobileDrawerProps,
+ children,
+}: NavigationFrameProps) => {
+ const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
+ const titleID = useId();
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const navigation = (
+ <Stack
+ component="nav"
+ aria-labelledby={titleID}
+ onKeyDown={(event) => {
+ if (event.key == "Escape" && searchQuery) {
+ event.stopPropagation();
+ setSearchQuery("");
+ }
+ }}
+ sx={(theme) => ({
+ "--gallery-navigation-surface": "#FFFFFF",
+ "--gallery-navigation-hover":
+ "color-mix(in srgb, var(--mui-palette-text-base) 8%, var(--gallery-navigation-surface))",
+ flexShrink: 0,
+ width: "100%",
+ height: "100%",
+ minHeight: 0,
+ px: mobile ? "12px" : "16px",
+ py: mobile ? "14px" : 0,
+ borderLeft: mobile ? 0 : "2px solid",
+ borderColor: "rgba(224, 224, 224, 0.5)",
+ gap: "16px",
+ letterSpacing: 0,
+ ...theme.applyStyles("dark", {
+ "--gallery-navigation-surface": "#212121",
+ borderColor: "rgba(62, 62, 62, 0.5)",
+ }),
+ })}
+ >
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ flexShrink: 0,
+ height: 38,
+ gap: 0.5,
+ "& .MuiIconButton-root": {
+ width: 38,
+ height: 38,
+ borderRadius: "12px",
+ bgcolor: "var(--gallery-navigation-surface)",
+ "&:hover": {
+ bgcolor: "var(--gallery-navigation-hover)",
+ },
+ },
+ }}
+ >
+ <Typography
+ component="h2"
+ id={titleID}
+ sx={{
+ flex: 1,
+ minWidth: 0,
+ fontFamily: '"Outfit Variable", Outfit, sans-serif',
+ fontSize: mobile ? 20 : 24,
+ fontWeight: 600,
+ lineHeight: mobile ? "26px" : "32px",
+ }}
+ >
+ {title}
+ </Typography>
+ {actions}
+ {mobile && (
+ <IconButton
+ aria-label={t("close")}
+ onClick={mobileDrawerProps.onClose}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ )}
+ </Stack>
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ flexShrink: 0,
+ display: "flex",
+ height: 52,
+ gap: "10px",
+ px: "16px",
+ borderRadius: "12px",
+ bgcolor: "var(--gallery-navigation-surface)",
+ border: "1px solid",
+ borderColor: "stroke.faint",
+ "&:focus-within": {
+ outline: "1px solid",
+ outlineColor: "stroke.muted",
+ outlineOffset: -1,
+ },
+ }}
+ >
+ <SearchIcon sx={{ fontSize: 18, color: "text.muted" }} />
+ <InputBase
+ inputRef={searchInputRef}
+ fullWidth
+ placeholder={searchPlaceholder}
+ inputProps={{ "aria-label": searchPlaceholder }}
+ value={searchQuery}
+ onChange={(event) => setSearchQuery(event.target.value)}
+ sx={{
+ fontSize: mobile ? 13 : 14,
+ fontWeight: 500,
+ color: "text.base",
+ "& input::placeholder": {
+ color: "text.muted",
+ opacity: 1,
+ },
+ }}
+ />
+ {searchQuery && (
+ <IconButton
+ aria-label={t("clear_search")}
+ onClick={() => {
+ setSearchQuery("");
+ searchInputRef.current?.focus();
+ }}
+ size="small"
+ >
+ <CloseIcon sx={{ fontSize: 18 }} />
+ </IconButton>
+ )}
+ </Stack>
+ {children}
+ </Stack>
+ );
+
+ return mobile ? (
+ <Drawer
+ {...mobileDrawerProps}
+ anchor="left"
+ slotProps={{
+ transition: { appear: true },
+ backdrop: { sx: { bgcolor: "rgba(0,0,0,0.4)" } },
+ paper: {
+ role: "dialog",
+ "aria-modal": true,
+ "aria-labelledby": titleID,
+ inert: !mobileDrawerProps.open,
+ sx: (theme) => ({
+ width: "100%",
+ borderRadius: 0,
+ boxShadow: "none",
+ bgcolor: "#F4F4F4",
+ ...theme.applyStyles("dark", { bgcolor: "#161616" }),
+ }),
+ },
+ }}
+ >
+ {navigation}
+ </Drawer>
+ ) : (
+ navigation
+ );
+};
+
+export const NavigationEmptyState = () => (
+ <Stack
+ role="status"
+ sx={{
+ flex: 1,
+ minHeight: 0,
+ alignItems: "center",
+ justifyContent: "safe center",
+ gap: "12px",
+ px: "16px",
+ py: "24px",
+ textAlign: "center",
+ overflowY: "auto",
+ }}
+ >
+ <Box
+ component="img"
+ src="/images/empty-state/no-matches.svg"
+ alt=""
+ draggable={false}
+ sx={{ width: 112, height: "auto", flexShrink: 0 }}
+ />
+ <Typography
+ sx={{
+ color: "text.base",
+ fontFamily: '"Outfit Variable", sans-serif',
+ fontSize: 18,
+ fontWeight: 600,
+ lineHeight: "26px",
+ }}
+ >
+ {t("no_results")}
+ </Typography>
+ </Stack>
+);
+
+interface CollectionBarCardProps {
+ collectionSummary: CollectionSummary;
+ indented: boolean;
+ activeCollectionID: number | undefined;
+ onSelectCollectionID: (collectionID: number) => void;
+}
+
+export const CollectionBarCard: React.FC<CollectionBarCardProps> = ({
+ collectionSummary,
+ indented,
+ activeCollectionID,
+ onSelectCollectionID,
+}: CollectionBarCardProps) => (
+ <BarCard
+ aria-label={collectionSummary.name}
+ aria-current={
+ activeCollectionID === collectionSummary.id ? "true" : undefined
+ }
+ title={collectionSummary.name}
+ onClick={() => onSelectCollectionID(collectionSummary.id)}
+ sx={
+ indented
+ ? { marginInlineStart: "20px", width: "calc(100% - 20px)" }
+ : undefined
+ }
+ >
+ <Box aria-hidden sx={{ flexShrink: 0 }}>
+ <ItemCard
+ TileComponent={BarThumbnail}
+ coverFile={collectionSummary.coverFile}
+ />
+ </Box>
+ <CardText>{collectionSummary.name}</CardText>
+ <CollectionBarCardIcon attributes={collectionSummary.attributes} />
+ </BarCard>
+);
+
+export const CardText: React.FC<React.PropsWithChildren> = ({ children }) => (
+ <Typography
+ noWrap
+ sx={(theme) => ({
+ flex: 1,
+ minWidth: 0,
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ [theme.breakpoints.down("md")]: { fontSize: 13 },
+ })}
+ >
+ {children}
+ </Typography>
+);
+
+interface CollectionBarCardIconProps {
+ attributes: Set<CollectionSummaryAttribute>;
+}
+
+const CollectionBarCardIcon: React.FC<CollectionBarCardIconProps> = ({
+ attributes,
+}) => (
+ <CollectionBarCardIcon_ aria-hidden>
+ {attributes.has("userFavorites") && (
+ <HugeiconsIcon
+ icon={StarIcon}
+ size={16}
+ fill="currentColor"
+ aria-hidden
+ />
+ )}
+ {(attributes.has("pinned") || attributes.has("shareePinned")) && (
+ <HugeiconsIcon icon={PinIcon} size={14} />
+ )}
+ {attributes.has("shared") && !attributes.has("sharedOnlyViaLink") && (
+ <PeopleIcon />
+ )}
+ {attributes.has("sharedViaLink") && (
+ <HugeiconsIcon icon={Link05Icon} size={16} />
+ )}
+ {attributes.has("archived") && <ArchiveIcon sx={{ opacity: 0.48 }} />}
+ </CollectionBarCardIcon_>
+);
+
+export const CollectionBarCardIcon_ = styled("span")`
+ display: flex;
+ flex-shrink: 0;
+ margin-inline-start: auto;
+ align-items: center;
+ gap: 4px;
+ color: #969696;
+ & > .MuiSvgIcon-root {
+ font-size: 16px;
+ }
+`;
+
+export const BarCard = styled(ButtonBase)(({ theme }) => ({
+ display: "flex",
+ justifyContent: "flex-start",
+ gap: "12px",
+ width: "100%",
+ height: 48,
+ paddingInline: "16px 12px",
+ borderRadius: "12px",
+ color: theme.vars.palette.text.base,
+ textAlign: "left",
+ '&[aria-current="true"], &[aria-current="page"]': {
+ backgroundColor: "var(--gallery-navigation-surface)",
+ },
+ "&:hover": { backgroundColor: "var(--gallery-navigation-hover)" },
+ "&.Mui-focusVisible": {
+ outline: "2px solid",
+ outlineColor: theme.vars.palette.stroke.base,
+ outlineOffset: -2,
+ },
+ [theme.breakpoints.down("md")]: { height: 44 },
+}));
+
+export const BarThumbnail = styled("div")({
+ width: 24,
+ height: 24,
+ position: "relative",
+ overflow: "hidden",
+ borderRadius: "6px",
+ "& > img": {
+ width: "100%",
+ height: "100%",
+ objectFit: "cover",
+ display: "block",
+ },
+ "& .MuiSvgIcon-root": { fontSize: 18 },
+});
diff --git a/web/apps/photos/src/components/gallery/NavigationSlide.tsx b/web/apps/photos/src/components/gallery/navigation/NavigationSlide.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/NavigationSlide.tsx
rename to web/apps/photos/src/components/gallery/navigation/NavigationSlide.tsx
diff --git a/web/apps/photos/src/components/gallery/PhotosNavigationContext.tsx b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationContext.tsx
similarity index 86%
rename from web/apps/photos/src/components/gallery/PhotosNavigationContext.tsx
rename to web/apps/photos/src/components/gallery/navigation/PhotosNavigationContext.tsx
index 27077c2841..f8f472ab06 100644
--- a/web/apps/photos/src/components/gallery/PhotosNavigationContext.tsx
+++ b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationContext.tsx
@@ -1,10 +1,12 @@
import type { AlbumFilter } from "@/utils/album-filters";
import type { SearchOption } from "ente-new/photos/services/search/types";
import { createContext, useContext } from "react";
-import type { PlaceSelection } from "./PlacesList";
-import type { GalleryBarMode } from "./reducer";
+import type { GalleryBarMode } from "../reducer";
+import type { PlaceSelection } from "../sections/places/PlacesList";
+import type { GallerySectionID } from "../sections/registry";
export interface PhotosNavigationActions {
+ openSection: (id: GallerySectionID) => boolean;
goHome: () => void;
changeMode: (mode: GalleryBarMode) => boolean;
showLibraryMap: () => void;
diff --git a/web/apps/photos/src/components/gallery/PhotosNavigationShell.tsx b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx
similarity index 53%
rename from web/apps/photos/src/components/gallery/PhotosNavigationShell.tsx
rename to web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx
index 05993ccdb4..ec994cc7f5 100644
--- a/web/apps/photos/src/components/gallery/PhotosNavigationShell.tsx
+++ b/web/apps/photos/src/components/gallery/navigation/PhotosNavigationShell.tsx
@@ -1,26 +1,18 @@
-import { CreateAlbumDialog } from "@/components/collections/CreateAlbumDialog";
-import { SearchBar, type SearchBarProps } from "@/components/SearchBar";
+import { SearchBar } from "@/components/SearchBar";
import { Sidebar } from "@/components/sidebar/Sidebar";
import { useIsOffline } from "@/components/utils/use-is-offline";
import { uploadManager } from "@/services/upload-manager";
import {
- DashboardSquare01Icon,
Home01Icon,
- Link04Icon,
- Location01Icon,
Settings01Icon,
Upload01Icon,
- User02Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import CloudOffIcon from "@mui/icons-material/CloudOff";
import {
Box,
- CircularProgress,
Stack,
SvgIcon,
Tooltip,
- Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
@@ -32,9 +24,7 @@ import { NavbarBase } from "ente-base/components/Navbar";
import { useIsSmallWidth } from "ente-base/components/utils/hooks";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { ut } from "ente-base/i18n";
-import { thumbnailGridPadding } from "ente-new/photos/components/utils/thumbnail-grid-layout";
import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
-import { isMLSupported } from "ente-new/photos/services/ml";
import type { SidebarActionID } from "ente-new/photos/services/search/types";
import { t } from "i18next";
import {
@@ -44,58 +34,56 @@ import {
useState,
type ReactNode,
} from "react";
-
-import type { RemotePullOpts } from ".";
import {
- GalleryBarImpl,
- type GalleryBarImplProps,
- type GalleryBarPresentationProps,
-} from "./BarImpl";
+ gallerySections,
+ sectionDefinition,
+ selectRailSection,
+ type GallerySectionID,
+} from "../sections/registry";
+import {
+ activeSectionID,
+ type GalleryNavigationState,
+} from "./navigation-state";
+
+import type { GallerySectionPresentation } from "./GallerySectionLayout";
import { NavigationSlide } from "./NavigationSlide";
import { usePhotosNavigation } from "./PhotosNavigationContext";
-import type { GalleryBarMode } from "./reducer";
-import { useNavigationContentMotion } from "./use-navigation-content-motion";
-type GalleryNavigation = Omit<
- GalleryBarImplProps,
- keyof GalleryBarPresentationProps | "mode" | "onCreateAlbum"
-> & { onRemotePull: (opts?: RemotePullOpts) => Promise<void> };
-
-type PhotosNavigationShellProps = SearchBarProps & {
- onSidebar: () => void;
+interface PhotosNavigationShellProps {
onUpload: () => void;
- isMapView: boolean;
- isMapSelected: boolean;
- mode: GalleryBarMode;
-};
+ navigation: GalleryNavigationState;
+}
export interface PhotosNavigationShellHandle {
showSettings: (action?: SidebarActionID) => void;
}
export const PhotosNavigationShell: React.FC<
- React.PropsWithChildren<
- Omit<PhotosNavigationShellProps, "isSettingsOpen" | "onSidebar"> & {
- ref?: React.Ref<PhotosNavigationShellHandle>;
- isFirstLoad: boolean;
- alternateHeader: ReactNode;
- galleryNavigation: GalleryNavigation | undefined;
- collectionNameByID: Map<number, string>;
- onAuthenticateUser: () => Promise<boolean>;
- }
- >
+ PhotosNavigationShellProps & {
+ ref?: React.Ref<PhotosNavigationShellHandle>;
+ isFirstLoad: boolean;
+ children: (presentation: GallerySectionPresentation) => ReactNode;
+ collectionNameByID: Map<number, string>;
+ onAuthenticateUser: () => Promise<boolean>;
+ }
> = ({
ref,
isFirstLoad,
- alternateHeader,
- galleryNavigation,
+ navigation,
collectionNameByID,
onAuthenticateUser,
children,
...props
}) => {
- const { changeMode, showLibraryMap, selectCollection, showCleanupView } =
- usePhotosNavigation();
+ const actions = usePhotosNavigation();
+ const { showCleanupView } = actions;
+ const sectionID = activeSectionID(navigation);
+ const hasNavigation = sectionDefinition(sectionID).hasNavigation;
+ const isHome =
+ navigation.overlay?.section !== "search" &&
+ navigation.destination.section === "albums" &&
+ navigation.destination.collectionID === PseudoCollectionID.all;
+
const { show: showSidebar, props: sidebarVisibilityProps } =
useModalVisibility();
const [pendingSidebarAction, setPendingSidebarAction] =
@@ -117,12 +105,8 @@ export const PhotosNavigationShell: React.FC<
const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
const [navigationCollapsed, setNavigationCollapsed] = useState(false);
const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
- const navigationAvailable = !!galleryNavigation && !props.isInSearchMode;
+ const navigationAvailable = hasNavigation;
const panelOpen = navigationAvailable && !navigationCollapsed;
- const contentRef = useNavigationContentMotion(
- `${mobile}-${panelOpen}`,
- reduceMotion,
- );
const { show: showMobileNavigation, props: mobileDrawerProps } =
useModalVisibility();
const { onClose: closeMobileNavigation } = mobileDrawerProps;
@@ -136,67 +120,15 @@ export const PhotosNavigationShell: React.FC<
setNavigationCollapsed((collapsed) => !collapsed);
}
};
- const selectCreatedCollection = useCallback(
- (id: number) => {
- if (galleryNavigation) selectCollection(id);
- closeMobileNavigation();
- },
- [galleryNavigation, selectCollection, closeMobileNavigation],
- );
- const { show: showAlbumNameInput, props: albumNameInputVisibilityProps } =
- useModalVisibility();
- const [createInHiddenSection, setCreateInHiddenSection] = useState(false);
- const openAlbumCreation = () => {
- setCreateInHiddenSection(props.mode == "hidden-albums");
- showAlbumNameInput();
- };
+ const panelMode =
+ navigation.destination.albumMode ?? navigation.destination.section;
+ const isInSearchMode = navigation.overlay?.section === "search";
useEffect(() => {
setNavigationCollapsed(false);
- }, [props.mode, props.isInSearchMode, props.isMapSelected]);
+ }, [panelMode, isInSearchMode, navigation.destination.section]);
useEffect(() => {
if (!mobile) closeMobileNavigation();
}, [mobile, closeMobileNavigation]);
- const handleChangeMode = (mode: GalleryBarMode) => {
- if (mode == "people" && !mobile) {
- closeMobileNavigation();
- changeMode(mode);
- return;
- }
- const reopeningSection =
- mobile &&
- mode == "albums" &&
- galleryNavigation &&
- !props.isInSearchMode &&
- (props.mode == "hidden-albums" || props.mode == "archive-albums");
- if (
- galleryNavigation &&
- !props.isInSearchMode &&
- ((props.mode == mode &&
- galleryNavigation.activeCollectionID !=
- PseudoCollectionID.all) ||
- reopeningSection)
- ) {
- if (mobile) {
- if (mobileDrawerProps.open) closeMobileNavigation();
- else showMobileNavigation();
- } else {
- setNavigationCollapsed((collapsed) => !collapsed);
- }
- return;
- }
- if (!changeMode(mode)) return;
- setNavigationCollapsed(false);
- if (mobile) showMobileNavigation();
- };
- const galleryBar = galleryNavigation && (
- <GalleryBarImpl
- {...galleryNavigation}
- mode={props.mode}
- collapsed={!panelOpen}
- mobileDrawerProps={mobileDrawerProps}
- onCreateAlbum={openAlbumCreation}
- />
- );
return (
<Stack
sx={(theme) => ({
@@ -220,16 +152,14 @@ export const PhotosNavigationShell: React.FC<
borderBottom: "none",
}}
>
- {alternateHeader ?? (
- <NormalHeaderContents
- onUpload={props.onUpload}
- {...{
- navigationAvailable,
- navigationOpen,
- toggleNavigation,
- }}
- />
- )}
+ <NormalHeaderContents
+ onUpload={props.onUpload}
+ {...{
+ navigationAvailable,
+ navigationOpen,
+ toggleNavigation,
+ }}
+ />
</NavbarBase>
<Stack
direction="row"
@@ -265,94 +195,37 @@ export const PhotosNavigationShell: React.FC<
}),
})}
>
- {alternateHeader == null && (
- <NormalNavigationRail
- {...props}
- isSettingsOpen={sidebarVisibilityProps.open}
- onSidebar={() => showSettings()}
- onShowMap={() => {
- showLibraryMap();
- setNavigationCollapsed(false);
- if (mobile) showMobileNavigation();
- }}
- isHome={
- !props.isMapSelected &&
- props.mode == "albums" &&
- !props.isInSearchMode &&
- galleryNavigation?.activeCollectionID ==
- PseudoCollectionID.all
- }
- onChangeMode={handleChangeMode}
- opensDialog={mobile}
- navigationOpen={
- !props.isMapSelected &&
- !!galleryNavigation &&
- (mobile
- ? mobileDrawerProps.open
- : !navigationCollapsed)
- }
- />
- )}
+ <NormalNavigationRail
+ navigation={navigation}
+ isHome={isHome}
+ isSettingsOpen={sidebarVisibilityProps.open}
+ onSidebar={() => showSettings()}
+ mobile={mobile}
+ navigationOpen={navigationOpen}
+ onSelect={(id) =>
+ selectRailSection(sectionDefinition(id), id, {
+ navigation,
+ mobile,
+ open: () => actions.openSection(id),
+ togglePanel: toggleNavigation,
+ closeDrawer: closeMobileNavigation,
+ openPanel: () => {
+ setNavigationCollapsed(false);
+ if (mobile) showMobileNavigation();
+ },
+ })
+ }
+ />
</Box>
</NavigationSlide>
- <Stack
- sx={{
- flex: 1,
- minWidth: 0,
- minHeight: 0,
- flexDirection: { xs: "column", md: "row" },
- }}
- >
- {galleryNavigation && !props.isInSearchMode && (
- <>
- <NavigationSlide
- open={panelOpen}
- width={328}
- reduceMotion={reduceMotion}
- disabled={mobile}
- >
- {galleryBar}
- </NavigationSlide>
- <CreateAlbumDialog
- {...albumNameInputVisibilityProps}
- isHidden={createInHiddenSection}
- onRemotePull={galleryNavigation.onRemotePull}
- onSelectCollectionID={selectCreatedCollection}
- />
- </>
- )}
- <Stack
- ref={contentRef}
- sx={{ flex: 1, minWidth: 0, minHeight: 0, gap: "8px" }}
- >
- <Stack
- sx={(theme) => ({
- flex: 1,
- minWidth: 0,
- minHeight: 0,
- pt: props.isMapView
- ? 0
- : {
- xs: `${thumbnailGridPadding}px`,
- md: "36px",
- },
- px: props.isMapView ? 0 : { xs: 0, md: "12px" },
- "--mui-palette-background-default": "#FFFFFF",
- bgcolor: "background.default",
- borderRadius: "20px",
- overflow: "hidden",
- ...theme.applyStyles("dark", {
- "--mui-palette-background-default":
- "#212121",
- }),
- })}
- >
- {children}
- </Stack>
- {isFirstLoad && <FirstLoadMessage />}
- {isOffline && <OfflineMessage />}
- </Stack>
- </Stack>
+ {children({
+ collapsed: !panelOpen,
+ mobile,
+ mobileDrawerProps,
+ reduceMotion,
+ isFirstLoad,
+ isOffline,
+ })}
</Stack>
<Sidebar
{...sidebarVisibilityProps}
@@ -447,28 +320,29 @@ const NormalHeaderContents: React.FC<
);
};
-const NormalNavigationRail: React.FC<
- Omit<PhotosNavigationShellProps, "onUpload" | "isMapView"> & {
- onChangeMode: (mode: GalleryBarMode) => void;
- onShowMap: () => void;
- isHome: boolean;
- opensDialog: boolean;
- navigationOpen: boolean;
- }
-> = ({
- onSidebar,
- onShowMap,
- isMapSelected,
- mode,
- onChangeMode,
+const NormalNavigationRail = ({
+ navigation,
isHome,
- opensDialog,
+ isSettingsOpen,
+ onSidebar,
+ mobile,
navigationOpen,
- ...props
+ onSelect,
+}: {
+ navigation: GalleryNavigationState;
+ isHome: boolean;
+ isSettingsOpen: boolean;
+ onSidebar: () => void;
+ mobile: boolean;
+ navigationOpen: boolean;
+ onSelect: (id: GallerySectionID) => void;
}) => (
<>
<HomeButton selected={isHome} />
- <SearchBar {...props} />
+ <SearchBar
+ isInSearchMode={navigation.overlay?.section === "search"}
+ isSettingsOpen={isSettingsOpen}
+ />
<Box
aria-hidden
sx={(theme) => ({
@@ -480,23 +354,24 @@ const NormalNavigationRail: React.FC<
...theme.applyStyles("dark", { bgcolor: "#3E3E3E" }),
})}
/>
- {(["albums", "people", "links"] as const).map((item) =>
- item == "people" && !isMLSupported ? null : (
- <Tooltip key={item} title={t(item)}>
+ {(Object.keys(gallerySections) as GallerySectionID[]).map((id) => {
+ const definition = sectionDefinition(id);
+ const rail = definition.rail;
+ if (!rail || (rail.available && !rail.available())) return null;
+ const selected = rail.selected
+ ? rail.selected(navigation, navigationOpen)
+ : navigationOpen &&
+ !isHome &&
+ navigation.overlay?.section !== "search" &&
+ navigation.destination.section === id;
+ return (
+ <Tooltip key={id} title={rail.label()}>
<FocusVisibleButton
color="secondary"
- aria-label={t(item)}
- aria-pressed={
- navigationOpen &&
- !isHome &&
- !props.isInSearchMode &&
- (mode == item ||
- (item == "albums" &&
- (mode == "hidden-albums" ||
- mode == "archive-albums")))
- }
- aria-haspopup={opensDialog ? "dialog" : undefined}
- onClick={() => onChangeMode(item)}
+ aria-label={rail.label()}
+ aria-pressed={selected}
+ aria-haspopup={mobile ? "dialog" : undefined}
+ onClick={() => onSelect(id)}
sx={{
minWidth: 0,
width: 38,
@@ -513,48 +388,14 @@ const NormalNavigationRail: React.FC<
}}
>
<HugeiconsIcon
- icon={
- item == "albums"
- ? DashboardSquare01Icon
- : item == "links"
- ? Link04Icon
- : User02Icon
- }
+ icon={rail.icon}
size={20}
strokeWidth={1.8}
/>
</FocusVisibleButton>
</Tooltip>
- ),
- )}
- <Tooltip title={t("map")}>
- <FocusVisibleButton
- color="secondary"
- aria-label={t("map")}
- aria-pressed={isMapSelected}
- onClick={onShowMap}
- sx={{
- minWidth: 0,
- width: 38,
- height: 38,
- flexShrink: 0,
- p: 0,
- borderRadius: "12px",
- color: "text.base",
- '&[aria-pressed="true"]': {
- color: "#FFFFFF",
- bgcolor: "accent.main",
- "&:hover": { bgcolor: "accent.main" },
- },
- }}
- >
- <HugeiconsIcon
- icon={Location01Icon}
- size={20}
- strokeWidth={1.8}
- />
- </FocusVisibleButton>
- </Tooltip>
+ );
+ })}
<Box sx={{ flex: 1 }} />
<Tooltip title={t("settings")}>
<FocusVisibleButton
@@ -662,50 +503,3 @@ const UploadButton: React.FC<ButtonishProps> = ({ onClick }) => {
</>
);
};
-
-const GalleryStatusMessage: React.FC<
- React.PropsWithChildren<{ icon: ReactNode }>
-> = ({ icon, children }) => (
- <Stack
- direction="row"
- role="status"
- sx={{
- flexShrink: 0,
- alignItems: "center",
- justifyContent: "center",
- gap: 1.25,
- px: 1,
- py: 1.25,
- color: "text.muted",
- opacity: 0.65,
- }}
- >
- {icon}
- <Typography variant="small" sx={{ textAlign: "center" }}>
- {children}
- </Typography>
- </Stack>
-);
-
-const FirstLoadMessage: React.FC = () => (
- <GalleryStatusMessage
- icon={
- <CircularProgress
- size={12}
- thickness={5}
- color="inherit"
- aria-hidden
- />
- }
- >
- {t("initial_load_delay_warning")}
- </GalleryStatusMessage>
-);
-
-const OfflineMessage: React.FC = () => (
- <GalleryStatusMessage
- icon={<CloudOffIcon sx={{ fontSize: 16 }} aria-hidden />}
- >
- {t("offline_message")}
- </GalleryStatusMessage>
-);
diff --git a/web/apps/photos/src/components/gallery/navigation/navigation-state.ts b/web/apps/photos/src/components/gallery/navigation/navigation-state.ts
new file mode 100644
index 0000000000..e02e489846
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/navigation/navigation-state.ts
@@ -0,0 +1,200 @@
+import type { AlbumFilter } from "@/utils/album-filters";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import type { SearchSuggestion } from "ente-new/photos/services/search/types";
+import type { GalleryState } from "../reducer";
+import type { PlaceSelection } from "../sections/places/PlacesList";
+import type { GallerySectionID } from "../sections/registry";
+
+export interface GalleryDestination {
+ section: GallerySectionID;
+ albumMode?: "albums" | "hidden-albums" | "archive-albums";
+ collectionID?: number;
+ albumFilter?: AlbumFilter;
+ personID?: string;
+ extraVisiblePersonID?: string;
+ collectionMap?: boolean;
+}
+
+export interface GalleryNavigationState {
+ destination: GalleryDestination;
+ overlay?: {
+ section: "search" | "duplicates" | "large-files";
+ suggestion?: SearchSuggestion;
+ searchRevision?: number;
+ };
+ selectedPlace?: PlaceSelection;
+ placeSelectionRevision: number;
+}
+
+export const homeDestination: GalleryDestination = {
+ section: "albums",
+ albumMode: "albums",
+ collectionID: PseudoCollectionID.all,
+};
+export const initialNavigationState: GalleryNavigationState = {
+ destination: homeDestination,
+ placeSelectionRevision: 0,
+};
+
+export type NavigationAction =
+ | { type: "openSection"; section: GallerySectionID }
+ | { type: "showCleanup"; section: "duplicates" | "large-files" }
+ | { type: "dismissCleanup" }
+ | { type: "resolveDestination"; destination: GalleryDestination }
+ | { type: "showAll" }
+ | { type: "showHidden" }
+ | { type: "showAlbumOverview"; albumFilter: AlbumFilter }
+ | { type: "showLinks"; collectionID?: number }
+ | { type: "selectLink"; collectionID: number }
+ | { type: "showAlbums" }
+ | {
+ type: "showCollectionSummary";
+ collectionSummaryID: number | undefined;
+ library: GalleryState;
+ }
+ | { type: "showPeople" }
+ | { type: "showPerson"; personID: string }
+ | {
+ type: "retainPerson";
+ personID: string | undefined;
+ extraVisiblePersonID: string | undefined;
+ }
+ | { type: "enterSearchMode"; searchSuggestion?: SearchSuggestion }
+ | { type: "exitSearch"; shouldExitSearchMode?: boolean }
+ | { type: "showMap" }
+ | { type: "closeMap" }
+ | {
+ type: "selectPlace";
+ place: PlaceSelection | undefined;
+ revise?: boolean;
+ };
+
+export const navigationReducer = (
+ state: GalleryNavigationState,
+ action: NavigationAction,
+): GalleryNavigationState => {
+ const destination = state.destination;
+ const navigate = (next: GalleryDestination): GalleryNavigationState => ({
+ ...state,
+ destination: next,
+ overlay: undefined,
+ });
+ switch (action.type) {
+ case "openSection":
+ return navigate({ section: action.section });
+ case "showCleanup":
+ return { ...state, overlay: { section: action.section } };
+ case "dismissCleanup":
+ return state.overlay && state.overlay.section !== "search"
+ ? { ...state, overlay: undefined }
+ : state;
+ case "resolveDestination":
+ return { ...state, destination: action.destination };
+ case "showAll":
+ return navigate(homeDestination);
+ case "showHidden":
+ return navigate({
+ section: "albums",
+ albumMode: "hidden-albums",
+ collectionID: PseudoCollectionID.hiddenItems,
+ });
+ case "showAlbumOverview":
+ return navigate({
+ section: "albums",
+ albumFilter: action.albumFilter,
+ });
+ case "showLinks":
+ case "selectLink":
+ return navigate({
+ section: "links",
+ collectionID: action.collectionID,
+ });
+ case "showAlbums":
+ return navigate(homeDestination);
+ case "showCollectionSummary": {
+ const id = action.collectionSummaryID ?? PseudoCollectionID.all;
+ const mode = action.library.hiddenCollectionSummaries.has(id)
+ ? "hidden-albums"
+ : action.library.archivedCollectionSummaries.has(id) &&
+ (destination.albumMode === "archive-albums" ||
+ id === PseudoCollectionID.archiveItems)
+ ? "archive-albums"
+ : "albums";
+ return navigate({
+ section: "albums",
+ albumMode: mode,
+ collectionID: id,
+ });
+ }
+ case "showPeople":
+ return navigate({ section: "people" });
+ case "showPerson":
+ return navigate({
+ section: "people",
+ personID: action.personID,
+ extraVisiblePersonID: destination.extraVisiblePersonID,
+ });
+ case "retainPerson":
+ return destination.section !== "people" ||
+ (destination.personID === action.personID &&
+ destination.extraVisiblePersonID ===
+ action.extraVisiblePersonID)
+ ? state
+ : {
+ ...state,
+ destination: {
+ ...destination,
+ personID: action.personID,
+ extraVisiblePersonID: action.extraVisiblePersonID,
+ },
+ };
+ case "enterSearchMode":
+ return {
+ ...state,
+ overlay: {
+ section: "search",
+ suggestion: action.searchSuggestion,
+ searchRevision: (state.overlay?.searchRevision ?? 0) + 1,
+ },
+ };
+ case "exitSearch":
+ return state.overlay?.section !== "search"
+ ? state
+ : {
+ ...state,
+ overlay:
+ action.shouldExitSearchMode === false
+ ? { section: "search" }
+ : undefined,
+ };
+ case "showMap":
+ return {
+ ...state,
+ destination:
+ destination.collectionID === PseudoCollectionID.all
+ ? { ...homeDestination, section: "places" }
+ : { ...destination, collectionMap: true },
+ };
+ case "closeMap":
+ return destination.section === "places"
+ ? { ...state, destination: homeDestination }
+ : destination.collectionMap
+ ? {
+ ...state,
+ destination: { ...destination, collectionMap: false },
+ }
+ : state;
+ case "selectPlace":
+ return {
+ ...state,
+ selectedPlace: action.place,
+ placeSelectionRevision:
+ state.placeSelectionRevision +
+ (action.revise === false ? 0 : 1),
+ };
+ }
+};
+
+export const activeSectionID = (
+ state: GalleryNavigationState,
+): GallerySectionID => state.overlay?.section ?? state.destination.section;
diff --git a/web/apps/photos/src/components/gallery/navigation/use-gallery-navigation.ts b/web/apps/photos/src/components/gallery/navigation/use-gallery-navigation.ts
new file mode 100644
index 0000000000..260387c616
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/navigation/use-gallery-navigation.ts
@@ -0,0 +1,200 @@
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import type { SidebarActionID } from "ente-new/photos/services/search/types";
+import { useRouter } from "next/router";
+import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
+import type { useGalleryLibrary } from "../hooks/use-gallery-library";
+import { useGalleryPreferences } from "../hooks/use-gallery-preferences";
+import type { GalleryBarMode } from "../reducer";
+import { useAlbumActions } from "../sections/albums/use-album-actions";
+import { usePeopleEntry } from "../sections/people/use-people-entry";
+import { useMapEntry } from "../sections/places/use-map-entry";
+import { sectionDefinition, type GallerySectionID } from "../sections/registry";
+import { useSearchNavigation } from "../sections/search/use-search-navigation";
+import type { PhotosNavigationActions } from "./PhotosNavigationContext";
+import type { PhotosNavigationShellHandle } from "./PhotosNavigationShell";
+import {
+ activeSectionID,
+ initialNavigationState,
+ navigationReducer,
+} from "./navigation-state";
+
+export const useGalleryNavigation = (
+ libraryOwner: ReturnType<typeof useGalleryLibrary>,
+ authenticateUser: () => Promise<boolean>,
+) => {
+ const [state, send] = useReducer(navigationReducer, initialNavigationState);
+ const {
+ state: library,
+ remoteFilesPull,
+ joinedCollectionID,
+ } = libraryOwner;
+ const navigationRef = useRef<PhotosNavigationShellHandle>(null);
+ const { destination } = state;
+ const sectionID = activeSectionID(state);
+ const barMode: GalleryBarMode =
+ destination.section === "people" || destination.section === "links"
+ ? destination.section
+ : (destination.albumMode ?? "albums");
+ const activeCollectionID =
+ destination.section === "albums" || destination.section === "places"
+ ? destination.collectionID
+ : undefined;
+ const preferences = useGalleryPreferences({
+ barMode,
+ activeCollectionID,
+ navigationAvailable: sectionDefinition(sectionID).hasNavigation,
+ });
+ const albums = useAlbumActions({
+ library,
+ navigation: state,
+ send,
+ preferences,
+ authenticateUser,
+ remoteFilesPull,
+ });
+ const { goHome, showAlbumOverview } = albums;
+ const showSettings = useCallback(
+ (action?: SidebarActionID) =>
+ navigationRef.current?.showSettings(action),
+ [],
+ );
+ const selectSearchOption = useSearchNavigation({
+ library,
+ navigation: state,
+ send,
+ showCollectionSummary: albums.showCollectionSummary,
+ showSettings,
+ });
+ const onPeople = useCallback(() => send({ type: "showPeople" }), []);
+ const { showPeople, dialogProps: peopleConsentDialogProps } =
+ usePeopleEntry({
+ isCurrentDestination: destination.section === "people",
+ onUnavailable: goHome,
+ onNavigate: onPeople,
+ });
+ const openMap = useCallback(() => send({ type: "showMap" }), []);
+ const showCollectionMap = useMapEntry(openMap);
+ const showLibraryMap = useCallback(() => {
+ send({ type: "selectPlace", place: undefined, revise: false });
+ goHome();
+ showCollectionMap();
+ }, [goHome, showCollectionMap]);
+ const showLinksOverview = useCallback(() => {
+ send({ type: "showLinks" });
+ return true;
+ }, []);
+ const changeMode = useCallback(
+ (mode: GalleryBarMode) => {
+ if (mode === "people") return showPeople();
+ if (mode === "links") return showLinksOverview();
+ showAlbumOverview("ente");
+ return true;
+ },
+ [showAlbumOverview, showLinksOverview, showPeople],
+ );
+ const selectPerson = useCallback(
+ (personID: string) => send({ type: "showPerson", personID }),
+ [],
+ );
+ const retainPerson = useCallback(
+ (
+ personID: string | undefined,
+ extraVisiblePersonID: string | undefined,
+ ) => send({ type: "retainPerson", personID, extraVisiblePersonID }),
+ [],
+ );
+ const backToPeople = useCallback(() => {
+ send({ type: "showPeople" });
+ }, []);
+ const selectPlace = useCallback<PhotosNavigationActions["selectPlace"]>(
+ (place) => send({ type: "selectPlace", place }),
+ [],
+ );
+ const showCleanupView = useCallback<
+ PhotosNavigationActions["showCleanupView"]
+ >((section) => {
+ send({ type: "closeMap" });
+ send({ type: "showCleanup", section });
+ }, []);
+ const actions = useMemo<PhotosNavigationActions>(() => {
+ const actions: PhotosNavigationActions = {
+ ...albums,
+ changeMode,
+ showPeople,
+ selectPerson,
+ backToPeople,
+ showLinksOverview,
+ showLibraryMap,
+ showCollectionMap,
+ selectPlace,
+ selectSearchOption,
+ showCleanupView,
+ openSection: (id: GallerySectionID) => {
+ const enter = sectionDefinition(id).enter;
+ if (enter) return enter(actions);
+ send({ type: "openSection", section: id });
+ return true;
+ },
+ };
+ return actions;
+ }, [
+ albums,
+ changeMode,
+ showPeople,
+ selectPerson,
+ backToPeople,
+ showLinksOverview,
+ showLibraryMap,
+ showCollectionMap,
+ selectPlace,
+ selectSearchOption,
+ showCleanupView,
+ ]);
+ useEffect(() => {
+ const resolve = sectionDefinition(destination.section).resolve;
+ const resolved = resolve?.(library, destination);
+ if (resolved && resolved !== destination)
+ send({ type: "resolveDestination", destination: resolved });
+ }, [library, destination]);
+ const handledJoin = useRef<number | undefined>(undefined);
+ useEffect(() => {
+ if (
+ joinedCollectionID !== undefined &&
+ joinedCollectionID !== handledJoin.current
+ ) {
+ handledJoin.current = joinedCollectionID;
+ send({
+ type: "showCollectionSummary",
+ collectionSummaryID: joinedCollectionID,
+ library,
+ });
+ }
+ }, [joinedCollectionID, library]);
+ const router = useRouter();
+ const overview = destination.albumFilter !== undefined;
+ useEffect(() => {
+ if (
+ !library.user ||
+ (!overview && activeCollectionID === undefined) ||
+ !router.isReady
+ )
+ return;
+ const query =
+ !overview && activeCollectionID !== PseudoCollectionID.all
+ ? `?collection=${activeCollectionID}`
+ : "";
+ const href = `/gallery${query}`;
+ if (router.asPath !== href)
+ void router.push(href, undefined, { shallow: true });
+ }, [activeCollectionID, overview, router, library.user]);
+ return {
+ state,
+ sectionID,
+ preferences,
+ actions,
+ navigationRef,
+ peopleConsentDialogProps,
+ showSettings,
+ retainPerson,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/use-navigation-content-motion.ts b/web/apps/photos/src/components/gallery/navigation/use-navigation-content-motion.ts
similarity index 100%
rename from web/apps/photos/src/components/gallery/use-navigation-content-motion.ts
rename to web/apps/photos/src/components/gallery/navigation/use-navigation-content-motion.ts
diff --git a/web/apps/photos/src/components/gallery/reducer.ts b/web/apps/photos/src/components/gallery/reducer.ts
index 1f3d373fd7..f122f2211b 100644
--- a/web/apps/photos/src/components/gallery/reducer.ts
+++ b/web/apps/photos/src/components/gallery/reducer.ts
@@ -1,4 +1,3 @@
-import type { AlbumFilter } from "@/utils/album-filters";
import type { LocalUser } from "ente-accounts/services/user";
import {
groupFilesByCollectionID,
@@ -11,7 +10,7 @@ import {
findUserUncategorizedCollection,
type Collection,
} from "ente-media/collection";
-import { sortCollectionFiles, sortFiles } from "ente-media/collection-sort";
+import { sortFiles } from "ente-media/collection-sort";
import type { EnteFile } from "ente-media/file";
import {
isArchivedFile,
@@ -33,8 +32,7 @@ import {
type CollectionSummaryAttribute,
type CollectionSummaryType,
} from "ente-new/photos/services/collection-summary";
-import type { PeopleState, Person } from "ente-new/photos/services/ml/people";
-import type { SearchSuggestion } from "ente-new/photos/services/search/types";
+import type { PeopleState } from "ente-new/photos/services/ml/people";
import { sortTrashItems, type TrashItem } from "ente-new/photos/services/trash";
import type {
FamilyData,
@@ -44,30 +42,11 @@ import { splitByPredicate } from "ente-utils/array";
import { includes } from "ente-utils/type-guards";
import { t } from "i18next";
import React, { useReducer } from "react";
-import { visibleQuickLinks } from "../../utils/quick-links";
-// TODO: Deprecated(?). Use GalleryView instead. Deprecated if it can be used in
-// all cases where the bar mode was in use.
export type GalleryBarMode =
"albums" | "hidden-albums" | "archive-albums" | "people" | "links";
-type GalleryView =
- | { type: "links"; selectedLinkID: number | undefined }
- | { type: "album-overview"; albumFilter: AlbumFilter }
- | {
- type: "albums" | "hidden-albums" | "archive-albums";
- activeCollectionSummaryID: number;
- activeCollection: Collection | undefined;
- activeCollectionSummary: CollectionSummary;
- }
- | {
- type: "people";
- visiblePeople: Person[];
- people: Person[];
- activePerson: Person | undefined;
- };
-
-interface GalleryState {
+export interface GalleryState {
user: LocalUser | undefined;
familyData: FamilyData | undefined;
@@ -108,23 +87,9 @@ interface GalleryState {
number,
MagicMetadata<FilePrivateMagicMetadataData>
>;
-
- selectedCollectionSummaryID: number | undefined;
- selectedPersonID: string | undefined;
- extraVisiblePerson: Person | undefined;
- searchSuggestion: SearchSuggestion | undefined;
- searchResults: EnteFile[] | undefined;
- isRecomputingSearchResults: boolean;
- pendingSearchSuggestions: SearchSuggestion[];
-
- view: GalleryView | undefined;
- isInSearchMode: boolean;
- // Undefined preserves relevance order; booleans request time sorting.
- searchSortAsc: boolean | undefined;
- filteredFiles: EnteFile[];
}
-type GalleryAction =
+export type GalleryAction =
| {
type: "mount";
user: LocalUser;
@@ -153,21 +118,7 @@ type GalleryAction =
fileID: number;
privateMagicMetadata: MagicMetadata<FilePrivateMagicMetadataData>;
}
- | { type: "clearUnsyncedState" }
- | { type: "showAll" }
- | { type: "showHidden" }
- | { type: "showAlbumOverview"; albumFilter: AlbumFilter }
- | { type: "showLinks"; collectionID?: number }
- | { type: "selectLink"; collectionID: number }
- | { type: "showAlbums" }
- | { type: "showCollectionSummary"; collectionSummaryID: number | undefined }
- | { type: "showPeople" }
- | { type: "showPerson"; personID: string }
- | { type: "enterSearchMode"; searchSuggestion?: SearchSuggestion }
- | { type: "updatingSearchResults" }
- | { type: "setSearchResults"; searchResults: EnteFile[] }
- | { type: "exitSearch"; shouldExitSearchMode?: boolean }
- | { type: "setSearchSortOrder"; asc: boolean | undefined };
+ | { type: "clearUnsyncedState" };
export const initialGalleryState: GalleryState = {
user: undefined,
@@ -198,17 +149,6 @@ export const initialGalleryState: GalleryState = {
unsyncedFavoriteUpdates: new Map(),
pendingVisibilityUpdates: new Set(),
unsyncedPrivateMagicMetadataUpdates: new Map(),
- selectedCollectionSummaryID: undefined,
- selectedPersonID: undefined,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view: undefined,
- filteredFiles: [],
- isInSearchMode: false,
- searchSortAsc: undefined,
};
export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
@@ -262,16 +202,7 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
hiddenFileIDs,
);
- const view = {
- type: "albums" as const,
- activeCollectionSummaryID: PseudoCollectionID.all,
- activeCollection: undefined,
- activeCollectionSummary: normalCollectionSummaries.get(
- PseudoCollectionID.all,
- )!,
- };
-
- return stateByUpdatingFilteredFiles({
+ return {
...state,
user,
familyData,
@@ -312,8 +243,7 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
normalCollections,
user.id,
),
- view,
- });
+ };
}
case "setUserDetails": {
@@ -378,34 +308,7 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
hiddenFileIDs,
);
- let view = state.view;
- let selectedCollectionSummaryID = state.selectedCollectionSummaryID;
- if (state.view?.type == "albums") {
- ({ view, selectedCollectionSummaryID } =
- deriveAlbumsViewAndSelectedID(
- collections,
- hiddenCollectionIDs,
- normalCollectionSummaries,
- selectedCollectionSummaryID,
- ));
- } else if (state.view?.type == "hidden-albums") {
- ({ view, selectedCollectionSummaryID } =
- deriveHiddenAlbumsViewAndSelectedID(
- collections,
- hiddenCollectionIDs,
- hiddenCollectionSummaries,
- selectedCollectionSummaryID,
- ));
- } else if (state.view?.type == "archive-albums") {
- ({ view, selectedCollectionSummaryID } =
- deriveArchiveAlbumsViewAndSelectedID(
- collections,
- archivedCollectionSummaries,
- selectedCollectionSummaryID,
- ));
- }
-
- return stateByUpdatingFilteredFiles({
+ return {
...state,
collections,
hiddenCollectionIDs,
@@ -442,26 +345,18 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
normalCollections,
state.user!.id,
),
- selectedCollectionSummaryID,
- pendingSearchSuggestions:
- enqueuePendingSearchSuggestionsIfNeeded(
- state.searchSuggestion,
- state.pendingSearchSuggestions,
- state.isInSearchMode,
- ),
- view,
- });
+ };
}
case "setCollectionFiles": {
const lastSyncedCollectionFiles = sortFiles(action.collectionFiles);
const collectionFiles = lastSyncedCollectionFiles;
- return stateByUpdatingFilteredFiles({
+ return {
...stateForUpdatedCollectionFiles(state, collectionFiles),
lastSyncedCollectionFiles,
unsyncedPrivateMagicMetadataUpdates: new Map(),
- });
+ };
}
case "uploadFile": {
@@ -476,16 +371,16 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
state.unsyncedPrivateMagicMetadataUpdates,
);
- return stateByUpdatingFilteredFiles({
+ return {
...stateForUpdatedCollectionFiles(state, collectionFiles),
lastSyncedCollectionFiles,
- });
+ };
}
case "setTrashItems": {
const trashItems = sortTrashItems(action.trashItems);
- return stateByUpdatingFilteredFiles({
+ return {
...state,
trashItems,
normalCollectionSummaries: deriveNormalCollectionSummaries(
@@ -498,61 +393,37 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
state.hiddenFileIDs,
state.archivedFileIDs,
),
- });
+ };
}
- case "setPeopleState": {
- const peopleState = action.peopleState;
-
- if (state.view?.type != "people") return { ...state, peopleState };
-
- const { view, extraVisiblePerson } = derivePeopleView(
- peopleState,
- state.tempDeletedFileIDs,
- state.tempHiddenFileIDs,
- state.selectedPersonID,
- state.extraVisiblePerson,
- );
- return stateByUpdatingFilteredFiles({
- ...state,
- peopleState,
- selectedPersonID: view.activePerson?.id,
- extraVisiblePerson,
- view,
- });
- }
+ case "setPeopleState":
+ return { ...state, peopleState: action.peopleState };
case "markTempDeleted":
- return stateByUpdatingFilteredFiles({
+ return {
...state,
tempDeletedFileIDs: new Set(
[...state.tempDeletedFileIDs].concat(
action.files.map((f) => f.id),
),
),
- });
+ };
case "clearTempDeleted":
- return stateByUpdatingFilteredFiles({
- ...state,
- tempDeletedFileIDs: new Set(),
- });
+ return { ...state, tempDeletedFileIDs: new Set() };
case "markTempHidden":
- return stateByUpdatingFilteredFiles({
+ return {
...state,
tempHiddenFileIDs: new Set(
[...state.tempHiddenFileIDs].concat(
action.files.map((f) => f.id),
),
),
- });
+ };
case "clearTempHidden":
- return stateByUpdatingFilteredFiles({
- ...state,
- tempHiddenFileIDs: new Set(),
- });
+ return { ...state, tempHiddenFileIDs: new Set() };
case "addPendingFavoriteUpdate": {
const pendingFavoriteUpdates = new Set(
@@ -630,10 +501,10 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
unsyncedPrivateMagicMetadataUpdates,
);
- return stateByUpdatingFilteredFiles({
+ return {
...stateForUpdatedCollectionFiles(state, collectionFiles),
unsyncedPrivateMagicMetadataUpdates,
- });
+ };
}
case "clearUnsyncedState": {
@@ -663,7 +534,7 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
const unsyncedPrivateMagicMetadataUpdates: GalleryState["unsyncedPrivateMagicMetadataUpdates"] =
new Map();
- return stateByUpdatingFilteredFiles({
+ return {
...stateForUpdatedCollectionFiles(
{
...state,
@@ -678,260 +549,8 @@ export const galleryReducer: React.Reducer<GalleryState, GalleryAction> = (
collectionFiles,
),
unsyncedPrivateMagicMetadataUpdates,
- });
- }
-
- case "showAll":
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID: undefined,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view: {
- type: "albums",
- activeCollectionSummaryID: PseudoCollectionID.all,
- activeCollection: undefined,
- activeCollectionSummary:
- state.normalCollectionSummaries.get(
- PseudoCollectionID.all,
- )!,
- },
- isInSearchMode: false,
- });
-
- case "showHidden":
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID: undefined,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view: {
- type: "hidden-albums",
- activeCollectionSummaryID: PseudoCollectionID.hiddenItems,
- activeCollection: undefined,
- activeCollectionSummary:
- state.hiddenCollectionSummaries.get(
- PseudoCollectionID.hiddenItems,
- )!,
- },
- isInSearchMode: false,
- });
-
- case "showLinks":
- case "selectLink":
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID: undefined,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- isInSearchMode: false,
- view: { type: "links", selectedLinkID: action.collectionID },
- });
-
- case "showAlbumOverview":
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID: undefined,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view: {
- type: "album-overview",
- albumFilter: action.albumFilter,
- },
- isInSearchMode: false,
- });
-
- case "showAlbums": {
- const { view, selectedCollectionSummaryID } =
- deriveAlbumsViewAndSelectedID(
- state.collections,
- state.hiddenCollectionIDs,
- state.normalCollectionSummaries,
- state.selectedCollectionSummaryID,
- );
-
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID,
- extraVisiblePerson: undefined,
- searchSuggestion: undefined,
- searchResults: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view,
- isInSearchMode: false,
- });
- }
-
- case "showCollectionSummary": {
- const selectedCollectionSummaryID = action.collectionSummaryID;
- const activeCollection = state.collections.find(
- ({ id }) => id == selectedCollectionSummaryID,
- );
-
- let view: GalleryState["view"];
- if (
- selectedCollectionSummaryID !== undefined &&
- state.hiddenCollectionSummaries.has(selectedCollectionSummaryID)
- ) {
- const activeCollectionSummaryID = selectedCollectionSummaryID;
- view = {
- type: "hidden-albums",
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary:
- state.hiddenCollectionSummaries.get(
- activeCollectionSummaryID,
- )!,
- };
- } else if (
- selectedCollectionSummaryID !== undefined &&
- state.archivedCollectionSummaries.has(
- selectedCollectionSummaryID,
- ) &&
- (state.view?.type == "archive-albums" ||
- selectedCollectionSummaryID ==
- PseudoCollectionID.archiveItems)
- ) {
- const activeCollectionSummaryID = selectedCollectionSummaryID;
- view = {
- type: "archive-albums",
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary:
- state.archivedCollectionSummaries.get(
- activeCollectionSummaryID,
- )!,
- };
- } else {
- const activeCollectionSummaryID =
- selectedCollectionSummaryID ?? PseudoCollectionID.all;
- view = {
- type: "albums",
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary:
- state.normalCollectionSummaries.get(
- activeCollectionSummaryID,
- )!,
- };
- }
-
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedCollectionSummaryID,
- extraVisiblePerson: undefined,
- searchResults: undefined,
- searchSuggestion: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view,
- isInSearchMode: false,
- });
- }
-
- case "showPeople": {
- const { view, extraVisiblePerson } = derivePeopleView(
- state.peopleState,
- state.tempDeletedFileIDs,
- state.tempHiddenFileIDs,
- undefined,
- undefined,
- );
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedPersonID: view.activePerson?.id,
- extraVisiblePerson,
- searchResults: undefined,
- searchSuggestion: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view,
- isInSearchMode: false,
- });
- }
-
- case "showPerson": {
- const { view, extraVisiblePerson } = derivePeopleView(
- state.peopleState,
- state.tempDeletedFileIDs,
- state.tempHiddenFileIDs,
- action.personID,
- state.extraVisiblePerson,
- );
- return stateByUpdatingFilteredFiles({
- ...state,
- selectedPersonID: view.activePerson?.id,
- extraVisiblePerson,
- searchResults: undefined,
- searchSuggestion: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- view,
- isInSearchMode: false,
- });
- }
-
- case "enterSearchMode": {
- const pendingSearchSuggestions = action.searchSuggestion
- ? [...state.pendingSearchSuggestions, action.searchSuggestion]
- : state.pendingSearchSuggestions;
-
- return stateByUpdatingFilteredFiles({
- ...state,
- isInSearchMode: true,
- searchSuggestion: action.searchSuggestion,
- pendingSearchSuggestions,
- });
- }
-
- case "updatingSearchResults":
- return stateByUpdatingFilteredFiles({
- ...state,
- isRecomputingSearchResults: true,
- pendingSearchSuggestions: [],
- });
-
- case "setSearchResults":
- if (!state.isRecomputingSearchResults) return state;
-
- return stateByUpdatingFilteredFiles({
- ...state,
- searchResults: action.searchResults,
- isRecomputingSearchResults: false,
- });
-
- case "exitSearch": {
- const shouldExitSearchMode = action.shouldExitSearchMode ?? true;
- return stateByUpdatingFilteredFiles({
- ...state,
- searchResults: undefined,
- searchSuggestion: undefined,
- isRecomputingSearchResults: false,
- pendingSearchSuggestions: [],
- isInSearchMode: shouldExitSearchMode
- ? false
- : state.isInSearchMode,
- });
+ };
}
-
- case "setSearchSortOrder":
- return stateByUpdatingFilteredFiles({
- ...state,
- searchSortAsc: action.asc,
- });
}
};
@@ -1455,160 +1074,6 @@ const findCoverFiles = (
return coverFiles;
};
-const deriveAlbumsViewAndSelectedID = (
- collections: GalleryState["collections"],
- hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],
- collectionSummaries: GalleryState["normalCollectionSummaries"],
- selectedCollectionSummaryID: GalleryState["selectedCollectionSummaryID"],
-) => {
- const candidateCollectionSummary = selectedCollectionSummaryID
- ? collectionSummaries.get(selectedCollectionSummaryID)
- : undefined;
- const selectedCollectionSummary =
- candidateCollectionSummary &&
- !candidateCollectionSummary.attributes.has("archiveItems") &&
- !candidateCollectionSummary.attributes.has("archived")
- ? candidateCollectionSummary
- : undefined;
-
- const activeCollectionSummaryID =
- selectedCollectionSummary?.id ?? PseudoCollectionID.all;
- const activeCollectionSummary = collectionSummaries.get(
- activeCollectionSummaryID,
- )!;
- const activeCollection =
- selectedCollectionSummary &&
- !hiddenCollectionIDs.has(activeCollectionSummaryID)
- ? collections.find(({ id }) => id == activeCollectionSummaryID)
- : undefined;
- return {
- selectedCollectionSummaryID: activeCollectionSummaryID,
- view: {
- type: "albums" as const,
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary,
- },
- };
-};
-
-const deriveHiddenAlbumsViewAndSelectedID = (
- collections: GalleryState["collections"],
- hiddenCollectionIDs: GalleryState["hiddenCollectionIDs"],
- hiddenCollectionSummaries: GalleryState["hiddenCollectionSummaries"],
- selectedCollectionSummaryID: GalleryState["selectedCollectionSummaryID"],
-) => {
- const selectedCollectionSummary = selectedCollectionSummaryID
- ? hiddenCollectionSummaries.get(selectedCollectionSummaryID)
- : undefined;
-
- const activeCollectionSummaryID =
- selectedCollectionSummary?.id ?? PseudoCollectionID.hiddenItems;
- const activeCollectionSummary = hiddenCollectionSummaries.get(
- activeCollectionSummaryID,
- )!;
- const activeCollection =
- selectedCollectionSummary &&
- hiddenCollectionIDs.has(activeCollectionSummaryID)
- ? collections.find(({ id }) => id == activeCollectionSummaryID)
- : undefined;
- return {
- selectedCollectionSummaryID: activeCollectionSummaryID,
- view: {
- type: "hidden-albums" as const,
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary,
- },
- };
-};
-
-const deriveArchiveAlbumsViewAndSelectedID = (
- collections: GalleryState["collections"],
- archivedCollectionSummaries: GalleryState["archivedCollectionSummaries"],
- selectedCollectionSummaryID: GalleryState["selectedCollectionSummaryID"],
-) => {
- const selectedCollectionSummary = selectedCollectionSummaryID
- ? archivedCollectionSummaries.get(selectedCollectionSummaryID)
- : undefined;
-
- const activeCollectionSummaryID =
- selectedCollectionSummary?.id ?? PseudoCollectionID.archiveItems;
- const activeCollectionSummary = archivedCollectionSummaries.get(
- activeCollectionSummaryID,
- )!;
- const activeCollection =
- selectedCollectionSummary &&
- activeCollectionSummaryID != PseudoCollectionID.archiveItems
- ? collections.find(({ id }) => id == activeCollectionSummaryID)
- : undefined;
- return {
- selectedCollectionSummaryID: activeCollectionSummaryID,
- view: {
- type: "archive-albums" as const,
- activeCollectionSummaryID,
- activeCollection,
- activeCollectionSummary,
- },
- };
-};
-
-const derivePeopleView = (
- peopleState: GalleryState["peopleState"],
- tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],
- tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],
- selectedPersonID: GalleryState["selectedPersonID"],
- extraVisiblePerson: GalleryState["extraVisiblePerson"],
-): {
- view: Extract<GalleryView, { type: "people" }>;
- extraVisiblePerson: GalleryState["extraVisiblePerson"];
-} => {
- let people = peopleState?.people ?? [];
- let visiblePeople = peopleState?.visiblePeople ?? [];
- if (tempDeletedFileIDs.size + tempHiddenFileIDs.size > 0) {
- const filterTemp = (ps: Person[]) =>
- ps
- .map((p) => ({
- ...p,
- fileIDs: p.fileIDs.filter(
- (id) =>
- !tempDeletedFileIDs.has(id) &&
- !tempHiddenFileIDs.has(id),
- ),
- }))
- .filter((p) => p.fileIDs.length > 0);
- people = filterTemp(people);
- visiblePeople = filterTemp(visiblePeople);
- }
-
- // Keep a selected small cluster visible until the user leaves this view.
- if (extraVisiblePerson) {
- if (!people.find((p) => p.id == extraVisiblePerson?.id))
- extraVisiblePerson = undefined;
- }
-
- const findByIDIn = (ps: Person[]) =>
- ps.find((p) => p.id == selectedPersonID);
- let activePerson = findByIDIn(visiblePeople);
- if (!activePerson) {
- activePerson = findByIDIn(people);
- if (activePerson) {
- extraVisiblePerson = activePerson;
- }
- }
-
- const view = {
- type: "people" as const,
- people,
- visiblePeople: extraVisiblePerson
- ? visiblePeople.concat([extraVisiblePerson])
- : visiblePeople,
- activePerson,
- };
-
- return { view, extraVisiblePerson };
-};
-
const stateForUpdatedCollectionFiles = (
state: GalleryState,
collectionFiles: GalleryState["collectionFiles"],
@@ -1662,221 +1127,9 @@ const stateForUpdatedCollectionFiles = (
collectionFiles,
hiddenFileIDs,
),
- pendingSearchSuggestions: enqueuePendingSearchSuggestionsIfNeeded(
- state.searchSuggestion,
- state.pendingSearchSuggestions,
- state.isInSearchMode,
- ),
};
};
-const stateByUpdatingFilteredFiles = (state: GalleryState) => {
- if (state.view?.type == "links") {
- const links = visibleQuickLinks(
- state.collections,
- state.user!.id,
- state.hiddenCollectionIDs,
- );
- const previousLinkID = state.view.selectedLinkID;
- const selectedLinkID = links.some(({ id }) => id == previousLinkID)
- ? state.view.selectedLinkID
- : undefined;
- state = { ...state, view: { type: "links", selectedLinkID } };
- }
- if (state.isInSearchMode) {
- const searchFiles = state.searchResults ?? state.filteredFiles;
- const visibleSearchFiles = suppressSharedFilesSavedByUser(
- searchFiles,
- state.user?.id,
- state.view?.type == "albums" ||
- state.view?.type == "hidden-albums" ||
- state.view?.type == "archive-albums"
- ? state.view.activeCollection
- : undefined,
- );
- const filteredFiles =
- state.searchSortAsc !== undefined
- ? sortFiles([...visibleSearchFiles], state.searchSortAsc)
- : visibleSearchFiles;
- return { ...state, filteredFiles };
- } else if (
- state.view?.type == "albums" ||
- state.view?.type == "hidden-albums" ||
- state.view?.type == "archive-albums"
- ) {
- const filteredFiles = deriveAlbumsOrHiddenAlbumsFilteredFiles(
- state.trashItems,
- state.collectionFiles,
- state.defaultHiddenCollectionIDs,
- state.hiddenFileIDs,
- state.archivedCollectionIDs,
- state.archivedFileIDs,
- state.tempDeletedFileIDs,
- state.tempHiddenFileIDs,
- state.view,
- state.user?.id,
- );
- return { ...state, filteredFiles };
- } else if (
- state.view?.type == "album-overview" ||
- state.view?.type == "links"
- ) {
- return { ...state, filteredFiles: [] };
- } else if (state.view?.type == "people") {
- const filteredFiles = derivePeopleFilteredFiles(
- state.collectionFiles,
- state.hiddenFileIDs,
- state.view,
- state.user?.id,
- );
- return { ...state, filteredFiles };
- } else {
- return state;
- }
-};
-
-const deriveAlbumsOrHiddenAlbumsFilteredFiles = (
- trashItems: GalleryState["trashItems"],
- collectionFiles: GalleryState["collectionFiles"],
- defaultHiddenCollectionIDs: GalleryState["defaultHiddenCollectionIDs"],
- hiddenFileIDs: GalleryState["hiddenFileIDs"],
- archivedCollectionIDs: GalleryState["archivedCollectionIDs"],
- archivedFileIDs: GalleryState["archivedFileIDs"],
- tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],
- tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],
- view: Extract<
- GalleryView,
- { type: "albums" | "hidden-albums" | "archive-albums" }
- >,
- currentUserID: number | undefined,
-) => {
- const activeCollectionSummaryID = view.activeCollectionSummaryID;
-
- if (activeCollectionSummaryID == PseudoCollectionID.trash) {
- return uniqueFilesByID([
- ...trashItems.map(({ file, deleteBy }) => ({ ...file, deleteBy })),
- ...collectionFiles.filter((file) =>
- tempDeletedFileIDs.has(file.id),
- ),
- ]);
- }
-
- const filteredFiles = collectionFiles.filter((file) => {
- if (tempDeletedFileIDs.has(file.id)) return false;
-
- if (
- activeCollectionSummaryID == PseudoCollectionID.hiddenItems &&
- defaultHiddenCollectionIDs.has(file.collectionID)
- ) {
- return true;
- }
-
- // A file can be individually archived and belong to an archived album.
- if (isArchivedFile(file)) {
- return (
- (activeCollectionSummaryID == PseudoCollectionID.archiveItems &&
- !hiddenFileIDs.has(file.id) &&
- !tempHiddenFileIDs.has(file.id)) ||
- activeCollectionSummaryID == file.collectionID
- );
- }
-
- if (archivedCollectionIDs.has(file.collectionID)) {
- return activeCollectionSummaryID === file.collectionID;
- }
-
- if (activeCollectionSummaryID === PseudoCollectionID.all) {
- if (hiddenFileIDs.has(file.id)) return false;
- if (tempHiddenFileIDs.has(file.id)) return false;
-
- if (archivedFileIDs.has(file.id)) {
- return false;
- }
-
- return true;
- }
-
- return activeCollectionSummaryID == file.collectionID;
- });
-
- return sortAndUniqueFilteredFiles(
- filteredFiles,
- view.activeCollection,
- currentUserID,
- );
-};
-
-const sortAndUniqueFilteredFiles = (
- files: EnteFile[],
- activeCollection: Collection | undefined,
- currentUserID: number | undefined,
-) => {
- const uniqueFiles = uniqueFilesByID(
- suppressSharedFilesSavedByUser(files, currentUserID, activeCollection),
- );
- const metadata = activeCollection?.pubMagicMetadata?.data;
- // The synced library is already in newest-first order.
- return metadata?.asc || metadata?.sortBy === "fileName"
- ? sortCollectionFiles(uniqueFiles, metadata)
- : uniqueFiles;
-};
-
-const suppressSharedFilesSavedByUser = (
- files: EnteFile[],
- currentUserID: number | undefined,
- activeCollection: Collection | undefined,
-) => {
- if (!currentUserID || activeCollection) return files;
-
- const ownedFileKeys = new Set<string>();
- for (const file of files) {
- if (file.ownerID != currentUserID) continue;
- const hash = metadataHash(file.metadata);
- if (!hash) continue;
- ownedFileKeys.add(`${hash}:${file.metadata.fileType}`);
- }
-
- if (!ownedFileKeys.size) return files;
-
- return files.filter((file) => {
- if (file.ownerID == currentUserID) return true;
-
- const hash = metadataHash(file.metadata);
- if (!hash) return true;
-
- return !ownedFileKeys.has(`${hash}:${file.metadata.fileType}`);
- });
-};
-
-const derivePeopleFilteredFiles = (
- collectionFiles: GalleryState["collectionFiles"],
- hiddenFileIDs: GalleryState["hiddenFileIDs"],
- view: Extract<GalleryView, { type: "people" }>,
- currentUserID: number | undefined,
-) => {
- const pfSet = new Set(view.activePerson?.fileIDs ?? []);
- return uniqueFilesByID(
- suppressSharedFilesSavedByUser(
- collectionFiles.filter((f) => {
- if (!pfSet.has(f.id)) return false;
- if (hiddenFileIDs.has(f.id)) return false;
- return true;
- }),
- currentUserID,
- undefined,
- ),
- );
-};
-
-const enqueuePendingSearchSuggestionsIfNeeded = (
- searchSuggestion: GalleryState["searchSuggestion"],
- pendingSearchSuggestions: GalleryState["pendingSearchSuggestions"],
- isInSearchMode: GalleryState["isInSearchMode"],
-) =>
- searchSuggestion && isInSearchMode
- ? [...pendingSearchSuggestions, searchSuggestion]
- : pendingSearchSuggestions;
-
const constructUserIDToEmailMap = (
user: LocalUser,
collections: GalleryState["collections"],
diff --git a/web/apps/photos/src/components/gallery/AlbumEmptyState.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumEmptyState.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/AlbumEmptyState.tsx
rename to web/apps/photos/src/components/gallery/sections/albums/AlbumEmptyState.tsx
diff --git a/web/apps/photos/src/components/gallery/AlbumTile.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumTile.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/AlbumTile.tsx
rename to web/apps/photos/src/components/gallery/sections/albums/AlbumTile.tsx
diff --git a/web/apps/photos/src/components/gallery/AlbumsHeader.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumsHeader.tsx
similarity index 98%
rename from web/apps/photos/src/components/gallery/AlbumsHeader.tsx
rename to web/apps/photos/src/components/gallery/sections/albums/AlbumsHeader.tsx
index 5c51b59c97..76a710ab1e 100644
--- a/web/apps/photos/src/components/gallery/AlbumsHeader.tsx
+++ b/web/apps/photos/src/components/gallery/sections/albums/AlbumsHeader.tsx
@@ -5,8 +5,8 @@ import { t } from "i18next";
import { useState } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList, type ListChildComponentProps } from "react-window";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
import { AlbumTile } from "./AlbumTile";
-import { usePhotosNavigation } from "./PhotosNavigationContext";
interface AlbumsHeaderProps {
title: string;
diff --git a/web/apps/photos/src/components/gallery/sections/albums/AlbumsNavigation.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumsNavigation.tsx
new file mode 100644
index 0000000000..f0c9d46487
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/albums/AlbumsNavigation.tsx
@@ -0,0 +1,495 @@
+import { CollectionsSortOptions } from "@/components/CollectionsSortOptions";
+import {
+ matchesAlbumFilter,
+ type AlbumFilter,
+ type albumFilters,
+} from "@/utils/album-filters";
+import { ArrowDown01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import AddIcon from "@mui/icons-material/Add";
+import {
+ Box,
+ Divider,
+ IconButton,
+ Stack,
+ Tooltip,
+ useMediaQuery,
+ useTheme,
+} from "@mui/material";
+import {
+ PseudoCollectionID,
+ type CollectionSummary,
+ type CollectionsSortBy,
+} from "ente-new/photos/services/collection-summary";
+import { wait } from "ente-utils/promise";
+import { t } from "i18next";
+import React, {
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import AutoSizer from "react-virtualized-auto-sizer";
+import {
+ FixedSizeList,
+ VariableSizeList,
+ areEqual,
+ type ListChildComponentProps,
+} from "react-window";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
+
+import {
+ BarCard,
+ CardText,
+ CollectionBarCard,
+ NavigationEmptyState,
+ NavigationFrame,
+ type GalleryBarPresentationProps,
+} from "../../navigation/NavigationPrimitives";
+export interface AlbumsNavigationProps extends GalleryBarPresentationProps {
+ mode: "albums" | "hidden-albums" | "archive-albums";
+ albumExpansion: {
+ value: AlbumFilter | undefined;
+ onChange: (
+ filter: AlbumFilter | undefined,
+ selectedFilter?: AlbumFilter,
+ ) => void;
+ };
+ albumFilter: AlbumFilter;
+ albumSearchQuery: string;
+ onAlbumSearchQueryChange: (query: string) => void;
+ collectionSummaries: CollectionSummary[];
+ visibleAlbumFilters: typeof albumFilters;
+ uncategorizedCollectionSummaryID: number;
+ activeCollectionID: number | undefined;
+ onCreateAlbum: () => void;
+ collectionsSortBy: CollectionsSortBy;
+ onChangeCollectionsSortBy: (by: CollectionsSortBy) => void;
+}
+export const AlbumsNavigation = ({
+ mode,
+ albumExpansion,
+ albumFilter,
+ albumSearchQuery,
+ onAlbumSearchQueryChange,
+ collectionSummaries,
+ visibleAlbumFilters,
+ uncategorizedCollectionSummaryID,
+ activeCollectionID,
+ onCreateAlbum,
+ collectionsSortBy,
+ onChangeCollectionsSortBy,
+ collapsed,
+ mobileDrawerProps,
+}: AlbumsNavigationProps) => {
+ const {
+ selectCollection,
+ showAlbumOverview: onShowAlbumOverview,
+ showCollectionSummary: onShowCollectionSummary,
+ } = usePhotosNavigation();
+ const { onClose: closeMobileNavigation } = mobileDrawerProps;
+ const onSelectCollectionID = useCallback(
+ (id: number) => {
+ selectCollection(id);
+ closeMobileNavigation();
+ },
+ [selectCollection, closeMobileNavigation],
+ );
+ const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
+ const listRef = useRef<FixedSizeList>(null);
+ const albumListRef = useRef<VariableSizeList>(null);
+ const [groupExpanded, setGroupExpanded] = useState(true);
+ useEffect(() => {
+ setGroupExpanded(true);
+ }, [mode]);
+ const searchQuery = albumSearchQuery;
+ const normalizedSearchQuery = searchQuery.trim().toLowerCase();
+ const isSearching = !!normalizedSearchQuery;
+ const [viewportHeight, setViewportHeight] = useState(0);
+ const { value: expandedAlbumFilter, onChange: setExpandedAlbumFilter } =
+ albumExpansion;
+ const displayedAlbumFilter =
+ isSearching &&
+ expandedAlbumFilter !== undefined &&
+ !visibleAlbumFilters.some(({ value }) => value == expandedAlbumFilter)
+ ? visibleAlbumFilters[0]?.value
+ : expandedAlbumFilter;
+ const displayedCollectionSummaries = useMemo(
+ () =>
+ mode == "albums"
+ ? collectionSummaries.filter(
+ (cs) =>
+ displayedAlbumFilter !== undefined &&
+ matchesAlbumFilter(cs, displayedAlbumFilter),
+ )
+ : collectionSummaries,
+ [mode, collectionSummaries, displayedAlbumFilter],
+ );
+
+ useEffect(() => {
+ if (isSearching) {
+ listRef.current?.scrollTo(0);
+ albumListRef.current?.scrollTo(0);
+ }
+ }, [searchQuery, isSearching]);
+ const itemData = useMemo(
+ () => ({
+ collectionSummaries: displayedCollectionSummaries,
+ activeCollectionID,
+ onSelectCollectionID,
+ indented: mode == "hidden-albums",
+ }),
+ [
+ displayedCollectionSummaries,
+ activeCollectionID,
+ onSelectCollectionID,
+ mode,
+ ],
+ );
+ const title = t(
+ mode == "hidden-albums"
+ ? "hidden_albums"
+ : mode == "archive-albums"
+ ? "section_archive"
+ : "albums",
+ );
+ const albumShortcuts = [
+ {
+ id: uncategorizedCollectionSummaryID,
+ label: t("section_uncategorized"),
+ active: activeCollectionID == uncategorizedCollectionSummaryID,
+ },
+ {
+ id: PseudoCollectionID.hiddenItems,
+ label: t("section_hidden"),
+ active: mode == "hidden-albums",
+ },
+ {
+ id: PseudoCollectionID.archiveItems,
+ label: t("section_archive"),
+ active: mode == "archive-albums",
+ },
+ {
+ id: PseudoCollectionID.trash,
+ label: t("section_trash"),
+ active: activeCollectionID == PseudoCollectionID.trash,
+ },
+ ].filter(({ label }) =>
+ label.toLowerCase().includes(normalizedSearchQuery),
+ );
+
+ const items = (
+ <Box sx={{ flex: 1, minHeight: 0, minWidth: 0 }}>
+ <AutoSizer onResize={({ height }) => setViewportHeight(height)}>
+ {({ width, height }) => (
+ <FixedSizeList
+ ref={listRef}
+ width={width}
+ height={height}
+ itemData={itemData}
+ itemKey={(i, data) =>
+ `collections-${data.collectionSummaries[i]!.id}-${data.collectionSummaries[i]!.coverFile?.id}`
+ }
+ itemCount={displayedCollectionSummaries.length}
+ itemSize={mobile ? 46 : 50}
+ style={{ overflowX: "hidden" }}
+ >
+ {ListItem}
+ </FixedSizeList>
+ )}
+ </AutoSizer>
+ </Box>
+ );
+
+ const rowHeight = mobile ? 46 : 50;
+ const albumNavigationRows: AlbumNavigationRow[] = [];
+ for (const filter of visibleAlbumFilters) {
+ albumNavigationRows.push({
+ key: `filter-${filter.value}`,
+ height: rowHeight,
+ content: (
+ <BarCard
+ aria-label={filter.title()}
+ aria-current={
+ activeCollectionID === undefined &&
+ albumFilter == filter.value
+ ? "page"
+ : undefined
+ }
+ aria-expanded={displayedAlbumFilter == filter.value}
+ onClick={() => {
+ setExpandedAlbumFilter(
+ displayedAlbumFilter == filter.value
+ ? undefined
+ : filter.value,
+ filter.value,
+ );
+ onShowAlbumOverview(filter.value);
+ mobileDrawerProps.onClose();
+ }}
+ sx={{ flexShrink: 0 }}
+ >
+ <CardText>{filter.label()}</CardText>
+ <Box
+ component={HugeiconsIcon}
+ icon={ArrowDown01Icon}
+ size={16}
+ strokeWidth={1.8}
+ sx={{
+ color: "text.muted",
+ transform:
+ displayedAlbumFilter == filter.value
+ ? undefined
+ : "rotate(-90deg)",
+ }}
+ />
+ </BarCard>
+ ),
+ });
+ if (displayedAlbumFilter == filter.value) {
+ for (const collectionSummary of displayedCollectionSummaries) {
+ albumNavigationRows.push({
+ key: `collection-${collectionSummary.id}`,
+ height: rowHeight,
+ content: (
+ <CollectionBarCard
+ key={`${collectionSummary.id}-${collectionSummary.coverFile?.id}`}
+ collectionSummary={collectionSummary}
+ activeCollectionID={activeCollectionID}
+ onSelectCollectionID={onSelectCollectionID}
+ indented={
+ !collectionSummary.attributes.has("system")
+ }
+ />
+ ),
+ });
+ }
+ }
+ }
+ if (visibleAlbumFilters.length && albumShortcuts.length) {
+ albumNavigationRows.push({
+ key: "shortcut-divider",
+ height: 18,
+ content: (
+ <Divider
+ sx={{
+ mt: "8px",
+ height: "2px",
+ border: 0,
+ bgcolor: "divider",
+ opacity: 0.5,
+ }}
+ />
+ ),
+ });
+ }
+ for (const { id, label, active } of albumShortcuts) {
+ albumNavigationRows.push({
+ key: `shortcut-${id}`,
+ height: rowHeight,
+ content: (
+ <BarCard
+ aria-label={label}
+ aria-current={active ? "true" : undefined}
+ onClick={() => {
+ void onShowCollectionSummary(
+ id,
+ id == PseudoCollectionID.hiddenItems,
+ ).then(async (success) => {
+ if (!success || !mobile) return;
+ if (id == PseudoCollectionID.hiddenItems)
+ await wait(10);
+ mobileDrawerProps.onClose();
+ });
+ }}
+ sx={{ flexShrink: 0 }}
+ >
+ <CardText>{label}</CardText>
+ </BarCard>
+ ),
+ });
+ }
+
+ const albumRowSizes = albumNavigationRows
+ .map(({ height }) => height)
+ .join(",");
+ const activeAlbumRowIndex = albumNavigationRows.findIndex(
+ ({ key }) => key == `collection-${activeCollectionID}`,
+ );
+ useEffect(() => {
+ albumListRef.current?.resetAfterIndex(0);
+ }, [albumRowSizes]);
+
+ useEffect(() => {
+ if (isSearching) return;
+ if (mode == "albums") {
+ if (activeAlbumRowIndex != -1)
+ albumListRef.current?.scrollToItem(
+ activeAlbumRowIndex,
+ "smart",
+ );
+ } else {
+ const i = displayedCollectionSummaries.findIndex(
+ ({ id }) => id == activeCollectionID,
+ );
+ if (i != -1) listRef.current?.scrollToItem(i, "smart");
+ }
+ }, [
+ mode,
+ activeAlbumRowIndex,
+ displayedCollectionSummaries,
+ activeCollectionID,
+ collapsed,
+ mobile,
+ mobileDrawerProps.open,
+ viewportHeight,
+ isSearching,
+ ]);
+ const isGroupOverview =
+ activeCollectionID == PseudoCollectionID.hiddenItems;
+ return (
+ <NavigationFrame
+ title={title}
+ actions={
+ <>
+ <CollectionsSortOptions
+ variant="v2"
+ activeSortBy={collectionsSortBy}
+ onChangeSortBy={onChangeCollectionsSortBy}
+ />
+ {mode != "archive-albums" && (
+ <Tooltip title={t("new_album")}>
+ <IconButton
+ aria-label={t("new_album")}
+ aria-haspopup="dialog"
+ onClick={() => {
+ mobileDrawerProps.onClose();
+ onCreateAlbum();
+ }}
+ >
+ <AddIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ </Tooltip>
+ )}
+ </>
+ }
+ searchPlaceholder={t("search_in_albums")}
+ searchQuery={searchQuery}
+ setSearchQuery={onAlbumSearchQueryChange}
+ mobileDrawerProps={mobileDrawerProps}
+ >
+ {isSearching &&
+ (mode == "albums"
+ ? !visibleAlbumFilters.length && !albumShortcuts.length
+ : !displayedCollectionSummaries.length) ? (
+ <NavigationEmptyState />
+ ) : mode == "albums" ? (
+ <Box
+ role="group"
+ aria-label={t("filter_albums")}
+ sx={{ flex: 1, minHeight: 0, minWidth: 0 }}
+ >
+ <AutoSizer
+ onResize={({ height }) => setViewportHeight(height)}
+ >
+ {({ width, height }) => (
+ <VariableSizeList
+ ref={albumListRef}
+ width={width}
+ height={height}
+ itemData={albumNavigationRows}
+ itemCount={albumNavigationRows.length}
+ itemKey={(index, rows) => rows[index]!.key}
+ itemSize={(index) =>
+ albumNavigationRows[index]!.height
+ }
+ style={{ overflowX: "hidden" }}
+ >
+ {AlbumNavigationItem}
+ </VariableSizeList>
+ )}
+ </AutoSizer>
+ </Box>
+ ) : mode == "hidden-albums" ? (
+ <Stack
+ role="group"
+ aria-label={t("section_hidden")}
+ sx={{ flex: 1, minHeight: 0, minWidth: 0 }}
+ >
+ <BarCard
+ aria-current={isGroupOverview ? "page" : undefined}
+ aria-expanded={isSearching || groupExpanded}
+ onClick={() => {
+ setGroupExpanded(
+ !isGroupOverview || !groupExpanded,
+ );
+ onSelectCollectionID(
+ PseudoCollectionID.hiddenItems,
+ );
+ mobileDrawerProps.onClose();
+ }}
+ sx={{ flexShrink: 0, height: rowHeight }}
+ >
+ <CardText>{t("section_hidden")}</CardText>
+ <Box
+ component={HugeiconsIcon}
+ icon={ArrowDown01Icon}
+ size={16}
+ strokeWidth={1.8}
+ sx={{
+ color: "text.muted",
+ transform:
+ isSearching || groupExpanded
+ ? undefined
+ : "rotate(-90deg)",
+ }}
+ />
+ </BarCard>
+ {(isSearching || groupExpanded) && items}
+ </Stack>
+ ) : (
+ items
+ )}
+ </NavigationFrame>
+ );
+};
+interface AlbumNavigationRow {
+ key: string;
+ height: number;
+ content: React.ReactNode;
+}
+
+const AlbumNavigationItem = memo(
+ ({ data, index, style }: ListChildComponentProps<AlbumNavigationRow[]>) => (
+ <div style={style}>{data[index]!.content}</div>
+ ),
+ areEqual,
+);
+
+interface ItemData {
+ collectionSummaries: CollectionSummary[];
+ activeCollectionID: number | undefined;
+ onSelectCollectionID: (id: number) => void;
+ indented: boolean;
+}
+const ListItem = memo(
+ ({ data, index, style }: ListChildComponentProps<ItemData>) => {
+ const collectionSummary = data.collectionSummaries[index]!;
+ return (
+ <div style={style}>
+ <CollectionBarCard
+ collectionSummary={collectionSummary}
+ activeCollectionID={data.activeCollectionID}
+ onSelectCollectionID={data.onSelectCollectionID}
+ indented={
+ data.indented &&
+ !collectionSummary.attributes.has("system")
+ }
+ />
+ </div>
+ );
+ },
+ areEqual,
+);
diff --git a/web/apps/photos/src/components/gallery/AlbumsOverview.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumsOverview.tsx
similarity index 99%
rename from web/apps/photos/src/components/gallery/AlbumsOverview.tsx
rename to web/apps/photos/src/components/gallery/sections/albums/AlbumsOverview.tsx
index c0ccfcb027..2effba8f90 100644
--- a/web/apps/photos/src/components/gallery/AlbumsOverview.tsx
+++ b/web/apps/photos/src/components/gallery/sections/albums/AlbumsOverview.tsx
@@ -20,12 +20,12 @@ import { t } from "i18next";
import { useEffect, useRef, useState } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList, type ListChildComponentProps } from "react-window";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
import {
AlbumTileButton as AlbumButton,
AlbumTile,
AlbumTileCover as Cover,
} from "./AlbumTile";
-import { usePhotosNavigation } from "./PhotosNavigationContext";
interface AlbumsOverviewProps {
albums: CollectionSummary[];
diff --git a/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx b/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx
new file mode 100644
index 0000000000..802555a512
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/albums/AlbumsSection.tsx
@@ -0,0 +1,403 @@
+import type { FileListHeaderOrFooter } from "@/components/FileList";
+import { AlbumContentHeader } from "@/components/collections/AlbumContentHeader";
+import { AlbumSlideshow } from "@/components/collections/AlbumSlideshow";
+import { CollectionMap } from "@/components/collections/CollectionMap";
+import {
+ EditAlbumDetailsDialog,
+ type AlbumDetails,
+} from "@/components/collections/EditAlbumDetailsDialog";
+import { GalleryEmptyState } from "@/components/gallery";
+import { AlbumsOverview } from "@/components/gallery/sections/albums/AlbumsOverview";
+import { useAlbumNavigationData } from "@/components/gallery/sections/albums/use-album-navigation-data";
+import { useGallerySlideshow } from "@/components/gallery/sections/albums/use-gallery-slideshow";
+import { albumFilters, visibleAlbumFilters } from "@/utils/album-filters";
+import { useModalVisibility } from "ente-base/components/utils/modal";
+import {
+ isSaveCancelled,
+ isSaveComplete,
+} from "ente-gallery/components/utils/save-groups";
+import { ItemVisibility } from "ente-media/file-metadata";
+import {
+ renameCollection,
+ updateCollectionDetails,
+} from "ente-new/photos/services/collection";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+
+import { uploadManager } from "@/services/upload-manager";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { albumFiles, albumView } from "./album-files";
+
+import { CreateAlbumDialog } from "@/components/collections/CreateAlbumDialog";
+import { GalleryMedia } from "../../media/GalleryMedia";
+import { GallerySectionLayout } from "../../navigation/GallerySectionLayout";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
+import type { GallerySectionProps } from "../types";
+import { AlbumsNavigation } from "./AlbumsNavigation";
+export const AlbumsSection = ({
+ library,
+ operations,
+ navigation,
+ preferences,
+ presentation,
+}: GallerySectionProps) => {
+ const state = library;
+ const {
+ user,
+ hiddenFileIDs,
+ tempDeletedFileIDs,
+ tempHiddenFileIDs,
+ favoriteFileIDs,
+ fileNormalCollectionIDs,
+ collectionNameByID,
+ } = library;
+ const {
+ onRemotePull: remotePull,
+ onRemoteFilesPull: remoteFilesPull,
+ onAddSaveGroup,
+ setBlockingLoad,
+ onMarkTempDeleted: handleMarkTempDeleted,
+ onAddFileToCollection: handleAddSingleFileToCollection,
+ onVisualFeedback: handleVisualFeedback,
+ } = operations;
+ const { selectedPlace, placeSelectionRevision } = navigation;
+ const isMapView = !!navigation.destination.collectionMap;
+ const isInSearchMode = navigation.overlay?.section === "search";
+ const {
+ albumFilter,
+ setAlbumFilter,
+ albumSearchQuery,
+ collectionsSortBy,
+ onChangeCollectionsSortBy,
+ albumExpansion,
+ albumOpenedFromOverview,
+ setAlbumSearchQuery,
+ } = preferences;
+ const view = useMemo(
+ () => albumView(library, navigation.destination),
+ [library, navigation.destination],
+ );
+ const filteredFiles = useMemo(
+ () => albumFiles(library, view),
+ [library, view],
+ );
+ const barMode =
+ view.type == "hidden-albums"
+ ? "hidden-albums"
+ : view.type == "archive-albums"
+ ? "archive-albums"
+ : "albums";
+ const isAlbumOverview = view.type == "album-overview";
+ const overviewFilter = isAlbumOverview ? view.albumFilter : undefined;
+ const activeCollectionID =
+ view.type == "albums" ||
+ view.type == "hidden-albums" ||
+ view.type == "archive-albums"
+ ? view.activeCollectionSummaryID
+ : undefined;
+ const activeCollection =
+ view.type == "albums" ||
+ view.type == "hidden-albums" ||
+ view.type == "archive-albums"
+ ? view.activeCollection
+ : undefined;
+ const activeCollectionSummary =
+ view.type == "albums" ||
+ view.type == "hidden-albums" ||
+ view.type == "archive-albums"
+ ? view.activeCollectionSummary
+ : undefined;
+ const [fileListHeader, setFileListHeader] =
+ useState<FileListHeaderOrFooter>();
+ const {
+ show: showEditAlbumDetails,
+ props: editAlbumDetailsVisibilityProps,
+ } = useModalVisibility();
+ const createAlbum = useModalVisibility();
+ const { selectCollection, showAlbumOverview } = usePhotosNavigation();
+ const barCollectionSummaries =
+ barMode == "hidden-albums"
+ ? library.hiddenCollectionSummaries
+ : barMode == "archive-albums"
+ ? library.archivedCollectionSummaries
+ : library.normalCollectionSummaries;
+ const collectionSummary =
+ activeCollectionID === undefined
+ ? undefined
+ : barCollectionSummaries.get(activeCollectionID);
+ const {
+ sidebarCollectionSummaries,
+ overviewAlbums,
+ visibleAlbumFilters: sidebarAlbumFilters,
+ } = useAlbumNavigationData({
+ mode: barMode,
+ collectionsSortBy,
+ collectionSummaries: barCollectionSummaries,
+ uncategorizedCollectionSummaryID:
+ library.uncategorizedCollectionSummaryID,
+ albumFilter,
+ albumSearchQuery,
+ });
+ useEffect(() => {
+ const available = visibleAlbumFilters([
+ ...library.normalCollectionSummaries.values(),
+ ]);
+ if (!available.some(({ value }) => value == albumFilter)) {
+ setAlbumFilter("ente");
+ if (overviewFilter) showAlbumOverview("ente");
+ }
+ }, [
+ library.normalCollectionSummaries,
+ albumFilter,
+ overviewFilter,
+ setAlbumFilter,
+ showAlbumOverview,
+ ]);
+ const isActiveCollectionDownloadInProgress = useCallback(() => {
+ const group = operations.saveGroups.find(
+ (g) => g.collectionSummaryID === activeCollectionID,
+ );
+ return !!group && !isSaveComplete(group) && !isSaveCancelled(group);
+ }, [operations.saveGroups, activeCollectionID]);
+ const activeCollectionFiles = useMemo(() => {
+ if (!activeCollection) return [];
+ if (barMode == "hidden-albums" || barMode == "archive-albums") {
+ return filteredFiles;
+ }
+
+ return filteredFiles.filter(({ id, magicMetadata }) => {
+ const visibility = magicMetadata?.data.visibility;
+ const isVisible =
+ visibility === undefined ||
+ visibility === ItemVisibility.visible;
+
+ return (
+ isVisible &&
+ !hiddenFileIDs.has(id) &&
+ !tempDeletedFileIDs.has(id) &&
+ !tempHiddenFileIDs.has(id)
+ );
+ });
+ }, [
+ activeCollection,
+ barMode,
+ filteredFiles,
+ hiddenFileIDs,
+ tempDeletedFileIDs,
+ tempHiddenFileIDs,
+ ]);
+ const { slideshow, startSlideshow, closeSlideshow } = useGallerySlideshow({
+ activeCollection,
+ activeCollectionFiles,
+ activeCollectionSummary,
+ isInSearchMode,
+ user,
+ });
+
+ const mapFileSource = useMemo(
+ () => ({
+ collectionFiles: state.collectionFiles,
+ favoriteFileIDs,
+ hiddenFileIDs,
+ archivedFileIDs: state.archivedFileIDs,
+ tempDeletedFileIDs,
+ tempHiddenFileIDs,
+ }),
+ [
+ favoriteFileIDs,
+ hiddenFileIDs,
+ state.archivedFileIDs,
+ state.collectionFiles,
+ tempDeletedFileIDs,
+ tempHiddenFileIDs,
+ ],
+ );
+ const handleEditAlbumDetails = useCallback(
+ async ({ name, description, coverID }: AlbumDetails) => {
+ if (!activeCollection) return;
+
+ let didAttemptWrite = false;
+ try {
+ if (activeCollection.name != name) {
+ didAttemptWrite = true;
+ await renameCollection(activeCollection, name);
+ }
+ const descriptionChanged =
+ (
+ activeCollection.pubMagicMetadata?.data.caption ?? ""
+ ).trim() != description;
+ if (descriptionChanged || coverID !== undefined) {
+ didAttemptWrite = true;
+ await updateCollectionDetails(activeCollection, {
+ description: descriptionChanged
+ ? description
+ : undefined,
+ coverID,
+ });
+ }
+ } finally {
+ if (didAttemptWrite) {
+ await remotePull({
+ silent: true,
+ source: "update-album-details",
+ });
+ }
+ }
+ },
+ [activeCollection, remotePull],
+ );
+
+ const collectionMap = activeCollectionSummary && (
+ <CollectionMap
+ collectionSummary={activeCollectionSummary}
+ files={activeCollection ? activeCollectionFiles : filteredFiles}
+ selectedPlace={
+ activeCollectionID === PseudoCollectionID.all
+ ? selectedPlace
+ : undefined
+ }
+ placeSelectionRevision={placeSelectionRevision}
+ mapFileSource={mapFileSource}
+ onRemotePull={remotePull}
+ onAddSaveGroup={onAddSaveGroup}
+ onMarkTempDeleted={handleMarkTempDeleted}
+ onAddFileToCollection={handleAddSingleFileToCollection}
+ onRemoteFilesPull={remoteFilesPull}
+ onVisualFeedback={handleVisualFeedback}
+ fileNormalCollectionIDs={fileNormalCollectionIDs}
+ collectionNameByID={collectionNameByID}
+ emailByUserID={state.emailByUserID}
+ />
+ );
+
+ const { setSectionActivity } = operations;
+ useEffect(() => {
+ setSectionActivity({
+ selection: !!slideshow || editAlbumDetailsVisibilityProps.open,
+ drop: !!slideshow,
+ });
+ return () => setSectionActivity({ selection: false, drop: false });
+ }, [slideshow, editAlbumDetailsVisibilityProps.open, setSectionActivity]);
+ return (
+ <GallerySectionLayout
+ presentation={presentation}
+ fullBleed={isMapView}
+ navigation={
+ <AlbumsNavigation
+ mode={barMode}
+ {...presentation}
+ albumExpansion={albumExpansion}
+ albumFilter={albumFilter}
+ albumSearchQuery={albumSearchQuery}
+ onAlbumSearchQueryChange={setAlbumSearchQuery}
+ collectionSummaries={sidebarCollectionSummaries}
+ visibleAlbumFilters={sidebarAlbumFilters}
+ uncategorizedCollectionSummaryID={
+ library.uncategorizedCollectionSummaryID
+ }
+ activeCollectionID={activeCollectionID}
+ onCreateAlbum={createAlbum.show}
+ collectionsSortBy={collectionsSortBy}
+ onChangeCollectionsSortBy={onChangeCollectionsSortBy}
+ />
+ }
+ >
+ {isMapView ? (
+ collectionMap
+ ) : !library.isFirstLoad &&
+ !library.collectionFiles.length &&
+ activeCollectionID === PseudoCollectionID.all ? (
+ <GalleryEmptyState
+ isUploadInProgress={uploadManager.isUploadInProgress()}
+ onUpload={operations.onUpload}
+ />
+ ) : !library.isFirstLoad && isAlbumOverview ? (
+ <AlbumsOverview
+ onRemotePull={remotePull}
+ albums={overviewAlbums}
+ title={(
+ albumFilters.find(
+ ({ value }) => value == overviewFilter,
+ ) ?? albumFilters[0]!
+ ).title()}
+ filter={overviewFilter!}
+ searchQuery={albumSearchQuery}
+ sortBy={collectionsSortBy}
+ onCreateAlbum={operations.onCreateAlbum}
+ />
+ ) : (
+ <GalleryMedia
+ {...{ library, operations, navigation }}
+ header={fileListHeader}
+ source={{
+ mode: barMode,
+ modePlus: barMode,
+ files: filteredFiles,
+ activeCollectionID: activeCollectionID!,
+ activeCollectionSummary,
+ activeCollection,
+ activePersonID: undefined,
+ disableGrouping:
+ activeCollection?.pubMagicMetadata?.data.sortBy ==
+ "fileName",
+ }}
+ >
+ {(hasActiveFileSelection) => (
+ <AlbumContentHeader
+ albums={sidebarCollectionSummaries}
+ user={user!}
+ activeCollection={activeCollection}
+ collectionSummary={collectionSummary}
+ setBlockingLoad={setBlockingLoad}
+ setFileListHeader={setFileListHeader}
+ hasActiveFileSelection={hasActiveFileSelection}
+ isActiveCollectionDownloadInProgress={
+ isActiveCollectionDownloadInProgress
+ }
+ onAddSaveGroup={onAddSaveGroup}
+ showBackToAlbums={
+ albumOpenedFromOverview !== undefined &&
+ albumOpenedFromOverview.collectionID ===
+ collectionSummary?.id
+ }
+ onEditAlbumDetails={showEditAlbumDetails}
+ onCollectionSlideshow={startSlideshow}
+ emailByUserID={library.emailByUserID}
+ shareSuggestionEmails={
+ library.shareSuggestionEmails
+ }
+ onRemotePull={remotePull}
+ />
+ )}
+ </GalleryMedia>
+ )}
+ <CreateAlbumDialog
+ {...createAlbum.props}
+ isHidden={barMode == "hidden-albums"}
+ onRemotePull={remotePull}
+ onSelectCollectionID={(id) => {
+ selectCollection(id);
+ presentation.mobileDrawerProps.onClose();
+ }}
+ />
+ {slideshow &&
+ slideshow.collectionID === activeCollection?.id &&
+ !isInSearchMode && (
+ <AlbumSlideshow
+ files={slideshow.files}
+ title={slideshow.title}
+ onClose={closeSlideshow}
+ />
+ )}
+ {activeCollection && editAlbumDetailsVisibilityProps.open && (
+ <EditAlbumDetailsDialog
+ key={activeCollection.id}
+ {...editAlbumDetailsVisibilityProps}
+ collection={activeCollection}
+ files={activeCollectionFiles}
+ initialCoverFile={activeCollectionSummary?.coverFile}
+ onSubmit={handleEditAlbumDetails}
+ />
+ )}
+ </GallerySectionLayout>
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/GalleryEmptyState.tsx b/web/apps/photos/src/components/gallery/sections/albums/GalleryEmptyState.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/GalleryEmptyState.tsx
rename to web/apps/photos/src/components/gallery/sections/albums/GalleryEmptyState.tsx
diff --git a/web/apps/photos/src/components/gallery/sections/albums/album-files.ts b/web/apps/photos/src/components/gallery/sections/albums/album-files.ts
new file mode 100644
index 0000000000..8e1342f2d3
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/albums/album-files.ts
@@ -0,0 +1,186 @@
+import { uniqueFilesByID } from "ente-gallery/utils/file";
+import type { Collection } from "ente-media/collection";
+import { sortCollectionFiles } from "ente-media/collection-sort";
+import type { EnteFile } from "ente-media/file";
+import { isArchivedFile } from "ente-media/file-metadata";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import { suppressSharedFilesSavedByUser } from "../../media/media-files";
+import type { GalleryDestination } from "../../navigation/navigation-state";
+import type { GalleryState } from "../../reducer";
+import type { GalleryView } from "../view-types";
+const deriveAlbumsOrHiddenAlbumsFilteredFiles = (
+ trashItems: GalleryState["trashItems"],
+ collectionFiles: GalleryState["collectionFiles"],
+ defaultHiddenCollectionIDs: GalleryState["defaultHiddenCollectionIDs"],
+ hiddenFileIDs: GalleryState["hiddenFileIDs"],
+ archivedCollectionIDs: GalleryState["archivedCollectionIDs"],
+ archivedFileIDs: GalleryState["archivedFileIDs"],
+ tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],
+ tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],
+ view: Extract<
+ GalleryView,
+ { type: "albums" | "hidden-albums" | "archive-albums" }
+ >,
+ currentUserID: number | undefined,
+) => {
+ const activeCollectionSummaryID = view.activeCollectionSummaryID;
+
+ if (activeCollectionSummaryID == PseudoCollectionID.trash) {
+ return uniqueFilesByID([
+ ...trashItems.map(({ file, deleteBy }) => ({ ...file, deleteBy })),
+ ...collectionFiles.filter((file) =>
+ tempDeletedFileIDs.has(file.id),
+ ),
+ ]);
+ }
+
+ const filteredFiles = collectionFiles.filter((file) => {
+ if (tempDeletedFileIDs.has(file.id)) return false;
+
+ if (
+ activeCollectionSummaryID == PseudoCollectionID.hiddenItems &&
+ defaultHiddenCollectionIDs.has(file.collectionID)
+ ) {
+ return true;
+ }
+
+ // A file can be individually archived and belong to an archived album.
+ if (isArchivedFile(file)) {
+ return (
+ (activeCollectionSummaryID == PseudoCollectionID.archiveItems &&
+ !hiddenFileIDs.has(file.id) &&
+ !tempHiddenFileIDs.has(file.id)) ||
+ activeCollectionSummaryID == file.collectionID
+ );
+ }
+
+ if (archivedCollectionIDs.has(file.collectionID)) {
+ return activeCollectionSummaryID === file.collectionID;
+ }
+
+ if (activeCollectionSummaryID === PseudoCollectionID.all) {
+ if (hiddenFileIDs.has(file.id)) return false;
+ if (tempHiddenFileIDs.has(file.id)) return false;
+
+ if (archivedFileIDs.has(file.id)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ return activeCollectionSummaryID == file.collectionID;
+ });
+
+ return sortAndUniqueFilteredFiles(
+ filteredFiles,
+ view.activeCollection,
+ currentUserID,
+ );
+};
+const sortAndUniqueFilteredFiles = (
+ files: EnteFile[],
+ activeCollection: Collection | undefined,
+ currentUserID: number | undefined,
+) => {
+ const uniqueFiles = uniqueFilesByID(
+ suppressSharedFilesSavedByUser(files, currentUserID, activeCollection),
+ );
+ const metadata = activeCollection?.pubMagicMetadata?.data;
+ // The synced library is already in newest-first order.
+ return metadata?.asc || metadata?.sortBy === "fileName"
+ ? sortCollectionFiles(uniqueFiles, metadata)
+ : uniqueFiles;
+};
+export const albumView = (
+ library: GalleryState,
+ destination: GalleryDestination,
+): Extract<
+ GalleryView,
+ { type: "albums" | "hidden-albums" | "archive-albums" | "album-overview" }
+> => {
+ if (destination.albumFilter)
+ return { type: "album-overview", albumFilter: destination.albumFilter };
+ const type = destination.albumMode ?? "albums";
+ const summaries =
+ type === "hidden-albums"
+ ? library.hiddenCollectionSummaries
+ : type === "archive-albums"
+ ? library.archivedCollectionSummaries
+ : library.normalCollectionSummaries;
+ const fallback =
+ type === "hidden-albums"
+ ? PseudoCollectionID.hiddenItems
+ : type === "archive-albums"
+ ? PseudoCollectionID.archiveItems
+ : PseudoCollectionID.all;
+ const id =
+ destination.collectionID !== undefined &&
+ summaries.has(destination.collectionID)
+ ? destination.collectionID
+ : fallback;
+ return {
+ type,
+ activeCollectionSummaryID: id,
+ activeCollection: library.collections.find((c) => c.id === id),
+ activeCollectionSummary: summaries.get(id)!,
+ };
+};
+
+export const albumFiles = (
+ library: GalleryState,
+ view: ReturnType<typeof albumView>,
+) =>
+ view.type === "album-overview"
+ ? []
+ : deriveAlbumsOrHiddenAlbumsFilteredFiles(
+ library.trashItems,
+ library.collectionFiles,
+ library.defaultHiddenCollectionIDs,
+ library.hiddenFileIDs,
+ library.archivedCollectionIDs,
+ library.archivedFileIDs,
+ library.tempDeletedFileIDs,
+ library.tempHiddenFileIDs,
+ view,
+ library.user?.id,
+ );
+
+export const resolveAlbumDestination = (
+ library: GalleryState,
+ destination: GalleryDestination,
+): GalleryDestination => {
+ if (destination.albumFilter || !library.user) return destination;
+ const mode = destination.albumMode ?? "albums";
+ const summaries =
+ mode === "hidden-albums"
+ ? library.hiddenCollectionSummaries
+ : mode === "archive-albums"
+ ? library.archivedCollectionSummaries
+ : library.normalCollectionSummaries;
+ const summary =
+ destination.collectionID === undefined
+ ? undefined
+ : summaries.get(destination.collectionID);
+ const valid =
+ summary &&
+ (mode !== "albums" ||
+ (!summary.attributes.has("archiveItems") &&
+ !summary.attributes.has("archived")));
+ const collectionID = valid
+ ? summary.id
+ : mode === "hidden-albums"
+ ? PseudoCollectionID.hiddenItems
+ : mode === "archive-albums"
+ ? PseudoCollectionID.archiveItems
+ : PseudoCollectionID.all;
+ if (collectionID === destination.collectionID) return destination;
+ return {
+ ...destination,
+ section:
+ destination.collectionMap && collectionID === PseudoCollectionID.all
+ ? "places"
+ : destination.section,
+ collectionID,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/sections/albums/use-album-actions.ts b/web/apps/photos/src/components/gallery/sections/albums/use-album-actions.ts
new file mode 100644
index 0000000000..871cd63046
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/albums/use-album-actions.ts
@@ -0,0 +1,143 @@
+import type { AlbumFilter } from "@/utils/album-filters";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { showCollectionSummaryWithAuthentication } from "../../helpers";
+import type { useGalleryLibrary } from "../../hooks/use-gallery-library";
+import type { useGalleryPreferences } from "../../hooks/use-gallery-preferences";
+import type {
+ GalleryNavigationState,
+ NavigationAction,
+} from "../../navigation/navigation-state";
+import type { GalleryState } from "../../reducer";
+
+export const useAlbumActions = ({
+ library,
+ navigation,
+ send,
+ preferences,
+ authenticateUser,
+ remoteFilesPull,
+}: {
+ library: GalleryState;
+ navigation: GalleryNavigationState;
+ send: React.Dispatch<NavigationAction>;
+ preferences: ReturnType<typeof useGalleryPreferences>;
+ authenticateUser: () => Promise<boolean>;
+ remoteFilesPull: ReturnType<typeof useGalleryLibrary>["remoteFilesPull"];
+}) => {
+ const lastAuthentication = useRef(0);
+ const currentLibrary = useRef(library);
+ useEffect(() => {
+ currentLibrary.current = library;
+ }, [library]);
+ const {
+ setAlbumOpenedFromOverview,
+ setAlbumFilter,
+ setAlbumSearchQuery,
+ albumOpenedFromOverview,
+ albumSearchQuery,
+ } = preferences;
+ const showSummary = useCallback(
+ (collectionSummaryID: number | undefined) => {
+ setAlbumOpenedFromOverview(undefined);
+ if (collectionSummaryID === PseudoCollectionID.trash)
+ void remoteFilesPull();
+ send({
+ type: "showCollectionSummary",
+ collectionSummaryID,
+ library: currentLibrary.current,
+ });
+ },
+ [remoteFilesPull, send, setAlbumOpenedFromOverview],
+ );
+ const showCollectionSummary = useCallback(
+ (id: number | undefined, hidden?: boolean) =>
+ showCollectionSummaryWithAuthentication(
+ id,
+ !!hidden &&
+ navigation.destination.albumMode !== "hidden-albums",
+ lastAuthentication,
+ authenticateUser,
+ showSummary,
+ ),
+ [authenticateUser, navigation.destination.albumMode, showSummary],
+ );
+ const goHome = useCallback(
+ () => showSummary(PseudoCollectionID.all),
+ [showSummary],
+ );
+ const selectCollection = useCallback(
+ (id: number) => {
+ if (navigation.destination.section === "links")
+ send({ type: "selectLink", collectionID: id });
+ else showSummary(id);
+ },
+ [navigation.destination.section, send, showSummary],
+ );
+ const selectCollectionFromViewer = useCallback(
+ (id: number) =>
+ send({
+ type: "showCollectionSummary",
+ collectionSummaryID: id,
+ library: currentLibrary.current,
+ }),
+ [send],
+ );
+ const showAlbumOverview = useCallback(
+ (filter: AlbumFilter) => {
+ setAlbumFilter(filter);
+ send({ type: "showAlbumOverview", albumFilter: filter });
+ },
+ [send, setAlbumFilter],
+ );
+ const backToAlbums = useCallback(() => {
+ const origin =
+ albumOpenedFromOverview?.collectionID ===
+ navigation.destination.collectionID
+ ? albumOpenedFromOverview
+ : undefined;
+ setAlbumSearchQuery(origin?.searchQuery ?? "");
+ showAlbumOverview(origin?.filter ?? "ente");
+ }, [
+ albumOpenedFromOverview,
+ navigation.destination.collectionID,
+ setAlbumSearchQuery,
+ showAlbumOverview,
+ ]);
+ const openOverviewAlbum = useCallback(
+ (collectionID: number) => {
+ showSummary(collectionID);
+ setAlbumOpenedFromOverview({
+ collectionID,
+ filter: navigation.destination.albumFilter!,
+ searchQuery: albumSearchQuery,
+ });
+ },
+ [
+ albumSearchQuery,
+ navigation.destination.albumFilter,
+ setAlbumOpenedFromOverview,
+ showSummary,
+ ],
+ );
+ return useMemo(
+ () => ({
+ showCollectionSummary,
+ goHome,
+ selectCollection,
+ selectCollectionFromViewer,
+ showAlbumOverview,
+ backToAlbums,
+ openOverviewAlbum,
+ }),
+ [
+ showCollectionSummary,
+ goHome,
+ selectCollection,
+ selectCollectionFromViewer,
+ showAlbumOverview,
+ backToAlbums,
+ openOverviewAlbum,
+ ],
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/use-album-navigation-data.ts b/web/apps/photos/src/components/gallery/sections/albums/use-album-navigation-data.ts
similarity index 67%
rename from web/apps/photos/src/components/gallery/use-album-navigation-data.ts
rename to web/apps/photos/src/components/gallery/sections/albums/use-album-navigation-data.ts
index cc6383e75b..5fa24b86d1 100644
--- a/web/apps/photos/src/components/gallery/use-album-navigation-data.ts
+++ b/web/apps/photos/src/components/gallery/sections/albums/use-album-navigation-data.ts
@@ -6,20 +6,19 @@ import {
import {
PseudoCollectionID,
sortCollectionSummaries,
- collectionsSortBy as supportedCollectionsSortBy,
type CollectionSummaries,
type CollectionsSortBy,
} from "ente-new/photos/services/collection-summary";
-import { includes } from "ente-utils/type-guards";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import type { GalleryBarMode } from "./reducer";
+import { useMemo } from "react";
+import type { GalleryBarMode } from "../../reducer";
interface AlbumNavigationDataOptions {
- mode: GalleryBarMode;
+ mode: Exclude<GalleryBarMode, "links"> | undefined;
collectionSummaries: CollectionSummaries;
uncategorizedCollectionSummaryID: number;
albumFilter: AlbumFilter;
albumSearchQuery: string;
+ collectionsSortBy: CollectionsSortBy;
}
// Prepare the shared album ordering and the sidebar and overview lists.
@@ -29,31 +28,17 @@ export const useAlbumNavigationData = ({
uncategorizedCollectionSummaryID,
albumFilter,
albumSearchQuery,
+ collectionsSortBy,
}: AlbumNavigationDataOptions) => {
- const [collectionsSortBy, setCollectionsSortBy] =
- useState<CollectionsSortBy>("updation-time-desc");
-
- useEffect(() => {
- const value = localStorage.getItem("collectionsSortBy");
- if (value && includes(supportedCollectionsSortBy, value))
- setCollectionsSortBy(value);
- }, []);
-
- const onChangeCollectionsSortBy = useCallback(
- (value: CollectionsSortBy) => {
- localStorage.setItem("collectionsSortBy", value);
- setCollectionsSortBy(value);
- },
- [],
- );
-
const sortedCollectionSummaries = useMemo(
() =>
- sortCollectionSummaries(
- [...collectionSummaries.values()],
- collectionsSortBy,
- ).sort((a, b) => b.sortPriority - a.sortPriority),
- [collectionsSortBy, collectionSummaries],
+ mode === undefined
+ ? []
+ : sortCollectionSummaries(
+ [...collectionSummaries.values()],
+ collectionsSortBy,
+ ).sort((a, b) => b.sortPriority - a.sortPriority),
+ [mode, collectionsSortBy, collectionSummaries],
);
const eligibleCollectionSummaries = useMemo(
() =>
@@ -98,11 +83,5 @@ export const useAlbumNavigationData = ({
[eligibleCollectionSummaries, albumFilter, albumSearchQuery],
);
- return {
- sidebarCollectionSummaries,
- overviewAlbums,
- visibleAlbumFilters,
- collectionsSortBy,
- onChangeCollectionsSortBy,
- };
+ return { sidebarCollectionSummaries, overviewAlbums, visibleAlbumFilters };
};
diff --git a/web/apps/photos/src/components/gallery/hooks/use-gallery-slideshow.ts b/web/apps/photos/src/components/gallery/sections/albums/use-gallery-slideshow.ts
similarity index 100%
rename from web/apps/photos/src/components/gallery/hooks/use-gallery-slideshow.ts
rename to web/apps/photos/src/components/gallery/sections/albums/use-gallery-slideshow.ts
diff --git a/web/apps/photos/src/components/gallery/DuplicatesView.tsx b/web/apps/photos/src/components/gallery/sections/cleanup/DuplicatesView.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/DuplicatesView.tsx
rename to web/apps/photos/src/components/gallery/sections/cleanup/DuplicatesView.tsx
diff --git a/web/apps/photos/src/components/gallery/LargeFilesView.tsx b/web/apps/photos/src/components/gallery/sections/cleanup/LargeFilesView.tsx
similarity index 100%
rename from web/apps/photos/src/components/gallery/LargeFilesView.tsx
rename to web/apps/photos/src/components/gallery/sections/cleanup/LargeFilesView.tsx
diff --git a/web/apps/photos/src/components/gallery/sections/links/LinksNavigation.tsx b/web/apps/photos/src/components/gallery/sections/links/LinksNavigation.tsx
new file mode 100644
index 0000000000..a2b70fe557
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/links/LinksNavigation.tsx
@@ -0,0 +1,195 @@
+import { CollectionsSortOptions } from "@/components/CollectionsSortOptions";
+import { ArrowDown01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box, Stack, useMediaQuery, useTheme } from "@mui/material";
+import type {
+ CollectionSummary,
+ CollectionsSortBy,
+} from "ente-new/photos/services/collection-summary";
+import { t } from "i18next";
+import { memo, useEffect, useMemo, useRef, useState } from "react";
+import AutoSizer from "react-virtualized-auto-sizer";
+import {
+ FixedSizeList,
+ areEqual,
+ type ListChildComponentProps,
+} from "react-window";
+import {
+ BarCard,
+ CardText,
+ CollectionBarCard,
+ NavigationEmptyState,
+ NavigationFrame,
+ type GalleryBarPresentationProps,
+} from "../../navigation/NavigationPrimitives";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
+
+interface LinksNavigationProps extends GalleryBarPresentationProps {
+ collectionSummaries: CollectionSummary[];
+ selectedLinkID: number | undefined;
+ searchQuery: string;
+ onSearchQueryChange: (query: string) => void;
+ collectionsSortBy: CollectionsSortBy;
+ onChangeCollectionsSortBy: (by: CollectionsSortBy) => void;
+}
+
+export const LinksNavigation = ({
+ collectionSummaries,
+ selectedLinkID,
+ searchQuery,
+ onSearchQueryChange,
+ collectionsSortBy,
+ onChangeCollectionsSortBy,
+ collapsed,
+ mobileDrawerProps,
+}: LinksNavigationProps) => {
+ const {
+ selectCollection: onSelectLink,
+ showLinksOverview: onShowOverview,
+ } = usePhotosNavigation();
+ const { onClose } = mobileDrawerProps;
+ const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
+ const listRef = useRef<FixedSizeList>(null);
+ const [groupExpanded, setGroupExpanded] = useState(true);
+ const [viewportHeight, setViewportHeight] = useState(0);
+ const isSearching = !!searchQuery.trim().toLowerCase();
+ const isGroupOverview = selectedLinkID === undefined;
+ const rowHeight = mobile ? 46 : 50;
+ const itemData = useMemo(
+ () => ({
+ collectionSummaries,
+ activeCollectionID: selectedLinkID,
+ onSelectCollectionID: (id: number) => {
+ onSelectLink(id);
+ onClose();
+ },
+ }),
+ [collectionSummaries, selectedLinkID, onSelectLink, onClose],
+ );
+
+ useEffect(() => {
+ if (isSearching) listRef.current?.scrollTo(0);
+ }, [searchQuery, isSearching]);
+ useEffect(() => {
+ if (isSearching || !listRef.current) return;
+ const i = collectionSummaries.findIndex(
+ ({ id }) => id === selectedLinkID,
+ );
+ if (i !== -1) listRef.current.scrollToItem(i, "smart");
+ }, [
+ collectionSummaries,
+ selectedLinkID,
+ collapsed,
+ mobile,
+ mobileDrawerProps.open,
+ viewportHeight,
+ isSearching,
+ ]);
+
+ return (
+ <NavigationFrame
+ title={t("links")}
+ actions={
+ <CollectionsSortOptions
+ variant="v2"
+ activeSortBy={collectionsSortBy}
+ onChangeSortBy={onChangeCollectionsSortBy}
+ />
+ }
+ searchPlaceholder={t("search_links")}
+ searchQuery={searchQuery}
+ setSearchQuery={onSearchQueryChange}
+ mobileDrawerProps={mobileDrawerProps}
+ >
+ {isSearching && !collectionSummaries.length ? (
+ <NavigationEmptyState />
+ ) : (
+ <Stack
+ role="group"
+ aria-label={t("links")}
+ sx={{ flex: 1, minHeight: 0, minWidth: 0 }}
+ >
+ <BarCard
+ aria-current={isGroupOverview ? "page" : undefined}
+ aria-expanded={isSearching || groupExpanded}
+ onClick={() => {
+ setGroupExpanded(
+ !isGroupOverview || !groupExpanded,
+ );
+ onShowOverview();
+ onClose();
+ }}
+ sx={{ flexShrink: 0, height: rowHeight }}
+ >
+ <CardText>{t("links")}</CardText>
+ <Box
+ component={HugeiconsIcon}
+ icon={ArrowDown01Icon}
+ size={16}
+ strokeWidth={1.8}
+ sx={{
+ color: "text.muted",
+ transform:
+ isSearching || groupExpanded
+ ? undefined
+ : "rotate(-90deg)",
+ }}
+ />
+ </BarCard>
+ {(isSearching || groupExpanded) && (
+ <Box sx={{ flex: 1, minHeight: 0, minWidth: 0 }}>
+ <AutoSizer
+ onResize={({ height }) =>
+ setViewportHeight(height)
+ }
+ >
+ {({ width, height }) => (
+ <FixedSizeList
+ ref={listRef}
+ width={width}
+ height={height}
+ itemData={itemData}
+ itemKey={(index, data) =>
+ `collections-${data.collectionSummaries[index]!.id}-${data.collectionSummaries[index]!.coverFile?.id}`
+ }
+ itemCount={collectionSummaries.length}
+ itemSize={rowHeight}
+ style={{ overflowX: "hidden" }}
+ >
+ {LinkRow}
+ </FixedSizeList>
+ )}
+ </AutoSizer>
+ </Box>
+ )}
+ </Stack>
+ )}
+ </NavigationFrame>
+ );
+};
+
+const LinkRow = memo(
+ ({
+ data,
+ index,
+ style,
+ }: ListChildComponentProps<{
+ collectionSummaries: CollectionSummary[];
+ activeCollectionID: number | undefined;
+ onSelectCollectionID: (id: number) => void;
+ }>) => {
+ const collectionSummary = data.collectionSummaries[index]!;
+ return (
+ <div style={style}>
+ <CollectionBarCard
+ key={collectionSummary.id}
+ collectionSummary={collectionSummary}
+ activeCollectionID={data.activeCollectionID}
+ onSelectCollectionID={data.onSelectCollectionID}
+ indented={!collectionSummary.attributes.has("system")}
+ />
+ </div>
+ );
+ },
+ areEqual,
+);
diff --git a/web/apps/photos/src/components/gallery/sections/links/LinksSection.tsx b/web/apps/photos/src/components/gallery/sections/links/LinksSection.tsx
new file mode 100644
index 0000000000..3074b92318
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/links/LinksSection.tsx
@@ -0,0 +1,35 @@
+import type { GallerySectionProps } from "../types";
+import { LinksView } from "./LinksView";
+
+export const LinksSection = ({
+ library,
+ operations,
+ navigation,
+ preferences,
+ presentation,
+}: GallerySectionProps) => {
+ const selectedLinkID = navigation.destination.collectionID;
+ return (
+ <LinksView
+ {...{ presentation, selectedLinkID }}
+ user={library.user!}
+ collections={library.collections}
+ collectionFiles={library.collectionFiles}
+ collectionSummaries={library.normalCollectionSummaries}
+ hiddenCollectionIDs={library.hiddenCollectionIDs}
+ hiddenFileIDs={library.hiddenFileIDs}
+ tempDeletedFileIDs={library.tempDeletedFileIDs}
+ tempHiddenFileIDs={library.tempHiddenFileIDs}
+ uncategorizedCollectionSummaryID={
+ library.uncategorizedCollectionSummaryID
+ }
+ searchQuery={preferences.albumSearchQuery}
+ onSearchQueryChange={preferences.setAlbumSearchQuery}
+ sortBy={preferences.collectionsSortBy}
+ onChangeSortBy={preferences.onChangeCollectionsSortBy}
+ onCreateAlbum={operations.onCreateAlbum}
+ setBlockingLoad={operations.setBlockingLoad}
+ onRemotePull={operations.onRemotePull}
+ />
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/LinksView.tsx b/web/apps/photos/src/components/gallery/sections/links/LinksView.tsx
similarity index 78%
rename from web/apps/photos/src/components/gallery/LinksView.tsx
rename to web/apps/photos/src/components/gallery/sections/links/LinksView.tsx
index c173cff42d..866703871c 100644
--- a/web/apps/photos/src/components/gallery/LinksView.tsx
+++ b/web/apps/photos/src/components/gallery/sections/links/LinksView.tsx
@@ -10,11 +10,19 @@ import {
} from "ente-new/photos/services/collection-summary";
import { t } from "i18next";
import { useMemo } from "react";
-import type { RemotePullOpts } from ".";
-import { AlbumsOverview } from "./AlbumsOverview";
+import type { RemotePullOpts } from "../..";
+import {
+ GallerySectionLayout,
+ type GallerySectionPresentation,
+} from "../../navigation/GallerySectionLayout";
+import { AlbumsOverview } from "../albums/AlbumsOverview";
+import { LinksNavigation } from "./LinksNavigation";
import { PublicLinkDetails } from "./PublicLinkDetails";
interface LinksViewProps {
+ presentation: GallerySectionPresentation;
+ onSearchQueryChange: (query: string) => void;
+ onChangeSortBy: (sortBy: CollectionsSortBy) => void;
user: LocalUser;
collections: Collection[];
collectionFiles: EnteFile[];
@@ -33,6 +41,9 @@ interface LinksViewProps {
}
export const LinksView = ({
+ presentation,
+ onSearchQueryChange,
+ onChangeSortBy,
user,
collections,
collectionFiles,
@@ -100,7 +111,7 @@ export const LinksView = ({
uncategorizedCollectionSummaryID,
]);
- return selectedLink ? (
+ const content = selectedLink ? (
<PublicLinkDetails
key={selectedLink.id}
collection={selectedLink}
@@ -124,4 +135,22 @@ export const LinksView = ({
onRemotePull={onRemotePull}
/>
);
+ return (
+ <GallerySectionLayout
+ presentation={presentation}
+ navigation={
+ <LinksNavigation
+ {...presentation}
+ collectionSummaries={overviewLinks}
+ selectedLinkID={selectedLink?.id}
+ searchQuery={searchQuery}
+ onSearchQueryChange={onSearchQueryChange}
+ collectionsSortBy={sortBy}
+ onChangeCollectionsSortBy={onChangeSortBy}
+ />
+ }
+ >
+ {content}
+ </GallerySectionLayout>
+ );
};
diff --git a/web/apps/photos/src/components/gallery/PublicLinkDetails.tsx b/web/apps/photos/src/components/gallery/sections/links/PublicLinkDetails.tsx
similarity index 99%
rename from web/apps/photos/src/components/gallery/PublicLinkDetails.tsx
rename to web/apps/photos/src/components/gallery/sections/links/PublicLinkDetails.tsx
index d57e5b3b70..914625d264 100644
--- a/web/apps/photos/src/components/gallery/PublicLinkDetails.tsx
+++ b/web/apps/photos/src/components/gallery/sections/links/PublicLinkDetails.tsx
@@ -29,7 +29,7 @@ import {
import { openURL } from "ente-new/photos/utils/web";
import { t } from "i18next";
import { useState } from "react";
-import type { RemotePullOpts } from ".";
+import type { RemotePullOpts } from "../..";
interface PublicLinkDetailsProps {
collection: Collection;
diff --git a/web/apps/photos/src/components/gallery/sections/links/link-selection.ts b/web/apps/photos/src/components/gallery/sections/links/link-selection.ts
new file mode 100644
index 0000000000..7210b9bb3b
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/links/link-selection.ts
@@ -0,0 +1,18 @@
+import { visibleQuickLinks } from "../../../../utils/quick-links";
+import type { GalleryDestination } from "../../navigation/navigation-state";
+import type { GalleryState } from "../../reducer";
+
+export const resolveLinksDestination = (
+ library: GalleryState,
+ destination: GalleryDestination,
+): GalleryDestination => {
+ const id = destination.collectionID;
+ if (id === undefined || !library.user) return destination;
+ return visibleQuickLinks(
+ library.collections,
+ library.user.id,
+ library.hiddenCollectionIDs,
+ ).some((link) => link.id === id)
+ ? destination
+ : { ...destination, collectionID: undefined };
+};
diff --git a/web/apps/photos/src/components/gallery/PeopleHeader.tsx b/web/apps/photos/src/components/gallery/sections/people/PeopleHeader.tsx
similarity index 99%
rename from web/apps/photos/src/components/gallery/PeopleHeader.tsx
rename to web/apps/photos/src/components/gallery/sections/people/PeopleHeader.tsx
index d85b64ffec..bbfae8835a 100644
--- a/web/apps/photos/src/components/gallery/PeopleHeader.tsx
+++ b/web/apps/photos/src/components/gallery/sections/people/PeopleHeader.tsx
@@ -97,7 +97,7 @@ import type {
} from "ente-new/photos/services/ml/people";
import { t } from "i18next";
import React, { useEffect, useReducer, useState } from "react";
-import { usePhotosNavigation } from "./PhotosNavigationContext";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
interface PeopleHeaderProps {
people: Person[];
diff --git a/web/apps/photos/src/components/gallery/sections/people/PeopleNavigation.tsx b/web/apps/photos/src/components/gallery/sections/people/PeopleNavigation.tsx
new file mode 100644
index 0000000000..b546cef1a8
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/people/PeopleNavigation.tsx
@@ -0,0 +1,205 @@
+import { PeopleSortOptions } from "@/components/PeopleSortOptions";
+import type { PeopleSortBy } from "@/utils/people-sort";
+import { PinIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box, ButtonBase, useMediaQuery, useTheme } from "@mui/material";
+import { ItemCard } from "ente-new/photos/components/Tiles";
+import type { Person } from "ente-new/photos/services/ml/people";
+import { t } from "i18next";
+import React, { memo, useEffect, useMemo, useRef, useState } from "react";
+import AutoSizer from "react-virtualized-auto-sizer";
+import {
+ FixedSizeList,
+ areEqual,
+ type ListChildComponentProps,
+} from "react-window";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
+
+import {
+ BarCard,
+ BarThumbnail,
+ CardText,
+ CollectionBarCardIcon_,
+ NavigationEmptyState,
+ NavigationFrame,
+ type GalleryBarPresentationProps,
+} from "../../navigation/NavigationPrimitives";
+interface PeopleNavigationProps extends GalleryBarPresentationProps {
+ people: Person[];
+ activePerson: Person | undefined;
+ peopleSortBy: PeopleSortBy;
+ onChangePeopleSortBy: (sort: PeopleSortBy) => void;
+}
+export const PeopleNavigation = ({
+ people,
+ activePerson,
+ peopleSortBy,
+ onChangePeopleSortBy,
+ collapsed,
+ mobileDrawerProps,
+}: PeopleNavigationProps) => {
+ const { selectPerson, showPeople } = usePhotosNavigation();
+ const { onClose } = mobileDrawerProps;
+ const mobile = useMediaQuery(useTheme().breakpoints.down("md"));
+ const [searchQuery, setSearchQuery] = useState("");
+ const [viewportHeight, setViewportHeight] = useState(0);
+ const listRef = useRef<FixedSizeList>(null);
+ const query = searchQuery.trim().toLowerCase();
+ const isSearching = !!query;
+ const matchingPeople = useMemo(
+ () =>
+ isSearching
+ ? people.filter((p) => p.name?.toLowerCase().includes(query))
+ : people,
+ [people, isSearching, query],
+ );
+ useEffect(() => {
+ if (mobile ? !mobileDrawerProps.open : collapsed) setSearchQuery("");
+ }, [mobile, mobileDrawerProps.open, collapsed]);
+ useEffect(() => {
+ if (isSearching) listRef.current?.scrollTo(0);
+ }, [searchQuery, isSearching]);
+ useEffect(() => {
+ if (isSearching) return;
+ const index = matchingPeople.findIndex((p) => p.id == activePerson?.id);
+ if (index != -1) listRef.current?.scrollToItem(index, "smart");
+ }, [
+ matchingPeople,
+ activePerson,
+ collapsed,
+ mobile,
+ mobileDrawerProps.open,
+ viewportHeight,
+ isSearching,
+ ]);
+ const itemData = useMemo(
+ () => ({
+ people: matchingPeople,
+ activePerson,
+ onSelectPerson: (id: string) => {
+ selectPerson(id);
+ onClose();
+ },
+ }),
+ [matchingPeople, activePerson, selectPerson, onClose],
+ );
+ return (
+ <NavigationFrame
+ title={
+ <ButtonBase
+ onClick={() => {
+ setSearchQuery("");
+ showPeople();
+ onClose();
+ }}
+ sx={{
+ font: "inherit",
+ justifyContent: "flex-start",
+ borderRadius: 1,
+ "&:hover": { color: "text.muted" },
+ "&.Mui-focusVisible": {
+ outline: "2px solid",
+ outlineColor: "primary.main",
+ outlineOffset: 2,
+ },
+ }}
+ >
+ {t("people")}
+ </ButtonBase>
+ }
+ actions={
+ <PeopleSortOptions
+ variant="v2"
+ activeSortBy={peopleSortBy}
+ onChangeSortBy={onChangePeopleSortBy}
+ />
+ }
+ searchPlaceholder={t("people_search_hint")}
+ searchQuery={searchQuery}
+ setSearchQuery={setSearchQuery}
+ mobileDrawerProps={mobileDrawerProps}
+ >
+ {isSearching && !matchingPeople.length ? (
+ <NavigationEmptyState />
+ ) : (
+ <Box sx={{ flex: 1, minHeight: 0, minWidth: 0 }}>
+ <AutoSizer
+ onResize={({ height }) => setViewportHeight(height)}
+ >
+ {({ width, height }) => (
+ <FixedSizeList
+ ref={listRef}
+ width={width}
+ height={height}
+ itemData={itemData}
+ itemKey={(index, data) =>
+ `people-${data.people[index]!.id}-${data.people[index]!.displayFaceID}`
+ }
+ itemCount={matchingPeople.length}
+ itemSize={mobile ? 46 : 50}
+ style={{ overflowX: "hidden" }}
+ >
+ {PersonRow}
+ </FixedSizeList>
+ )}
+ </AutoSizer>
+ </Box>
+ )}
+ </NavigationFrame>
+ );
+};
+const PersonRow = memo(
+ ({
+ data,
+ index,
+ style,
+ }: ListChildComponentProps<{
+ people: Person[];
+ activePerson: Person | undefined;
+ onSelectPerson: (id: string) => void;
+ }>) => (
+ <div style={style}>
+ <PersonCard
+ person={data.people[index]!}
+ activePerson={data.activePerson}
+ onSelectPerson={data.onSelectPerson}
+ />
+ </div>
+ ),
+ areEqual,
+);
+interface PersonCardProps {
+ person: Person;
+ activePerson: Person | undefined;
+ onSelectPerson: (personID: string) => void;
+}
+
+const PersonCard: React.FC<PersonCardProps> = ({
+ person,
+ activePerson,
+ onSelectPerson,
+}) => (
+ <BarCard
+ aria-label={person.name || t("unnamed_person")}
+ aria-current={activePerson?.id === person.id ? "true" : undefined}
+ title={person.name || t("unnamed_person")}
+ onClick={() => onSelectPerson(person.id)}
+ >
+ <Box
+ aria-hidden
+ sx={{ flexShrink: 0, borderRadius: "50%", overflow: "hidden" }}
+ >
+ <ItemCard
+ TileComponent={BarThumbnail}
+ coverFile={person.displayFaceFile}
+ coverFaceID={person.displayFaceID}
+ />
+ </Box>
+ <CardText>{person.name || t("unnamed_person")}</CardText>
+ {person.isPinned && (
+ <CollectionBarCardIcon_ aria-hidden>
+ <HugeiconsIcon icon={PinIcon} size={14} />
+ </CollectionBarCardIcon_>
+ )}
+ </BarCard>
+);
diff --git a/web/apps/photos/src/components/gallery/PeopleOverview.tsx b/web/apps/photos/src/components/gallery/sections/people/PeopleOverview.tsx
similarity index 99%
rename from web/apps/photos/src/components/gallery/PeopleOverview.tsx
rename to web/apps/photos/src/components/gallery/sections/people/PeopleOverview.tsx
index 7dd17037ec..211280bc8b 100644
--- a/web/apps/photos/src/components/gallery/PeopleOverview.tsx
+++ b/web/apps/photos/src/components/gallery/sections/people/PeopleOverview.tsx
@@ -18,8 +18,8 @@ import { t } from "i18next";
import { useMemo, useState } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
import { VariableSizeList, type ListChildComponentProps } from "react-window";
-import { PeopleEmptyState } from ".";
-import { usePhotosNavigation } from "./PhotosNavigationContext";
+import { PeopleEmptyState } from "../..";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
export const PeopleOverview = ({
people,
diff --git a/web/apps/photos/src/components/gallery/sections/people/PeopleSection.tsx b/web/apps/photos/src/components/gallery/sections/people/PeopleSection.tsx
new file mode 100644
index 0000000000..32275a0ee3
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/people/PeopleSection.tsx
@@ -0,0 +1,110 @@
+import { sortPeople } from "@/utils/people-sort";
+import { useEffect, useMemo } from "react";
+import { GalleryMedia } from "../../media/GalleryMedia";
+import { GallerySectionLayout } from "../../navigation/GallerySectionLayout";
+import type { GallerySectionProps } from "../types";
+import { derivePeopleFilteredFiles, derivePeopleView } from "./people-files";
+import { PeopleHeader } from "./PeopleHeader";
+import { PeopleNavigation } from "./PeopleNavigation";
+import { PeopleOverview } from "./PeopleOverview";
+
+export const PeopleSection = ({
+ library,
+ operations,
+ navigation,
+ preferences,
+ presentation,
+}: GallerySectionProps) => {
+ const { personID, extraVisiblePersonID } = navigation.destination;
+ const { view, extraVisiblePerson } = useMemo(
+ () =>
+ derivePeopleView(
+ library.peopleState,
+ library.tempDeletedFileIDs,
+ library.tempHiddenFileIDs,
+ personID,
+ library.peopleState?.people.find(
+ (p) => p.id === extraVisiblePersonID,
+ ),
+ ),
+ [
+ library.peopleState,
+ library.tempDeletedFileIDs,
+ library.tempHiddenFileIDs,
+ personID,
+ extraVisiblePersonID,
+ ],
+ );
+ const files = useMemo(
+ () =>
+ derivePeopleFilteredFiles(
+ library.collectionFiles,
+ library.hiddenFileIDs,
+ view,
+ library.user?.id,
+ ),
+ [
+ library.collectionFiles,
+ library.hiddenFileIDs,
+ view,
+ library.user?.id,
+ ],
+ );
+ const { retainPerson } = navigation;
+ useEffect(() => {
+ retainPerson(view.activePerson?.id, extraVisiblePerson?.id);
+ }, [view.activePerson?.id, extraVisiblePerson?.id, retainPerson]);
+ const people = useMemo(
+ () => sortPeople(view.visiblePeople, preferences.peopleSortBy),
+ [view.visiblePeople, preferences.peopleSortBy],
+ );
+ const activePerson = view.activePerson;
+ const visiblePeople = view.visiblePeople;
+ const header = useMemo(
+ () => ({
+ component: activePerson ? (
+ <PeopleHeader person={activePerson} people={visiblePeople} />
+ ) : (
+ <></>
+ ),
+ height: 72,
+ }),
+ [activePerson, visiblePeople],
+ );
+ return (
+ <GallerySectionLayout
+ presentation={presentation}
+ navigation={
+ <PeopleNavigation
+ {...presentation}
+ people={people}
+ activePerson={activePerson}
+ peopleSortBy={preferences.peopleSortBy}
+ onChangePeopleSortBy={preferences.setPeopleSortBy}
+ />
+ }
+ >
+ {!library.isFirstLoad && !activePerson ? (
+ <PeopleOverview
+ people={view.visiblePeople}
+ allPeople={view.people}
+ peopleSortBy={preferences.peopleSortBy}
+ />
+ ) : (
+ <GalleryMedia
+ {...{ library, operations, navigation }}
+ header={header}
+ source={{
+ mode: "people",
+ modePlus: "people",
+ files,
+ activeCollectionID: undefined,
+ activePersonID: activePerson?.id,
+ activeCollectionSummary: undefined,
+ disableGrouping: false,
+ }}
+ />
+ )}
+ </GallerySectionLayout>
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/sections/people/people-files.ts b/web/apps/photos/src/components/gallery/sections/people/people-files.ts
new file mode 100644
index 0000000000..f10197b0fa
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/people/people-files.ts
@@ -0,0 +1,107 @@
+import { uniqueFilesByID } from "ente-gallery/utils/file";
+import type { Person } from "ente-new/photos/services/ml/people";
+import { suppressSharedFilesSavedByUser } from "../../media/media-files";
+import type { GalleryDestination } from "../../navigation/navigation-state";
+import type { GalleryState } from "../../reducer";
+import type { GalleryView } from "../view-types";
+export const derivePeopleView = (
+ peopleState: GalleryState["peopleState"],
+ tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],
+ tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],
+ selectedPersonID: string | undefined,
+ extraVisiblePerson: Person | undefined,
+): {
+ view: Extract<GalleryView, { type: "people" }>;
+ extraVisiblePerson: Person | undefined;
+} => {
+ let people = peopleState?.people ?? [];
+ let visiblePeople = peopleState?.visiblePeople ?? [];
+ if (tempDeletedFileIDs.size + tempHiddenFileIDs.size > 0) {
+ const filterTemp = (ps: Person[]) =>
+ ps
+ .map((p) => ({
+ ...p,
+ fileIDs: p.fileIDs.filter(
+ (id) =>
+ !tempDeletedFileIDs.has(id) &&
+ !tempHiddenFileIDs.has(id),
+ ),
+ }))
+ .filter((p) => p.fileIDs.length > 0);
+ people = filterTemp(people);
+ visiblePeople = filterTemp(visiblePeople);
+ }
+
+ // Keep a selected small cluster visible until the user leaves this view.
+ if (extraVisiblePerson) {
+ if (!people.find((p) => p.id == extraVisiblePerson?.id))
+ extraVisiblePerson = undefined;
+ }
+
+ const findByIDIn = (ps: Person[]) =>
+ ps.find((p) => p.id == selectedPersonID);
+ let activePerson = findByIDIn(visiblePeople);
+ if (!activePerson) {
+ activePerson = findByIDIn(people);
+ if (activePerson) {
+ extraVisiblePerson = activePerson;
+ }
+ }
+
+ const view = {
+ type: "people" as const,
+ people,
+ visiblePeople: extraVisiblePerson
+ ? visiblePeople.concat([extraVisiblePerson])
+ : visiblePeople,
+ activePerson,
+ };
+
+ return { view, extraVisiblePerson };
+};
+export const derivePeopleFilteredFiles = (
+ collectionFiles: GalleryState["collectionFiles"],
+ hiddenFileIDs: GalleryState["hiddenFileIDs"],
+ view: Extract<GalleryView, { type: "people" }>,
+ currentUserID: number | undefined,
+) => {
+ const pfSet = new Set(view.activePerson?.fileIDs ?? []);
+ return uniqueFilesByID(
+ suppressSharedFilesSavedByUser(
+ collectionFiles.filter((f) => {
+ if (!pfSet.has(f.id)) return false;
+ if (hiddenFileIDs.has(f.id)) return false;
+ return true;
+ }),
+ currentUserID,
+ undefined,
+ ),
+ );
+};
+
+export const resolvePeopleDestination = (
+ library: GalleryState,
+ destination: GalleryDestination,
+): GalleryDestination => {
+ const exists = (id: string | undefined) =>
+ id !== undefined &&
+ library.peopleState?.people.some(
+ (person) =>
+ person.id === id &&
+ person.fileIDs.some(
+ (fileID) =>
+ !library.tempDeletedFileIDs.has(fileID) &&
+ !library.tempHiddenFileIDs.has(fileID),
+ ),
+ );
+ const personID = exists(destination.personID)
+ ? destination.personID
+ : undefined;
+ const extraVisiblePersonID = exists(destination.extraVisiblePersonID)
+ ? destination.extraVisiblePersonID
+ : undefined;
+ return personID === destination.personID &&
+ extraVisiblePersonID === destination.extraVisiblePersonID
+ ? destination
+ : { ...destination, personID, extraVisiblePersonID };
+};
diff --git a/web/apps/photos/src/components/gallery/sections/people/use-people-entry.ts b/web/apps/photos/src/components/gallery/sections/people/use-people-entry.ts
new file mode 100644
index 0000000000..d0a9f4bae3
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/people/use-people-entry.ts
@@ -0,0 +1,47 @@
+import type { PeopleConsentDialog } from "@/components/gallery";
+import { useModalVisibility } from "ente-base/components/utils/modal";
+import { useMLStatusSnapshot } from "ente-new/photos/components/utils/use-snapshot";
+import { isMLEnabled } from "ente-new/photos/services/ml";
+import { useCallback, useEffect, useRef, type ComponentProps } from "react";
+
+export const usePeopleEntry = ({
+ isCurrentDestination,
+ onUnavailable,
+ onNavigate,
+}: {
+ isCurrentDestination: boolean;
+ onUnavailable: () => void;
+ onNavigate: () => void;
+}) => {
+ const mlStatus = useMLStatusSnapshot();
+ const { show: showConsent, props: consentProps } = useModalVisibility();
+ const pendingSearchReset = useRef<(() => void) | undefined>(undefined);
+ useEffect(() => {
+ if (isCurrentDestination && mlStatus?.phase == "disabled")
+ onUnavailable();
+ }, [isCurrentDestination, mlStatus?.phase, onUnavailable]);
+ const showPeople = useCallback(
+ (resetSearch?: () => void) => {
+ if (!isMLEnabled()) {
+ pendingSearchReset.current = resetSearch;
+ showConsent();
+ return false;
+ }
+ resetSearch?.();
+ onNavigate();
+ return true;
+ },
+ [showConsent, onNavigate],
+ );
+ const dialogProps: ComponentProps<typeof PeopleConsentDialog> = {
+ ...consentProps,
+ onClose: () => {
+ pendingSearchReset.current = undefined;
+ consentProps.onClose();
+ },
+ onEnabled: () => {
+ showPeople(pendingSearchReset.current);
+ },
+ };
+ return { showPeople, dialogProps };
+};
diff --git a/web/apps/photos/src/components/gallery/PlacesList.tsx b/web/apps/photos/src/components/gallery/sections/places/PlacesList.tsx
similarity index 99%
rename from web/apps/photos/src/components/gallery/PlacesList.tsx
rename to web/apps/photos/src/components/gallery/sections/places/PlacesList.tsx
index f246d90905..9b301e0fba 100644
--- a/web/apps/photos/src/components/gallery/PlacesList.tsx
+++ b/web/apps/photos/src/components/gallery/sections/places/PlacesList.tsx
@@ -13,7 +13,7 @@ import type { EnteFile } from "ente-media/file";
import { ItemCard, PreviewItemTile } from "ente-new/photos/components/Tiles";
import { t } from "i18next";
import { useEffect, useRef, useState } from "react";
-import { listPlaces } from "../../services/places";
+import { listPlaces } from "../../../../services/places";
export interface PlaceSelection {
latitude: number;
diff --git a/web/apps/photos/src/components/gallery/sections/places/PlacesSection.tsx b/web/apps/photos/src/components/gallery/sections/places/PlacesSection.tsx
new file mode 100644
index 0000000000..ecf9def7e9
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/places/PlacesSection.tsx
@@ -0,0 +1,91 @@
+import { CollectionMap } from "@/components/collections/CollectionMap";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import { t } from "i18next";
+import { useMemo, useState } from "react";
+import { GallerySectionLayout } from "../../navigation/GallerySectionLayout";
+import { homeDestination } from "../../navigation/navigation-state";
+import { NavigationFrame } from "../../navigation/NavigationPrimitives";
+import { usePhotosNavigation } from "../../navigation/PhotosNavigationContext";
+import { albumFiles, albumView } from "../albums/album-files";
+import type { GallerySectionProps } from "../types";
+import { PlacesList } from "./PlacesList";
+
+export const PlacesSection = ({
+ library,
+ operations,
+ navigation,
+ presentation,
+}: GallerySectionProps) => {
+ const files = useMemo(
+ () => albumFiles(library, albumView(library, homeDestination)),
+ [library],
+ );
+ const [query, setQuery] = useState("");
+ const { selectPlace } = usePhotosNavigation();
+ const mapFileSource = useMemo(
+ () => ({
+ collectionFiles: library.collectionFiles,
+ favoriteFileIDs: library.favoriteFileIDs,
+ hiddenFileIDs: library.hiddenFileIDs,
+ archivedFileIDs: library.archivedFileIDs,
+ tempDeletedFileIDs: library.tempDeletedFileIDs,
+ tempHiddenFileIDs: library.tempHiddenFileIDs,
+ }),
+ [
+ library.collectionFiles,
+ library.favoriteFileIDs,
+ library.hiddenFileIDs,
+ library.archivedFileIDs,
+ library.tempDeletedFileIDs,
+ library.tempHiddenFileIDs,
+ ],
+ );
+ const summary = library.normalCollectionSummaries.get(
+ PseudoCollectionID.all,
+ );
+ return (
+ <GallerySectionLayout
+ presentation={presentation}
+ fullBleed
+ navigation={
+ <NavigationFrame
+ title={t("search_places")}
+ actions={null}
+ searchPlaceholder={t("search_in_places")}
+ searchQuery={query}
+ setSearchQuery={setQuery}
+ mobileDrawerProps={presentation.mobileDrawerProps}
+ >
+ <PlacesList
+ files={files}
+ searchQuery={query}
+ selectedPlace={navigation.selectedPlace}
+ onSelectPlace={(place) => {
+ selectPlace(place);
+ presentation.mobileDrawerProps.onClose();
+ }}
+ />
+ </NavigationFrame>
+ }
+ >
+ {summary && (
+ <CollectionMap
+ collectionSummary={summary}
+ files={files}
+ selectedPlace={navigation.selectedPlace}
+ placeSelectionRevision={navigation.placeSelectionRevision}
+ mapFileSource={mapFileSource}
+ onRemotePull={operations.onRemotePull}
+ onAddSaveGroup={operations.onAddSaveGroup}
+ onMarkTempDeleted={operations.onMarkTempDeleted}
+ onAddFileToCollection={operations.onAddFileToCollection}
+ onRemoteFilesPull={operations.onRemoteFilesPull}
+ onVisualFeedback={operations.onVisualFeedback}
+ fileNormalCollectionIDs={library.fileNormalCollectionIDs}
+ collectionNameByID={library.collectionNameByID}
+ emailByUserID={library.emailByUserID}
+ />
+ )}
+ </GallerySectionLayout>
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/sections/places/use-map-entry.ts b/web/apps/photos/src/components/gallery/sections/places/use-map-entry.ts
new file mode 100644
index 0000000000..da0d74ec6e
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/places/use-map-entry.ts
@@ -0,0 +1,22 @@
+import { useBaseContext } from "ente-base/context";
+import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";
+import { updateMapEnabled } from "ente-new/photos/services/settings";
+import { useCallback } from "react";
+
+export const useMapEntry = (onOpen: () => void) => {
+ const { mapEnabled } = useSettingsSnapshot();
+ const { onGenericError } = useBaseContext();
+ return useCallback(() => {
+ void (async () => {
+ if (!mapEnabled) {
+ try {
+ await updateMapEnabled(true);
+ } catch (error) {
+ onGenericError(error);
+ return;
+ }
+ }
+ onOpen();
+ })();
+ }, [mapEnabled, onGenericError, onOpen]);
+};
diff --git a/web/apps/photos/src/components/gallery/sections/registry.tsx b/web/apps/photos/src/components/gallery/sections/registry.tsx
new file mode 100644
index 0000000000..47ab12988f
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/registry.tsx
@@ -0,0 +1,196 @@
+import {
+ DashboardSquare01Icon,
+ Link04Icon,
+ Location01Icon,
+ User02Icon,
+} from "@hugeicons/core-free-icons";
+import type { HugeiconsIcon } from "@hugeicons/react";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import { isMLSupported } from "ente-new/photos/services/ml";
+import { t } from "i18next";
+import type { ComponentProps, ComponentType } from "react";
+import { GallerySectionLayout } from "../navigation/GallerySectionLayout";
+import type {
+ GalleryDestination,
+ GalleryNavigationState,
+} from "../navigation/navigation-state";
+import type { PhotosNavigationActions } from "../navigation/PhotosNavigationContext";
+import type { GalleryState } from "../reducer";
+import { resolveAlbumDestination } from "./albums/album-files";
+import { AlbumsSection } from "./albums/AlbumsSection";
+import { DuplicatesView } from "./cleanup/DuplicatesView";
+import { LargeFilesView } from "./cleanup/LargeFilesView";
+import { resolveLinksDestination } from "./links/link-selection";
+import { LinksSection } from "./links/LinksSection";
+import { resolvePeopleDestination } from "./people/people-files";
+import { PeopleSection } from "./people/PeopleSection";
+import { PlacesSection } from "./places/PlacesSection";
+import { SearchSection } from "./search/SearchSection";
+import type { GallerySectionProps } from "./types";
+
+interface SectionEntry {
+ navigation: GalleryNavigationState;
+ mobile: boolean;
+ open: () => boolean;
+ openPanel: () => void;
+ closeDrawer: () => void;
+ togglePanel: () => void;
+}
+export interface GallerySectionDefinition {
+ View: ComponentType<GallerySectionProps>;
+ hasNavigation: boolean;
+ resolve?: (
+ library: GalleryState,
+ destination: GalleryDestination,
+ ) => GalleryDestination;
+ enter?: (actions: PhotosNavigationActions) => boolean;
+ rail?: {
+ label: () => string;
+ icon: ComponentProps<typeof HugeiconsIcon>["icon"];
+ available?: () => boolean;
+ select?: (entry: SectionEntry) => void;
+ selected?: (
+ navigation: GalleryNavigationState,
+ panelOpen: boolean,
+ ) => boolean;
+ };
+}
+
+const albumsEntry: NonNullable<GallerySectionDefinition["enter"]> = (actions) =>
+ actions.changeMode("albums");
+const albumsSelection: NonNullable<
+ NonNullable<GallerySectionDefinition["rail"]>["select"]
+> = ({ navigation, mobile, open, openPanel, togglePanel }) => {
+ const { destination, overlay } = navigation;
+ const search = overlay !== undefined;
+ const sameMode =
+ destination.albumMode === "albums" ||
+ destination.albumFilter !== undefined;
+ const reopening =
+ mobile &&
+ (destination.albumMode === "hidden-albums" ||
+ destination.albumMode === "archive-albums");
+ if (
+ !search &&
+ destination.section === "albums" &&
+ ((sameMode && destination.collectionID !== PseudoCollectionID.all) ||
+ reopening)
+ )
+ togglePanel();
+ else if (open()) openPanel();
+};
+const peopleEntry: NonNullable<GallerySectionDefinition["enter"]> = (actions) =>
+ actions.changeMode("people");
+const peopleSelection: NonNullable<
+ NonNullable<GallerySectionDefinition["rail"]>["select"]
+> = ({ navigation, mobile, open, closeDrawer, togglePanel, openPanel }) => {
+ if (!mobile) {
+ closeDrawer();
+ open();
+ } else if (
+ !navigation.overlay &&
+ navigation.destination.section === "people"
+ )
+ togglePanel();
+ else if (open()) openPanel();
+};
+const linksEntry: NonNullable<GallerySectionDefinition["enter"]> = (actions) =>
+ actions.changeMode("links");
+const placesEntry: NonNullable<GallerySectionDefinition["enter"]> = (
+ actions,
+) => {
+ actions.showLibraryMap();
+ return true;
+};
+const placesSelection: NonNullable<
+ NonNullable<GallerySectionDefinition["rail"]>["select"]
+> = ({ open, openPanel }) => {
+ open();
+ openPanel();
+};
+const placesSelected: NonNullable<
+ NonNullable<GallerySectionDefinition["rail"]>["selected"]
+> = (navigation) =>
+ navigation.overlay?.section !== "search" &&
+ navigation.destination.section === "places";
+const duplicatesView: GallerySectionDefinition["View"] = ({
+ operations,
+ presentation,
+}) => (
+ <GallerySectionLayout presentation={presentation}>
+ <DuplicatesView onRemoteFilesPull={operations.onRemoteFilesPull} />
+ </GallerySectionLayout>
+);
+const largeFilesView: GallerySectionDefinition["View"] = ({
+ operations,
+ presentation,
+}) => (
+ <GallerySectionLayout presentation={presentation}>
+ <LargeFilesView onRemoteFilesPull={operations.onRemoteFilesPull} />
+ </GallerySectionLayout>
+);
+export const gallerySections = {
+ albums: {
+ View: AlbumsSection,
+ resolve: resolveAlbumDestination,
+ hasNavigation: true,
+ enter: albumsEntry,
+ rail: {
+ label: () => t("albums"),
+ icon: DashboardSquare01Icon,
+ select: albumsSelection,
+ },
+ },
+ people: {
+ View: PeopleSection,
+ resolve: resolvePeopleDestination,
+ hasNavigation: true,
+ enter: peopleEntry,
+ rail: {
+ label: () => t("people"),
+ icon: User02Icon,
+ available: () => isMLSupported,
+ select: peopleSelection,
+ },
+ },
+ links: {
+ View: LinksSection,
+ resolve: resolveLinksDestination,
+ hasNavigation: true,
+ enter: linksEntry,
+ rail: { label: () => t("links"), icon: Link04Icon },
+ },
+ places: {
+ View: PlacesSection,
+ hasNavigation: true,
+ enter: placesEntry,
+ rail: {
+ label: () => t("map"),
+ icon: Location01Icon,
+ select: placesSelection,
+ selected: placesSelected,
+ },
+ },
+ search: { View: SearchSection, hasNavigation: false },
+ duplicates: { hasNavigation: false, View: duplicatesView },
+ "large-files": { hasNavigation: false, View: largeFilesView },
+} satisfies Record<string, GallerySectionDefinition>;
+
+export type GallerySectionID = keyof typeof gallerySections;
+export const sectionDefinition = (
+ id: GallerySectionID,
+): GallerySectionDefinition => gallerySections[id];
+
+export const selectRailSection = (
+ definition: GallerySectionDefinition,
+ id: string,
+ entry: SectionEntry,
+) => {
+ if (definition.rail?.select) definition.rail.select(entry);
+ else if (
+ !entry.navigation.overlay &&
+ entry.navigation.destination.section === id
+ )
+ entry.togglePanel();
+ else if (entry.open()) entry.openPanel();
+};
diff --git a/web/apps/photos/src/components/gallery/sections/search/SearchSection.tsx b/web/apps/photos/src/components/gallery/sections/search/SearchSection.tsx
new file mode 100644
index 0000000000..e8922fa5b2
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/search/SearchSection.tsx
@@ -0,0 +1,116 @@
+import type { FileListHeaderOrFooter } from "@/components/FileList";
+import { sortFiles } from "ente-media/collection-sort";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { SearchResultsHeader } from "../..";
+import { GalleryMedia } from "../../media/GalleryMedia";
+import { suppressSharedFilesSavedByUser } from "../../media/media-files";
+import { GallerySectionLayout } from "../../navigation/GallerySectionLayout";
+import { albumFiles, albumView } from "../albums/album-files";
+import {
+ derivePeopleFilteredFiles,
+ derivePeopleView,
+} from "../people/people-files";
+import type { GallerySectionProps } from "../types";
+import { useSearchResults } from "./use-search-results";
+
+export const SearchSection = ({
+ library,
+ operations,
+ navigation,
+ preferences,
+ presentation,
+}: GallerySectionProps) => {
+ const destination = navigation.destination;
+ const mode =
+ destination.section === "people" || destination.section === "links"
+ ? destination.section
+ : (destination.albumMode ?? "albums");
+ const collectionView =
+ destination.section === "albums" || destination.section === "places"
+ ? albumView(library, destination)
+ : undefined;
+ const activeCollection =
+ collectionView && collectionView.type !== "album-overview"
+ ? collectionView.activeCollection
+ : undefined;
+ const activePersonID = destination.personID;
+ const suggestion = navigation.overlay?.suggestion;
+ const results = useSearchResults(suggestion, library.searchIndexRevision);
+ const [initialFiles] = useState(() => {
+ if (collectionView) return albumFiles(library, collectionView);
+ if (destination.section === "people") {
+ const { view } = derivePeopleView(
+ library.peopleState,
+ library.tempDeletedFileIDs,
+ library.tempHiddenFileIDs,
+ destination.personID,
+ library.peopleState?.people.find(
+ (person) => person.id === destination.extraVisiblePersonID,
+ ),
+ );
+ return derivePeopleFilteredFiles(
+ library.collectionFiles,
+ library.hiddenFileIDs,
+ view,
+ library.user?.id,
+ );
+ }
+ return [];
+ });
+ const previousFiles = useRef(initialFiles);
+ const { searchSortAsc, setSearchSortAsc } = preferences;
+ const files = useMemo(() => {
+ const visible = suppressSharedFilesSavedByUser(
+ results ?? previousFiles.current,
+ library.user?.id,
+ activeCollection,
+ );
+ return searchSortAsc === undefined
+ ? visible
+ : sortFiles([...visible], searchSortAsc);
+ }, [results, library.user?.id, activeCollection, searchSortAsc]);
+ useEffect(() => {
+ previousFiles.current = files;
+ }, [files]);
+ const [header, setHeader] = useState<FileListHeaderOrFooter>();
+ useEffect(() => {
+ if (suggestion)
+ setHeader({
+ component: (
+ <SearchResultsHeader
+ searchSuggestion={suggestion}
+ fileCount={results?.length ?? 0}
+ sortAsc={searchSortAsc}
+ onSortOrderChange={setSearchSortAsc}
+ />
+ ),
+ height: 104,
+ });
+ }, [suggestion, results, searchSortAsc, setSearchSortAsc]);
+ return (
+ <GallerySectionLayout presentation={presentation}>
+ <GalleryMedia
+ {...{ library, operations, navigation }}
+ header={header}
+ source={{
+ mode,
+ modePlus: "search",
+ files,
+ activeCollectionID:
+ collectionView &&
+ collectionView.type !== "album-overview"
+ ? collectionView.activeCollectionSummaryID
+ : undefined,
+ activeCollection,
+ activeCollectionSummary:
+ collectionView &&
+ collectionView.type !== "album-overview"
+ ? collectionView.activeCollectionSummary
+ : undefined,
+ activePersonID,
+ disableGrouping: suggestion?.type == "clip",
+ }}
+ />
+ </GallerySectionLayout>
+ );
+};
diff --git a/web/apps/photos/src/components/gallery/sections/search/search-results-queue.ts b/web/apps/photos/src/components/gallery/sections/search/search-results-queue.ts
new file mode 100644
index 0000000000..67711c427f
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/search/search-results-queue.ts
@@ -0,0 +1,46 @@
+import type { EnteFile } from "ente-media/file";
+import type { SearchSuggestion } from "ente-new/photos/services/search/types";
+
+export const createSearchResultsQueue = (
+ search: (suggestion: SearchSuggestion) => Promise<EnteFile[]>,
+ onResult: (files: EnteFile[]) => void,
+ onError: (error: unknown) => void,
+) => {
+ let pending: SearchSuggestion | undefined;
+ let revision = 0;
+ let running = false;
+ let disposed = false;
+ const isCurrent = (requestRevision: number) =>
+ !disposed && requestRevision === revision;
+ const drain = async () => {
+ if (running) return;
+ running = true;
+ try {
+ while (pending && !disposed) {
+ const suggestion = pending;
+ const requestRevision = revision;
+ pending = undefined;
+ try {
+ const files = await search(suggestion);
+ if (isCurrent(requestRevision)) onResult(files);
+ } catch (error) {
+ if (isCurrent(requestRevision)) onError(error);
+ }
+ }
+ } finally {
+ running = false;
+ }
+ };
+ return {
+ enqueue(suggestion: SearchSuggestion | undefined) {
+ if (disposed) return;
+ revision++;
+ pending = suggestion;
+ void drain();
+ },
+ dispose() {
+ disposed = true;
+ pending = undefined;
+ },
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/sections/search/use-search-navigation.ts b/web/apps/photos/src/components/gallery/sections/search/use-search-navigation.ts
new file mode 100644
index 0000000000..ce1e623186
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/search/use-search-navigation.ts
@@ -0,0 +1,81 @@
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import type {
+ SearchOption,
+ SidebarActionID,
+} from "ente-new/photos/services/search/types";
+import { useCallback } from "react";
+import { albumShortcutCollectionID } from "../../helpers";
+import type {
+ GalleryNavigationState,
+ NavigationAction,
+} from "../../navigation/navigation-state";
+import type { PhotosNavigationActions } from "../../navigation/PhotosNavigationContext";
+import type { GalleryState } from "../../reducer";
+
+export const useSearchNavigation = ({
+ library,
+ navigation,
+ send,
+ showCollectionSummary,
+ showSettings,
+}: {
+ library: GalleryState;
+ navigation: GalleryNavigationState;
+ send: React.Dispatch<NavigationAction>;
+ showCollectionSummary: PhotosNavigationActions["showCollectionSummary"];
+ showSettings: (action?: SidebarActionID) => void;
+}) =>
+ useCallback(
+ (
+ option: SearchOption | undefined,
+ options?: { shouldExitSearchMode?: boolean },
+ ) => {
+ send({ type: "closeMap" });
+ if (!option) {
+ send({
+ type: "exitSearch",
+ shouldExitSearchMode: options?.shouldExitSearchMode ?? true,
+ });
+ return;
+ }
+ const suggestion = option.suggestion;
+ if (suggestion.type === "sidebarAction") {
+ const id = albumShortcutCollectionID(
+ suggestion.actionID,
+ library.uncategorizedCollectionSummaryID,
+ );
+ if (id !== undefined) {
+ void showCollectionSummary(
+ id,
+ id === PseudoCollectionID.hiddenItems,
+ );
+ return;
+ }
+ send({ type: "dismissCleanup" });
+ showSettings(suggestion.actionID);
+ send({
+ type: "exitSearch",
+ shouldExitSearchMode: options?.shouldExitSearchMode ?? true,
+ });
+ } else if (suggestion.type === "collection")
+ send({
+ type: "showCollectionSummary",
+ collectionSummaryID: suggestion.collectionID,
+ library,
+ });
+ else if (suggestion.type === "person")
+ send({ type: "showPerson", personID: suggestion.person.id });
+ else {
+ if (navigation.destination.albumMode === "hidden-albums")
+ send({ type: "showAlbums" });
+ send({ type: "enterSearchMode", searchSuggestion: suggestion });
+ }
+ },
+ [
+ library,
+ navigation.destination.albumMode,
+ send,
+ showCollectionSummary,
+ showSettings,
+ ],
+ );
diff --git a/web/apps/photos/src/components/gallery/sections/search/use-search-results.ts b/web/apps/photos/src/components/gallery/sections/search/use-search-results.ts
new file mode 100644
index 0000000000..85d316f44a
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/search/use-search-results.ts
@@ -0,0 +1,30 @@
+import { useBaseContext } from "ente-base/context";
+import type { EnteFile } from "ente-media/file";
+import { filterSearchableFiles } from "ente-new/photos/services/search";
+import type { SearchSuggestion } from "ente-new/photos/services/search/types";
+import { useEffect, useRef, useState } from "react";
+import { createSearchResultsQueue } from "./search-results-queue";
+
+export const useSearchResults = (
+ suggestion: SearchSuggestion | undefined,
+ searchIndexRevision: number,
+) => {
+ const [results, setResults] = useState<EnteFile[]>();
+ const { onGenericError } = useBaseContext();
+ const queue =
+ useRef<ReturnType<typeof createSearchResultsQueue>>(undefined);
+ useEffect(() => {
+ const current = createSearchResultsQueue(
+ filterSearchableFiles,
+ setResults,
+ onGenericError,
+ );
+ queue.current = current;
+ return () => current.dispose();
+ }, [onGenericError]);
+ useEffect(() => {
+ if (!suggestion) setResults(undefined);
+ queue.current?.enqueue(suggestion);
+ }, [suggestion, searchIndexRevision, onGenericError]);
+ return results;
+};
diff --git a/web/apps/photos/src/components/gallery/sections/types.ts b/web/apps/photos/src/components/gallery/sections/types.ts
new file mode 100644
index 0000000000..19731a5034
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/types.ts
@@ -0,0 +1,64 @@
+import type { FileListWithViewerProps } from "@/components/FileListWithViewer";
+import type { UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
+import type { useSaveGroups } from "ente-gallery/components/utils/save-groups";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import type { PeopleState } from "ente-new/photos/services/ml/people";
+import type { Dispatch, SetStateAction } from "react";
+import type { useGalleryPreferences } from "../hooks/use-gallery-preferences";
+import type { useSelectedFileOperations } from "../media/use-selected-file-operations";
+import type { GallerySectionPresentation } from "../navigation/GallerySectionLayout";
+import type { GalleryNavigationState } from "../navigation/navigation-state";
+import type { GalleryAction, GalleryState } from "../reducer";
+
+export type GalleryMediaSource = Pick<
+ FileListWithViewerProps,
+ | "mode"
+ | "modePlus"
+ | "files"
+ | "activeCollectionID"
+ | "activeCollectionSummary"
+ | "activePersonID"
+ | "disableGrouping"
+> & { activeCollection?: Collection | undefined };
+
+export type GallerySectionOperations = Pick<
+ FileListWithViewerProps,
+ | "onAddSaveGroup"
+ | "onFileVisibilityUpdate"
+ | "onMarkTempDeleted"
+ | "onRemotePull"
+ | "onVisualFeedback"
+ | "onAddFileToCollection"
+> & {
+ onRemoteFilesPull: () => Promise<void>;
+ dispatch: Dispatch<GalleryAction>;
+ peopleState: PeopleState | undefined;
+ mutations: Parameters<typeof useSelectedFileOperations>[0]["mutations"];
+ selectionDisabled: boolean;
+ onToggleFavorite: (file: EnteFile) => Promise<void>;
+ onSendLink: (file: EnteFile) => Promise<void>;
+ setBlockingLoad: Dispatch<SetStateAction<boolean>>;
+ onUpload: (intent?: UploadTypeSelectorIntent) => void;
+ onCreateAlbum: () => void;
+ saveGroups: ReturnType<typeof useSaveGroups>["saveGroups"];
+ setSectionActivity: Dispatch<
+ SetStateAction<{ selection: boolean; drop: boolean }>
+ >;
+};
+
+export interface GallerySectionProps {
+ library: Readonly<GalleryState> & {
+ isFirstLoad: boolean;
+ searchIndexRevision: number;
+ };
+ operations: GallerySectionOperations;
+ navigation: GalleryNavigationState & {
+ retainPerson: (
+ personID: string | undefined,
+ extraVisiblePersonID: string | undefined,
+ ) => void;
+ };
+ preferences: ReturnType<typeof useGalleryPreferences>;
+ presentation: GallerySectionPresentation;
+}
diff --git a/web/apps/photos/src/components/gallery/sections/view-types.ts b/web/apps/photos/src/components/gallery/sections/view-types.ts
new file mode 100644
index 0000000000..90cd178f65
--- /dev/null
+++ b/web/apps/photos/src/components/gallery/sections/view-types.ts
@@ -0,0 +1,19 @@
+import type { AlbumFilter } from "@/utils/album-filters";
+import type { Collection } from "ente-media/collection";
+import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
+import type { Person } from "ente-new/photos/services/ml/people";
+export type GalleryView =
+ | { type: "links"; selectedLinkID: number | undefined }
+ | { type: "album-overview"; albumFilter: AlbumFilter }
+ | {
+ type: "albums" | "hidden-albums" | "archive-albums";
+ activeCollectionSummaryID: number;
+ activeCollection: Collection | undefined;
+ activeCollectionSummary: CollectionSummary;
+ }
+ | {
+ type: "people";
+ visiblePeople: Person[];
+ people: Person[];
+ activePerson: Person | undefined;
+ };
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 5b71f5ccb4..16a1f7ea7d 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -1,2566 +1,84 @@
-// TODO: Audit this file (the code here is mostly fine, but needs revisiting
-// the file it depends on have been audited and their interfaces fixed).
-/* eslint-disable react-hooks/exhaustive-deps */
import { AuthenticateUser } from "@/components/AuthenticateUser";
-import {
- CollectionSelector,
- type CollectionSelectorAttributes,
-} from "@/components/CollectionSelector";
+import { CollectionSelector } from "@/components/CollectionSelector";
import { DesktopWhatsNew } from "@/components/DesktopWhatsNew";
-import type { FileListHeaderOrFooter } from "@/components/FileList";
-import { FileListWithViewer } from "@/components/FileListWithViewer";
-import { FixCreationTime } from "@/components/FixCreationTime";
import { QuickLinkCreatedNotification } from "@/components/QuickLinkCreatedNotification";
-import {
- SelectedFileOptions,
- type CollectionOp,
- type FileOp,
-} from "@/components/SelectedFileOptions";
import { Upload } from "@/components/Upload";
-import { AlbumSlideshow } from "@/components/collections/AlbumSlideshow";
-import { CollectionMap } from "@/components/collections/CollectionMap";
-import {
- EditAlbumDetailsDialog,
- type AlbumDetails,
-} from "@/components/collections/EditAlbumDetailsDialog";
-import { GalleryBarAndListHeader } from "@/components/collections/GalleryBarAndListHeader";
-import {
- GalleryEmptyState,
- PeopleConsentDialog,
- SearchResultsHeader,
- type RemotePullOpts,
-} from "@/components/gallery";
-import { AlbumsOverview } from "@/components/gallery/AlbumsOverview";
-import { DuplicatesView } from "@/components/gallery/DuplicatesView";
-import { LargeFilesView } from "@/components/gallery/LargeFilesView";
-import { LinksView } from "@/components/gallery/LinksView";
-import { PeopleOverview } from "@/components/gallery/PeopleOverview";
-import {
- PhotosNavigationContext,
- type PhotosNavigationActions,
-} from "@/components/gallery/PhotosNavigationContext";
-import {
- PhotosNavigationShell,
- type PhotosNavigationShellHandle,
-} from "@/components/gallery/PhotosNavigationShell";
-import type { PlaceSelection } from "@/components/gallery/PlacesList";
-import {
- albumShortcutCollectionID,
- findCollectionCreatingIfNeeded,
- performCollectionOp,
- showCollectionSummaryWithAuthentication,
-} from "@/components/gallery/helpers";
+import { PeopleConsentDialog } from "@/components/gallery";
import { useGalleryAuthentication } from "@/components/gallery/hooks/use-gallery-authentication";
-import { useGallerySlideshow } from "@/components/gallery/hooks/use-gallery-slideshow";
-import { useSubscriptionCompletionRedirect } from "@/components/gallery/hooks/use-subscription-completion-redirect";
-import {
- useGalleryReducer,
- type GalleryBarMode,
-} from "@/components/gallery/reducer";
-import { useAlbumNavigationData } from "@/components/gallery/use-album-navigation-data";
-import {
- notifyOthersFilesDialogAttributes,
- notifyUnsupportedSharedFavoritesDialogAttributes,
- trashFilesDialogAttributes,
-} from "@/components/utils/dialog-attributes";
-import exportService from "@/services/export";
-import { processPendingAlbumJoin } from "@/services/join-album";
-import {
- albumFilters,
- visibleAlbumFilters,
- type AlbumFilter,
-} from "@/utils/album-filters";
-import { externalLink } from "@/utils/link";
-import { sortPeople, type PeopleSortBy } from "@/utils/people-sort";
-import { visibleQuickLinks } from "@/utils/quick-links";
-import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";
-import { Typography } from "@mui/material";
-import { sessionExpiredDialogAttributes } from "ente-accounts/components/utils/dialog";
-import {
- getAndClearIsFirstLogin,
- savedJustSignedUp,
-} from "ente-accounts/services/accounts-db";
-import { stashRedirect } from "ente-accounts/services/redirect";
-import { isSessionInvalid } from "ente-accounts/services/session";
-import { ensureLocalUser } from "ente-accounts/services/user";
-import { Notification } from "ente-base/components/Notification";
+import { useGalleryLibrary } from "@/components/gallery/hooks/use-gallery-library";
+import { useGalleryOperations } from "@/components/gallery/hooks/use-gallery-operations";
+import { GalleryDownloadNotifications } from "@/components/gallery/media/GalleryDownloadNotifications";
+import { PhotosNavigationContext } from "@/components/gallery/navigation/PhotosNavigationContext";
+import { PhotosNavigationShell } from "@/components/gallery/navigation/PhotosNavigationShell";
+import { useGalleryNavigation } from "@/components/gallery/navigation/use-gallery-navigation";
+import { sectionDefinition } from "@/components/gallery/sections/registry";
import { SingleInputDialog } from "ente-base/components/SingleInputDialog";
import { TranslucentLoadingOverlay } from "ente-base/components/loaders";
-import { errorDialogAttributes } from "ente-base/components/utils/dialog";
-import { useModalVisibility } from "ente-base/components/utils/modal";
-import { useBaseContext } from "ente-base/context";
-import { subscribeMainWindowFocus } from "ente-base/electron";
-import { isNamedError } from "ente-base/error";
-import { isHTTPErrorWithStatus } from "ente-base/http";
-import { hasPendingAlbumToJoin } from "ente-base/join-album";
-import log from "ente-base/log";
-import {
- clearSessionStorage,
- haveMasterKeyInSession,
-} from "ente-base/session-storage";
-import { savedAuthToken } from "ente-base/token";
-import type { Location } from "ente-base/types";
-import { initContacts, pullContacts } from "ente-contacts";
-import { DownloadStatusNotifications } from "ente-gallery/components/DownloadStatusNotifications";
import { FullScreenDropZone } from "ente-gallery/components/FullScreenDropZone";
-import type { UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
-import {
- isSaveCancelled,
- isSaveComplete,
- useSaveGroups,
-} from "ente-gallery/components/utils/save-groups";
-import type { FileViewerInitialSidebar } from "ente-gallery/components/viewer/FileViewer";
-import type { Collection } from "ente-media/collection";
-import type { EnteFile } from "ente-media/file";
-import { ItemVisibility, metadataHash } from "ente-media/file-metadata";
-import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
-import { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";
-import {
- useMLStatusSnapshot,
- usePeopleStateSnapshot,
- useSettingsSnapshot,
- useUserDetailsSnapshot,
-} from "ente-new/photos/components/utils/use-snapshot";
-import { masterKeyFromSession } from "ente-new/photos/services/account-keys";
-import {
- addToCollection,
- addToFavoritesCollection,
- canAddFilesToCollection,
- createAlbum,
- createHiddenAlbum,
- createPublicURL,
- createQuickLinkCollection,
- removeFromCollection,
- removeFromFavoritesCollection,
- renameCollection,
- updateCollectionDetails,
-} from "ente-new/photos/services/collection";
-import {
- haveOnlySystemCollections,
- PseudoCollectionID,
-} from "ente-new/photos/services/collection-summary";
-import {
- updateFilesLocation,
- updateFilesVisibility,
-} from "ente-new/photos/services/file";
-import {
- addManualFileAssignmentsToPerson,
- isMLEnabled,
-} from "ente-new/photos/services/ml";
-import { contactsGetDiff, contactsGetProfilePicture } from "ente-photos-wasm";
-
-import { ensureAuthenticatedSession } from "@/services/authenticated-session";
-import { postPullFiles, prePullFiles, pullFiles } from "@/services/pull";
-import { uploadManager } from "@/services/upload-manager";
-import watcher from "@/services/watch";
-import {
- selectedFavoriteCount as countSelectedFavorites,
- getSelectedFiles,
- performFileOp,
- type SelectedState,
-} from "@/utils/file";
-import type { FileContextAction } from "@/utils/file-actions";
-import {
- quickLinkNameForFiles,
- resolveQuickLinkURL,
-} from "ente-gallery/utils/quick-link";
-import {
- savedCollectionFiles,
- savedCollections,
- savedTrashItems,
-} from "ente-new/photos/services/photos-fdb";
-import {
- filterSearchableFiles,
- updateSearchCollectionsAndFiles,
-} from "ente-new/photos/services/search";
-import type { SearchOption } from "ente-new/photos/services/search/types";
-import {
- initSettings,
- updateMapEnabled,
-} from "ente-new/photos/services/settings";
-import { savedUserDetailsOrTriggerPull } from "ente-new/photos/services/user-details";
-import { usePhotosAppContext } from "ente-new/photos/types/context";
-import { PromiseQueue } from "ente-utils/promise";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { FileWithPath } from "react-dropzone";
-import { Trans } from "react-i18next";
+import { useMemo } from "react";
const Page: React.FC = () => {
- const { logout, showMiniDialog, onGenericError } = useBaseContext();
- const {
- showLoadingBar,
- hideLoadingBar,
- watchFolderView,
- showNotification,
- } = usePhotosAppContext();
-
- const [state, dispatch] = useGalleryReducer();
-
- const [cleanupView, setCleanupView] = useState<
- "large-files" | "duplicates"
- >();
- const isCleanupViewOpen = cleanupView !== undefined;
- const [isFirstLoad, setIsFirstLoad] = useState(false);
- const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);
- const [suppressContextSelectionBar, setSuppressContextSelectionBar] =
- useState(false);
- const [selected, setSelected] = useState<SelectedState>({
- ownCount: 0,
- count: 0,
- collectionID: 0,
- context: { mode: "albums", collectionID: PseudoCollectionID.all },
- });
- const [albumFilter, setAlbumFilter] = useState<AlbumFilter>("ente");
- const [albumSearchQuery, setAlbumSearchQuery] = useState("");
- const [albumOpenedFromOverview, setAlbumOpenedFromOverview] = useState<{
- collectionID: number;
- filter: AlbumFilter;
- searchQuery: string;
- }>();
- const [blockingLoad, setBlockingLoad] = useState(false);
- const [peopleSortBy, setPeopleSortBy] =
- useState<PeopleSortBy>("count-desc");
- const [shouldDisableDropzone, setShouldDisableDropzone] = useState(false);
- const [dragAndDropFiles, setDragAndDropFiles] = useState<FileWithPath[]>(
- [],
- );
- const [isFileViewerOpen, setIsFileViewerOpen] = useState(false);
- const [pendingFileNavigation, setPendingFileNavigation] = useState<{
- fileIndex: number;
- sidebar?: FileViewerInitialSidebar;
- commentID?: string;
- }>();
-
- const pendingSingleFileAdd = useRef<
- { file: EnteFile; sourceCollectionSummaryID?: number } | undefined
- >(undefined);
- // Pull pipelines mutate the same local DB and reducer state.
- const remoteFilesPullQueue = useRef(new PromiseQueue<void>());
- const remotePullQueue = useRef(new PromiseQueue<void>());
-
- const [uploadTypeSelectorView, setUploadTypeSelectorView] = useState(false);
- const [uploadTypeSelectorIntent, setUploadTypeSelectorIntent] =
- useState<UploadTypeSelectorIntent>("upload");
-
- const [fixCreationTimeFiles, setFixCreationTimeFiles] = useState<
- EnteFile[]
- >([]);
- const [fileListHeader, setFileListHeader] = useState<
- FileListHeaderOrFooter | undefined
- >(undefined);
-
- const [openCollectionSelector, setOpenCollectionSelector] = useState(false);
- const [collectionSelectorAttributes, setCollectionSelectorAttributes] =
- useState<CollectionSelectorAttributes | undefined>();
-
- const { customDomain, mapEnabled } = useSettingsSnapshot();
- const userDetails = useUserDetailsSnapshot();
- const peopleState = usePeopleStateSnapshot();
- const mlStatus = useMLStatusSnapshot();
-
- const {
- show: showContextMenuAssignPerson,
- props: contextMenuAssignPersonProps,
- } = useModalVisibility();
-
- const namedPeople = useMemo(
- () =>
- (peopleState?.visiblePeople ?? []).filter(
- (p) => p.type == "cgroup" && !!p.name,
- ),
- [peopleState],
- );
- const showAddPersonAction = useMemo(
- () => isMLEnabled() && namedPeople.length > 0,
- [namedPeople],
- );
-
- const { saveGroups, onAddSaveGroup, onRemoveSaveGroup } = useSaveGroups();
- const [postCreateAlbumOp, setPostCreateAlbumOp] = useState<
- CollectionOp | undefined
- >(undefined);
- const postCreateAlbumHidden = useRef(false);
- const navigationRef = useRef<PhotosNavigationShellHandle>(null);
-
- const lastAuthenticationForHiddenTimestamp = useRef<number>(0);
-
- const { show: showPeopleConsent, props: peopleConsentVisibilityProps } =
- useModalVisibility();
- const pendingPeopleSearchReset = useRef<(() => void) | undefined>(
- undefined,
- );
- const { show: showFixCreationTime, props: fixCreationTimeVisibilityProps } =
- useModalVisibility();
+ const libraryOwner = useGalleryLibrary();
+ const { state, isFirstLoad, searchIndexRevision } = libraryOwner;
const { authenticateUser, authenticateUserDialogProps } =
useGalleryAuthentication();
- const { show: showAlbumNameInput, props: albumNameInputVisibilityProps } =
- useModalVisibility();
- const { show: showEditLocation, props: editLocationVisibilityProps } =
- useModalVisibility();
+ const navigation = useGalleryNavigation(libraryOwner, authenticateUser);
const {
- show: showEditAlbumDetails,
- props: editAlbumDetailsVisibilityProps,
- } = useModalVisibility();
- const [selectedPlace, setSelectedPlace] = useState<PlaceSelection>();
- const [placeSelectionRevision, setPlaceSelectionRevision] = useState(0);
- const [isMapView, setIsMapView] = useState(false);
- const closeCollectionMap = useCallback(() => setIsMapView(false), []);
-
- const handleShowCollectionMap = useCallback(() => {
- void (async () => {
- if (!mapEnabled) {
- try {
- await updateMapEnabled(true);
- } catch (e) {
- onGenericError(e);
- return;
- }
- }
- setIsMapView(true);
- })();
- }, [mapEnabled, onGenericError]);
-
- const [albumAddedNotification, setAlbumAddedNotification] = useState<{
- open: boolean;
- albumName?: string;
- }>({ open: false });
- const [publicLinkToast, setPublicLinkToast] = useState<{
- open: boolean;
- url?: string;
- }>({ open: false });
-
- const {
- user,
- favoriteFileIDs,
- collectionNameByID,
- fileNormalCollectionIDs,
- hiddenCollectionIDs,
- normalCollectionSummaries,
- hiddenFileIDs,
- tempDeletedFileIDs,
- tempHiddenFileIDs,
- pendingFavoriteUpdates,
- pendingVisibilityUpdates,
- isInSearchMode,
- filteredFiles,
- } = state;
-
- const isAlbumOverview = state.view?.type == "album-overview";
- const barMode =
- state.view?.type == "album-overview"
- ? "albums"
- : (state.view?.type ?? "albums");
- const overviewFilter =
- state.view?.type == "album-overview"
- ? state.view.albumFilter
- : undefined;
- const quickLinkVisibility =
- barMode == "hidden-albums"
- ? ItemVisibility.hidden
- : ItemVisibility.visible;
- const activeCollectionID =
- state.view?.type == "people" ||
- state.view?.type == "album-overview" ||
- state.view?.type == "links"
- ? undefined
- : state.view?.activeCollectionSummaryID;
- const activeCollection =
- state.view?.type == "people" ||
- state.view?.type == "album-overview" ||
- state.view?.type == "links"
- ? undefined
- : state.view?.activeCollection;
- const activeCollectionSummary =
- state.view?.type == "people" ||
- state.view?.type == "album-overview" ||
- state.view?.type == "links"
- ? undefined
- : state.view?.activeCollectionSummary;
- const selectedLinkID =
- state.view?.type == "links" ? state.view.selectedLinkID : undefined;
- const galleryBarActiveCollectionID =
- barMode == "links" ? selectedLinkID : activeCollectionID;
- const isActiveCollectionDownloadInProgress = useCallback(() => {
- const group = saveGroups.find(
- (g) => g.collectionSummaryID === galleryBarActiveCollectionID,
- );
- return !!group && !isSaveComplete(group) && !isSaveCancelled(group);
- }, [saveGroups, galleryBarActiveCollectionID]);
- const quickLinks = useMemo(
- () =>
- visibleQuickLinks(
- state.collections,
- user?.id ?? 0,
- state.hiddenCollectionIDs,
- ),
- [state.collections, user?.id, state.hiddenCollectionIDs],
- );
- const linkSummaries = useMemo(
- () =>
- new Map(
- quickLinks.flatMap((collection) => {
- const summary = normalCollectionSummaries.get(
- collection.id,
- );
- return summary ? [[collection.id, summary] as const] : [];
- }),
- ),
- [quickLinks, normalCollectionSummaries],
- );
- const activePerson =
- state.view?.type == "people" ? state.view.activePerson : undefined;
- const people =
- (state.view?.type == "people" ? state.view.visiblePeople : undefined) ??
- [];
- const sortedPeople = useMemo(
- () => sortPeople(people, peopleSortBy),
- [people, peopleSortBy],
- );
- const activePersonID = activePerson?.id;
- const fileCollectionIDs = useMemo(
- () =>
- state.collectionFiles.reduce((result, file) => {
- const collectionIDs = result.get(file.id);
- if (collectionIDs) {
- if (!collectionIDs.includes(file.collectionID)) {
- collectionIDs.push(file.collectionID);
- }
- } else {
- result.set(file.id, [file.collectionID]);
- }
- return result;
- }, new Map<number, number[]>()),
- [state.collectionFiles],
- );
-
- const activeCollectionFiles = useMemo(() => {
- if (!activeCollection) return [];
- if (barMode == "hidden-albums" || barMode == "archive-albums") {
- return filteredFiles;
- }
-
- return filteredFiles.filter(({ id, magicMetadata }) => {
- const visibility = magicMetadata?.data.visibility;
- const isVisible =
- visibility === undefined ||
- visibility === ItemVisibility.visible;
-
- return (
- isVisible &&
- !hiddenFileIDs.has(id) &&
- !tempDeletedFileIDs.has(id) &&
- !tempHiddenFileIDs.has(id)
- );
- });
- }, [
- activeCollection,
- barMode,
- filteredFiles,
- hiddenFileIDs,
- tempDeletedFileIDs,
- tempHiddenFileIDs,
- ]);
- const { slideshow, startSlideshow, closeSlideshow } = useGallerySlideshow({
- activeCollection,
- activeCollectionFiles,
- activeCollectionSummary,
- isInSearchMode,
- user,
- });
-
- const mapFileSource = useMemo(
- () => ({
- collectionFiles: state.collectionFiles,
- favoriteFileIDs,
- hiddenFileIDs,
- archivedFileIDs: state.archivedFileIDs,
- tempDeletedFileIDs,
- tempHiddenFileIDs,
- }),
- [
- favoriteFileIDs,
- hiddenFileIDs,
- state.archivedFileIDs,
- state.collectionFiles,
- tempDeletedFileIDs,
- tempHiddenFileIDs,
- ],
- );
- const selectedFilesInView = useMemo(
- () => getSelectedFiles(selected, filteredFiles),
- [selected, filteredFiles],
- );
- const isAllSelectedInView =
- filteredFiles.length > 0 &&
- selectedFilesInView.length === filteredFiles.length;
-
- const barCollectionSummaries =
- barMode == "links"
- ? linkSummaries
- : barMode == "hidden-albums"
- ? state.hiddenCollectionSummaries
- : barMode == "archive-albums"
- ? state.archivedCollectionSummaries
- : state.normalCollectionSummaries;
-
- const collectionSummary = barCollectionSummaries.get(
- galleryBarActiveCollectionID!,
- );
-
- const {
- sidebarCollectionSummaries,
- overviewAlbums,
- visibleAlbumFilters: sidebarAlbumFilters,
- collectionsSortBy,
- onChangeCollectionsSortBy,
- } = useAlbumNavigationData({
- mode: barMode,
- collectionSummaries: barCollectionSummaries,
- uncategorizedCollectionSummaryID:
- state.uncategorizedCollectionSummaryID,
- albumFilter,
- albumSearchQuery,
- });
-
- useEffect(() => {
- setAlbumSearchQuery("");
- }, [barMode]);
-
- useEffect(() => {
- if (barMode == "albums" && activeCollectionID == PseudoCollectionID.all)
- setAlbumSearchQuery("");
- }, [barMode, activeCollectionID]);
-
- useEffect(() => {
- const available = visibleAlbumFilters([
- ...normalCollectionSummaries.values(),
- ]);
- if (!available.some(({ value }) => value == albumFilter)) {
- setAlbumFilter("ente");
- if (overviewFilter)
- dispatch({ type: "showAlbumOverview", albumFilter: "ente" });
- }
- }, [normalCollectionSummaries, albumFilter, overviewFilter]);
-
- const router = useRouter();
-
- useEffect(() => {
- const electron = globalThis.electron;
- let syncIntervalID: ReturnType<typeof setInterval> | undefined;
- let unsubscribeMainWindowFocus: (() => void) | undefined;
-
- void (async () => {
- const authToken = await savedAuthToken();
- if (!haveMasterKeyInSession() || !authToken) {
- stashRedirect("/gallery");
- void router.push("/");
- return;
- }
-
- if (savedJustSignedUp()) {
- void router.replace("/plan");
- return;
- }
-
- try {
- await ensureAuthenticatedSession();
- } catch (e) {
- if (isNamedError(e, "missing_recovery_key")) {
- showMiniDialog(sessionExpiredDialogAttributes(logout));
- } else {
- onGenericError(e);
- }
- return;
- }
-
- initSettings();
- setupSelectAllKeyBoardShortcutHandler();
-
- dispatch({ type: "showAll" });
-
- setIsFirstLoad(getAndClearIsFirstLogin());
-
- const user = ensureLocalUser();
- void initContacts(
- user.id,
- ensureAuthenticatedSession,
- contactsGetDiff,
- contactsGetProfilePicture,
- )
- .then(pullContacts)
- .catch((error: unknown) => {
- log.warn(
- "[gallery] Failed to warm contacts display cache",
- error,
- );
- });
- const userDetails = await savedUserDetailsOrTriggerPull();
- dispatch({
- type: "mount",
- user,
- familyData: userDetails?.familyData,
- collections: await savedCollections(),
- collectionFiles: await savedCollectionFiles(),
- trashItems: await savedTrashItems(),
- });
-
- // Join first so the initial pull includes the new album.
- let joinedAlbumId: number | null = null;
-
- if (hasPendingAlbumToJoin()) {
- try {
- const joinedCollectionId = await processPendingAlbumJoin();
- if (joinedCollectionId) {
- joinedAlbumId = joinedCollectionId;
- }
- } catch (error) {
- log.error("Failed to join album", error);
- showMiniDialog({
- title: t("error"),
- message: t("album_join_failed"),
- });
- }
- }
-
- await remotePull({ source: "gallery-mount" });
-
- if (joinedAlbumId) {
- dispatch({
- type: "showCollectionSummary",
- collectionSummaryID: joinedAlbumId,
- });
- }
-
- setIsFirstLoad(false);
-
- syncIntervalID = setInterval(
- () => remotePull({ silent: true, source: "gallery-periodic" }),
- 5 * 60 * 1000,
- );
-
- if (electron) {
- unsubscribeMainWindowFocus = subscribeMainWindowFocus(() => {
- void remotePull({ silent: true, source: "desktop-focus" });
- void watcher.checkAccessibility();
- });
- }
- })();
-
- return () => {
- clearInterval(syncIntervalID);
- unsubscribeMainWindowFocus?.();
- };
- }, []);
-
- useEffect(() => {
- if (state.user && userDetails) {
- dispatch({ type: "setUserDetails", userDetails });
- }
- }, [state.user, userDetails]);
-
- useEffect(() => {
- if (
- (!isAlbumOverview && typeof activeCollectionID == "undefined") ||
- !router.isReady
- ) {
- return;
- }
- let collectionURL = "";
- if (!isAlbumOverview && activeCollectionID !== PseudoCollectionID.all) {
- // TODO: Is this URL param even used?
- collectionURL = `?collection=${activeCollectionID}`;
- }
- const href = `/gallery${collectionURL}`;
- void router.push(href, undefined, { shallow: true });
- }, [activeCollectionID, isAlbumOverview, router.isReady]);
-
- useEffect(() => {
- if (!activeCollectionSummary) closeCollectionMap();
- }, [activeCollectionSummary, closeCollectionMap]);
-
- useSubscriptionCompletionRedirect();
-
- useEffect(() => {
- updateSearchCollectionsAndFiles(
- state.collections,
- state.collectionFiles,
- state.hiddenCollectionIDs,
- state.hiddenFileIDs,
- );
- }, [
- state.collections,
- state.collectionFiles,
- state.hiddenCollectionIDs,
- state.hiddenFileIDs,
- ]);
-
- useEffect(() => {
- dispatch({ type: "setPeopleState", peopleState });
- }, [peopleState]);
-
- useEffect(() => {
- if (isInSearchMode && state.searchSuggestion) {
- setFileListHeader({
- component: (
- <SearchResultsHeader
- searchSuggestion={state.searchSuggestion}
- fileCount={state.searchResults?.length ?? 0}
- sortAsc={state.searchSortAsc}
- onSortOrderChange={(asc) =>
- dispatch({ type: "setSearchSortOrder", asc })
- }
- />
- ),
- height: 104,
- });
- }
- }, [
- isInSearchMode,
- state.searchSuggestion,
- state.searchResults,
- state.searchSortAsc,
- ]);
-
- useEffect(() => {
- const pendingSearchSuggestion = state.pendingSearchSuggestions.at(-1);
- if (!state.isRecomputingSearchResults && pendingSearchSuggestion) {
- dispatch({ type: "updatingSearchResults" });
- // TODO: A rejection leaves isRecomputingSearchResults stuck true,
- // and search stops until it is exited. Recovery needs a reducer
- // change.
- void filterSearchableFiles(pendingSearchSuggestion).then(
- (searchResults) => {
- dispatch({ type: "setSearchResults", searchResults });
- },
- );
- }
- }, [state.isRecomputingSearchResults, state.pendingSearchSuggestions]);
-
- const selectAll = (e: KeyboardEvent) => {
- if (
- e.target instanceof HTMLInputElement ||
- e.target instanceof HTMLTextAreaElement
- ) {
- return;
- }
-
- e.preventDefault();
-
- if (
- !user ||
- !filteredFiles.length ||
- uploadTypeSelectorView ||
- openCollectionSelector ||
- fixCreationTimeVisibilityProps.open ||
- authenticateUserDialogProps.open ||
- albumNameInputVisibilityProps.open ||
- editAlbumDetailsVisibilityProps.open ||
- isFileViewerOpen ||
- slideshow
- ) {
- return;
- }
-
- const selected: SelectedState = {
- ownCount: 0,
- count: 0,
- collectionID: activeCollectionID,
- context:
- barMode == "people" && activePersonID
- ? { mode: "people", personID: activePersonID }
- : {
- mode: barMode as
- "albums" | "hidden-albums" | "archive-albums",
- collectionID: activeCollectionID!,
- },
- };
-
- filteredFiles.forEach((item) => {
- if (item.ownerID === user.id) {
- selected.ownCount++;
- }
- selected.count++;
- selected[item.id] = true;
- });
- setSelected(selected);
- };
-
- const handleSelectAll = () => {
- if (!user || !filteredFiles.length) return;
-
- const selected: SelectedState = {
- ownCount: 0,
- count: 0,
- collectionID: activeCollectionID,
- context:
- barMode == "people" && activePersonID
- ? { mode: "people", personID: activePersonID }
- : {
- mode: barMode as
- "albums" | "hidden-albums" | "archive-albums",
- collectionID: activeCollectionID!,
- },
- };
-
- filteredFiles.forEach((item) => {
- if (item.ownerID === user.id) {
- selected.ownCount++;
- }
- selected.count++;
- selected[item.id] = true;
- });
- setSelected(selected);
- };
-
- const clearSelection = useCallback(() => {
- if (!selected.count) {
- return;
- }
- setSelected({
- ownCount: 0,
- count: 0,
- collectionID: 0,
- context: undefined,
- });
- }, [selected.count]);
-
- const keyboardShortcutHandlerRef = useRef({
- selectAll,
- clearSelection,
- isCleanupViewOpen,
- });
-
- useEffect(() => {
- keyboardShortcutHandlerRef.current = {
- selectAll,
- clearSelection,
- isCleanupViewOpen,
- };
- }, [selectAll, clearSelection, isCleanupViewOpen]);
-
- const showSessionExpiredDialog = useCallback(
- () => showMiniDialog(sessionExpiredDialogAttributes(logout)),
- [showMiniDialog, logout],
- );
-
- const handleVisualFeedback = useCallback(() => {
- showLoadingBar();
- setTimeout(hideLoadingBar, 0);
- }, [showLoadingBar, hideLoadingBar]);
-
- const handlePendingNavigationConsumed = useCallback(() => {
- setPendingFileNavigation(undefined);
- }, []);
-
- // Use this for collection/file/trash-only effects; a full pull costs more.
- const remoteFilesPull = useCallback(
- () =>
- remoteFilesPullQueue.current.add(() =>
- pullFiles({
- onSetCollections: (collections) =>
- dispatch({ type: "setCollections", collections }),
- onSetCollectionFiles: (collectionFiles) =>
- dispatch({
- type: "setCollectionFiles",
- collectionFiles,
- }),
- onSetTrashedItems: (trashItems) =>
- dispatch({ type: "setTrashItems", trashItems }),
- onDidUpdateCollectionFiles: () =>
- exportService.onLocalFilesUpdated(),
- }),
- ),
- [],
- );
-
- const remotePull = useCallback(
- async (opts?: RemotePullOpts) =>
- remotePullQueue.current.add(async () => {
- const { silent, source, strict } = opts ?? {};
-
- if (!navigator.onLine) {
- if (strict) throw new Error("Remote pull failed: offline");
- return;
- }
- if (await isSessionInvalid()) {
- showSessionExpiredDialog();
- if (strict)
- throw new Error("Remote pull failed: invalid session");
- return;
- }
- if (!(await masterKeyFromSession())) {
- clearSessionStorage();
- void router.push("/credentials");
- if (strict)
- throw new Error(
- "Remote pull failed: missing master key",
- );
- return;
- }
-
- try {
- if (!silent) showLoadingBar();
- await prePullFiles();
- await remoteFilesPull();
- await postPullFiles(source);
- } catch (e) {
- // A later pull retries transient failures after remote mutations.
- log.error("Remote pull failed", e);
- if (strict) throw e;
- } finally {
- dispatch({ type: "clearUnsyncedState" });
- if (!silent) hideLoadingBar();
- }
- }),
- [
- showLoadingBar,
- hideLoadingBar,
- router,
- showSessionExpiredDialog,
- remoteFilesPull,
- ],
- );
-
- const setupSelectAllKeyBoardShortcutHandler = () => {
- const handleKeyUp = (e: KeyboardEvent) => {
- if (keyboardShortcutHandlerRef.current.isCleanupViewOpen) return;
- switch (e.key) {
- case "Escape":
- keyboardShortcutHandlerRef.current.clearSelection();
- break;
- case "a":
- if (e.ctrlKey || e.metaKey) {
- keyboardShortcutHandlerRef.current.selectAll(e);
- }
- break;
- }
- };
- document.addEventListener("keydown", handleKeyUp);
- return () => {
- document.removeEventListener("keydown", handleKeyUp);
- };
- };
-
- const handleRemoveFilesFromCollection = (collection: Collection) => {
- void (async () => {
- showLoadingBar();
- let notifyOthersFiles = false;
- try {
- setOpenCollectionSelector(false);
- const selectedFiles = getSelectedFiles(selected, filteredFiles);
- const processedCount = await removeFromCollection(
- collection,
- selectedFiles,
- );
- notifyOthersFiles = processedCount != selectedFiles.length;
- clearSelection();
- await remotePull({
- silent: true,
- source: "remove-from-collection",
- });
- } catch (e) {
- onGenericError(e);
- } finally {
- hideLoadingBar();
- }
-
- if (notifyOthersFiles) {
- showMiniDialog(notifyOthersFilesDialogAttributes());
- }
- })();
- };
-
- const createOnSelectForCollectionOp =
- (op: CollectionOp) => (selectedCollection: Collection) => {
- const selectedFiles = getSelectedFiles(selected, filteredFiles);
- const userFiles = selectedFiles.filter(
- (f) => f.ownerID == user!.id,
- );
- const sourceCollectionID = selected.collectionID;
-
- const performSelectedCollectionOp = async (
- op: CollectionOp,
- filesToProcess: EnteFile[],
- notifySkippedFiles = false,
- ) => {
- showLoadingBar();
- try {
- setOpenCollectionSelector(false);
- if (filesToProcess.length > 0) {
- await performCollectionOp(
- op,
- selectedCollection,
- filesToProcess,
- sourceCollectionID,
- );
- }
- if (notifySkippedFiles) {
- showMiniDialog(notifyOthersFilesDialogAttributes());
- }
- clearSelection();
- await remotePull({
- silent: true,
- source: `collection-op:${op}`,
- });
- } finally {
- hideLoadingBar();
- }
- };
-
- const shouldAddInsteadOfMove =
- op == "move" &&
- selectedCollection.owner.id != user!.id &&
- canAddFilesToCollection(selectedCollection);
-
- if (shouldAddInsteadOfMove) {
- showMiniDialog({
- title: t("cannot_move_to_shared_albums"),
- message: t("cannot_move_to_shared_albums_message"),
- continue: {
- text: t("add"),
- action: () =>
- performSelectedCollectionOp("add", selectedFiles),
- },
- cancel: t("cancel"),
- });
- return;
- }
-
- void (async () => {
- try {
- const filesToProcess =
- op == "add" ? selectedFiles : userFiles;
- await performSelectedCollectionOp(
- op,
- filesToProcess,
- op != "add" && userFiles.length != selectedFiles.length,
- );
- } catch (e) {
- onGenericError(e);
- }
- })();
- };
-
- const createOnCreateForCollectionOp = useCallback(
- (op: CollectionOp) => {
- setPostCreateAlbumOp(op);
- postCreateAlbumHidden.current =
- (op == "add" || op == "move") && barMode == "hidden-albums";
- return showAlbumNameInput;
- },
- [showAlbumNameInput, barMode],
- );
-
- const handleAlbumNameSubmit = useCallback(
- async (name: string) => {
- try {
- const collection = postCreateAlbumHidden.current
- ? await createHiddenAlbum(name)
- : await createAlbum(name);
-
- if (pendingSingleFileAdd.current) {
- await performCollectionOp(
- "add",
- collection,
- [pendingSingleFileAdd.current.file],
- pendingSingleFileAdd.current.sourceCollectionSummaryID,
- );
-
- await remotePull({
- silent: true,
- source: "single-file-add-new-album",
- });
- setAlbumAddedNotification({
- open: true,
- albumName: collection.name,
- });
- setOpenCollectionSelector(false);
- setPostCreateAlbumOp(undefined);
- postCreateAlbumHidden.current = false;
- return;
- }
-
- if (postCreateAlbumOp === undefined) {
- await remotePull();
- showNotification({
- color: "primary",
- title: t("album_created"),
- });
- return;
- }
-
- createOnSelectForCollectionOp(postCreateAlbumOp)(collection);
- setPostCreateAlbumOp(undefined);
- postCreateAlbumHidden.current = false;
- } finally {
- pendingSingleFileAdd.current = undefined;
- }
- },
- [
- createOnSelectForCollectionOp,
- postCreateAlbumOp,
- remotePull,
- showNotification,
- ],
- );
-
- const handleFavoriteFileOp = async (
- op: Extract<FileOp, "favorite" | "unfavorite">,
- selectedFiles: EnteFile[],
- ) => {
- const filesToProcess: EnteFile[] = [];
- let skippedUnsupportedSharedFile = false;
-
- // Shared copies need a metadata hash to find their owned equivalent.
- for (const file of selectedFiles) {
- if (file.ownerID == user!.id || metadataHash(file.metadata)) {
- filesToProcess.push(file);
- } else {
- skippedUnsupportedSharedFile = true;
- }
- }
-
- if (!filesToProcess.length) {
- return { processed: false, skippedUnsupportedSharedFile };
- }
-
- const isFavorite = op == "favorite";
- const previousFavoriteByFileID = new Map(
- filesToProcess.map((file) => [
- file.id,
- favoriteFileIDs.has(file.id),
- ]),
- );
-
- for (const file of filesToProcess) {
- dispatch({ type: "addPendingFavoriteUpdate", fileID: file.id });
- dispatch({ type: "unsyncedFavoriteUpdate", file, isFavorite });
- }
-
- try {
- const action = isFavorite
- ? addToFavoritesCollection
- : removeFromFavoritesCollection;
- await action(filesToProcess);
- return { processed: true, skippedUnsupportedSharedFile };
- } catch (e) {
- for (const file of filesToProcess) {
- dispatch({
- type: "unsyncedFavoriteUpdate",
- file,
- isFavorite: previousFavoriteByFileID.get(file.id)!,
- });
- }
- throw e;
- } finally {
- for (const file of filesToProcess) {
- dispatch({
- type: "removePendingFavoriteUpdate",
- fileID: file.id,
- });
- }
- }
- };
-
- const onSendLinkError = useCallback(
- (e: unknown) => {
- if (isHTTPErrorWithStatus(e, 402)) {
- log.error("Could not create share link", e);
- showMiniDialog(
- errorDialogAttributes(
- t("share_link_subscription_required"),
- ),
- );
- } else {
- onGenericError(e);
- }
- },
- [showMiniDialog, onGenericError],
- );
-
- const createFileOpHandler =
- (op: FileOp, options?: { suppressSelectionBar?: boolean }) => () => {
- return (async () => {
- if (options?.suppressSelectionBar) {
- setSuppressContextSelectionBar(true);
- }
- showLoadingBar();
- try {
- if (op == "sendLink") {
- const selectedFiles = getSelectedFiles(
- selected,
- filteredFiles,
- );
- const ownedSelectedFiles = selectedFiles.filter(
- (file) => file.ownerID == user!.id,
- );
- if (!ownedSelectedFiles.length) return;
- if (ownedSelectedFiles.length != selectedFiles.length) {
- showMiniDialog(notifyOthersFilesDialogAttributes());
- }
-
- const quickLinkCollection =
- await createQuickLinkCollection(
- quickLinkNameForFiles(ownedSelectedFiles),
- quickLinkVisibility,
- );
- await addToCollection(
- quickLinkCollection,
- ownedSelectedFiles,
- );
- const publicURL = await createPublicURL(
- quickLinkCollection.id,
- { enableJoin: false },
- );
- const resolvedURL = await resolveQuickLinkURL(
- publicURL.url,
- quickLinkCollection.key,
- customDomain,
- );
- setPublicLinkToast({ open: true, url: resolvedURL });
-
- clearSelection();
- await remotePull({
- silent: true,
- source: "selected-files-quick-link",
- });
- return;
- }
-
- // Hide every non-hidden copy, including copies outside this view.
- const opFiles =
- op == "hide"
- ? state.collectionFiles.filter(
- (f) => !state.hiddenFileIDs.has(f.id),
- )
- : filteredFiles;
- const selectedFiles = getSelectedFiles(selected, opFiles);
- if (op == "favorite" || op == "unfavorite") {
- const { processed, skippedUnsupportedSharedFile } =
- await handleFavoriteFileOp(op, selectedFiles);
- clearSelection();
- if (processed) {
- await remotePull({
- silent: true,
- source: `file-op:${op}`,
- });
- }
- if (skippedUnsupportedSharedFile) {
- showMiniDialog(
- notifyUnsupportedSharedFavoritesDialogAttributes(),
- );
- }
- return;
- }
-
- const ownedSelectedFiles =
- op == "download"
- ? selectedFiles
- : selectedFiles.filter(
- (file) => file.ownerID == user!.id,
- );
- if (ownedSelectedFiles.length > 0) {
- await performFileOp(
- op,
- ownedSelectedFiles,
- onAddSaveGroup,
- handleMarkTempDeleted,
- () => dispatch({ type: "clearTempDeleted" }),
- (files) =>
- dispatch({ type: "markTempHidden", files }),
- () => dispatch({ type: "clearTempHidden" }),
- (files) => {
- setFixCreationTimeFiles(files);
- showFixCreationTime();
- },
- );
- }
-
- if (
- op != "download" &&
- ownedSelectedFiles.length != selectedFiles.length
- ) {
- showMiniDialog(notifyOthersFilesDialogAttributes());
- }
- clearSelection();
- await remotePull({ silent: true, source: `file-op:${op}` });
- } catch (e) {
- if (op == "trash") {
- throw e;
- } else if (op == "sendLink") {
- onSendLinkError(e);
- } else {
- onGenericError(e);
- }
- } finally {
- if (options?.suppressSelectionBar) {
- setSuppressContextSelectionBar(false);
- }
- hideLoadingBar();
- }
- })();
- };
-
- const handleAddPersonToSelectedFiles = useCallback(
- async (personID: string) => {
- showLoadingBar();
- try {
- const selectedFiles = getSelectedFiles(selected, filteredFiles);
- await addManualFileAssignmentsToPerson(
- personID,
- selectedFiles.map((f) => f.id),
- );
- clearSelection();
- const personName = namedPeople.find(
- (p) => p.id === personID,
- )?.name;
- showNotification({
- color: "secondary",
- startIcon: CheckmarkCircle02Icon,
- title: t("added_to_person"),
- caption: personName,
- });
- } catch (e) {
- onGenericError(e);
- } finally {
- hideLoadingBar();
- }
- },
- [
- selected,
- filteredFiles,
- clearSelection,
- showNotification,
- namedPeople,
- showLoadingBar,
- hideLoadingBar,
- onGenericError,
- ],
- );
-
- const handleContextMenuSelectPerson = useCallback(
- (personID: string) => {
- contextMenuAssignPersonProps.onClose();
- void handleAddPersonToSelectedFiles(personID);
- },
- [contextMenuAssignPersonProps, handleAddPersonToSelectedFiles],
- );
-
- const handleEditLocationConfirm = useCallback(
- async (location: Location) => {
- const userFiles = selectedFilesInView.filter(
- (f) => f.ownerID == user!.id,
- );
- if (userFiles.length > 0) {
- await updateFilesLocation(
- userFiles,
- location.latitude,
- location.longitude,
- );
- }
- void remotePull({ silent: true, source: "edit-location" });
- },
- [selectedFilesInView, user, remotePull],
- );
-
- const openUploader = (intent?: UploadTypeSelectorIntent) => {
- if (uploadManager.isUploadInProgress()) return;
- setUploadTypeSelectorView(true);
- setUploadTypeSelectorIntent(intent ?? "upload");
- };
-
- const handleShowCollectionSummaryWithID = useCallback(
- (collectionSummaryID: number | undefined) => {
- setAlbumOpenedFromOverview(undefined);
- setIsMapView(false);
- setCleanupView(undefined);
- // Museum deletes collection contents asynchronously; pull on entry.
- if (collectionSummaryID == PseudoCollectionID.trash) {
- void remoteFilesPull();
- }
-
- dispatch({ type: "showCollectionSummary", collectionSummaryID });
- },
- [],
- );
-
- useEffect(() => {
- if (mlStatus?.phase == "disabled" && barMode == "people") {
- handleShowCollectionSummaryWithID(PseudoCollectionID.all);
- }
- }, [mlStatus?.phase, barMode, handleShowCollectionSummaryWithID]);
-
- const showCollectionSummary = useCallback(
- (
- collectionSummaryID: number | undefined,
- isHiddenCollectionSummary?: boolean,
- ) =>
- showCollectionSummaryWithAuthentication(
- collectionSummaryID,
- !!isHiddenCollectionSummary && barMode != "hidden-albums",
- lastAuthenticationForHiddenTimestamp,
- authenticateUser,
- handleShowCollectionSummaryWithID,
- ),
- [authenticateUser, handleShowCollectionSummaryWithID, barMode],
- );
-
- const handleSelectSearchOption = useCallback(
- (
- searchOption: SearchOption | undefined,
- options?: { shouldExitSearchMode?: boolean },
- ) => {
- setIsMapView(false);
- if (searchOption) {
- const type = searchOption.suggestion.type;
- if (type == "sidebarAction") {
- const collectionID = albumShortcutCollectionID(
- searchOption.suggestion.actionID,
- state.uncategorizedCollectionSummaryID,
- );
- if (collectionID !== undefined) {
- void showCollectionSummary(
- collectionID,
- collectionID == PseudoCollectionID.hiddenItems,
- );
- return;
- }
- }
- setCleanupView(undefined);
- if (type == "collection") {
- dispatch({
- type: "showCollectionSummary",
- collectionSummaryID:
- searchOption.suggestion.collectionID,
- });
- } else if (type == "person") {
- dispatch({
- type: "showPerson",
- personID: searchOption.suggestion.person.id,
- });
- } else if (type == "sidebarAction") {
- navigationRef.current?.showSettings(
- searchOption.suggestion.actionID,
- );
-
- const shouldExitSearchMode =
- options?.shouldExitSearchMode ?? true;
- dispatch({ type: "exitSearch", shouldExitSearchMode });
- } else {
- if (barMode === "hidden-albums") {
- dispatch({ type: "showAlbums" });
- }
- dispatch({
- type: "enterSearchMode",
- searchSuggestion: searchOption.suggestion,
- });
- }
- } else {
- const shouldExitSearchMode =
- options?.shouldExitSearchMode ?? true;
- dispatch({ type: "exitSearch", shouldExitSearchMode });
- }
- },
- [
- barMode,
- dispatch,
- showCollectionSummary,
- state.uncategorizedCollectionSummaryID,
- ],
- );
-
- const handleShowCleanupView = useCallback(
- (view: "large-files" | "duplicates") => {
- setIsMapView(false);
- setSelected({
- ownCount: 0,
- count: 0,
- collectionID: 0,
- context: undefined,
- });
- closeCollectionMap();
- closeSlideshow();
- dispatch({ type: "exitSearch", shouldExitSearchMode: true });
- setCleanupView(view);
- },
- [closeCollectionMap, closeSlideshow],
- );
-
- const handleShowPeople = useCallback(
- (onNavigate?: () => void) => {
- if (!isMLEnabled()) {
- pendingPeopleSearchReset.current = onNavigate;
- showPeopleConsent();
- return false;
- }
- onNavigate?.();
- setIsMapView(false);
- setCleanupView(undefined);
- dispatch({ type: "showPeople" });
- return true;
- },
- [dispatch, showPeopleConsent],
- );
-
- const handleBackToPeople = useCallback(() => {
- setCleanupView(undefined);
- setSelected({
- ownCount: 0,
- count: 0,
- collectionID: 0,
- context: undefined,
- });
- dispatch({ type: "showPeople" });
- }, []);
-
- const handleShowAlbumOverview = useCallback(
- (filter: AlbumFilter) => {
- setCleanupView(undefined);
- clearSelection();
- setAlbumFilter(filter);
- dispatch({ type: "showAlbumOverview", albumFilter: filter });
- },
- [clearSelection, dispatch],
- );
-
- const handleBackToAlbums = useCallback(() => {
- setCleanupView(undefined);
- const origin =
- albumOpenedFromOverview?.collectionID === collectionSummary?.id
- ? albumOpenedFromOverview
- : undefined;
- const filter = origin?.filter ?? "ente";
- setAlbumSearchQuery(origin?.searchQuery ?? "");
- setSelected({
- ownCount: 0,
- count: 0,
- collectionID: 0,
- context: undefined,
- });
- setAlbumFilter(filter);
- dispatch({ type: "showAlbumOverview", albumFilter: filter });
- }, [albumOpenedFromOverview, collectionSummary?.id]);
-
- const handleChangeBarMode = useCallback(
- (mode: GalleryBarMode) => {
- if (mode == "links") {
- setCleanupView(undefined);
- clearSelection();
- dispatch({ type: "showLinks" });
- return true;
- }
- if (mode == "people") {
- return handleShowPeople();
- }
- setCleanupView(undefined);
- handleShowAlbumOverview("ente");
- return true;
- },
- [clearSelection, dispatch, handleShowAlbumOverview, handleShowPeople],
- );
-
- const handleFileViewerToggleFavorite = useCallback(
- async (file: EnteFile) => {
- const fileID = file.id;
- const isFavorite = favoriteFileIDs.has(fileID);
-
- dispatch({ type: "addPendingFavoriteUpdate", fileID });
- dispatch({
- type: "unsyncedFavoriteUpdate",
- file,
- isFavorite: !isFavorite,
- });
- try {
- const action = isFavorite
- ? removeFromFavoritesCollection
- : addToFavoritesCollection;
- await action([file]);
- } catch (e) {
- dispatch({ type: "unsyncedFavoriteUpdate", file, isFavorite });
- throw e;
- } finally {
- dispatch({ type: "removePendingFavoriteUpdate", fileID });
- }
- },
- [favoriteFileIDs],
- );
-
- const handleFileViewerFileVisibilityUpdate = useCallback(
- async (file: EnteFile, visibility: ItemVisibility) => {
- const fileID = file.id;
- dispatch({ type: "addPendingVisibilityUpdate", fileID });
- try {
- await updateFilesVisibility([file], visibility);
- // Keep the UI ahead of the background pull.
- // TODO: Replace with files pull?
- dispatch({
- type: "unsyncedPrivateMagicMetadataUpdate",
- fileID,
- privateMagicMetadata: {
- ...file.magicMetadata,
- count: file.magicMetadata?.count ?? 0,
- version: (file.magicMetadata?.version ?? 0) + 1,
- data: { ...file.magicMetadata?.data, visibility },
- },
- });
- } finally {
- dispatch({ type: "removePendingVisibilityUpdate", fileID });
- }
- },
- [],
- );
-
- const handleFileViewerSendLink = useCallback(
- async (file: EnteFile) => {
- if (file.ownerID != user?.id) return;
-
- showLoadingBar();
- try {
- const quickLinkCollection = await createQuickLinkCollection(
- quickLinkNameForFiles([file]),
- quickLinkVisibility,
- );
- await addToCollection(quickLinkCollection, [file]);
- const publicURL = await createPublicURL(
- quickLinkCollection.id,
- { enableJoin: false },
- );
- const resolvedURL = await resolveQuickLinkURL(
- publicURL.url,
- quickLinkCollection.key,
- customDomain,
- );
- setPublicLinkToast({ open: true, url: resolvedURL });
- await remotePull({ silent: true, source: "viewer-send-link" });
- } catch (e) {
- onSendLinkError(e);
- } finally {
- hideLoadingBar();
- }
- },
- [
- user?.id,
- showLoadingBar,
- hideLoadingBar,
- customDomain,
- quickLinkVisibility,
- remotePull,
- onSendLinkError,
- ],
- );
-
- const handleMarkTempDeleted = useCallback(
- (files: EnteFile[]) => dispatch({ type: "markTempDeleted", files }),
- [],
- );
-
- const handleSelectCollection = useCallback(
- (collectionID: number) => {
- setIsMapView(false);
- closeCollectionMap();
- dispatch({
- type: "showCollectionSummary",
- collectionSummaryID: collectionID,
- });
- },
- [closeCollectionMap],
- );
-
- const handleSelectPerson = useCallback(
- (personID: string) => {
- setCleanupView(undefined);
- setIsMapView(false);
- closeCollectionMap();
- dispatch({ type: "showPerson", personID });
- },
- [closeCollectionMap],
- );
-
- const handleOpenCollectionSelector = useCallback(
- (attributes: CollectionSelectorAttributes) => {
- setCollectionSelectorAttributes(attributes);
- setOpenCollectionSelector(true);
- },
- [],
- );
-
- const selectedCount = selected.count;
- const selectedOwnCount = selected.ownCount;
- const handleDeleteFiles = useCallback(
- (suppressSelectionBar = false) => {
- if (selectedOwnCount === 0) return;
- showMiniDialog(
- trashFilesDialogAttributes(
- selectedOwnCount,
- createFileOpHandler("trash", { suppressSelectionBar }),
- ),
- );
- },
- [selectedOwnCount, createFileOpHandler, showMiniDialog],
- );
- const selectedFavoriteCount = useMemo(
- () => countSelectedFavorites(selected, favoriteFileIDs),
- [favoriteFileIDs, selected],
- );
-
- const handleEditAlbumDetails = useCallback(
- async ({ name, description, coverID }: AlbumDetails) => {
- if (!activeCollection) return;
-
- let didAttemptWrite = false;
- try {
- if (activeCollection.name != name) {
- didAttemptWrite = true;
- await renameCollection(activeCollection, name);
- }
- const descriptionChanged =
- (
- activeCollection.pubMagicMetadata?.data.caption ?? ""
- ).trim() != description;
- if (descriptionChanged || coverID !== undefined) {
- didAttemptWrite = true;
- await updateCollectionDetails(activeCollection, {
- description: descriptionChanged
- ? description
- : undefined,
- coverID,
- });
- }
- } finally {
- if (didAttemptWrite) {
- await remotePull({
- silent: true,
- source: "update-album-details",
- });
- }
- }
- },
- [activeCollection, remotePull],
- );
-
- const handleContextMenuAction = useCallback(
- (
- action: FileContextAction,
- _targetFile?: EnteFile,
- meta?: { isEphemeralSingleSelection: boolean },
- ) => {
- const suppressSelectionBar = !!meta?.isEphemeralSingleSelection;
- switch (action) {
- case "sendLink":
- void createFileOpHandler("sendLink", {
- suppressSelectionBar,
- })();
- break;
- case "download":
- void createFileOpHandler("download", {
- suppressSelectionBar,
- })();
- break;
- case "favorite":
- void createFileOpHandler("favorite", {
- suppressSelectionBar,
- })();
- break;
- case "unfavorite":
- void createFileOpHandler("unfavorite", {
- suppressSelectionBar,
- })();
- break;
- case "archive":
- void createFileOpHandler("archive", {
- suppressSelectionBar,
- })();
- break;
- case "unarchive":
- void createFileOpHandler("unarchive", {
- suppressSelectionBar,
- })();
- break;
- case "hide":
- void createFileOpHandler("hide", {
- suppressSelectionBar,
- })();
- break;
- case "fixTime":
- void createFileOpHandler("fixTime", {
- suppressSelectionBar,
- })();
- break;
- case "trash":
- handleDeleteFiles(suppressSelectionBar);
- break;
- case "deletePermanently":
- showMiniDialog({
- title: t("delete_files_title"),
- kind: "warning",
- message: t("delete_files_message"),
- continue: {
- text: t("delete"),
- color: "critical",
- action: createFileOpHandler("deletePermanently", {
- suppressSelectionBar,
- }),
- },
- });
- break;
- case "restore":
- handleOpenCollectionSelector({
- action: "restore",
- onCreateCollection:
- createOnCreateForCollectionOp("restore"),
- onSelectCollection:
- createOnSelectForCollectionOp("restore"),
- });
- break;
- case "addToAlbum":
- handleOpenCollectionSelector({
- action: "add",
- sourceCollectionSummaryID: activeCollectionSummary?.id,
- showHiddenCollections: barMode == "hidden-albums",
- onCreateCollection:
- createOnCreateForCollectionOp("add"),
- onSelectCollection:
- createOnSelectForCollectionOp("add"),
- });
- break;
- case "moveToAlbum":
- handleOpenCollectionSelector({
- action: "move",
- sourceCollectionSummaryID: activeCollectionSummary?.id,
- showHiddenCollections: barMode == "hidden-albums",
- onCreateCollection:
- createOnCreateForCollectionOp("move"),
- onSelectCollection:
- createOnSelectForCollectionOp("move"),
- });
- break;
- case "removeFromAlbum": {
- if (!activeCollection) break;
- const isSharedIncoming =
- activeCollectionSummary?.attributes.has(
- "sharedIncoming",
- );
- const isSharedOutgoing =
- activeCollectionSummary?.attributes.has(
- "sharedOutgoing",
- );
- const isRemovingOthers = selectedCount != selectedOwnCount;
- const remove = () =>
- handleRemoveFilesFromCollection(activeCollection);
-
- if (isSharedIncoming) {
- if (isRemovingOthers) {
- showMiniDialog({
- title: t("remove_from_album"),
- message: t("remove_from_album_others_message"),
- continue: {
- text: t("remove"),
- color: "critical",
- action: remove,
- },
- cancel: t("cancel"),
- });
- } else {
- remove();
- }
- break;
- }
-
- if (isSharedOutgoing && isRemovingOthers) {
- showMiniDialog({
- title: t("remove_from_album"),
- message: t("remove_from_album_others_message"),
- continue: {
- text: t("remove"),
- color: "critical",
- action: remove,
- },
- });
- break;
- }
-
- const onlyUserFiles = !isRemovingOthers;
- showMiniDialog({
- title: t("remove_from_album"),
- message: onlyUserFiles
- ? t("confirm_remove_message")
- : t("confirm_remove_incl_others_message"),
- continue: {
- text: t("yes_remove"),
- color: onlyUserFiles ? "primary" : "critical",
- action: remove,
- },
- });
- break;
- }
- case "unhide":
- handleOpenCollectionSelector({
- action: "unhide",
- onCreateCollection:
- createOnCreateForCollectionOp("unhide"),
- onSelectCollection:
- createOnSelectForCollectionOp("unhide"),
- });
- break;
- case "addPerson":
- showContextMenuAssignPerson();
- break;
- case "editLocation":
- showEditLocation();
- break;
- }
- },
- [
- createFileOpHandler,
- createOnCreateForCollectionOp,
- createOnSelectForCollectionOp,
- handleOpenCollectionSelector,
- handleRemoveFilesFromCollection,
- handleDeleteFiles,
- showMiniDialog,
- showContextMenuAssignPerson,
- showEditLocation,
- activeCollectionSummary,
- activeCollection,
- barMode,
- selectedCount,
- selectedOwnCount,
- ],
- );
-
- const handleCloseCollectionSelector = useCallback(
- () => setOpenCollectionSelector(false),
- [],
- );
- const handleCollectionSelectorExited = useCallback(
- () => setCollectionSelectorAttributes(undefined),
- [],
- );
-
- const handleAddSingleFileToCollection = useCallback(
- (file: EnteFile, sourceCollectionSummaryID?: number) => {
- pendingSingleFileAdd.current = { file, sourceCollectionSummaryID };
-
- const handleSelect = async (collection: Collection) => {
- try {
- setAlbumAddedNotification({ open: false });
- showLoadingBar();
- await performCollectionOp(
- "add",
- collection,
- [file],
- sourceCollectionSummaryID,
- );
- await remotePull({
- silent: true,
- source: "single-file-add-to-album",
- });
- setAlbumAddedNotification({
- open: true,
- albumName: collection.name,
- });
- } catch (e) {
- onGenericError(e);
- } finally {
- pendingSingleFileAdd.current = undefined;
- hideLoadingBar();
- }
- };
-
- const handleCreate = () => {
- setPostCreateAlbumOp("add");
- postCreateAlbumHidden.current = false;
- showAlbumNameInput();
- };
-
- handleOpenCollectionSelector({
- action: "add",
- sourceCollectionSummaryID,
- onSelectCollection: (collection) =>
- void handleSelect(collection),
- onCreateCollection: handleCreate,
- onCancel: () => {
- pendingSingleFileAdd.current = undefined;
- },
- });
- },
- [handleOpenCollectionSelector, remotePull, onGenericError],
- );
-
- const showAppDownloadFooter =
- state.collectionFiles.length < 30 && !isInSearchMode;
-
- const fileListFooter = useMemo(
- () => (showAppDownloadFooter ? createAppDownloadFooter() : undefined),
- [showAppDownloadFooter],
- );
-
- const hasActiveFileSelection =
- selected.count > 0 && selected.collectionID === activeCollectionID;
- const showSelectionBar =
- hasActiveFileSelection &&
- !suppressContextSelectionBar &&
- !(isContextMenuOpen && selected.count === 1);
-
- const selectGalleryCollection = useCallback(
- (collectionID: number) => {
- if (barMode == "links") {
- dispatch({ type: "selectLink", collectionID });
- } else {
- handleShowCollectionSummaryWithID(collectionID);
- }
- },
- [barMode, dispatch, handleShowCollectionSummaryWithID],
- );
- const handleGoHome = useCallback(() => {
- setIsMapView(false);
- handleShowCollectionSummaryWithID(PseudoCollectionID.all);
- }, [handleShowCollectionSummaryWithID]);
- const handleChangeMode = useCallback(
- (mode: GalleryBarMode) => {
- const changed = handleChangeBarMode(mode);
- if (changed) setIsMapView(false);
- return changed;
- },
- [handleChangeBarMode],
- );
- const handleShowLibraryMap = useCallback(() => {
- setSelectedPlace(undefined);
- handleShowCollectionSummaryWithID(PseudoCollectionID.all);
- handleShowCollectionMap();
- }, [handleShowCollectionSummaryWithID, handleShowCollectionMap]);
- const handleSelectPlace = useCallback(
- (place: PlaceSelection | undefined) => {
- setSelectedPlace(place);
- setPlaceSelectionRevision((revision) => revision + 1);
- },
- [],
- );
- const handleOpenOverviewAlbum = useCallback(
- (collectionID: number) => {
- handleShowCollectionSummaryWithID(collectionID);
- setAlbumOpenedFromOverview({
- collectionID,
- filter: overviewFilter!,
- searchQuery: albumSearchQuery,
- });
- },
- [handleShowCollectionSummaryWithID, overviewFilter, albumSearchQuery],
- );
- const handleShowLinksOverview = useCallback(
- () => handleChangeBarMode("links"),
- [handleChangeBarMode],
- );
- const handleDownloadStatusNotificationsShowCollectionSummary = useCallback(
- (
- collectionSummaryID: number | undefined,
- isHiddenCollectionSummary: boolean | undefined,
- ) => {
- void showCollectionSummary(
- collectionSummaryID,
- isHiddenCollectionSummary,
- );
- },
- [showCollectionSummary],
- );
-
- const navigationActions = useMemo<PhotosNavigationActions>(
- () => ({
- goHome: handleGoHome,
- changeMode: handleChangeMode,
- showLibraryMap: handleShowLibraryMap,
- showCollectionMap: handleShowCollectionMap,
- selectPlace: handleSelectPlace,
- showCollectionSummary,
- selectCollection: selectGalleryCollection,
- selectCollectionFromViewer: handleSelectCollection,
- openOverviewAlbum: handleOpenOverviewAlbum,
- showAlbumOverview: handleShowAlbumOverview,
- backToAlbums: handleBackToAlbums,
- showLinksOverview: handleShowLinksOverview,
- showPeople: handleShowPeople,
- selectPerson: handleSelectPerson,
- backToPeople: handleBackToPeople,
- selectSearchOption: handleSelectSearchOption,
- showCleanupView: handleShowCleanupView,
- }),
- [
- handleGoHome,
- handleChangeMode,
- handleShowLibraryMap,
- handleShowCollectionMap,
- handleSelectPlace,
- showCollectionSummary,
- selectGalleryCollection,
- handleSelectCollection,
- handleOpenOverviewAlbum,
- handleShowAlbumOverview,
- handleBackToAlbums,
- handleShowLinksOverview,
- handleShowPeople,
- handleSelectPerson,
- handleBackToPeople,
- handleSelectSearchOption,
- handleShowCleanupView,
- ],
- );
-
- if (!user) {
- // Children rely on user after the mount dispatch.
- return <div></div>;
- }
-
- const collectionMap = activeCollectionSummary && (
- <CollectionMap
- collectionSummary={activeCollectionSummary}
- files={activeCollection ? activeCollectionFiles : filteredFiles}
- selectedPlace={
- activeCollectionID === PseudoCollectionID.all
- ? selectedPlace
- : undefined
- }
- placeSelectionRevision={placeSelectionRevision}
- mapFileSource={mapFileSource}
- onRemotePull={remotePull}
- onAddSaveGroup={onAddSaveGroup}
- onMarkTempDeleted={handleMarkTempDeleted}
- onAddFileToCollection={handleAddSingleFileToCollection}
- onRemoteFilesPull={remoteFilesPull}
- onVisualFeedback={handleVisualFeedback}
- fileNormalCollectionIDs={fileNormalCollectionIDs}
- collectionNameByID={collectionNameByID}
- emailByUserID={state.emailByUserID}
- />
- );
-
+ operations,
+ dropzoneProps,
+ blockingLoad,
+ collectionSelectorProps,
+ albumNameInputProps,
+ downloadNotificationsProps,
+ uploadProps,
+ quickLinkNotificationProps,
+ } = useGalleryOperations(
+ libraryOwner,
+ navigation.state,
+ authenticateUserDialogProps.open,
+ navigation.showSettings,
+ );
+ const library = useMemo(
+ () => ({ ...state, isFirstLoad, searchIndexRevision }),
+ [state, isFirstLoad, searchIndexRevision],
+ );
+ const { View } = sectionDefinition(navigation.sectionID);
+ if (!state.user) return <div />;
return (
- <PhotosNavigationContext.Provider value={navigationActions}>
- <FullScreenDropZone
- message={
- watchFolderView
- ? t("watch_folder_dropzone_hint")
- : undefined
- }
- disabled={
- shouldDisableDropzone || !!slideshow || isCleanupViewOpen
- }
- onDrop={setDragAndDropFiles}
- >
- {blockingLoad && <TranslucentLoadingOverlay />}
- <CollectionSelector
- open={openCollectionSelector}
- onClose={handleCloseCollectionSelector}
- onExited={handleCollectionSelectorExited}
- attributes={collectionSelectorAttributes}
- collectionSummaries={
- collectionSelectorAttributes?.showHiddenCollections
- ? state.hiddenCollectionSummaries
- : normalCollectionSummaries
- }
- collectionForCollectionSummaryID={(id) =>
- findCollectionCreatingIfNeeded(state.collections, id)
- }
- />
- <DownloadStatusNotifications
- {...{ saveGroups, onRemoveSaveGroup }}
- onShowCollectionSummary={
- handleDownloadStatusNotificationsShowCollectionSummary
- }
- />
- <FixCreationTime
- {...fixCreationTimeVisibilityProps}
- files={fixCreationTimeFiles}
- onRemotePull={remotePull}
- />
+ <PhotosNavigationContext.Provider value={navigation.actions}>
+ <FullScreenDropZone {...dropzoneProps}>
<PhotosNavigationShell
- ref={navigationRef}
+ ref={navigation.navigationRef}
isFirstLoad={isFirstLoad}
- isInSearchMode={isInSearchMode}
- collectionNameByID={collectionNameByID}
+ navigation={navigation.state}
+ collectionNameByID={state.collectionNameByID}
onAuthenticateUser={authenticateUser}
- mode={barMode}
- isMapView={isMapView}
- isMapSelected={
- isMapView &&
- activeCollectionID === PseudoCollectionID.all
- }
- onUpload={openUploader}
- galleryNavigation={
- isCleanupViewOpen
- ? undefined
- : {
- selectedPlace,
- placesFiles:
- isMapView &&
- activeCollectionID ===
- PseudoCollectionID.all
- ? filteredFiles
- : undefined,
- activeCollectionID:
- galleryBarActiveCollectionID,
- onRemotePull: remotePull,
- activePerson,
- albumFilter,
- albumSearchQuery,
- onAlbumSearchQueryChange: setAlbumSearchQuery,
- collectionSummaries:
- sidebarCollectionSummaries,
- visibleAlbumFilters: sidebarAlbumFilters,
- uncategorizedCollectionSummaryID:
- state.uncategorizedCollectionSummaryID,
- collectionsSortBy,
- onChangeCollectionsSortBy,
- peopleSortBy,
- onChangePeopleSortBy: setPeopleSortBy,
- people: sortedPeople,
- }
- }
- alternateHeader={
- showSelectionBar ? (
- <SelectedFileOptions
- barMode={barMode}
- isInSearchMode={isInSearchMode}
- collection={
- isInSearchMode
- ? undefined
- : activeCollection
- }
- collectionSummary={
- isInSearchMode
- ? undefined
- : activeCollectionSummary
- }
- selectedFileCount={selected.count}
- selectedOwnFileCount={selected.ownCount}
- selectedFavoriteCount={selectedFavoriteCount}
- onClearSelection={clearSelection}
- onDelete={() => handleDeleteFiles()}
- onRemoveFilesFromCollection={
- handleRemoveFilesFromCollection
- }
- onOpenCollectionSelector={
- handleOpenCollectionSelector
- }
- onSelectAll={handleSelectAll}
- isAllSelected={isAllSelectedInView}
- {...{
- createOnCreateForCollectionOp,
- createOnSelectForCollectionOp,
- createFileOpHandler,
- onShowAssignPersonDialog:
- showAddPersonAction
- ? showContextMenuAssignPerson
- : undefined,
- }}
- onEditLocation={showEditLocation}
- />
- ) : null
- }
+ onUpload={operations.onUpload}
>
- {!isMapView && !isCleanupViewOpen && (
- <>
- <GalleryBarAndListHeader
- albums={sidebarCollectionSummaries}
- {...{
- user,
- activeCollection,
- activePerson,
- collectionSummary,
- people,
- setBlockingLoad,
- setFileListHeader,
- hasActiveFileSelection,
- isActiveCollectionDownloadInProgress,
- onAddSaveGroup,
- }}
- showBackToAlbums={
- albumOpenedFromOverview !== undefined &&
- albumOpenedFromOverview.collectionID ===
- collectionSummary?.id
- }
- mode={barMode}
- shouldHide={isInSearchMode}
- onEditAlbumDetails={showEditAlbumDetails}
- onCollectionSlideshow={startSlideshow}
- emailByUserID={state.emailByUserID}
- shareSuggestionEmails={
- state.shareSuggestionEmails
- }
- onRemotePull={remotePull}
- />
- </>
- )}
- {isMapView ? (
- collectionMap
- ) : cleanupView === "duplicates" ? (
- <DuplicatesView onRemoteFilesPull={remoteFilesPull} />
- ) : cleanupView === "large-files" ? (
- <LargeFilesView onRemoteFilesPull={remoteFilesPull} />
- ) : !isInSearchMode && barMode == "links" ? (
- <LinksView
- user={user}
- collections={state.collections}
- collectionFiles={state.collectionFiles}
- collectionSummaries={normalCollectionSummaries}
- hiddenCollectionIDs={hiddenCollectionIDs}
- hiddenFileIDs={hiddenFileIDs}
- tempDeletedFileIDs={tempDeletedFileIDs}
- tempHiddenFileIDs={tempHiddenFileIDs}
- uncategorizedCollectionSummaryID={
- state.uncategorizedCollectionSummaryID
- }
- selectedLinkID={selectedLinkID}
- searchQuery={albumSearchQuery}
- sortBy={collectionsSortBy}
- onCreateAlbum={showAlbumNameInput}
- setBlockingLoad={setBlockingLoad}
- onRemotePull={remotePull}
- />
- ) : !isInSearchMode &&
- !isFirstLoad &&
- !state.collectionFiles.length &&
- activeCollectionID === PseudoCollectionID.all ? (
- <GalleryEmptyState
- isUploadInProgress={uploadManager.isUploadInProgress()}
- onUpload={openUploader}
- />
- ) : !isInSearchMode && !isFirstLoad && isAlbumOverview ? (
- <AlbumsOverview
- onRemotePull={remotePull}
- albums={overviewAlbums}
- title={(
- albumFilters.find(
- ({ value }) => value == overviewFilter,
- ) ?? albumFilters[0]!
- ).title()}
- filter={overviewFilter!}
- searchQuery={albumSearchQuery}
- sortBy={collectionsSortBy}
- onCreateAlbum={() => {
- setPostCreateAlbumOp(undefined);
- postCreateAlbumHidden.current = false;
- showAlbumNameInput();
+ {(presentation) => (
+ <View
+ library={library}
+ operations={operations}
+ navigation={{
+ ...navigation.state,
+ retainPerson: navigation.retainPerson,
}}
- />
- ) : !isInSearchMode &&
- !isFirstLoad &&
- state.view?.type == "people" &&
- !state.view.activePerson ? (
- <PeopleOverview
- people={state.view.visiblePeople}
- allPeople={state.view.people}
- peopleSortBy={peopleSortBy}
- />
- ) : (
- <FileListWithViewer
- mode={barMode}
- modePlus={isInSearchMode ? "search" : barMode}
- header={fileListHeader}
- footer={fileListFooter}
- user={user}
- files={filteredFiles}
- enableDownload={true}
- disableGrouping={
- state.searchSuggestion?.type == "clip" ||
- (!isInSearchMode &&
- activeCollection?.pubMagicMetadata?.data
- .sortBy === "fileName")
- }
- enableSelect={true}
- selected={selected}
- setSelected={setSelected}
- // TODO: Incorrect assertion, need to update the type
- activeCollectionID={activeCollectionID!}
- activeCollectionSummary={activeCollectionSummary}
- activePersonID={activePerson?.id}
- isInIncomingSharedCollection={activeCollectionSummary?.attributes.has(
- "sharedIncoming",
- )}
- isInHiddenSection={barMode == "hidden-albums"}
- onContextMenuAction={handleContextMenuAction}
- onContextMenuOpenChange={setIsContextMenuOpen}
- suppressSelectionUI={suppressContextSelectionBar}
- showAddPersonAction={showAddPersonAction}
- showEditLocationAction={selected.ownCount > 0}
- {...{
- favoriteFileIDs,
- collectionNameByID,
- fileNormalCollectionIDs,
- fileCollectionIDs,
- hiddenCollectionIDs,
- pendingFavoriteUpdates,
- pendingVisibilityUpdates,
- onAddSaveGroup,
- }}
- collectionSummaries={normalCollectionSummaries}
- emailByUserID={state.emailByUserID}
- onToggleFavorite={handleFileViewerToggleFavorite}
- onFileVisibilityUpdate={
- handleFileViewerFileVisibilityUpdate
- }
- onSendLink={handleFileViewerSendLink}
- onMarkTempDeleted={handleMarkTempDeleted}
- onSetOpenFileViewer={setIsFileViewerOpen}
- onRemotePull={remotePull}
- onRemoteFilesPull={remoteFilesPull}
- onVisualFeedback={handleVisualFeedback}
- onAddFileToCollection={
- handleAddSingleFileToCollection
- }
- pendingFileIndex={pendingFileNavigation?.fileIndex}
- pendingFileSidebar={pendingFileNavigation?.sidebar}
- pendingHighlightCommentID={
- pendingFileNavigation?.commentID
- }
- onPendingNavigationConsumed={
- handlePendingNavigationConsumed
- }
+ preferences={navigation.preferences}
+ presentation={presentation}
/>
)}
</PhotosNavigationShell>
- <Upload
- {...{
- user,
- dragAndDropFiles,
- uploadTypeSelectorIntent,
- uploadTypeSelectorView,
- }}
- isFirstUpload={haveOnlySystemCollections(
- normalCollectionSummaries,
- )}
- activeCollection={activeCollection}
- closeUploadTypeSelector={setUploadTypeSelectorView.bind(
- null,
- false,
- )}
- setLoading={setBlockingLoad}
- setShouldDisableDropzone={setShouldDisableDropzone}
- onRemotePull={remotePull}
- onRemoteFilesPull={remoteFilesPull}
- onOpenCollectionSelector={handleOpenCollectionSelector}
- onCloseCollectionSelector={handleCloseCollectionSelector}
- onUploadFile={(file) =>
- dispatch({ type: "uploadFile", file })
- }
- onShowSubscription={() =>
- navigationRef.current?.showSettings("subscription")
- }
- onShowSessionExpiredDialog={showSessionExpiredDialog}
- isInHiddenSection={barMode == "hidden-albums"}
- />
+ {blockingLoad && <TranslucentLoadingOverlay />}
+ <CollectionSelector {...collectionSelectorProps} />
+ <SingleInputDialog {...albumNameInputProps} />
+ <GalleryDownloadNotifications {...downloadNotificationsProps} />
+ {uploadProps && <Upload {...uploadProps} />}
+ <QuickLinkCreatedNotification {...quickLinkNotificationProps} />
<DesktopWhatsNew />
- <PeopleConsentDialog
- {...peopleConsentVisibilityProps}
- onClose={() => {
- pendingPeopleSearchReset.current = undefined;
- peopleConsentVisibilityProps.onClose();
- }}
- onEnabled={() =>
- handleShowPeople(pendingPeopleSearchReset.current)
- }
- />
- <AssignPersonDialog
- {...contextMenuAssignPersonProps}
- people={namedPeople}
- title={t("add_a_person")}
- onSelectPerson={handleContextMenuSelectPerson}
- />
- {slideshow &&
- slideshow.collectionID === activeCollection?.id &&
- !isInSearchMode && (
- <AlbumSlideshow
- files={slideshow.files}
- title={slideshow.title}
- onClose={closeSlideshow}
- />
- )}
- {activeCollection && editAlbumDetailsVisibilityProps.open && (
- <EditAlbumDetailsDialog
- key={activeCollection.id}
- {...editAlbumDetailsVisibilityProps}
- collection={activeCollection}
- files={activeCollectionFiles}
- initialCoverFile={activeCollectionSummary?.coverFile}
- onSubmit={handleEditAlbumDetails}
- />
- )}
+ <PeopleConsentDialog {...navigation.peopleConsentDialogProps} />
<AuthenticateUser {...authenticateUserDialogProps} />
</FullScreenDropZone>
- <SingleInputDialog
- {...albumNameInputVisibilityProps}
- title={t("new_album")}
- label={t("album_name")}
- submitButtonTitle={t("create")}
- onClose={() => {
- // Do not leak a cancelled add into the next album creation.
- pendingSingleFileAdd.current = undefined;
- postCreateAlbumHidden.current = false;
- setPostCreateAlbumOp(undefined);
- albumNameInputVisibilityProps.onClose();
- }}
- onSubmit={handleAlbumNameSubmit}
- />
- <QuickLinkCreatedNotification
- open={publicLinkToast.open}
- onCopy={() => {
- if (publicLinkToast.url) {
- void navigator.clipboard.writeText(publicLinkToast.url);
- }
- }}
- onClose={() =>
- setPublicLinkToast((prev) => ({ ...prev, open: false }))
- }
- />
- <Notification
- open={albumAddedNotification.open}
- onClose={() =>
- setAlbumAddedNotification((s) => ({ ...s, open: false }))
- }
- keepOpenOnClick
- attributes={{
- color: "inherit",
- startIcon: null,
- title: t("added_to_album"),
- caption: albumAddedNotification.albumName,
- }}
- />
- <EditLocationDialog
- {...editLocationVisibilityProps}
- files={selectedFilesInView}
- onConfirm={handleEditLocationConfirm}
- />
</PhotosNavigationContext.Provider>
);
};
-
export default Page;
-
-const createAppDownloadFooter = (): FileListHeaderOrFooter => ({
- component: (
- <Typography
- variant="small"
- sx={{
- alignSelf: "flex-end",
- marginInline: "auto",
- marginBlock: 0.75,
- textAlign: "center",
- color: "text.faint",
- }}
- >
- <Trans
- i18nKey="install_mobile_app"
- components={{
- a: externalLink(
- "https://play.google.com/store/apps/details?id=io.ente.photos",
- ),
- b: externalLink(
- "https://apps.apple.com/in/app/ente-photos/id1542026904",
- ),
- }}
- />
- </Typography>
- ),
- height: 90,
-});
diff --git a/web/apps/photos/src/utils/photoFrame/index.ts b/web/apps/photos/src/utils/photoFrame/index.ts
index 8bc71857e6..60a8a033fe 100644
--- a/web/apps/photos/src/utils/photoFrame/index.ts
+++ b/web/apps/photos/src/utils/photoFrame/index.ts
@@ -9,7 +9,7 @@ export const handleSelectCreator =
setSelected: SetSelectedState,
mode: GalleryBarMode | undefined,
userID: number | undefined,
- activeCollectionID: number,
+ activeCollectionID: number | undefined,
activePersonID: string | undefined,
setRangeStartIndex: (index: number | undefined) => void,
) =>
@@ -66,7 +66,7 @@ export const handleSelectCreatorMulti =
setSelected: SetSelectedState,
mode: GalleryBarMode | undefined,
userID: number | undefined,
- activeCollectionID: number,
+ activeCollectionID: number | undefined,
activePersonID: string | undefined,
) =>
(files: { id: number; ownerID: number }[]) =>
@@ -114,7 +114,7 @@ export const handleSelectCreatorMulti =
const createSelectedAndContext = (
mode: GalleryBarMode | undefined,
- activeCollectionID: number,
+ activeCollectionID: number | undefined,
activePersonID: string | undefined,
selected: SelectedState,
) => {
diff --git a/web/apps/photos/tests/album-navigation-data.test.tsx b/web/apps/photos/tests/album-navigation-data.test.tsx
index d551028de2..de7ded90af 100644
--- a/web/apps/photos/tests/album-navigation-data.test.tsx
+++ b/web/apps/photos/tests/album-navigation-data.test.tsx
@@ -4,7 +4,7 @@ import {
} from "ente-new/photos/services/collection-summary";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, test, vi } from "vitest";
-import { useAlbumNavigationData } from "../src/components/gallery/use-album-navigation-data";
+import { useAlbumNavigationData } from "../src/components/gallery/sections/albums/use-album-navigation-data";
vi.mock("@/utils/album-filters", () => import("../src/utils/album-filters"));
@@ -32,6 +32,7 @@ const navigationData = (
const Gallery = () => {
result = useAlbumNavigationData({
mode: "albums",
+ collectionsSortBy: "updation-time-desc",
collectionSummaries: new Map(summaries.map((cs) => [cs.id, cs])),
uncategorizedCollectionSummaryID: 99,
albumFilter: "ente",
@@ -54,7 +55,6 @@ describe("album navigation data", () => {
album(3),
];
const data = navigationData(summaries);
- expect(data.collectionsSortBy).toBe("updation-time-desc");
expect(ids(data.sidebarCollectionSummaries)).toEqual([2, 3, 1]);
expect(ids(data.overviewAlbums)).toEqual([2, 3, 1]);
expect(ids(summaries)).toEqual([1, 2, 3]);
diff --git a/web/apps/photos/tests/album-overview-navigation.test.ts b/web/apps/photos/tests/album-overview-navigation.test.ts
index 813f4bb4f8..c368fa3b50 100644
--- a/web/apps/photos/tests/album-overview-navigation.test.ts
+++ b/web/apps/photos/tests/album-overview-navigation.test.ts
@@ -1,46 +1,51 @@
import type { LocalUser } from "ente-accounts/services/user";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
import { describe, expect, test } from "vitest";
+import {
+ initialNavigationState,
+ navigationReducer,
+} from "../src/components/gallery/navigation/navigation-state";
import {
galleryReducer,
initialGalleryState,
} from "../src/components/gallery/reducer";
+import {
+ albumFiles,
+ albumView,
+} from "../src/components/gallery/sections/albums/album-files";
-const mounted = () =>
+const mounted = (
+ collections: Collection[] = [],
+ collectionFiles: EnteFile[] = [],
+) =>
galleryReducer(initialGalleryState, {
type: "mount",
user: { id: 1 } as LocalUser,
familyData: undefined,
- collections: [],
- collectionFiles: [],
+ collections,
+ collectionFiles,
trashItems: [],
});
describe("album overview navigation", () => {
test("opens a group without an active collection or stale photo search results", () => {
- const state = galleryReducer(
- {
- ...mounted(),
- isInSearchMode: true,
- isRecomputingSearchResults: true,
- },
+ const navigation = navigationReducer(
+ { ...initialNavigationState, overlay: { section: "search" } },
{ type: "showAlbumOverview", albumFilter: "shared" },
);
- expect(state.view).toEqual({
- type: "album-overview",
- albumFilter: "shared",
- });
- expect(state.selectedCollectionSummaryID).toBeUndefined();
- expect(state.filteredFiles).toEqual([]);
- expect(state.isInSearchMode).toBe(false);
- expect(state.isRecomputingSearchResults).toBe(false);
- expect(state.searchResults).toBeUndefined();
+ const library = mounted();
+ const view = albumView(library, navigation.destination);
+ expect(view).toEqual({ type: "album-overview", albumFilter: "shared" });
+ expect(navigation.destination.collectionID).toBeUndefined();
+ expect(albumFiles(library, view)).toEqual([]);
+ expect(navigation.overlay).toBeUndefined();
});
-
test("supports repeated group navigation, opening an album and returning Home", () => {
- const start = mounted();
- const favorite: CollectionSummary = {
+ const library = mounted();
+ const summary: CollectionSummary = {
id: 10,
type: "album",
name: "Test album",
@@ -51,68 +56,112 @@ describe("album overview navigation", () => {
latestFile: undefined,
updationTime: undefined,
};
- start.normalCollectionSummaries.set(favorite.id, favorite);
- let state = galleryReducer(start, {
+ library.normalCollectionSummaries.set(summary.id, summary);
+ let navigation = navigationReducer(initialNavigationState, {
type: "showAlbumOverview",
albumFilter: "ente",
});
- state = galleryReducer(state, {
+ navigation = navigationReducer(navigation, {
type: "showAlbumOverview",
albumFilter: "received",
});
- state = galleryReducer(state, {
+ navigation = navigationReducer(navigation, {
type: "showCollectionSummary",
- collectionSummaryID: favorite.id,
+ collectionSummaryID: 10,
+ library,
});
- expect(state.view?.type).toBe("albums");
- expect(state.selectedCollectionSummaryID).toBe(favorite.id);
- state = galleryReducer(state, { type: "showAll" });
- expect(
- state.view?.type == "albums" &&
- state.view.activeCollectionSummaryID,
- ).toBe(PseudoCollectionID.all);
+ expect(albumView(library, navigation.destination).type).toBe("albums");
+ expect(navigation.destination.collectionID).toBe(10);
+ navigation = navigationReducer(navigation, { type: "showAll" });
+ expect(navigation.destination.collectionID).toBe(
+ PseudoCollectionID.all,
+ );
});
-
- test("keeps the group overview through collection refreshes", () => {
- let state = galleryReducer(mounted(), {
+ test("refreshes populated album summaries while keeping the group overview", () => {
+ const album: Collection = {
+ id: 10,
+ name: "Original album",
+ type: "album",
+ owner: { id: 1 },
+ key: "album-key",
+ sharees: [],
+ publicURLs: [],
+ updationTime: 1,
+ };
+ const files: EnteFile[] = [1, 2, 3].map((id) => ({
+ id,
+ collectionID: album.id,
+ ownerID: 1,
+ key: "file-key",
+ file: { decryptionHeader: "" },
+ thumbnail: { decryptionHeader: "" },
+ updationTime: id,
+ metadata: {
+ fileType: 0,
+ title: `${id}.jpg`,
+ creationTime: id,
+ modificationTime: id,
+ },
+ }));
+ let library = mounted([album], files.slice(0, 1));
+ const navigation = navigationReducer(initialNavigationState, {
type: "showAlbumOverview",
albumFilter: "ente",
});
- state = galleryReducer(state, {
+ expect(library.normalCollectionSummaries.get(album.id)).toMatchObject({
+ name: "Original album",
+ fileCount: 1,
+ coverFile: { id: 1 },
+ });
+ library = galleryReducer(library, {
type: "setCollections",
- collections: [],
+ collections: [{ ...album, name: "Renamed album", updationTime: 2 }],
+ });
+ expect(library.normalCollectionSummaries.get(album.id)).toMatchObject({
+ name: "Renamed album",
+ fileCount: 1,
+ coverFile: { id: 1 },
});
- state = galleryReducer(state, {
+ library = galleryReducer(library, {
type: "setCollectionFiles",
- collectionFiles: [],
+ collectionFiles: files.slice(1),
});
- state = galleryReducer(state, {
+ expect(library.normalCollectionSummaries.get(album.id)).toMatchObject({
+ name: "Renamed album",
+ fileCount: 2,
+ coverFile: { id: 3 },
+ });
+ library = galleryReducer(library, {
type: "setTrashItems",
- trashItems: [],
+ trashItems: [{ file: files[0]!, updatedAt: 4, deleteBy: 5 }],
});
- state = galleryReducer(state, { type: "clearUnsyncedState" });
- expect(state.view).toEqual({
- type: "album-overview",
- albumFilter: "ente",
+ expect(
+ library.normalCollectionSummaries.get(PseudoCollectionID.trash)
+ ?.fileCount,
+ ).toBe(1);
+ library = galleryReducer(library, { type: "clearUnsyncedState" });
+ const view = albumView(library, navigation.destination);
+ expect(view).toEqual({ type: "album-overview", albumFilter: "ente" });
+ expect(library.normalCollectionSummaries.get(album.id)).toMatchObject({
+ name: "Renamed album",
+ fileCount: 2,
+ coverFile: { id: 3 },
});
- expect(state.filteredFiles).toEqual([]);
});
-
test("switches between the People overview and album groups", () => {
- let state = galleryReducer(mounted(), {
+ let navigation = navigationReducer(initialNavigationState, {
type: "showAlbumOverview",
albumFilter: "ente",
});
- state = galleryReducer(state, { type: "showPeople" });
- expect(state.view?.type).toBe("people");
- state = galleryReducer(state, {
+ navigation = navigationReducer(navigation, { type: "showPeople" });
+ expect(navigation.destination.section).toBe("people");
+ navigation = navigationReducer(navigation, {
type: "showAlbumOverview",
albumFilter: "shared",
});
- expect(state.view).toEqual({
+ expect(albumView(mounted(), navigation.destination)).toEqual({
type: "album-overview",
albumFilter: "shared",
});
- expect(state.filteredFiles).toEqual([]);
});
});
diff --git a/web/apps/photos/tests/albums-section-summary.test.tsx b/web/apps/photos/tests/albums-section-summary.test.tsx
new file mode 100644
index 0000000000..4337520c9b
--- /dev/null
+++ b/web/apps/photos/tests/albums-section-summary.test.tsx
@@ -0,0 +1,225 @@
+import { AlbumContentHeader } from "@/components/collections/AlbumContentHeader";
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import { ItemVisibility } from "ente-media/file-metadata";
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import type { ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, expect, test, vi } from "vitest";
+import {
+ galleryReducer,
+ initialGalleryState,
+ type GalleryState,
+} from "../src/components/gallery/reducer";
+import { AlbumsSection } from "../src/components/gallery/sections/albums/AlbumsSection";
+import type { GallerySectionProps } from "../src/components/gallery/sections/types";
+
+vi.mock("@/components/collections/AlbumContentHeader", () => ({
+ AlbumContentHeader: vi.fn(() => null),
+}));
+vi.mock("@/components/collections/AlbumSlideshow", () => ({
+ AlbumSlideshow: () => null,
+}));
+vi.mock("@/components/collections/CollectionMap", () => ({
+ CollectionMap: () => null,
+}));
+vi.mock("@/components/collections/EditAlbumDetailsDialog", () => ({
+ EditAlbumDetailsDialog: () => null,
+}));
+vi.mock("@/components/collections/CreateAlbumDialog", () => ({
+ CreateAlbumDialog: () => null,
+}));
+vi.mock("@/components/gallery", () => ({ GalleryEmptyState: () => null }));
+vi.mock("@/components/gallery/sections/albums/AlbumsOverview", () => ({
+ AlbumsOverview: () => null,
+}));
+vi.mock("@/components/gallery/sections/albums/use-gallery-slideshow", () => ({
+ useGallerySlideshow: () => ({
+ slideshow: undefined,
+ startSlideshow: vi.fn(),
+ closeSlideshow: vi.fn(),
+ }),
+}));
+vi.mock(
+ "@/components/gallery/sections/albums/use-album-navigation-data",
+ () =>
+ import("../src/components/gallery/sections/albums/use-album-navigation-data"),
+);
+vi.mock("@/utils/album-filters", () => import("../src/utils/album-filters"));
+vi.mock("@/services/upload-manager", () => ({ uploadManager: {} }));
+vi.mock("../src/components/gallery/sections/albums/AlbumsNavigation", () => ({
+ AlbumsNavigation: () => null,
+}));
+vi.mock("../src/components/gallery/media/GalleryMedia", () => ({
+ GalleryMedia: ({
+ children,
+ }: {
+ children?: (hasSelection: boolean) => ReactNode;
+ }) => children?.(false),
+}));
+vi.mock("../src/components/gallery/navigation/GallerySectionLayout", () => ({
+ GallerySectionLayout: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("../src/components/gallery/navigation/PhotosNavigationContext", () => ({
+ usePhotosNavigation: () => ({
+ selectCollection: vi.fn(),
+ showAlbumOverview: vi.fn(),
+ }),
+}));
+
+beforeEach(() => vi.clearAllMocks());
+
+const files: EnteFile[] = [1, 2].map((id) => ({
+ id,
+ collectionID: 10,
+ ownerID: 1,
+ key: "file-key",
+ file: { decryptionHeader: "" },
+ thumbnail: { decryptionHeader: "" },
+ updationTime: id,
+ metadata: {
+ fileType: 0,
+ title: `${id}.jpg`,
+ creationTime: id,
+ modificationTime: id,
+ },
+}));
+
+const openAlbum = (
+ visibility: ItemVisibility = ItemVisibility.visible,
+ collectionFiles: EnteFile[] = [],
+) => {
+ const album: Collection = {
+ id: 10,
+ name: "Album",
+ type: "album",
+ owner: { id: 1 },
+ key: "album-key",
+ sharees: [],
+ publicURLs: [],
+ updationTime: 1,
+ magicMetadata: { version: 1, count: 1, data: { visibility } },
+ };
+ const state = galleryReducer(initialGalleryState, {
+ type: "mount",
+ user: { id: 1, email: "[email protected]", token: "test-token" },
+ familyData: undefined,
+ collections: [album],
+ collectionFiles: [...collectionFiles],
+ trashItems: [],
+ });
+ return state;
+};
+
+const headerSummary = (state: GalleryState, collectionID = 10) => {
+ const props: GallerySectionProps = {
+ library: { ...state, isFirstLoad: false, searchIndexRevision: 0 },
+ operations: {
+ dispatch: vi.fn(),
+ peopleState: undefined,
+ selectionDisabled: false,
+ mutations: {
+ setPublicLinkToast: vi.fn(),
+ handleFavoriteFileOp: vi.fn(),
+ onSendLinkError: vi.fn(),
+ handleMarkTempDeleted: vi.fn(),
+ },
+ onAddSaveGroup: vi.fn(),
+ onToggleFavorite: vi.fn(),
+ onSendLink: vi.fn(),
+ onFileVisibilityUpdate: vi.fn(),
+ onMarkTempDeleted: vi.fn(),
+ onRemotePull: vi.fn(),
+ onRemoteFilesPull: vi.fn(),
+ onVisualFeedback: vi.fn(),
+ onAddFileToCollection: vi.fn(),
+ setBlockingLoad: vi.fn(),
+ onUpload: vi.fn(),
+ onCreateAlbum: vi.fn(),
+ saveGroups: [],
+ setSectionActivity: vi.fn(),
+ },
+ navigation: {
+ destination: {
+ section: "albums",
+ collectionID,
+ albumMode: state.hiddenCollectionIDs.has(collectionID)
+ ? "hidden-albums"
+ : state.archivedCollectionIDs.has(collectionID)
+ ? "archive-albums"
+ : "albums",
+ },
+ retainPerson: vi.fn(),
+ selectedPlace: undefined,
+ placeSelectionRevision: 0,
+ },
+ preferences: {
+ searchSortAsc: undefined,
+ setSearchSortAsc: vi.fn(),
+ albumFilter: "ente",
+ setAlbumFilter: vi.fn(),
+ albumSearchQuery: "",
+ setAlbumSearchQuery: vi.fn(),
+ albumOpenedFromOverview: undefined,
+ setAlbumOpenedFromOverview: vi.fn(),
+ peopleSortBy: "count-desc",
+ setPeopleSortBy: vi.fn(),
+ collectionsSortBy: "updation-time-desc",
+ onChangeCollectionsSortBy: vi.fn(),
+ albumExpansion: { value: "ente", onChange: vi.fn() },
+ },
+ presentation: {
+ collapsed: false,
+ mobile: false,
+ mobileDrawerProps: { open: false, onClose: vi.fn() },
+ reduceMotion: true,
+ isFirstLoad: false,
+ isOffline: false,
+ },
+ };
+ renderToStaticMarkup(<AlbumsSection {...props} />);
+ return vi.mocked(AlbumContentHeader).mock.lastCall![0].collectionSummary;
+};
+
+test.each([
+ ["normal", ItemVisibility.visible],
+ ["hidden", ItemVisibility.hidden],
+ ["archived", ItemVisibility.archived],
+])("updates the %s album header after a file sync", (_, visibility) => {
+ const before = openAlbum(visibility);
+ const after = galleryReducer(before, {
+ type: "setCollectionFiles",
+ collectionFiles: [...files],
+ });
+ const summary = headerSummary(after);
+ expect(summary?.fileCount).toBe(2);
+ expect(summary?.coverFile?.id).toBe(2);
+});
+
+test("updates the header as a file uploads into an empty album", () => {
+ const after = galleryReducer(openAlbum(), {
+ type: "uploadFile",
+ file: files[0]!,
+ });
+ const summary = headerSummary(after);
+ expect(summary?.fileCount).toBe(1);
+ expect(summary?.coverFile?.id).toBe(1);
+});
+
+test("clears the header count and cover when the last files are removed", () => {
+ const after = galleryReducer(openAlbum(ItemVisibility.visible, files), {
+ type: "setCollectionFiles",
+ collectionFiles: [],
+ });
+ const summary = headerSummary(after);
+ expect(summary?.fileCount).toBe(0);
+ expect(summary?.coverFile).toBeUndefined();
+});
+
+test("updates the Trash header when trash items arrive after collections", () => {
+ const after = galleryReducer(openAlbum(), {
+ type: "setTrashItems",
+ trashItems: [{ file: files[0]!, updatedAt: 1, deleteBy: 2 }],
+ });
+ expect(headerSummary(after, PseudoCollectionID.trash)?.fileCount).toBe(1);
+});
diff --git a/web/apps/photos/tests/collection-operations.test.tsx b/web/apps/photos/tests/collection-operations.test.tsx
new file mode 100644
index 0000000000..faa5f106a6
--- /dev/null
+++ b/web/apps/photos/tests/collection-operations.test.tsx
@@ -0,0 +1,309 @@
+import type { Collection } from "ente-media/collection";
+import type { EnteFile } from "ente-media/file";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, expect, test, vi } from "vitest";
+import { useCollectionDialogs } from "../src/components/gallery/media/use-collection-dialogs";
+import { useCollectionOperations } from "../src/components/gallery/media/use-collection-operations";
+import { initialGalleryState } from "../src/components/gallery/reducer";
+
+const services = vi.hoisted(() => ({
+ createAlbum: vi.fn(),
+ renameCollection: vi.fn(),
+ performCollectionOp: vi.fn(),
+ onGenericError: vi.fn(),
+ hideLoadingBar: vi.fn(),
+ showNotification: vi.fn(),
+}));
+
+vi.mock("@/components/CollectionSelector", () => ({
+ CollectionSelector: () => null,
+}));
+vi.mock("@/components/gallery/helpers", () => ({
+ findCollectionCreatingIfNeeded: vi.fn(),
+ performCollectionOp: services.performCollectionOp,
+}));
+vi.mock("@/components/utils/dialog-attributes", () => ({
+ notifyOthersFilesDialogAttributes: vi.fn(),
+}));
+vi.mock("@/utils/file", () => import("../src/utils/file"));
+vi.mock("@/services/save", () => ({ downloadAndSaveFiles: vi.fn() }));
+vi.mock("ente-base/components/Notification", () => ({
+ Notification: () => null,
+}));
+vi.mock("ente-base/components/SingleInputDialog", () => ({
+ SingleInputDialog: () => null,
+}));
+vi.mock("ente-base/context", () => ({
+ useBaseContext: () => ({
+ showMiniDialog: vi.fn(),
+ onGenericError: services.onGenericError,
+ }),
+}));
+vi.mock("ente-new/photos/types/context", () => ({
+ usePhotosAppContext: () => ({
+ showLoadingBar: vi.fn(),
+ hideLoadingBar: services.hideLoadingBar,
+ showNotification: services.showNotification,
+ }),
+}));
+vi.mock("ente-new/photos/services/collection", () => ({
+ createAlbum: services.createAlbum,
+ renameCollection: services.renameCollection,
+ createHiddenAlbum: vi.fn(),
+ canAddFilesToCollection: vi.fn(),
+ removeFromCollection: vi.fn(),
+}));
+
+const album: Collection = {
+ id: 20,
+ name: "New album",
+ type: "album",
+ owner: { id: 1 },
+ key: "album-key",
+ sharees: [],
+ publicURLs: [],
+ updationTime: 1,
+};
+const files: EnteFile[] = [1, 2, 3].map((id) => ({
+ id,
+ collectionID: 10,
+ ownerID: 1,
+ key: "file-key",
+ file: { decryptionHeader: "" },
+ thumbnail: { decryptionHeader: "" },
+ updationTime: id,
+ metadata: {
+ fileType: 0,
+ title: `${id}.jpg`,
+ creationTime: id,
+ modificationTime: id,
+ },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ services.createAlbum.mockReset().mockResolvedValue(album);
+ services.renameCollection.mockReset().mockResolvedValue(undefined);
+ services.performCollectionOp.mockReset().mockResolvedValue(undefined);
+});
+
+const openAddDialog = () => {
+ let operations: ReturnType<typeof useCollectionOperations>;
+ let initialized = false;
+ const Harness = () => {
+ operations = useCollectionOperations({
+ state: {
+ ...initialGalleryState,
+ user: {
+ id: 1,
+ email: "[email protected]",
+ token: "test-token",
+ },
+ },
+ selected: {
+ 1: true,
+ 2: true,
+ count: 2,
+ ownCount: 2,
+ collectionID: 10,
+ context: undefined,
+ },
+ filteredFiles: files,
+ barMode: "albums",
+ clearSelection: vi.fn(),
+ remotePull: vi.fn().mockResolvedValue(undefined),
+ });
+ if (!initialized) {
+ initialized = true;
+ operations.createOnCreateForCollectionOp("add")();
+ }
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ const dialogProps = operations!.albumNameInputProps;
+ return {
+ operations: operations!,
+ close: dialogProps.onClose,
+ submit: () => dialogProps.onSubmit("New album", vi.fn()),
+ };
+};
+
+test("closing a submitted dialog retains its selected photos", async () => {
+ const creation = Promise.withResolvers<Collection>();
+ services.createAlbum.mockReturnValueOnce(creation.promise);
+ const dialog = openAddDialog();
+ const submitted = dialog.submit();
+ dialog.close();
+ creation.resolve(album);
+ await submitted;
+ expect(services.performCollectionOp).toHaveBeenCalledExactlyOnceWith(
+ "add",
+ album,
+ files.slice(0, 2),
+ 10,
+ );
+});
+
+test("a newer operation cannot replace a pending album's operation", async () => {
+ const creation = Promise.withResolvers<Collection>();
+ services.createAlbum.mockReturnValueOnce(creation.promise);
+ const dialog = openAddDialog();
+ const submitted = dialog.submit();
+ dialog.close();
+ dialog.operations.createOnCreateForCollectionOp("move")();
+ creation.resolve(album);
+ await submitted;
+ expect(services.performCollectionOp).toHaveBeenCalledExactlyOnceWith(
+ "add",
+ album,
+ files.slice(0, 2),
+ 10,
+ );
+});
+
+test("retrying a failed creation retains its selected photos", async () => {
+ services.createAlbum.mockRejectedValueOnce(new Error("HTTP 500"));
+ const dialog = openAddDialog();
+ await expect(dialog.submit()).rejects.toThrow("HTTP 500");
+ expect(services.performCollectionOp).not.toHaveBeenCalled();
+ await dialog.submit();
+ expect(services.performCollectionOp).toHaveBeenCalledExactlyOnceWith(
+ "add",
+ album,
+ files.slice(0, 2),
+ 10,
+ );
+});
+
+const openSingleFileAddDialog = () => {
+ let dialogs: ReturnType<typeof useCollectionDialogs>;
+ let step = 0;
+ const remotePull = vi.fn().mockResolvedValue(undefined);
+ const Harness = () => {
+ dialogs = useCollectionDialogs({
+ state: initialGalleryState,
+ remotePull,
+ });
+ if (step === 0) {
+ step++;
+ dialogs.handleAddSingleFileToCollection(files[0]!, 10);
+ } else if (step === 1) {
+ step++;
+ dialogs.collectionSelectorProps.attributes!.onCreateCollection();
+ }
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ return {
+ remotePull,
+ submit: (name = "New album") =>
+ dialogs!.albumNameInputProps.onSubmit(name, vi.fn()),
+ select: () =>
+ dialogs!.collectionSelectorProps.attributes!.onSelectCollection(
+ album,
+ ),
+ };
+};
+
+test("creating an album from the viewer adds the file and refreshes the gallery", async () => {
+ const dialog = openSingleFileAddDialog();
+ await dialog.submit();
+ expect(services.performCollectionOp).toHaveBeenCalledExactlyOnceWith(
+ "add",
+ album,
+ [files[0]],
+ 10,
+ );
+ expect(dialog.remotePull).toHaveBeenCalledExactlyOnceWith({
+ silent: true,
+ source: "single-file-add-to-album",
+ });
+ expect(services.showNotification).toHaveBeenCalledOnce();
+ expect(services.hideLoadingBar).toHaveBeenCalledOnce();
+});
+
+test("a single-file add failure reaches the album-name form", async () => {
+ services.performCollectionOp.mockRejectedValueOnce(new Error("HTTP 500"));
+ const dialog = openSingleFileAddDialog();
+ await expect(dialog.submit()).rejects.toThrow("HTTP 500");
+ expect(services.onGenericError).not.toHaveBeenCalled();
+ expect(services.showNotification).not.toHaveBeenCalled();
+ expect(dialog.remotePull).not.toHaveBeenCalled();
+ expect(services.hideLoadingBar).toHaveBeenCalledOnce();
+});
+
+test("retrying a failed single-file add reuses the created album", async () => {
+ services.performCollectionOp.mockRejectedValueOnce(new Error("HTTP 500"));
+ const dialog = openSingleFileAddDialog();
+ await expect(dialog.submit()).rejects.toThrow("HTTP 500");
+ await dialog.submit();
+ expect(services.createAlbum).toHaveBeenCalledExactlyOnceWith("New album");
+ expect(services.performCollectionOp).toHaveBeenCalledTimes(2);
+ expect(services.performCollectionOp).toHaveBeenLastCalledWith(
+ "add",
+ album,
+ [files[0]],
+ 10,
+ );
+ expect(dialog.remotePull).toHaveBeenCalledOnce();
+ expect(services.showNotification).toHaveBeenCalledOnce();
+});
+
+test("retrying a failed refresh does not recreate the album or add the file again", async () => {
+ const dialog = openSingleFileAddDialog();
+ dialog.remotePull.mockRejectedValueOnce(new Error("HTTP 500"));
+ await expect(dialog.submit()).rejects.toThrow("HTTP 500");
+ expect(services.showNotification).not.toHaveBeenCalled();
+ await dialog.submit();
+ expect(services.createAlbum).toHaveBeenCalledOnce();
+ expect(services.performCollectionOp).toHaveBeenCalledOnce();
+ expect(dialog.remotePull).toHaveBeenCalledTimes(2);
+ expect(services.showNotification).toHaveBeenCalledOnce();
+});
+
+test("a failed single-file album creation can be retried", async () => {
+ services.createAlbum.mockRejectedValueOnce(new Error("HTTP 500"));
+ const dialog = openSingleFileAddDialog();
+ await expect(dialog.submit()).rejects.toThrow("HTTP 500");
+ expect(services.performCollectionOp).not.toHaveBeenCalled();
+ await dialog.submit();
+ expect(services.createAlbum).toHaveBeenCalledTimes(2);
+ expect(services.performCollectionOp).toHaveBeenCalledOnce();
+ expect(dialog.remotePull).toHaveBeenCalledOnce();
+});
+
+test("editing the name on retry renames the same album and retains it after a rename failure", async () => {
+ services.performCollectionOp.mockRejectedValueOnce(new Error("Add failed"));
+ services.renameCollection.mockRejectedValueOnce(new Error("Rename failed"));
+ const dialog = openSingleFileAddDialog();
+ await expect(dialog.submit()).rejects.toThrow("Add failed");
+ await expect(dialog.submit("Renamed album")).rejects.toThrow(
+ "Rename failed",
+ );
+ expect(services.performCollectionOp).toHaveBeenCalledOnce();
+ await dialog.submit("Renamed album");
+ expect(services.createAlbum).toHaveBeenCalledOnce();
+ expect(services.renameCollection).toHaveBeenCalledTimes(2);
+ expect(services.renameCollection).toHaveBeenLastCalledWith(
+ album,
+ "Renamed album",
+ );
+ expect(services.performCollectionOp).toHaveBeenLastCalledWith(
+ "add",
+ { ...album, name: "Renamed album" },
+ [files[0]],
+ 10,
+ );
+});
+
+test("an existing-album add failure still reports a generic error", async () => {
+ const error = new Error("HTTP 500");
+ services.performCollectionOp.mockRejectedValueOnce(error);
+ const dialog = openSingleFileAddDialog();
+ dialog.select();
+ await vi.waitFor(() =>
+ expect(services.onGenericError).toHaveBeenCalledExactlyOnceWith(error),
+ );
+ expect(services.showNotification).not.toHaveBeenCalled();
+ expect(services.hideLoadingBar).toHaveBeenCalledOnce();
+});
diff --git a/web/apps/photos/tests/file-selection.test.ts b/web/apps/photos/tests/file-selection.test.ts
new file mode 100644
index 0000000000..96d1b09b59
--- /dev/null
+++ b/web/apps/photos/tests/file-selection.test.ts
@@ -0,0 +1,55 @@
+import type { EnteFile } from "ente-media/file";
+import { expect, test } from "vitest";
+import {
+ emptySelection,
+ retainVisibleSelection,
+} from "../src/components/gallery/media/file-selection";
+
+const files = [
+ { id: 1, ownerID: 1 },
+ { id: 2, ownerID: 2 },
+ { id: 3, ownerID: 1 },
+] as EnteFile[];
+const selected = {
+ ...emptySelection,
+ 1: true,
+ 2: true,
+ count: 2,
+ ownCount: 1,
+ collectionID: 10,
+};
+
+test("sorting and refreshed file objects retain the selection", () => {
+ expect(
+ retainVisibleSelection(
+ selected,
+ files.toReversed().map((file) => ({ ...file })),
+ 1,
+ ),
+ ).toBe(selected);
+});
+
+test("removing a selected photo updates counts without selecting an upload", () => {
+ const next = retainVisibleSelection(selected, files.slice(1), 1);
+ expect(next).toMatchObject({
+ 2: true,
+ count: 1,
+ ownCount: 0,
+ collectionID: 10,
+ });
+ expect(next[1]).toBeUndefined();
+ expect(next[3]).toBeUndefined();
+});
+
+test("empty results remove the selection", () => {
+ expect(retainVisibleSelection(selected, [], 1)).toMatchObject({
+ count: 0,
+ ownCount: 0,
+ });
+});
+
+test("duplicate collection memberships do not inflate selected counts", () => {
+ expect(retainVisibleSelection(selected, [...files, files[0]!], 1)).toBe(
+ selected,
+ );
+});
diff --git a/web/apps/photos/tests/gallery-media-projections.test.ts b/web/apps/photos/tests/gallery-media-projections.test.ts
new file mode 100644
index 0000000000..7a6d08be95
--- /dev/null
+++ b/web/apps/photos/tests/gallery-media-projections.test.ts
@@ -0,0 +1,155 @@
+import type { LocalUser } from "ente-accounts/services/user";
+import type { EnteFile } from "ente-media/file";
+import { ItemVisibility } from "ente-media/file-metadata";
+import {
+ PseudoCollectionID,
+ type CollectionSummary,
+} from "ente-new/photos/services/collection-summary";
+import type { PeopleState, Person } from "ente-new/photos/services/ml/people";
+import { expect, test } from "vitest";
+import { homeDestination } from "../src/components/gallery/navigation/navigation-state";
+import {
+ galleryReducer,
+ initialGalleryState,
+ type GalleryState,
+} from "../src/components/gallery/reducer";
+import {
+ albumFiles,
+ albumView,
+ resolveAlbumDestination,
+} from "../src/components/gallery/sections/albums/album-files";
+import {
+ derivePeopleFilteredFiles,
+ derivePeopleView,
+ resolvePeopleDestination,
+} from "../src/components/gallery/sections/people/people-files";
+
+const file = (id: number, collectionID = 10): EnteFile =>
+ ({
+ id,
+ collectionID,
+ ownerID: 1,
+ metadata: { creationTime: id, fileType: 0 },
+ }) as EnteFile;
+const library = (): GalleryState => ({
+ ...initialGalleryState,
+ user: { id: 1 } as LocalUser,
+ collectionFiles: [file(1), file(2), file(3), file(4), file(1, 11)],
+ hiddenFileIDs: new Set([2]),
+ archivedFileIDs: new Set([3]),
+ normalCollectionSummaries: new Map([
+ [
+ PseudoCollectionID.all,
+ {
+ id: PseudoCollectionID.all,
+ attributes: new Set(),
+ } as CollectionSummary,
+ ],
+ ]),
+});
+
+test("All Photos keeps visibility, deduplication, and optimistic deletion rules", () => {
+ let state = library();
+ state.collectionFiles[2]!.magicMetadata = {
+ version: 1,
+ count: 1,
+ data: { visibility: ItemVisibility.archived },
+ };
+ const files = () =>
+ albumFiles(state, albumView(state, homeDestination)).map(
+ (file) => file.id,
+ );
+ expect(files()).toEqual([1, 4]);
+ state = galleryReducer(state, {
+ type: "markTempDeleted",
+ files: [file(4)],
+ });
+ expect(files()).toEqual([1]);
+ const trash = albumFiles(state, {
+ type: "albums",
+ activeCollectionSummaryID: PseudoCollectionID.trash,
+ activeCollection: undefined,
+ activeCollectionSummary: {
+ id: PseudoCollectionID.trash,
+ } as CollectionSummary,
+ });
+ expect(trash.map((file) => file.id)).toEqual([4]);
+});
+
+test("removing the album shown on a map falls back to the library map", () => {
+ const destination = resolveAlbumDestination(library(), {
+ section: "albums",
+ albumMode: "albums",
+ collectionID: 10,
+ collectionMap: true,
+ });
+ expect(destination.section).toBe("places");
+ expect(destination.collectionID).toBe(PseudoCollectionID.all);
+});
+
+test("People keeps a selected small cluster and filters hidden and duplicate files", () => {
+ const small = { id: "small", fileIDs: [1, 2], name: undefined } as Person;
+ const named = { id: "named", fileIDs: [4], name: "Named" } as Person;
+ const people: PeopleState = {
+ people: [small, named],
+ visiblePeople: [named],
+ personByFaceID: new Map(),
+ };
+ const selected = derivePeopleView(
+ people,
+ new Set(),
+ new Set(),
+ "small",
+ undefined,
+ );
+ expect(selected.view.visiblePeople.map((person) => person.id)).toEqual([
+ "named",
+ "small",
+ ]);
+ const state = library();
+ expect(
+ derivePeopleFilteredFiles(
+ state.collectionFiles,
+ state.hiddenFileIDs,
+ selected.view,
+ 1,
+ ).map((file) => file.id),
+ ).toEqual([1]);
+ const next = derivePeopleView(
+ people,
+ new Set(),
+ new Set(),
+ "named",
+ selected.extraVisiblePerson,
+ );
+ expect(next.view.visiblePeople.map((person) => person.id)).toContain(
+ "small",
+ );
+ const removed = derivePeopleView(
+ people,
+ new Set([1, 2]),
+ new Set(),
+ "small",
+ selected.extraVisiblePerson,
+ );
+ expect(removed.view.activePerson).toBeUndefined();
+ expect(removed.extraVisiblePerson).toBeUndefined();
+ expect(
+ resolvePeopleDestination(
+ {
+ ...state,
+ peopleState: people,
+ tempDeletedFileIDs: new Set([1, 2]),
+ },
+ {
+ section: "people",
+ personID: "small",
+ extraVisiblePersonID: "small",
+ },
+ ),
+ ).toEqual({
+ section: "people",
+ personID: undefined,
+ extraVisiblePersonID: undefined,
+ });
+});
diff --git a/web/apps/photos/tests/gallery-sections.test.tsx b/web/apps/photos/tests/gallery-sections.test.tsx
new file mode 100644
index 0000000000..98bf21c09c
--- /dev/null
+++ b/web/apps/photos/tests/gallery-sections.test.tsx
@@ -0,0 +1,144 @@
+import { Link04Icon } from "@hugeicons/core-free-icons";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, describe, expect, test, vi } from "vitest";
+import {
+ activeSectionID,
+ initialNavigationState,
+ navigationReducer,
+} from "../src/components/gallery/navigation/navigation-state";
+import {
+ gallerySections,
+ sectionDefinition,
+ selectRailSection,
+ type GallerySectionDefinition,
+ type GallerySectionID,
+} from "../src/components/gallery/sections/registry";
+import type { GallerySectionProps } from "../src/components/gallery/sections/types";
+
+vi.mock("../src/components/gallery/sections/albums/AlbumsSection", () => ({
+ AlbumsSection: () => <div>Albums</div>,
+}));
+vi.mock("../src/components/gallery/sections/people/PeopleSection", () => ({
+ PeopleSection: () => <div>People</div>,
+}));
+vi.mock("../src/components/gallery/sections/places/PlacesSection", () => ({
+ PlacesSection: () => <div>Places</div>,
+}));
+vi.mock("../src/components/gallery/sections/links/LinksSection", () => ({
+ LinksSection: () => <div>Links</div>,
+}));
+vi.mock("../src/components/gallery/sections/search/SearchSection", () => ({
+ SearchSection: () => <div>Search</div>,
+}));
+vi.mock("../src/components/gallery/sections/cleanup/DuplicatesView", () => ({
+ DuplicatesView: () => null,
+}));
+vi.mock("../src/components/gallery/sections/cleanup/LargeFilesView", () => ({
+ LargeFilesView: () => null,
+}));
+vi.mock("ente-new/photos/services/ml", () => ({ isMLSupported: false }));
+
+const fixtureID = "fixture" as GallerySectionID;
+const registry = gallerySections as Record<string, GallerySectionDefinition>;
+afterEach(() => {
+ delete registry.fixture;
+});
+
+test("a component and one definition add a selectable section", () => {
+ const Feature = vi.fn(() => <div>Fixture content</div>);
+ registry.fixture = {
+ View: Feature,
+ hasNavigation: false,
+ rail: { label: () => "Fixture", icon: Link04Icon },
+ };
+ const state = navigationReducer(initialNavigationState, {
+ type: "openSection",
+ section: fixtureID,
+ });
+ const selected = sectionDefinition(activeSectionID(state));
+ expect(selected.rail?.label()).toBe("Fixture");
+ expect(
+ renderToStaticMarkup(
+ <selected.View {...({} as GallerySectionProps)} />,
+ ),
+ ).toContain("Fixture content");
+ expect(Feature).toHaveBeenCalledOnce();
+ const { View } = sectionDefinition("albums");
+ renderToStaticMarkup(<View {...({} as GallerySectionProps)} />);
+ expect(Feature).toHaveBeenCalledOnce();
+});
+
+const entry = () => ({
+ navigation: initialNavigationState,
+ mobile: false,
+ open: vi.fn(() => true),
+ openPanel: vi.fn(),
+ closeDrawer: vi.fn(),
+ togglePanel: vi.fn(),
+});
+describe("rail entry behavior", () => {
+ test("ordinary sections open and repeated selection toggles their panel", () => {
+ const controls = entry();
+ selectRailSection(sectionDefinition("links"), "links", controls);
+ expect(controls.open).toHaveBeenCalledOnce();
+ expect(controls.openPanel).toHaveBeenCalledOnce();
+ controls.navigation = navigationReducer(initialNavigationState, {
+ type: "showLinks",
+ });
+ selectRailSection(sectionDefinition("links"), "links", controls);
+ expect(controls.togglePanel).toHaveBeenCalledOnce();
+ expect(controls.open).toHaveBeenCalledOnce();
+ });
+ test("desktop People uses its consent entry without toggling the panel", () => {
+ const controls = entry();
+ controls.open.mockReturnValue(false);
+ selectRailSection(sectionDefinition("people"), "people", controls);
+ expect(controls.closeDrawer).toHaveBeenCalledOnce();
+ expect(controls.open).toHaveBeenCalledOnce();
+ expect(controls.openPanel).not.toHaveBeenCalled();
+ expect(controls.togglePanel).not.toHaveBeenCalled();
+ expect(sectionDefinition("people").rail?.available?.()).toBe(false);
+ });
+ test("map entry opens the mobile panel immediately", () => {
+ const controls = { ...entry(), mobile: true };
+ selectRailSection(sectionDefinition("places"), "places", controls);
+ expect(controls.open).toHaveBeenCalledOnce();
+ expect(controls.openPanel).toHaveBeenCalledOnce();
+ });
+ test("leaving cleanup opens Links even when it was the underlying destination", () => {
+ const controls = entry();
+ controls.navigation = navigationReducer(
+ navigationReducer(initialNavigationState, { type: "showLinks" }),
+ { type: "showCleanup", section: "duplicates" },
+ );
+ selectRailSection(sectionDefinition("links"), "links", controls);
+ expect(controls.open).toHaveBeenCalledOnce();
+ expect(controls.togglePanel).not.toHaveBeenCalled();
+ });
+});
+
+test("temporary search and cleanup retain their underlying destination", () => {
+ let state = navigationReducer(initialNavigationState, {
+ type: "showAlbumOverview",
+ albumFilter: "shared",
+ });
+ const origin = state.destination;
+ state = navigationReducer(state, { type: "enterSearchMode" });
+ expect(activeSectionID(state)).toBe("search");
+ state = navigationReducer(state, {
+ type: "exitSearch",
+ shouldExitSearchMode: false,
+ });
+ expect(activeSectionID(state)).toBe("search");
+ state = navigationReducer(state, { type: "exitSearch" });
+ expect(state.destination).toBe(origin);
+ state = navigationReducer(state, {
+ type: "showCleanup",
+ section: "large-files",
+ });
+ expect(activeSectionID(state)).toBe("large-files");
+ expect(state.destination).toBe(origin);
+ state = navigationReducer(state, { type: "showAll" });
+ expect(activeSectionID(state)).toBe("albums");
+ expect(state.overlay).toBeUndefined();
+});
diff --git a/web/apps/photos/tests/gallery-selection-lifetime.test.tsx b/web/apps/photos/tests/gallery-selection-lifetime.test.tsx
new file mode 100644
index 0000000000..717e1f6bf5
--- /dev/null
+++ b/web/apps/photos/tests/gallery-selection-lifetime.test.tsx
@@ -0,0 +1,66 @@
+import type { EnteFile } from "ente-media/file";
+import { useState } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test } from "vitest";
+import { emptySelection } from "../src/components/gallery/media/file-selection";
+import { useGallerySelection } from "../src/components/gallery/media/use-gallery-selection";
+
+const files = [
+ { id: 1, ownerID: 1 },
+ { id: 2, ownerID: 2 },
+] as EnteFile[];
+const both = { ...emptySelection, 1: true, 2: true, count: 2, ownCount: 1 };
+
+test("finishing an older operation preserves a newer user selection", () => {
+ let stage = 0;
+ let finish: () => void;
+ const Harness = () => {
+ const selection = useGallerySelection(files, 1);
+ if (stage === 0) {
+ stage++;
+ selection.setSelected(both);
+ } else if (stage === 1) {
+ stage++;
+ finish = selection.clearSelection;
+ selection.setSelected({
+ ...emptySelection,
+ 2: true,
+ count: 1,
+ ownCount: 0,
+ });
+ } else if (stage === 2) {
+ stage++;
+ finish();
+ }
+ return (
+ <span>
+ {selection.selected.count}:
+ {selection.selected[2] ? "second" : "none"}
+ </span>
+ );
+ };
+ expect(renderToStaticMarkup(<Harness />)).toBe("<span>1:second</span>");
+});
+
+test("finishing an operation still clears its selection after a data refresh", () => {
+ let stage = 0;
+ let finish: () => void;
+ const Harness = () => {
+ const [visible, setVisible] = useState(files);
+ const selection = useGallerySelection(visible, 1);
+ if (stage === 0) {
+ stage++;
+ selection.setSelected(both);
+ } else if (stage === 1) {
+ stage++;
+ finish = selection.clearSelection;
+ setVisible(files.slice(1));
+ } else if (stage === 2) {
+ stage++;
+ expect(selection.selected.count).toBe(1);
+ finish();
+ }
+ return <span>{selection.selected.count}</span>;
+ };
+ expect(renderToStaticMarkup(<Harness />)).toBe("<span>0</span>");
+});
diff --git a/web/apps/photos/tests/gallery-upload-target.test.tsx b/web/apps/photos/tests/gallery-upload-target.test.tsx
new file mode 100644
index 0000000000..08f49aaace
--- /dev/null
+++ b/web/apps/photos/tests/gallery-upload-target.test.tsx
@@ -0,0 +1,108 @@
+import { CollectionSubType, type Collection } from "ente-media/collection";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, expect, test, vi } from "vitest";
+import { useGalleryOperations } from "../src/components/gallery/hooks/use-gallery-operations";
+import type { useGalleryUploads } from "../src/components/gallery/hooks/use-gallery-uploads";
+import {
+ initialNavigationState,
+ type GalleryDestination,
+} from "../src/components/gallery/navigation/navigation-state";
+import { initialGalleryState } from "../src/components/gallery/reducer";
+
+const uploads = vi.hoisted(() =>
+ vi.fn<
+ (input: Parameters<typeof useGalleryUploads>[0]) => {
+ dropzoneProps: object;
+ }
+ >(() => ({ dropzoneProps: {} })),
+);
+
+vi.mock("@/components/QuickLinkCreatedNotification", () => ({
+ QuickLinkCreatedNotification: () => null,
+}));
+vi.mock("@/components/gallery/media/GalleryDownloadNotifications", () => ({
+ GalleryDownloadNotifications: () => null,
+}));
+vi.mock("@/components/gallery/media/use-file-mutations", () => ({
+ useFileMutations: () => ({ publicLinkToast: { open: false } }),
+}));
+vi.mock("../src/components/gallery/media/use-collection-dialogs", () => ({
+ useCollectionDialogs: () => ({ albumNameInputVisibilityProps: {} }),
+}));
+vi.mock("@/components/gallery/hooks/use-gallery-uploads", () => ({
+ useGalleryUploads: uploads,
+}));
+vi.mock("ente-gallery/components/utils/save-groups", () => ({
+ useSaveGroups: () => ({ saveGroups: [] }),
+}));
+vi.mock("ente-new/photos/types/context", () => ({
+ usePhotosAppContext: () => ({}),
+}));
+
+const collection: Collection = {
+ id: 10,
+ name: "Public link",
+ type: "album",
+ owner: { id: 1 },
+ key: "test-key",
+ sharees: [],
+ publicURLs: [],
+ updationTime: 1,
+ magicMetadata: {
+ version: 1,
+ count: 1,
+ data: { subType: CollectionSubType.quicklink },
+ },
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+const uploadTarget = (destination: GalleryDestination) => {
+ const Harness = () => {
+ useGalleryOperations(
+ {
+ state: { ...initialGalleryState, collections: [collection] },
+ searchIndexRevision: 0,
+ isFirstLoad: false,
+ dispatch: vi.fn(),
+ peopleState: undefined,
+ remotePull: vi.fn(),
+ remoteFilesPull: vi.fn(),
+ showSessionExpiredDialog: vi.fn(),
+ joinedCollectionID: undefined,
+ },
+ { ...initialNavigationState, destination },
+ false,
+ vi.fn(),
+ );
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ return uploads.mock.lastCall![0].activeCollection;
+};
+
+test("a selected public link does not become the drop upload target", () => {
+ expect(
+ uploadTarget({ section: "links", collectionID: 10 }),
+ ).toBeUndefined();
+});
+
+test.each<GalleryDestination>([
+ { section: "albums", albumMode: "albums", collectionID: 10 },
+ { section: "albums", albumMode: "hidden-albums", collectionID: 10 },
+ { section: "albums", albumMode: "archive-albums", collectionID: 10 },
+ { section: "albums", collectionID: 10, collectionMap: true },
+])("an album destination retains its upload target: %j", (destination) => {
+ expect(uploadTarget(destination)).toBe(collection);
+});
+
+test.each<GalleryDestination>([
+ { section: "albums", albumFilter: "ente" },
+ { section: "people", personID: "person" },
+ { section: "places", collectionID: -1 },
+])(
+ "a destination without an album requires album selection: %j",
+ (destination) => {
+ expect(uploadTarget(destination)).toBeUndefined();
+ },
+);
diff --git a/web/apps/photos/tests/links-view.test.tsx b/web/apps/photos/tests/links-view.test.tsx
index b16f4ed614..8f1514c55a 100644
--- a/web/apps/photos/tests/links-view.test.tsx
+++ b/web/apps/photos/tests/links-view.test.tsx
@@ -2,25 +2,42 @@ import type { LocalUser } from "ente-accounts/services/user";
import { CollectionSubType, type Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { ItemVisibility } from "ente-media/file-metadata";
-import type { ComponentProps } from "react";
+import type { ComponentProps, ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, expect, test, vi } from "vitest";
-import { AlbumsOverview } from "../src/components/gallery/AlbumsOverview";
-import { LinksView } from "../src/components/gallery/LinksView";
-import { PublicLinkDetails } from "../src/components/gallery/PublicLinkDetails";
import {
galleryReducer,
initialGalleryState,
} from "../src/components/gallery/reducer";
+import { AlbumsOverview } from "../src/components/gallery/sections/albums/AlbumsOverview";
+import { LinksView } from "../src/components/gallery/sections/links/LinksView";
+import { PublicLinkDetails } from "../src/components/gallery/sections/links/PublicLinkDetails";
vi.mock("@/utils/quick-links", () => import("../src/utils/quick-links"));
-vi.mock("../src/components/gallery/AlbumsOverview", () => ({
+vi.mock("../src/components/gallery/sections/albums/AlbumsOverview", () => ({
AlbumsOverview: vi.fn(() => null),
}));
-vi.mock("../src/components/gallery/PublicLinkDetails", () => ({
+vi.mock("../src/components/gallery/sections/links/PublicLinkDetails", () => ({
PublicLinkDetails: vi.fn(() => null),
}));
+vi.mock("../src/components/gallery/sections/links/LinksNavigation", () => ({
+ LinksNavigation: vi.fn(() => null),
+}));
+vi.mock("../src/components/gallery/navigation/GallerySectionLayout", () => ({
+ GallerySectionLayout: ({
+ navigation,
+ children,
+ }: {
+ navigation: ReactNode;
+ children: ReactNode;
+ }) => (
+ <>
+ {navigation}
+ {children}
+ </>
+ ),
+}));
beforeEach(() => vi.clearAllMocks());
const link = (id: number, overrides: Partial<Collection> = {}): Collection => ({
@@ -81,6 +98,16 @@ const props = (
trashItems: [],
});
return {
+ presentation: {
+ collapsed: false,
+ mobile: false,
+ mobileDrawerProps: { open: false, onClose: vi.fn() },
+ reduceMotion: true,
+ isFirstLoad: false,
+ isOffline: false,
+ },
+ onSearchQueryChange: vi.fn(),
+ onChangeSortBy: vi.fn(),
user,
collections,
collectionFiles: state.collectionFiles,
diff --git a/web/apps/photos/tests/map-entry.test.tsx b/web/apps/photos/tests/map-entry.test.tsx
new file mode 100644
index 0000000000..378d6677fb
--- /dev/null
+++ b/web/apps/photos/tests/map-entry.test.tsx
@@ -0,0 +1,68 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, expect, test, vi } from "vitest";
+import { useMapEntry } from "../src/components/gallery/sections/places/use-map-entry";
+
+const settings = vi.hoisted(() => ({
+ enabled: false,
+ update: vi.fn(),
+ error: vi.fn(),
+}));
+vi.mock("ente-base/context", () => ({
+ useBaseContext: () => ({ onGenericError: settings.error }),
+}));
+vi.mock("ente-new/photos/components/utils/use-snapshot", () => ({
+ useSettingsSnapshot: () => ({ mapEnabled: settings.enabled }),
+}));
+vi.mock("ente-new/photos/services/settings", () => ({
+ updateMapEnabled: settings.update,
+}));
+beforeEach(() => {
+ vi.clearAllMocks();
+ settings.enabled = false;
+ settings.update.mockResolvedValue(undefined);
+});
+
+const entry = () => {
+ const open = vi.fn();
+ let activate: ReturnType<typeof useMapEntry>;
+ const Harness = () => {
+ activate = useMapEntry(open);
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ return { open, activate: activate! };
+};
+
+test("waits for map enablement before opening", async () => {
+ let finish: () => void;
+ settings.update.mockReturnValue(
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const controller = entry();
+ controller.activate();
+ expect(settings.update).toHaveBeenCalledWith(true);
+ expect(controller.open).not.toHaveBeenCalled();
+ finish!();
+ await Promise.resolve();
+ expect(controller.open).toHaveBeenCalledOnce();
+});
+
+test("keeps the destination unchanged when map enablement fails", async () => {
+ const error = new Error("enable failed");
+ settings.update.mockRejectedValue(error);
+ const controller = entry();
+ controller.activate();
+ await Promise.resolve();
+ expect(controller.open).not.toHaveBeenCalled();
+ expect(settings.error).toHaveBeenCalledWith(error);
+});
+
+test("opens an enabled map without writing settings again", () => {
+ settings.enabled = true;
+ const controller = entry();
+ controller.activate();
+ expect(settings.update).not.toHaveBeenCalled();
+ expect(controller.open).toHaveBeenCalledOnce();
+});
diff --git a/web/apps/photos/tests/people-entry.test.tsx b/web/apps/photos/tests/people-entry.test.tsx
new file mode 100644
index 0000000000..81a23042fe
--- /dev/null
+++ b/web/apps/photos/tests/people-entry.test.tsx
@@ -0,0 +1,78 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, expect, test, vi } from "vitest";
+import { usePeopleEntry } from "../src/components/gallery/sections/people/use-people-entry";
+
+const consent = vi.hoisted(() => ({
+ enabled: false,
+ show: vi.fn(),
+ close: vi.fn(),
+}));
+vi.mock("ente-base/components/utils/modal", () => ({
+ useModalVisibility: () => ({
+ show: consent.show,
+ props: { open: false, onClose: consent.close },
+ }),
+}));
+vi.mock("ente-new/photos/components/utils/use-snapshot", () => ({
+ useMLStatusSnapshot: () => undefined,
+}));
+vi.mock("ente-new/photos/services/ml", () => ({
+ isMLEnabled: () => consent.enabled,
+}));
+
+beforeEach(() => {
+ consent.enabled = false;
+ vi.clearAllMocks();
+});
+
+const entry = () => {
+ const navigate = vi.fn();
+ let result: ReturnType<typeof usePeopleEntry>;
+ const Harness = () => {
+ result = usePeopleEntry({
+ isCurrentDestination: false,
+ onUnavailable: vi.fn(),
+ onNavigate: navigate,
+ });
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ return { ...result!, navigate };
+};
+
+test("defers navigation and search reset until consent succeeds", () => {
+ const controller = entry();
+ const reset = vi.fn();
+ expect(controller.showPeople(reset)).toBe(false);
+ expect(consent.show).toHaveBeenCalledOnce();
+ expect(reset).not.toHaveBeenCalled();
+ expect(controller.navigate).not.toHaveBeenCalled();
+ consent.enabled = true;
+ controller.dialogProps.onEnabled();
+ expect(reset).toHaveBeenCalledOnce();
+ expect(controller.navigate).toHaveBeenCalledOnce();
+});
+
+test("cancelling consent discards the pending search reset", () => {
+ const controller = entry();
+ const reset = vi.fn();
+ controller.showPeople(reset);
+ controller.dialogProps.onClose();
+ expect(consent.close).toHaveBeenCalledOnce();
+ expect(controller.navigate).not.toHaveBeenCalled();
+ consent.enabled = true;
+ expect(controller.showPeople()).toBe(true);
+ expect(reset).not.toHaveBeenCalled();
+ expect(controller.navigate).toHaveBeenCalledOnce();
+});
+
+test("enabled People navigation preserves reset-before-navigation order", () => {
+ consent.enabled = true;
+ const controller = entry();
+ const reset = vi.fn();
+ expect(controller.showPeople(reset)).toBe(true);
+ expect(consent.show).not.toHaveBeenCalled();
+ expect(reset.mock.invocationCallOrder[0]).toBeLessThan(
+ controller.navigate.mock.invocationCallOrder[0]!,
+ );
+});
diff --git a/web/apps/photos/tests/quick-links.test.ts b/web/apps/photos/tests/quick-links.test.ts
index 5760358109..a3b5237852 100644
--- a/web/apps/photos/tests/quick-links.test.ts
+++ b/web/apps/photos/tests/quick-links.test.ts
@@ -2,10 +2,18 @@ import type { LocalUser } from "ente-accounts/services/user";
import { CollectionSubType, type Collection } from "ente-media/collection";
import { ItemVisibility } from "ente-media/file-metadata";
import { describe, expect, test } from "vitest";
+import {
+ initialNavigationState,
+ navigationReducer,
+ type GalleryNavigationState,
+ type NavigationAction,
+} from "../src/components/gallery/navigation/navigation-state";
+import type { GalleryState } from "../src/components/gallery/reducer";
import {
galleryReducer,
initialGalleryState,
} from "../src/components/gallery/reducer";
+import { resolveLinksDestination } from "../src/components/gallery/sections/links/link-selection";
import { visibleQuickLinks } from "../src/utils/quick-links";
const link = (id: number, overrides: Partial<Collection> = {}): Collection => ({
@@ -35,7 +43,7 @@ const link = (id: number, overrides: Partial<Collection> = {}): Collection => ({
],
...overrides,
});
-const mounted = (collections = [link(1), link(2)]) =>
+const library = (collections = [link(1), link(2)]) =>
galleryReducer(initialGalleryState, {
type: "mount",
user: { id: 1 } as LocalUser,
@@ -45,6 +53,36 @@ const mounted = (collections = [link(1), link(2)]) =>
trashItems: [],
});
+const mounted = (collections = [link(1), link(2)]) => ({
+ library: library(collections),
+ navigation: initialNavigationState,
+});
+const update = (
+ state: ReturnType<typeof mounted>,
+ action:
+ | Exclude<NavigationAction, { type: "showCollectionSummary" }>
+ | { type: "setCollections"; collections: Collection[] },
+) =>
+ action.type === "setCollections"
+ ? { ...state, library: galleryReducer(state.library, action) }
+ : { ...state, navigation: navigationReducer(state.navigation, action) };
+const view = ({
+ library,
+ navigation,
+}: {
+ library: GalleryState;
+ navigation: GalleryNavigationState;
+}) =>
+ navigation.destination.section === "links"
+ ? {
+ type: "links",
+ selectedLinkID: resolveLinksDestination(
+ library,
+ navigation.destination,
+ ).collectionID,
+ }
+ : { type: navigation.destination.section };
+
describe("quick link membership", () => {
test("lists owned public quick links, including expired and empty links", () => {
const expired = link(2);
@@ -67,59 +105,53 @@ describe("quick link membership", () => {
describe("Links navigation", () => {
test("opens the overview and clears stale photo search state", () => {
- const state = galleryReducer(
+ const state = update(
{
...mounted(),
- isInSearchMode: true,
- isRecomputingSearchResults: true,
- searchResults: [],
+ navigation: {
+ ...initialNavigationState,
+ overlay: { section: "search" },
+ },
},
{ type: "showLinks" },
);
- expect(state.view).toEqual({
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
- expect(state.selectedCollectionSummaryID).toBeUndefined();
- expect(state.filteredFiles).toEqual([]);
- expect(state.searchResults).toBeUndefined();
- expect(state.isInSearchMode).toBe(false);
- expect(state.isRecomputingSearchResults).toBe(false);
+ expect(state.navigation.destination.collectionID).toBeUndefined();
+ expect(state.navigation.overlay).toBeUndefined();
});
test("returns to the overview when the Links group is selected again", () => {
- let state = galleryReducer(mounted(), {
- type: "selectLink",
- collectionID: 1,
- });
- state = galleryReducer(state, { type: "showLinks" });
- state = galleryReducer(state, {
+ let state = update(mounted(), { type: "selectLink", collectionID: 1 });
+ state = update(state, { type: "showLinks" });
+ state = update(state, {
type: "setCollections",
collections: [link(1), link(2), link(3)],
});
- expect(state.view).toEqual({
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
});
test("preserves selection when the list refreshes", () => {
- let state = galleryReducer(mounted(), {
- type: "selectLink",
- collectionID: 1,
- });
- state = galleryReducer(state, {
+ let state = update(mounted(), { type: "selectLink", collectionID: 1 });
+ state = update(state, {
type: "setCollections",
collections: [link(1, { name: "Updated" }), link(2), link(3)],
});
- expect(state.view).toEqual({ type: "links", selectedLinkID: 1 });
- expect(state.normalCollectionSummaries.get(1)?.name).toBe("Updated");
+ expect(view(state)).toEqual({ type: "links", selectedLinkID: 1 });
+ expect(state.library.normalCollectionSummaries.get(1)?.name).toBe(
+ "Updated",
+ );
});
test.each(["removed", "hidden", "unlinked", "shared"])(
"reconciles a selected link that becomes %s",
(change) => {
- let state = galleryReducer(mounted(), {
+ let state = update(mounted(), {
type: "selectLink",
collectionID: 2,
});
@@ -128,12 +160,12 @@ describe("Links navigation", () => {
updated.magicMetadata!.data.visibility = ItemVisibility.hidden;
if (change == "unlinked") updated.publicURLs = [];
if (change == "shared") updated.sharees = [{ id: 2 }];
- state = galleryReducer(state, {
+ state = update(state, {
type: "setCollections",
collections:
change == "removed" ? [link(1)] : [link(1), updated],
});
- expect(state.view).toEqual({
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
@@ -141,20 +173,17 @@ describe("Links navigation", () => {
);
test("keeps an empty Links view after removing the final link", () => {
- let state = galleryReducer(mounted([link(1)]), { type: "showLinks" });
- state = galleryReducer(state, {
- type: "setCollections",
- collections: [],
- });
- expect(state.view).toEqual({
+ let state = update(mounted([link(1)]), { type: "showLinks" });
+ state = update(state, { type: "setCollections", collections: [] });
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
- state = galleryReducer(state, {
+ state = update(state, {
type: "setCollections",
collections: [link(3)],
});
- expect(state.view).toEqual({
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
@@ -163,22 +192,22 @@ describe("Links navigation", () => {
test("does not open a hidden link by an explicit ID", () => {
const hidden = link(3);
hidden.magicMetadata!.data.visibility = ItemVisibility.hidden;
- const state = galleryReducer(mounted([link(1), hidden]), {
+ const state = update(mounted([link(1), hidden]), {
type: "selectLink",
collectionID: 3,
});
- expect(state.view).toEqual({
+ expect(view(state)).toEqual({
type: "links",
selectedLinkID: undefined,
});
});
test("supports returning to Home and People", () => {
- let state = galleryReducer(mounted(), { type: "showLinks" });
- state = galleryReducer(state, { type: "showAll" });
- expect(state.view?.type).toBe("albums");
- state = galleryReducer(state, { type: "showLinks" });
- state = galleryReducer(state, { type: "showPeople" });
- expect(state.view?.type).toBe("people");
+ let state = update(mounted(), { type: "showLinks" });
+ state = update(state, { type: "showAll" });
+ expect(view(state).type).toBe("albums");
+ state = update(state, { type: "showLinks" });
+ state = update(state, { type: "showPeople" });
+ expect(view(state).type).toBe("people");
});
});
diff --git a/web/apps/photos/tests/search-navigation.test.tsx b/web/apps/photos/tests/search-navigation.test.tsx
new file mode 100644
index 0000000000..9577561875
--- /dev/null
+++ b/web/apps/photos/tests/search-navigation.test.tsx
@@ -0,0 +1,125 @@
+import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import type { SearchOption } from "ente-new/photos/services/search/types";
+import { renderToStaticMarkup } from "react-dom/server";
+import { expect, test, vi } from "vitest";
+import { showCollectionSummaryWithAuthentication } from "../src/components/gallery/helpers";
+import {
+ activeSectionID,
+ initialNavigationState,
+ navigationReducer,
+ type NavigationAction,
+} from "../src/components/gallery/navigation/navigation-state";
+import type { PhotosNavigationActions } from "../src/components/gallery/navigation/PhotosNavigationContext";
+import { initialGalleryState } from "../src/components/gallery/reducer";
+import { useSearchNavigation } from "../src/components/gallery/sections/search/use-search-navigation";
+
+const hidden: SearchOption = {
+ suggestion: {
+ type: "sidebarAction",
+ actionID: "shortcuts.hidden",
+ label: "Hidden",
+ path: [],
+ },
+ fileCount: 0,
+ previewFiles: [],
+};
+
+const controller = (section: "duplicates" | "large-files") => {
+ let navigation = navigationReducer(initialNavigationState, {
+ type: "showCleanup",
+ section,
+ });
+ const authentication = Promise.withResolvers<boolean>();
+ const showSettings = vi.fn();
+ const send = (action: NavigationAction) => {
+ navigation = navigationReducer(navigation, action);
+ };
+ const showCollectionSummary = vi.fn<
+ PhotosNavigationActions["showCollectionSummary"]
+ >((id, isHidden) =>
+ showCollectionSummaryWithAuthentication(
+ id,
+ !!isHidden,
+ { current: 0 },
+ () => authentication.promise,
+ (collectionSummaryID) =>
+ send({
+ type: "showCollectionSummary",
+ collectionSummaryID,
+ library: initialGalleryState,
+ }),
+ ),
+ );
+ let select: ReturnType<typeof useSearchNavigation>;
+ const Harness = () => {
+ select = useSearchNavigation({
+ library: initialGalleryState,
+ navigation,
+ send,
+ showCollectionSummary,
+ showSettings,
+ });
+ return null;
+ };
+ renderToStaticMarkup(<Harness />);
+ return {
+ select: select!,
+ state: () => navigation,
+ showSettings,
+ authenticate: async (success: boolean) => {
+ authentication.resolve(success);
+ await showCollectionSummary.mock.results[0]!.value;
+ },
+ };
+};
+
+test.each(["duplicates", "large-files"] as const)(
+ "%s stays open while Hidden authentication is pending or cancelled",
+ async (section) => {
+ const navigation = controller(section);
+ const origin = navigation.state();
+ navigation.select(hidden);
+ expect(navigation.state()).toEqual(origin);
+ await navigation.authenticate(false);
+ expect(navigation.state()).toEqual(origin);
+ },
+);
+
+test.each(["duplicates", "large-files"] as const)(
+ "%s exits when Hidden authentication succeeds",
+ async (section) => {
+ const navigation = controller(section);
+ navigation.select(hidden);
+ await navigation.authenticate(true);
+ expect(activeSectionID(navigation.state())).toBe("albums");
+ expect(navigation.state().destination.collectionID).toBe(
+ PseudoCollectionID.hiddenItems,
+ );
+ },
+);
+
+test("a settings search shortcut still dismisses cleanup", () => {
+ const navigation = controller("duplicates");
+ navigation.select({
+ ...hidden,
+ suggestion: {
+ type: "sidebarAction",
+ actionID: "utility.preferences",
+ label: "Preferences",
+ path: [],
+ },
+ });
+ expect(navigation.showSettings).toHaveBeenCalledExactlyOnceWith(
+ "utility.preferences",
+ );
+ expect(navigation.state().overlay).toBeUndefined();
+});
+
+test("a file search still replaces cleanup with results", () => {
+ const navigation = controller("large-files");
+ navigation.select({
+ ...hidden,
+ suggestion: { type: "fileName", label: "photo", fileIDs: [1] },
+ });
+ expect(activeSectionID(navigation.state())).toBe("search");
+});
diff --git a/web/apps/photos/tests/search-results-queue.test.ts b/web/apps/photos/tests/search-results-queue.test.ts
new file mode 100644
index 0000000000..0ca8e04b40
--- /dev/null
+++ b/web/apps/photos/tests/search-results-queue.test.ts
@@ -0,0 +1,72 @@
+import type { EnteFile } from "ente-media/file";
+import type { SearchSuggestion } from "ente-new/photos/services/search/types";
+import { expect, test, vi } from "vitest";
+import { createSearchResultsQueue } from "../src/components/gallery/sections/search/search-results-queue";
+
+const suggestion = (label: string): SearchSuggestion => ({
+ type: "fileName",
+ label,
+ fileIDs: [],
+});
+const deferred = () => {
+ let resolve: (files: EnteFile[]) => void;
+ let reject: (error: unknown) => void;
+ const promise = new Promise<EnteFile[]>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve: resolve!, reject: reject! };
+};
+
+test("serializes searches and coalesces pending requests to the latest suggestion", async () => {
+ const first = deferred();
+ const latest: EnteFile[] = [];
+ const search = vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValueOnce(latest);
+ const result = vi.fn();
+ const queue = createSearchResultsQueue(search, result, vi.fn());
+ const a = suggestion("a"),
+ b = suggestion("b"),
+ c = suggestion("c");
+ queue.enqueue(a);
+ queue.enqueue(b);
+ queue.enqueue(c);
+ expect(search).toHaveBeenCalledExactlyOnceWith(a);
+ first.resolve([]);
+ await vi.waitFor(() => expect(search).toHaveBeenCalledTimes(2));
+ expect(search).toHaveBeenLastCalledWith(c);
+ expect(result).toHaveBeenCalledExactlyOnceWith(latest);
+});
+
+test.each(["clear", "unmount"])("ignores results after %s", async (action) => {
+ const pending = deferred();
+ const result = vi.fn();
+ const queue = createSearchResultsQueue(
+ () => pending.promise,
+ result,
+ vi.fn(),
+ );
+ queue.enqueue(suggestion("a"));
+ if (action == "clear") queue.enqueue(undefined);
+ else queue.dispose();
+ pending.resolve([]);
+ await Promise.resolve();
+ expect(result).not.toHaveBeenCalled();
+});
+
+test("a failed request does not block a later search", async () => {
+ const error = new Error("search failed");
+ const search = vi
+ .fn()
+ .mockRejectedValueOnce(error)
+ .mockResolvedValueOnce([]);
+ const result = vi.fn(),
+ failure = vi.fn();
+ const queue = createSearchResultsQueue(search, result, failure);
+ queue.enqueue(suggestion("a"));
+ await vi.waitFor(() => expect(failure).toHaveBeenCalledWith(error));
+ queue.enqueue(suggestion("b"));
+ await vi.waitFor(() => expect(result).toHaveBeenCalledOnce());
+});
diff --git a/web/apps/photos/tests/sidebar-album-search.test.tsx b/web/apps/photos/tests/sidebar-album-search.test.tsx
index e76a941b20..cb0266426a 100644
--- a/web/apps/photos/tests/sidebar-album-search.test.tsx
+++ b/web/apps/photos/tests/sidebar-album-search.test.tsx
@@ -4,15 +4,16 @@ import type { CollectionSummary } from "ente-new/photos/services/collection-summ
import type { ComponentProps } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, test, vi } from "vitest";
-import {
- GalleryBarImpl,
- type GalleryBarImplProps,
-} from "../src/components/gallery/BarImpl";
import {
PhotosNavigationContext,
type PhotosNavigationActions,
-} from "../src/components/gallery/PhotosNavigationContext";
-import { useAlbumNavigationData } from "../src/components/gallery/use-album-navigation-data";
+} from "../src/components/gallery/navigation/PhotosNavigationContext";
+import {
+ AlbumsNavigation,
+ type AlbumsNavigationProps,
+} from "../src/components/gallery/sections/albums/AlbumsNavigation";
+import { useAlbumNavigationData } from "../src/components/gallery/sections/albums/use-album-navigation-data";
+import { LinksNavigation } from "../src/components/gallery/sections/links/LinksNavigation";
const viewport = vi.hoisted(() => ({ scrollToEnd: false }));
@@ -100,13 +101,13 @@ const albums = [owned, shared, link];
const renderSearch = (
query: string,
- albumFilter: GalleryBarImplProps["albumFilter"] = "ente",
- mode: GalleryBarImplProps["mode"] = "albums",
+ albumFilter: AlbumsNavigationProps["albumFilter"] = "ente",
+ mode: AlbumsNavigationProps["mode"] | "links" = "albums",
summaries = mode == "links" ? [link] : albums,
scrollToEnd = false,
) => {
- const props: GalleryBarImplProps = {
- mode,
+ const props: Omit<AlbumsNavigationProps, "mode"> = {
+ albumExpansion: { value: albumFilter, onChange: vi.fn() },
albumFilter,
albumSearchQuery: query,
collectionSummaries: [],
@@ -114,17 +115,14 @@ const renderSearch = (
uncategorizedCollectionSummaryID: 99,
activeCollectionID: undefined,
collectionsSortBy: "updation-time-desc",
- peopleSortBy: "name-asc",
- people: [],
- activePerson: undefined,
collapsed: false,
mobileDrawerProps: { open: false, onClose: vi.fn() },
onAlbumSearchQueryChange: vi.fn(),
onCreateAlbum: vi.fn(),
onChangeCollectionsSortBy: vi.fn(),
- onChangePeopleSortBy: vi.fn(),
};
const navigation: PhotosNavigationActions = {
+ openSection: vi.fn(() => true),
goHome: vi.fn(),
changeMode: vi.fn(() => true),
showLibraryMap: vi.fn(),
@@ -146,16 +144,34 @@ const renderSearch = (
const Sidebar = () => {
const data = useAlbumNavigationData({
...props,
+ mode: mode == "links" ? undefined : mode,
collectionSummaries: new Map(summaries.map((cs) => [cs.id, cs])),
});
return (
<ThemeProvider theme={photosTheme}>
<PhotosNavigationContext.Provider value={navigation}>
- <GalleryBarImpl
- {...props}
- {...data}
- collectionSummaries={data.sidebarCollectionSummaries}
- />
+ {mode == "links" ? (
+ <LinksNavigation
+ {...props}
+ collectionSummaries={summaries.filter((cs) =>
+ cs.name
+ .toLowerCase()
+ .includes(query.trim().toLowerCase()),
+ )}
+ selectedLinkID={undefined}
+ searchQuery={query}
+ onSearchQueryChange={vi.fn()}
+ />
+ ) : (
+ <AlbumsNavigation
+ mode={mode}
+ {...props}
+ {...data}
+ collectionSummaries={
+ data.sidebarCollectionSummaries
+ }
+ />
+ )}
</PhotosNavigationContext.Provider>
</ThemeProvider>
);
diff --git a/web/checks/lint-exceptions/suppressions.json b/web/checks/lint-exceptions/suppressions.json
index c78b9ec55a..c90164ed68 100644
--- a/web/checks/lint-exceptions/suppressions.json
+++ b/web/checks/lint-exceptions/suppressions.json
@@ -14,7 +14,7 @@
"web/apps/photos/src/components/collections/CollectionShare.tsx": [
"@typescript-eslint/no-unnecessary-condition"
],
- "web/apps/photos/src/components/collections/GalleryBarAndListHeader.tsx": [
+ "web/apps/photos/src/components/collections/AlbumContentHeader.tsx": [
"react-hooks/exhaustive-deps"
],
"web/apps/photos/src/components/PlanSelector.tsx": [
@@ -32,7 +32,6 @@
"web/apps/photos/src/components/sidebar/WatchFolder.tsx": [
"react-hooks/exhaustive-deps"
],
- "web/apps/photos/src/pages/gallery.tsx": ["react-hooks/exhaustive-deps"],
"web/apps/photos/src/services/export.ts": [
"@typescript-eslint/no-non-null-asserted-optional-chain",
"@typescript-eslint/no-unnecessary-condition"
diff --git a/web/packages/gallery/components/viewer/FileViewer.tsx b/web/packages/gallery/components/viewer/FileViewer.tsx
index ab6dcdcfbc..96340b4cd4 100644
--- a/web/packages/gallery/components/viewer/FileViewer.tsx
+++ b/web/packages/gallery/components/viewer/FileViewer.tsx
@@ -120,7 +120,7 @@ interface FileViewerAnnotatedFile {
itemData: ItemData;
}
-export type FileViewerInitialSidebar = "likes" | "comments";
+type FileViewerInitialSidebar = "likes" | "comments";
export type FileViewerProps = ModalVisibilityProps & {
user?: LocalUser;