Skip to content

armgit / ente

Public Imported from GitHub
0

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

[web] Add bulk delete action to empty albums header

AswinAsok5037ed736c85
diff --git a/web/apps/photos/src/components/Collections/AllAlbums.tsx b/web/apps/photos/src/components/Collections/AllAlbums.tsx
index bfa4968619..cbefc37d4b 100644
--- a/web/apps/photos/src/components/Collections/AllAlbums.tsx
+++ b/web/apps/photos/src/components/Collections/AllAlbums.tsx
@@ -19,6 +19,7 @@ import {
collectionDialogSurfaceStrokeDark as surfaceStrokeDark,
collectionDialogTitleSx as titleSx,
} from "@/components/CollectionDialog/styles";
+import { useDeleteEmptyAlbums } from "@/components/Collections/useDeleteEmptyAlbums";
import { CollectionsSortOptions } from "@/components/CollectionsSortOptions";
import type { RemotePullOpts } from "@/components/gallery";
import {
@@ -50,29 +51,19 @@ import {
type SxProps,
type Theme,
} from "@mui/material";
-import { ensureLocalUser } from "ente-accounts/services/user";
import { FilledIconButton } from "ente-base/components/mui";
import { SingleInputDialog } from "ente-base/components/SingleInputDialog";
import { useModalVisibility } from "ente-base/components/utils/modal";
-import { useBaseContext } from "ente-base/context";
import { SlideUpTransition } from "ente-new/photos/components/mui/SlideUpTransition";
import { ItemCard } from "ente-new/photos/components/Tiles";
import {
createAlbum,
createHiddenAlbum,
- deleteCollection,
- isArchivedCollection,
- isDefaultHiddenCollection,
} from "ente-new/photos/services/collection";
-import {
- isBulkDeletableEmptyAlbum,
- type CollectionsSortBy,
- type CollectionSummary,
+import type {
+ CollectionsSortBy,
+ CollectionSummary,
} from "ente-new/photos/services/collection-summary";
-import {
- savedCollectionFiles,
- savedCollections,
-} from "ente-new/photos/services/photos-fdb";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
import memoize from "memoize-one";
@@ -113,7 +104,6 @@ export const AllAlbums: React.FC<AllAlbums> = ({
const [searchTerm, setSearchTerm] = useState("");
const [albumFilter, setAlbumFilter] = useState<AlbumFilter>("ente");
const showAlbumFilters = !isInHiddenSection && !isInArchiveSection;
- const { showMiniDialog } = useBaseContext();
const { showNotification } = usePhotosAppContext();
const { show: showAlbumNameInput, props: albumNameInputVisibilityProps } =
useModalVisibility();
@@ -157,11 +147,8 @@ export const AllAlbums: React.FC<AllAlbums> = ({
})();
};
- const emptyAlbumCandidates = useMemo(
- () => collectionSummaries.filter(isBulkDeletableEmptyAlbum),
- [collectionSummaries],
- );
- const hasEnoughEmptyAlbums = emptyAlbumCandidates.length >= 3;
+ const { handleDeleteEmptyAlbums, hasEnoughEmptyAlbums } =
+ useDeleteEmptyAlbums(collectionSummaries, onRemotePull);
const showDeleteEmptyAlbums =
showAlbumFilters &&
@@ -185,91 +172,6 @@ export const AllAlbums: React.FC<AllAlbums> = ({
}
}, [albumFilter, visibleAlbumFilters]);
- const deleteEmptyAlbums = async (candidateIDs: number[]) => {
- let failedCount = 0;
- let confirmedCandidateIDs: number[];
-
- try {
- await onRemotePull({ strict: true });
-
- const [collections, collectionFiles] = await Promise.all([
- savedCollections(),
- savedCollectionFiles(),
- ]);
- const candidateIDSet = new Set(candidateIDs);
- const nonEmptyCollectionIDs = new Set(
- collectionFiles.map((file) => file.collectionID),
- );
- const userID = ensureLocalUser().id;
- confirmedCandidateIDs = collections
- .filter(
- (collection) =>
- candidateIDSet.has(collection.id) &&
- !nonEmptyCollectionIDs.has(collection.id) &&
- (collection.type == "album" ||
- collection.type == "folder") &&
- collection.owner.id == userID &&
- !collection.sharees.length &&
- !collection.publicURLs.length &&
- !isArchivedCollection(collection) &&
- !isDefaultHiddenCollection(collection),
- )
- .map((collection) => collection.id);
- } catch {
- showNotification({
- color: "critical",
- title: t("delete_empty_albums_failed", {
- count: candidateIDs.length,
- }),
- });
- return;
- }
-
- if (!confirmedCandidateIDs.length) return;
-
- for (const id of confirmedCandidateIDs) {
- try {
- await deleteCollection(id, { keepFiles: true });
- } catch {
- failedCount++;
- }
- }
-
- let refreshFailed = false;
- try {
- await onRemotePull({ strict: true });
- } catch {
- refreshFailed = true;
- }
-
- if (failedCount > 0) {
- showNotification({
- color: "critical",
- title: t("delete_empty_albums_failed", { count: failedCount }),
- });
- } else if (refreshFailed) {
- showNotification({
- color: "critical",
- title: t("delete_empty_albums_refresh_failed"),
- });
- }
- };
-
- const handleDeleteEmptyAlbums = () => {
- const candidateIDs = emptyAlbumCandidates.map((cs) => cs.id);
- showMiniDialog({
- title: t("delete_empty_albums_title"),
- message: t("delete_empty_albums_message", {
- count: candidateIDs.length,
- }),
- continue: {
- text: t("delete"),
- color: "critical",
- action: () => deleteEmptyAlbums(candidateIDs),
- },
- });
- };
-
const filteredCollectionSummaries = useMemo(() => {
const albumFilteredCollectionSummaries = !showAlbumFilters
? collectionSummaries
diff --git a/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts b/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts
new file mode 100644
index 0000000000..631994ed7d
--- /dev/null
+++ b/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts
@@ -0,0 +1,120 @@
+import type { RemotePullOpts } from "@/components/gallery";
+import { ensureLocalUser } from "ente-accounts/services/user";
+import { useBaseContext } from "ente-base/context";
+import {
+ deleteCollection,
+ isArchivedCollection,
+ isDefaultHiddenCollection,
+} from "ente-new/photos/services/collection";
+import {
+ isBulkDeletableEmptyAlbum,
+ type CollectionSummary,
+} from "ente-new/photos/services/collection-summary";
+import {
+ savedCollectionFiles,
+ savedCollections,
+} from "ente-new/photos/services/photos-fdb";
+import { usePhotosAppContext } from "ente-new/photos/types/context";
+import { t } from "i18next";
+
+/** Shared confirmation and sync-validated deletion for empty album listings. */
+export const useDeleteEmptyAlbums = (
+ collectionSummaries: CollectionSummary[],
+ onRemotePull: (opts?: RemotePullOpts) => Promise<void>,
+) => {
+ const { showMiniDialog } = useBaseContext();
+ const { showNotification } = usePhotosAppContext();
+ const emptyAlbumCandidates = collectionSummaries.filter(
+ isBulkDeletableEmptyAlbum,
+ );
+
+ const deleteEmptyAlbums = async (candidateIDs: number[]) => {
+ let failedCount = 0;
+ let confirmedCandidateIDs: number[];
+
+ try {
+ await onRemotePull({ strict: true });
+
+ const [collections, collectionFiles] = await Promise.all([
+ savedCollections(),
+ savedCollectionFiles(),
+ ]);
+ const candidateIDSet = new Set(candidateIDs);
+ const nonEmptyCollectionIDs = new Set(
+ collectionFiles.map((file) => file.collectionID),
+ );
+ const userID = ensureLocalUser().id;
+ confirmedCandidateIDs = collections
+ .filter(
+ (collection) =>
+ candidateIDSet.has(collection.id) &&
+ !nonEmptyCollectionIDs.has(collection.id) &&
+ (collection.type == "album" ||
+ collection.type == "folder") &&
+ collection.owner.id == userID &&
+ !collection.sharees.length &&
+ !collection.publicURLs.length &&
+ !isArchivedCollection(collection) &&
+ !isDefaultHiddenCollection(collection),
+ )
+ .map((collection) => collection.id);
+ } catch {
+ showNotification({
+ color: "critical",
+ title: t("delete_empty_albums_failed", {
+ count: candidateIDs.length,
+ }),
+ });
+ return;
+ }
+
+ if (!confirmedCandidateIDs.length) return;
+
+ for (const id of confirmedCandidateIDs) {
+ try {
+ await deleteCollection(id, { keepFiles: true });
+ } catch {
+ failedCount++;
+ }
+ }
+
+ let refreshFailed = false;
+ try {
+ await onRemotePull({ strict: true });
+ } catch {
+ refreshFailed = true;
+ }
+
+ if (failedCount > 0) {
+ showNotification({
+ color: "critical",
+ title: t("delete_empty_albums_failed", { count: failedCount }),
+ });
+ } else if (refreshFailed) {
+ showNotification({
+ color: "critical",
+ title: t("delete_empty_albums_refresh_failed"),
+ });
+ }
+ };
+
+ const handleDeleteEmptyAlbums = () => {
+ const candidateIDs = emptyAlbumCandidates.map((cs) => cs.id);
+ showMiniDialog({
+ title: t("delete_empty_albums_title"),
+ message: t("delete_empty_albums_message", {
+ count: candidateIDs.length,
+ }),
+ continue: {
+ text: t("delete"),
+ color: "critical",
+ action: () => deleteEmptyAlbums(candidateIDs),
+ },
+ });
+ };
+
+ return {
+ handleDeleteEmptyAlbums,
+ hasEnoughEmptyAlbums: emptyAlbumCandidates.length >= 3,
+ };
+};
diff --git a/web/apps/photos/src/components/gallery/AlbumsOverview.tsx b/web/apps/photos/src/components/gallery/AlbumsOverview.tsx
index 9e57ffbd69..3e05a71e9c 100644
--- a/web/apps/photos/src/components/gallery/AlbumsOverview.tsx
+++ b/web/apps/photos/src/components/gallery/AlbumsOverview.tsx
@@ -1,9 +1,15 @@
+import { useDeleteEmptyAlbums } from "@/components/Collections/useDeleteEmptyAlbums";
+import type { RemotePullOpts } from "@/components/gallery";
import type { AlbumFilter } from "@/utils/album-filters";
+import { Delete02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import AddIcon from "@mui/icons-material/Add";
import PushPinIcon from "@mui/icons-material/PushPin";
import {
Box,
+ IconButton,
Stack,
+ Tooltip,
Typography,
styled,
useMediaQuery,
@@ -28,6 +34,7 @@ interface AlbumsOverviewProps {
sortBy: CollectionsSortBy;
onSelectAlbum: (id: number) => void;
onCreateAlbum: () => void;
+ onRemotePull: (opts?: RemotePullOpts) => Promise<void>;
}
export const AlbumsOverview = ({
@@ -38,6 +45,7 @@ export const AlbumsOverview = ({
sortBy,
onSelectAlbum,
onCreateAlbum,
+ onRemotePull,
}: AlbumsOverviewProps) => {
const compact = useMediaQuery(useTheme().breakpoints.down("md"));
const listRef = useRef<FixedSizeList>(null);
@@ -55,6 +63,12 @@ export const AlbumsOverview = ({
return () => observer.disconnect();
}, [listElement]);
const normalizedSearchQuery = searchQuery.trim().toLowerCase();
+ const { handleDeleteEmptyAlbums, hasEnoughEmptyAlbums } =
+ useDeleteEmptyAlbums(albums, onRemotePull);
+ const showDeleteEmptyAlbums =
+ filter == "empty-albums" &&
+ hasEnoughEmptyAlbums &&
+ !normalizedSearchQuery;
const showCreate = filter == "ente" && !normalizedSearchQuery;
const tileWidth = compact ? 104 : 140;
const columnGap = compact ? 12 : 22;
@@ -86,30 +100,50 @@ export const AlbumsOverview = ({
sx={{
flexShrink: 0,
minHeight: 54,
- justifyContent: "center",
- gap: "2px",
+ flexDirection: "row",
+ alignItems: "center",
+ justifyContent: "space-between",
+ flexWrap: "wrap",
+ gap: 2,
}}
>
- <Typography
- component="h1"
- sx={{
- fontFamily: '"Outfit Variable", Outfit, sans-serif',
- fontSize: { xs: 20, md: 24 },
- lineHeight: { xs: "26px", md: "32px" },
- fontWeight: 600,
- }}
- >
- {displayTitle}
- </Typography>
- <Typography
- sx={{
- fontSize: { xs: 12, md: 14 },
- lineHeight: "20px",
- color: "text.muted",
- }}
- >
- {t("album_overview_count", { count: albums.length })}
- </Typography>
+ <Stack sx={{ minWidth: 0, gap: "2px" }}>
+ <Typography
+ component="h1"
+ sx={{
+ fontFamily: '"Outfit Variable", Outfit, sans-serif',
+ fontSize: { xs: 20, md: 24 },
+ lineHeight: { xs: "26px", md: "32px" },
+ fontWeight: 600,
+ }}
+ >
+ {displayTitle}
+ </Typography>
+ <Typography
+ sx={{
+ fontSize: { xs: 12, md: 14 },
+ lineHeight: "20px",
+ color: "text.muted",
+ }}
+ >
+ {t("album_overview_count", { count: albums.length })}
+ </Typography>
+ </Stack>
+ {showDeleteEmptyAlbums && (
+ <Tooltip title={t("delete_empty_albums")}>
+ <IconButton
+ aria-label={t("delete_empty_albums")}
+ onClick={handleDeleteEmptyAlbums}
+ sx={{ flexShrink: 0, marginInlineStart: "auto" }}
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ size={22}
+ strokeWidth={1.5}
+ />
+ </IconButton>
+ </Tooltip>
+ )}
</Stack>
{!albums.length && !showCreate ? (
<Typography
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 5f5ec23be3..f41b185bc9 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -2206,6 +2206,7 @@ const Page: React.FC = () => {
/>
) : !isInSearchMode && !isFirstLoad && isAlbumOverview ? (
<AlbumsOverview
+ onRemotePull={remotePull}
albums={overviewAlbums}
title={(
albumFilters.find(
diff --git a/web/apps/photos/tests/delete-empty-albums.test.ts b/web/apps/photos/tests/delete-empty-albums.test.ts
new file mode 100644
index 0000000000..6ae20d3b90
--- /dev/null
+++ b/web/apps/photos/tests/delete-empty-albums.test.ts
@@ -0,0 +1,134 @@
+import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { useDeleteEmptyAlbums } from "../src/components/Collections/useDeleteEmptyAlbums";
+
+const mocks = vi.hoisted(() => ({
+ dialog: vi.fn<
+ (dialog: {
+ message: unknown;
+ continue: { action: () => Promise<void> };
+ }) => void
+ >(),
+ notify: vi.fn<
+ (notification: { title: { key: string; opts?: unknown } }) => void
+ >(),
+ pull: vi.fn(),
+ collections: vi.fn(),
+ files: vi.fn(),
+ remove: vi.fn(),
+}));
+vi.mock("ente-base/context", () => ({
+ useBaseContext: () => ({ showMiniDialog: mocks.dialog }),
+}));
+vi.mock("ente-new/photos/types/context", () => ({
+ usePhotosAppContext: () => ({ showNotification: mocks.notify }),
+}));
+vi.mock("ente-accounts/services/user", () => ({
+ ensureLocalUser: () => ({ id: 1 }),
+}));
+vi.mock("ente-new/photos/services/collection", () => ({
+ deleteCollection: mocks.remove,
+ isArchivedCollection: (c: { archived?: boolean }) => !!c.archived,
+ isDefaultHiddenCollection: (c: { hidden?: boolean }) => !!c.hidden,
+}));
+vi.mock("ente-new/photos/services/photos-fdb", () => ({
+ savedCollections: mocks.collections,
+ savedCollectionFiles: mocks.files,
+}));
+vi.mock("i18next", () => ({
+ t: (key: string, opts?: unknown) => ({ key, opts }),
+}));
+
+const summary = (id: number): CollectionSummary => ({
+ id,
+ name: `${id}`,
+ type: "album",
+ fileCount: 0,
+ attributes: new Set(),
+ latestFile: undefined,
+ coverFile: undefined,
+ updationTime: undefined,
+ sortPriority: 0,
+});
+const collection = (id: number) => ({
+ id,
+ type: "album",
+ owner: { id: 1 },
+ sharees: [],
+ publicURLs: [],
+});
+const start = (ids = [1, 2, 3]) => {
+ const result = useDeleteEmptyAlbums(ids.map(summary), mocks.pull);
+ result.handleDeleteEmptyAlbums();
+ return mocks.dialog.mock.calls[0]![0];
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.pull.mockResolvedValue(undefined);
+ mocks.collections.mockResolvedValue([1, 2, 3].map(collection));
+ mocks.files.mockResolvedValue([]);
+ mocks.remove.mockResolvedValue(undefined);
+});
+describe("shared empty album deletion", () => {
+ test("confirms the candidate count and does nothing until confirmed", () => {
+ const dialog = start();
+ expect(dialog.message).toEqual({
+ key: "delete_empty_albums_message",
+ opts: { count: 3 },
+ });
+ expect(mocks.pull).not.toHaveBeenCalled();
+ expect(mocks.remove).not.toHaveBeenCalled();
+ expect(
+ useDeleteEmptyAlbums([summary(1), summary(2)], mocks.pull)
+ .hasEnoughEmptyAlbums,
+ ).toBe(false);
+ });
+ test("revalidates candidates and does not include new albums", async () => {
+ mocks.collections.mockResolvedValue([
+ collection(1),
+ collection(2),
+ { ...collection(3), publicURLs: [{}] },
+ { ...collection(4), owner: { id: 2 } },
+ { ...collection(5), archived: true },
+ { ...collection(6), hidden: true },
+ { ...collection(7), type: "favorites" },
+ { ...collection(8), sharees: [{}] },
+ collection(9),
+ ]);
+ mocks.files.mockResolvedValue([{ collectionID: 2 }]);
+ await start([1, 2, 3, 4, 5, 6, 7, 8]).continue.action();
+ expect(mocks.remove.mock.calls).toEqual([[1, { keepFiles: true }]]);
+ expect(mocks.pull.mock.calls).toEqual([
+ [{ strict: true }],
+ [{ strict: true }],
+ ]);
+ });
+ test("aborts on initial sync failure", async () => {
+ mocks.pull.mockRejectedValueOnce(new Error("sync"));
+ await start().continue.action();
+ expect(mocks.remove).not.toHaveBeenCalled();
+ expect(mocks.notify.mock.calls[0]![0].title).toEqual({
+ key: "delete_empty_albums_failed",
+ opts: { count: 3 },
+ });
+ });
+ test("continues after a deletion failure and reports the failed count", async () => {
+ mocks.remove.mockRejectedValueOnce(new Error("delete"));
+ await start().continue.action();
+ expect(mocks.remove).toHaveBeenCalledTimes(3);
+ expect(mocks.pull).toHaveBeenCalledTimes(2);
+ expect(mocks.notify.mock.calls[0]![0].title).toEqual({
+ key: "delete_empty_albums_failed",
+ opts: { count: 1 },
+ });
+ });
+ test("reports refresh failure after successful deletion", async () => {
+ mocks.pull
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error("refresh"));
+ await start().continue.action();
+ expect(mocks.notify.mock.calls[0]![0].title.key).toBe(
+ "delete_empty_albums_refresh_failed",
+ );
+ });
+});