Skip to content

armgit / ente

Public Imported from GitHub
0

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

refractor(web):move-photos-specfic-component-from-pkgs-p2

Aswin Asok4459a1575c64
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index a9772ac569..a066444fda 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -1,3 +1,4 @@
+import { downloadAndSaveCollectionFiles } from "@/services/save";
import {
CleanIcon,
Delete02Icon,
@@ -33,7 +34,6 @@ import { SingleInputDialog } from "ente-base/components/SingleInputDialog";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";
-import { downloadAndSaveCollectionFiles } from "ente-gallery/services/save";
import { uniqueFilesByID } from "ente-gallery/utils/file";
import {
CollectionOrder,
diff --git a/web/packages/new/photos/components/Export.tsx b/web/apps/photos/src/components/Export.tsx
similarity index 99%
rename from web/packages/new/photos/components/Export.tsx
rename to web/apps/photos/src/components/Export.tsx
index 0815c2238b..c7dfd3c713 100644
--- a/web/packages/new/photos/components/Export.tsx
+++ b/web/apps/photos/src/components/Export.tsx
@@ -1,4 +1,11 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
+import exportService, {
+ CustomError,
+ ExportStage,
+ selectAndPrepareExportDirectory,
+ type ExportOpts,
+ type ExportProgress,
+} from "@/services/export";
import FolderIcon from "@mui/icons-material/Folder";
import {
Box,
@@ -47,13 +54,6 @@ import {
type ListChildComponentProps,
type ListItemKeySelector,
} from "react-window";
-import exportService, {
- CustomError,
- ExportStage,
- selectAndPrepareExportDirectory,
- type ExportOpts,
- type ExportProgress,
-} from "../services/export";
type ExportProps = ModalVisibilityProps & {
/**
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index 6ff278497b..b0e676c708 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -1,4 +1,5 @@
import { CollectionMapDialog } from "@/components/Collections/CollectionMapDialog";
+import { downloadAndSaveFiles } from "@/services/save";
import { uploadManager } from "@/services/upload-manager";
import { IconButton, Tooltip, styled } from "@mui/material";
import { useColorScheme, useTheme } from "@mui/material/styles";
@@ -12,7 +13,6 @@ import {
type FileViewerInitialSidebar,
type FileViewerProps,
} from "ente-gallery/components/viewer/FileViewer";
-import { downloadAndSaveFiles } from "ente-gallery/services/save";
import type { Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { fileCreationPhotoDate, fileFileName } from "ente-media/file-metadata";
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 35123b447a..a14b5b0b09 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -7,6 +7,7 @@ import { ReferralSettings } from "@/components/sidebar/ReferralSettings";
import { SessionsSettings } from "@/components/sidebar/SessionsSettings";
import { TwoFactorSettings } from "@/components/sidebar/TwoFactorSettings";
import { downloadAppDialogAttributes } from "@/components/utils/download";
+import exportService from "@/services/export";
import {
Delete02Icon,
Download05Icon,
@@ -93,7 +94,6 @@ import {
PseudoCollectionID,
type CollectionSummaries,
} from "ente-new/photos/services/collection-summary";
-import exportService from "ente-new/photos/services/export";
import { isMLSupported } from "ente-new/photos/services/ml";
import { performSidebarAction as performSidebarRegistryAction } from "ente-new/photos/services/search/sidebar-search-registry";
import type { SidebarActionID } from "ente-new/photos/services/search/types";
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index 5756e1536a..2927dd9ea2 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -9,6 +9,7 @@ import {
useSetupAppLock,
} from "@/components/utils/use-app-lock";
import { useDesktopAppLockRoute } from "@/components/utils/use-app-lock-route";
+import { resumeExportsIfNeeded } from "@/services/export";
import { photosLogout } from "@/services/logout";
import { runMigrations } from "@/services/migration";
import "@fontsource-variable/inter";
@@ -48,7 +49,6 @@ import {
isHLSGenerationSupported,
} from "ente-gallery/services/video";
import { useAppLockSnapshot } from "ente-new/photos/components/utils/use-snapshot";
-import { resumeExportsIfNeeded } from "ente-new/photos/services/export";
import { initML, isMLSupported } from "ente-new/photos/services/ml";
import { PhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
diff --git a/web/apps/photos/src/pages/duplicates.tsx b/web/apps/photos/src/pages/duplicates.tsx
index a1361f75c7..b2b9e1b461 100644
--- a/web/apps/photos/src/pages/duplicates.tsx
+++ b/web/apps/photos/src/pages/duplicates.tsx
@@ -1 +1,665 @@
-export { default } from "ente-new/photos/pages/duplicates";
+import {
+ deduceDuplicates,
+ removeSelectedDuplicateGroups,
+ type DuplicateGroup,
+} from "@/services/dedup";
+import ArrowBackIcon from "@mui/icons-material/ArrowBack";
+import DoneIcon from "@mui/icons-material/Done";
+import RemoveCircleOutlinedIcon from "@mui/icons-material/RemoveCircleOutlined";
+import SortIcon from "@mui/icons-material/Sort";
+import {
+ Box,
+ Checkbox,
+ Divider,
+ IconButton,
+ LinearProgress,
+ Stack,
+ styled,
+ Tooltip,
+ Typography,
+} from "@mui/material";
+import { useRedirectIfNeedsCredentials } from "ente-accounts/components/utils/use-redirect";
+import { CenteredFill, SpacedRow } from "ente-base/components/containers";
+import { ActivityErrorIndicator } from "ente-base/components/ErrorIndicator";
+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import {
+ OverflowMenu,
+ OverflowMenuOption,
+} from "ente-base/components/OverflowMenu";
+import { Ellipsized2LineTypography } from "ente-base/components/Typography";
+import { useBaseContext } from "ente-base/context";
+import log from "ente-base/log";
+import { formattedByteSize } from "ente-gallery/utils/units";
+import {
+ DuplicateItemTile,
+ ItemCard,
+ TileBottomTextOverlay,
+} from "ente-new/photos/components/Tiles";
+import {
+ computeThumbnailGridLayoutParams,
+ type ThumbnailGridLayoutParams,
+} from "ente-new/photos/components/utils/thumbnail-grid-layout";
+import { t } from "i18next";
+import { useRouter } from "next/router";
+import React, {
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+ useReducer,
+} from "react";
+import Autosizer from "react-virtualized-auto-sizer";
+import {
+ areEqual,
+ VariableSizeList,
+ type ListChildComponentProps,
+} from "react-window";
+
+const Page: React.FC = () => {
+ const { onGenericError } = useBaseContext();
+
+ const [state, dispatch] = useReducer(dedupReducer, initialDedupState);
+
+ useRedirectIfNeedsCredentials("/duplicates");
+
+ useEffect(() => {
+ dispatch({ type: "analyze" });
+ void deduceDuplicates()
+ .then((duplicateGroups) =>
+ dispatch({ type: "analysisCompleted", duplicateGroups }),
+ )
+ .catch((e: unknown) => {
+ log.error("Failed to detect duplicates", e);
+ dispatch({ type: "analysisFailed" });
+ });
+ }, []);
+
+ const handleRemoveDuplicates = useCallback(() => {
+ dispatch({ type: "dedupe" });
+ void removeSelectedDuplicateGroups(
+ state.duplicateGroups,
+ (progress: number) =>
+ dispatch({ type: "setDedupeProgress", progress }),
+ )
+ .then((removedGroupIDs) =>
+ dispatch({ type: "dedupeCompleted", removedGroupIDs }),
+ )
+
+ .catch((e: unknown) => {
+ onGenericError(e);
+ dispatch({ type: "dedupeFailed" });
+ });
+ }, [state.duplicateGroups, onGenericError]);
+
+ const contents = (() => {
+ switch (state.analysisStatus) {
+ case undefined:
+ case "started":
+ return <Loading />;
+ case "failed":
+ return <LoadFailed />;
+ case "completed":
+ if (state.duplicateGroups.length == 0) {
+ return <NoDuplicatesFound />;
+ } else {
+ return (
+ <Duplicates
+ duplicateGroups={state.duplicateGroups}
+ sortOrder={state.sortOrder}
+ onToggleSelection={(index) =>
+ dispatch({ type: "toggleSelection", index })
+ }
+ prunableCount={state.prunableCount}
+ prunableSize={state.prunableSize}
+ dedupeProgress={state.dedupeProgress}
+ onRemoveDuplicates={handleRemoveDuplicates}
+ />
+ );
+ }
+ }
+ })();
+
+ return (
+ <Stack sx={{ height: "100vh" }}>
+ <Navbar
+ sortOrder={state.sortOrder}
+ onChangeSortOrder={(sortOrder) =>
+ dispatch({ type: "changeSortOrder", sortOrder })
+ }
+ onDeselectAll={() => dispatch({ type: "deselectAll" })}
+ />
+ {contents}
+ </Stack>
+ );
+};
+
+export default Page;
+
+type SortOrder = "prunableCount" | "prunableSize";
+
+interface DedupState {
+ /** Status of the analysis ("loading") process. */
+ analysisStatus: undefined | "started" | "failed" | "completed";
+ /**
+ * Groups of duplicates.
+ *
+ * These are groups of files that our algorithm has detected as exact
+ * duplicates, augmented with UI state and various cached properties to make
+ * them more amenable to be directly used by the UI component.
+ *
+ * These are sorted in order of display, reflecting the {@link sortType}
+ * user preference.
+ */
+ duplicateGroups: DuplicateGroup[];
+ /**
+ * The attribute to use for sorting {@link duplicateGroups}.
+ */
+ sortOrder: SortOrder;
+ /**
+ * The number of files that will be pruned if the user decides to dedup the
+ * current selection.
+ */
+ prunableCount: number;
+ /**
+ * The size (in bytes) that can be saved if the user decides to dedup the
+ * current selection.
+ */
+ prunableSize: number;
+ /**
+ * If a dedupe is in progress, then this will indicate its progress
+ * percentage (a number between 0 and 100).
+ */
+ dedupeProgress: number | undefined;
+}
+
+type DedupAction =
+ | { type: "analyze" }
+ | { type: "analysisFailed" }
+ | { type: "analysisCompleted"; duplicateGroups: DuplicateGroup[] }
+ | { type: "changeSortOrder"; sortOrder: SortOrder }
+ | { type: "toggleSelection"; index: number }
+ | { type: "deselectAll" }
+ | { type: "dedupe" }
+ | { type: "setDedupeProgress"; progress: number }
+ | { type: "dedupeFailed" }
+ | { type: "dedupeCompleted"; removedGroupIDs: Set<string> };
+
+const initialDedupState: DedupState = {
+ analysisStatus: undefined,
+ duplicateGroups: [],
+ sortOrder: "prunableSize",
+ prunableCount: 0,
+ prunableSize: 0,
+ dedupeProgress: undefined,
+};
+
+const dedupReducer: React.Reducer<DedupState, DedupAction> = (
+ state,
+ action,
+) => {
+ switch (action.type) {
+ case "analyze":
+ return { ...state, analysisStatus: "started" };
+ case "analysisFailed":
+ return { ...state, analysisStatus: "failed" };
+ case "analysisCompleted": {
+ const duplicateGroups = sortedCopyOfDuplicateGroups(
+ action.duplicateGroups,
+ state.sortOrder,
+ );
+ const selected = duplicateGroups.map(() => true);
+ const { prunableCount, prunableSize } =
+ deducePrunableCountAndSize(duplicateGroups);
+ return {
+ ...state,
+ analysisStatus: "completed",
+ duplicateGroups,
+ selected,
+ prunableCount,
+ prunableSize,
+ };
+ }
+
+ case "changeSortOrder": {
+ const sortOrder = action.sortOrder;
+ const duplicateGroups = sortedCopyOfDuplicateGroups(
+ state.duplicateGroups,
+ sortOrder,
+ );
+ return { ...state, sortOrder, duplicateGroups };
+ }
+
+ case "toggleSelection": {
+ const duplicateGroups = [...state.duplicateGroups];
+ const duplicateGroup = duplicateGroups[action.index]!;
+ duplicateGroup.isSelected = !duplicateGroup.isSelected;
+ const { prunableCount, prunableSize } =
+ deducePrunableCountAndSize(duplicateGroups);
+ return { ...state, duplicateGroups, prunableCount, prunableSize };
+ }
+
+ case "deselectAll": {
+ const duplicateGroups = state.duplicateGroups.map(
+ (duplicateGroup) => ({ ...duplicateGroup, isSelected: false }),
+ );
+ const { prunableCount, prunableSize } =
+ deducePrunableCountAndSize(duplicateGroups);
+ return { ...state, duplicateGroups, prunableCount, prunableSize };
+ }
+
+ case "dedupe":
+ return { ...state, dedupeProgress: 0 };
+
+ case "setDedupeProgress": {
+ return { ...state, dedupeProgress: action.progress };
+ }
+
+ case "dedupeFailed":
+ return { ...state, dedupeProgress: undefined };
+
+ case "dedupeCompleted": {
+ const duplicateGroups = state.duplicateGroups.filter(
+ ({ id }) => !action.removedGroupIDs.has(id),
+ );
+ const { prunableCount, prunableSize } =
+ deducePrunableCountAndSize(duplicateGroups);
+ return {
+ ...state,
+ duplicateGroups,
+ prunableCount,
+ prunableSize,
+ dedupeProgress: undefined,
+ };
+ }
+ }
+};
+
+/**
+ * Return a copy of the given {@link duplicateGroups}, also sorting them as per
+ * the given {@link sortOrder}.
+ *
+ * Helper method for the reducer.
+ */
+const sortedCopyOfDuplicateGroups = (
+ duplicateGroups: DuplicateGroup[],
+ sortOrder: DedupState["sortOrder"],
+) =>
+ [...duplicateGroups].sort((a, b) =>
+ sortOrder == "prunableSize"
+ ? b.prunableSize - a.prunableSize
+ : b.prunableCount - a.prunableCount,
+ );
+
+/** Helper method for the reducer. */
+const deducePrunableCountAndSize = (duplicateGroups: DuplicateGroup[]) => {
+ const prunableCount = duplicateGroups.reduce(
+ (sum, { prunableCount, isSelected }) =>
+ sum + (isSelected ? prunableCount : 0),
+ 0,
+ );
+ const prunableSize = duplicateGroups.reduce(
+ (sum, { prunableSize, isSelected }) =>
+ sum + (isSelected ? prunableSize : 0),
+ 0,
+ );
+ return { prunableCount, prunableSize };
+};
+
+interface NavbarProps {
+ /**
+ * The current sort order.
+ */
+ sortOrder: SortOrder;
+ /**
+ * Called when the user changes the sort order using the sort order menu
+ * visible via the navbar.
+ */
+ onChangeSortOrder: (sortOrder: SortOrder) => void;
+ /**
+ * Called when the user selects the deselect all option.
+ */
+ onDeselectAll: () => void;
+}
+
+const Navbar: React.FC<NavbarProps> = ({
+ sortOrder,
+ onChangeSortOrder,
+ onDeselectAll,
+}) => {
+ const router = useRouter();
+
+ return (
+ <Stack
+ direction="row"
+ sx={(theme) => ({
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "8px 4px",
+ borderBottom: `1px solid ${theme.vars.palette.divider}`,
+ })}
+ >
+ <Box sx={{ minWidth: "100px" /* 2 icons + gap */ }}>
+ <IconButton onClick={router.back}>
+ <ArrowBackIcon />
+ </IconButton>
+ </Box>
+ <Typography variant="h6">{t("remove_duplicates")}</Typography>
+ <Stack direction="row" sx={{ gap: "4px" }}>
+ <SortMenu {...{ sortOrder, onChangeSortOrder }} />
+ <OptionsMenu {...{ onDeselectAll }} />
+ </Stack>
+ </Stack>
+ );
+};
+
+type SortMenuProps = Pick<NavbarProps, "sortOrder" | "onChangeSortOrder">;
+
+const SortMenu: React.FC<SortMenuProps> = ({
+ sortOrder,
+ onChangeSortOrder,
+}) => (
+ <OverflowMenu
+ ariaID="duplicates-sort"
+ triggerButtonIcon={
+ <Tooltip title={t("sort_by")}>
+ <SortIcon />
+ </Tooltip>
+ }
+ >
+ <OverflowMenuOption
+ endIcon={sortOrder == "prunableSize" ? <DoneIcon /> : undefined}
+ onClick={() => onChangeSortOrder("prunableSize")}
+ >
+ {t("total_size")}
+ </OverflowMenuOption>
+ <OverflowMenuOption
+ endIcon={sortOrder == "prunableCount" ? <DoneIcon /> : undefined}
+ onClick={() => onChangeSortOrder("prunableCount")}
+ >
+ {t("count")}
+ </OverflowMenuOption>
+ </OverflowMenu>
+);
+
+type OptionsMenuProps = Pick<NavbarProps, "onDeselectAll">;
+
+const OptionsMenu: React.FC<OptionsMenuProps> = ({ onDeselectAll }) => (
+ <OverflowMenu ariaID="duplicates-options">
+ <OverflowMenuOption
+ startIcon={<RemoveCircleOutlinedIcon />}
+ onClick={onDeselectAll}
+ >
+ {t("deselect_all")}
+ </OverflowMenuOption>
+ </OverflowMenu>
+);
+
+const Loading: React.FC = () => (
+ <CenteredFill>
+ <ActivityIndicator />
+ </CenteredFill>
+);
+
+const LoadFailed: React.FC = () => (
+ <CenteredFill>
+ <ActivityErrorIndicator />
+ </CenteredFill>
+);
+
+const NoDuplicatesFound: React.FC = () => (
+ <CenteredFill>
+ <Typography sx={{ color: "text.muted", textAlign: "center" }}>
+ {t("no_duplicates")}
+ </Typography>
+ </CenteredFill>
+);
+
+type DuplicatesProps = Pick<
+ DuplicatesListProps,
+ "duplicateGroups" | "sortOrder" | "onToggleSelection"
+> &
+ DeduplicateButtonProps;
+
+const Duplicates: React.FC<DuplicatesProps> = ({
+ duplicateGroups,
+ sortOrder,
+ onToggleSelection,
+ ...deduplicateButtonProps
+}) => (
+ <Stack sx={{ flex: 1 }}>
+ <Box sx={{ flex: 1, overflow: "hidden", paddingBlockEnd: 1 }}>
+ <Autosizer>
+ {({ width, height }) => (
+ <DuplicatesList
+ {...{
+ width,
+ height,
+ duplicateGroups,
+ sortOrder,
+ onToggleSelection,
+ }}
+ />
+ )}
+ </Autosizer>
+ </Box>
+ <Stack sx={{ margin: 1 }}>
+ <DeduplicateButton {...deduplicateButtonProps} />
+ </Stack>
+ </Stack>
+);
+
+interface DuplicatesListProps {
+ /**
+ * The width (px) that the list should size itself to.
+ */
+ width: number;
+ /**
+ * The height (px) that the list should size itself to.
+ */
+ height: number;
+ /**
+ * Groups of duplicates. Guaranteed to be non-empty.
+ */
+ duplicateGroups: DuplicateGroup[];
+ /**
+ * The current {@link SortOrder} that is being used for sorting {@link duplicateGroups}.
+ */
+ sortOrder: SortOrder;
+ /**
+ * Called when the user toggles the selection for the duplicate group at the
+ * given {@link index}.
+ */
+ onToggleSelection: (index: number) => void;
+}
+
+type DuplicatesListItemData = Pick<
+ DuplicatesListProps,
+ "duplicateGroups" | "onToggleSelection"
+> & { layoutParams: ThumbnailGridLayoutParams };
+
+const DuplicatesList: React.FC<DuplicatesListProps> = ({
+ width,
+ height,
+ duplicateGroups,
+ sortOrder,
+ onToggleSelection,
+}) => {
+ const layoutParams = useMemo(
+ () => computeThumbnailGridLayoutParams(width),
+ [width],
+ );
+
+ const itemData = { layoutParams, duplicateGroups, onToggleSelection };
+ const itemCount = duplicateGroups.length;
+ const itemSize = (index: number) => {
+ // The height of the header is driven by the height of the Checkbox,
+ // which is 42px high, and the divider, which is 1px. The rest of the
+ // height comes from the fixed paddings, margins on the header, the
+ // divider, and on the row itself.
+ const fixedHeight = 24 + 42 + 4 + 1 + 20 + 16;
+
+ const duplicateGroup = duplicateGroups[index]!;
+ const rowCount = Math.ceil(
+ duplicateGroup.items.length / layoutParams.columns,
+ );
+ const rowHeight = layoutParams.itemHeight + layoutParams.gap;
+
+ return fixedHeight + rowCount * rowHeight;
+ };
+ const itemKey = (index: number, itemData: DuplicatesListItemData) =>
+ itemData.duplicateGroups[index]!.id;
+
+ // Derive a key based on aspects whose change should cause the list to be
+ // recreated. This is the easiest way I've found to get react-window to
+ // invalidate `itemSize` values when, say, the width changes.
+ const key = `${width}-${sortOrder}`;
+
+ return (
+ <VariableSizeList
+ key={key}
+ style={
+ {
+ "--et-padding-inline": `${layoutParams.paddingInline}px`,
+ } as React.CSSProperties
+ }
+ {...{ height, width, itemData, itemCount, itemSize, itemKey }}
+ >
+ {ListItem}
+ </VariableSizeList>
+ );
+};
+
+const ListItem: React.FC<ListChildComponentProps<DuplicatesListItemData>> =
+ memo(({ index, style, data }) => {
+ const { layoutParams, duplicateGroups, onToggleSelection } = data;
+
+ // For smaller screens, hide to divider to reduce visual noise. For
+ // larger screens, the divider is helpful in guiding the user's eyes to
+ // the checkbox which is otherwise at the right end of the header.
+ const hideDivider = layoutParams.isSmallerLayout;
+
+ const duplicateGroup = duplicateGroups[index]!;
+ const items = duplicateGroup.items;
+ const count = items.length;
+ const itemSize = formattedByteSize(duplicateGroup.itemSize);
+ const checked = duplicateGroup.isSelected;
+ const onChange = () => onToggleSelection(index);
+
+ return (
+ <Stack
+ {...{ style }}
+ sx={[
+ { paddingBlockEnd: "16px" },
+ checked ? { opacity: 1 } : { opacity: 0.8 },
+ ]}
+ >
+ <SpacedRow
+ sx={{
+ mx: 1,
+ paddingInline: "var(--et-padding-inline)",
+ paddingBlock: "24px 0px",
+ }}
+ >
+ <Typography
+ sx={{ color: checked ? "text.base" : "text.muted" }}
+ >
+ {t("duplicate_group_description", { count, itemSize })}
+ </Typography>
+ {/* The size of this Checkbox is 42px. */}
+ <Checkbox {...{ checked, onChange }} />
+ </SpacedRow>
+ <Divider
+ variant="middle"
+ sx={[
+ { marginBlock: "4px 20px" },
+ hideDivider ? { opacity: 0 } : { opacity: 0.8 },
+ ]}
+ />
+ <ItemGrid {...{ layoutParams }}>
+ {items.map((item, j) => (
+ <ItemCard
+ key={j}
+ TileComponent={DuplicateItemTile}
+ coverFile={item.file}
+ >
+ <TileBottomTextOverlay>
+ <Ellipsized2LineTypography variant="small">
+ {item.collectionName}
+ </Ellipsized2LineTypography>
+ </TileBottomTextOverlay>
+ </ItemCard>
+ ))}
+ </ItemGrid>
+ </Stack>
+ );
+ }, areEqual);
+
+type ItemGridProps = Pick<DuplicatesListItemData, "layoutParams">;
+
+const ItemGrid = styled("div", {
+ shouldForwardProp: (prop) => prop != "layoutParams",
+})<ItemGridProps>(
+ ({ layoutParams }) => `
+ display: grid;
+ padding-inline: ${layoutParams.paddingInline}px;
+ grid-template-columns: repeat(${layoutParams.columns}, ${layoutParams.itemWidth}px);
+ grid-auto-rows: ${layoutParams.itemHeight}px;
+ gap: ${layoutParams.gap}px;
+`,
+);
+
+type DeduplicateButtonProps = Pick<
+ DedupState,
+ "prunableCount" | "prunableSize" | "dedupeProgress"
+> & {
+ /**
+ * Called when the user presses the button to remove duplicates.
+ */
+ onRemoveDuplicates: () => void;
+};
+
+const DeduplicateButton: React.FC<DeduplicateButtonProps> = ({
+ prunableCount,
+ prunableSize,
+ dedupeProgress,
+ onRemoveDuplicates,
+}) => (
+ <FocusVisibleButton
+ sx={{ minWidth: "min(100%, 320px)", margin: "auto" }}
+ disabled={prunableCount == 0 || dedupeProgress !== undefined}
+ onClick={onRemoveDuplicates}
+ >
+ <Stack
+ sx={{
+ gap: 1,
+ // Prevent a layout shift by giving a minHeight that is larger
+ // than all expected states.
+ minHeight: "45px",
+ justifyContent: "center",
+ flex: 1,
+ }}
+ >
+ {dedupeProgress !== undefined ? (
+ <LinearProgress
+ sx={{ borderRadius: "4px" }}
+ variant={
+ dedupeProgress === 0 ? "indeterminate" : "determinate"
+ }
+ value={dedupeProgress}
+ />
+ ) : (
+ <>
+ <Typography>
+ {t("remove_duplicates_button_count", {
+ count: prunableCount,
+ })}
+ </Typography>
+ <Typography variant="small" sx={{ fontWeight: "regular" }}>
+ {formattedByteSize(prunableSize)}
+ </Typography>
+ </>
+ )}
+ </Stack>
+ </FocusVisibleButton>
+);
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 6cfb2f6e95..4fb2466703 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -7,6 +7,7 @@ import { AlbumAddedNotification } from "@/components/AlbumAddedNotification";
import { AuthenticateUser } from "@/components/AuthenticateUser";
import { GalleryBarAndListHeader } from "@/components/Collections/GalleryBarAndListHeader";
import { PickCoverPhotoDialog } from "@/components/Collections/PickCoverPhotoDialog";
+import { Export } from "@/components/Export";
import { FamilyManagement } from "@/components/FamilyManagement";
import type { FileListHeaderOrFooter } from "@/components/FileList";
import { FileListWithViewer } from "@/components/FileListWithViewer";
@@ -22,6 +23,7 @@ import {
} from "@/components/utils/dialog-attributes";
import { useIsOffline } from "@/components/utils/use-is-offline";
import { shouldShowWhatsNew } from "@/services/changelog";
+import exportService from "@/services/export";
import { Upload01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
@@ -74,7 +76,6 @@ import {
type CollectionSelectorAttributes,
} from "ente-new/photos/components/CollectionSelector";
import { EditLocationDialog } from "ente-new/photos/components/EditLocationDialog";
-import { Export } from "ente-new/photos/components/Export";
import {
SearchBar,
type SearchBarProps,
@@ -120,7 +121,6 @@ import {
haveOnlySystemCollections,
PseudoCollectionID,
} from "ente-new/photos/services/collection-summary";
-import exportService from "ente-new/photos/services/export";
import {
updateFilesLocation,
updateFilesVisibility,
@@ -130,6 +130,7 @@ import {
isMLEnabled,
} from "ente-new/photos/services/ml";
+import { postPullFiles, prePullFiles, pullFiles } from "@/services/pull";
import { uploadManager } from "@/services/upload-manager";
import watcher from "@/services/watch";
import {
@@ -146,11 +147,6 @@ import {
savedCollections,
savedTrashItems,
} from "ente-new/photos/services/photos-fdb";
-import {
- postPullFiles,
- prePullFiles,
- pullFiles,
-} from "ente-new/photos/services/pull";
import {
filterSearchableFiles,
updateSearchCollectionsAndFiles,
diff --git a/web/apps/photos/src/pages/large-files.tsx b/web/apps/photos/src/pages/large-files.tsx
index 541bf85a26..58b8bdeae5 100644
--- a/web/apps/photos/src/pages/large-files.tsx
+++ b/web/apps/photos/src/pages/large-files.tsx
@@ -1,3 +1,11 @@
+import {
+ deleteSelectedLargeFiles,
+ findLargeFiles,
+ largeFilesInitialState,
+ largeFilesReducer,
+ type LargeFileFilter,
+ type LargeFileItem,
+} from "@/services/large-files";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import ImageIcon from "@mui/icons-material/Image";
import VideocamIcon from "@mui/icons-material/Videocam";
@@ -27,14 +35,6 @@ import {
computeThumbnailGridLayoutParams,
type ThumbnailGridLayoutParams,
} from "ente-new/photos/components/utils/thumbnail-grid-layout";
-import {
- deleteSelectedLargeFiles,
- findLargeFiles,
- largeFilesInitialState,
- largeFilesReducer,
- type LargeFileFilter,
- type LargeFileItem,
-} from "ente-new/photos/services/large-files";
import { t } from "i18next";
import { useRouter } from "next/router";
import React, {
diff --git a/web/packages/new/photos/services/dedup.ts b/web/apps/photos/src/services/dedup.ts
similarity index 98%
rename from web/packages/new/photos/services/dedup.ts
rename to web/apps/photos/src/services/dedup.ts
index ca549e6571..4ec12e1316 100644
--- a/web/packages/new/photos/services/dedup.ts
+++ b/web/apps/photos/src/services/dedup.ts
@@ -8,8 +8,8 @@ import {
createCollectionNameByID,
moveToTrash,
savedNormalCollections,
-} from "./collection";
-import { savedCollectionFiles } from "./photos-fdb";
+} from "ente-new/photos/services/collection";
+import { savedCollectionFiles } from "ente-new/photos/services/photos-fdb";
import { pullFiles } from "./pull";
/**
diff --git a/web/packages/new/photos/services/export.ts b/web/apps/photos/src/services/export.ts
similarity index 99%
rename from web/packages/new/photos/services/export.ts
rename to web/apps/photos/src/services/export.ts
index 5025f0b9d4..8a02887802 100644
--- a/web/packages/new/photos/services/export.ts
+++ b/web/apps/photos/src/services/export.ts
@@ -5,6 +5,7 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
/* eslint-disable @typescript-eslint/no-floating-promises */
+import { safeDirectoryName, safeFileName } from "@/utils/native-fs";
import {
ensureElectron,
suppressMainWindowBlurForTrustedPrompt,
@@ -31,14 +32,13 @@ import {
createCollectionNameByID,
} from "ente-new/photos/services/collection";
import {
- safeDirectoryName,
- safeFileName,
-} from "ente-new/photos/utils/native-fs";
+ savedCollectionFiles,
+ savedCollections,
+} from "ente-new/photos/services/photos-fdb";
import { PromiseQueue } from "ente-utils/promise";
import { nullToUndefined } from "ente-utils/transform";
import i18n from "i18next";
import { z } from "zod";
-import { savedCollectionFiles, savedCollections } from "./photos-fdb";
// TODO: Audit the uses of these constants
export const CustomError = {
diff --git a/web/packages/new/photos/services/large-files.ts b/web/apps/photos/src/services/large-files.ts
similarity index 98%
rename from web/packages/new/photos/services/large-files.ts
rename to web/apps/photos/src/services/large-files.ts
index ce95c6e55a..0d796ffb21 100644
--- a/web/packages/new/photos/services/large-files.ts
+++ b/web/apps/photos/src/services/large-files.ts
@@ -2,8 +2,11 @@ import { ensureLocalUser } from "ente-accounts/services/user";
import { newID } from "ente-base/id";
import type { EnteFile } from "ente-media/file";
import { FileType } from "ente-media/file-type";
-import { moveToTrash, savedNormalCollections } from "./collection";
-import { savedCollectionFiles } from "./photos-fdb";
+import {
+ moveToTrash,
+ savedNormalCollections,
+} from "ente-new/photos/services/collection";
+import { savedCollectionFiles } from "ente-new/photos/services/photos-fdb";
import { pullFiles } from "./pull";
/**
diff --git a/web/apps/photos/src/services/logout.ts b/web/apps/photos/src/services/logout.ts
index b45d5eb9e3..79c002b26d 100644
--- a/web/apps/photos/src/services/logout.ts
+++ b/web/apps/photos/src/services/logout.ts
@@ -1,3 +1,4 @@
+import exportService from "@/services/export";
import {
accountLogout,
logoutClearStateAgain,
@@ -10,7 +11,6 @@ import { clearFilesDB } from "ente-gallery/services/files-db";
import { resetUploadState } from "ente-gallery/services/upload";
import { resetVideoState } from "ente-gallery/services/video";
import { logoutAppLock } from "ente-new/photos/services/app-lock";
-import exportService from "ente-new/photos/services/export";
import { logoutML, terminateMLWorker } from "ente-new/photos/services/ml";
import { logoutSearch } from "ente-new/photos/services/search";
import { logoutSettings } from "ente-new/photos/services/settings";
diff --git a/web/packages/new/photos/services/pull.ts b/web/apps/photos/src/services/pull.ts
similarity index 93%
rename from web/packages/new/photos/services/pull.ts
rename to web/apps/photos/src/services/pull.ts
index 69e85d1bbc..bf8d34488e 100644
--- a/web/packages/new/photos/services/pull.ts
+++ b/web/apps/photos/src/services/pull.ts
@@ -10,11 +10,15 @@ import {
movePendingRemovalActionsToUncategorized,
pullCollectionFiles,
pullCollections,
-} from "./collection";
-import { isMLSupported, mlSync, pullMLStatus } from "./ml";
-import { searchDataSync } from "./search";
-import { pullSettings } from "./settings";
-import { pullTrash, type TrashItem } from "./trash";
+} from "ente-new/photos/services/collection";
+import {
+ isMLSupported,
+ mlSync,
+ pullMLStatus,
+} from "ente-new/photos/services/ml";
+import { searchDataSync } from "ente-new/photos/services/search";
+import { pullSettings } from "ente-new/photos/services/settings";
+import { pullTrash, type TrashItem } from "ente-new/photos/services/trash";
/**
* Called during a full remote pull, before doing the files pull.
diff --git a/web/packages/gallery/services/save.ts b/web/apps/photos/src/services/save.ts
similarity index 97%
rename from web/packages/gallery/services/save.ts
rename to web/apps/photos/src/services/save.ts
index ffb922d571..e9a11277e4 100644
--- a/web/packages/gallery/services/save.ts
+++ b/web/apps/photos/src/services/save.ts
@@ -1,23 +1,20 @@
+import { safeDirectoryName, safeFileName } from "@/utils/native-fs";
import { assertionFailed } from "ente-base/assert";
import { suppressMainWindowBlurForTrustedPrompt } from "ente-base/electron";
import { joinPath } from "ente-base/file-name";
import log from "ente-base/log";
import type { Electron } from "ente-base/types/ipc";
+import type {
+ AddSaveGroup,
+ UpdateSaveGroup,
+} from "ente-gallery/components/utils/save-groups";
import { downloadManager } from "ente-gallery/services/download";
+import { downloadAndSaveFilesWeb } from "ente-gallery/services/save-core";
import { writeStream } from "ente-gallery/utils/native-stream";
import type { EnteFile } from "ente-media/file";
import { fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
import { decodeLivePhoto } from "ente-media/live-photo";
-import {
- safeDirectoryName,
- safeFileName,
-} from "ente-new/photos/utils/native-fs";
-import type {
- AddSaveGroup,
- UpdateSaveGroup,
-} from "../components/utils/save-groups";
-import { downloadAndSaveFilesWeb } from "./save-core";
/**
* Save the given {@link files} to the user's device.
diff --git a/web/apps/photos/src/utils/file/index.ts b/web/apps/photos/src/utils/file/index.ts
index c9c9474916..2f10f0de69 100644
--- a/web/apps/photos/src/utils/file/index.ts
+++ b/web/apps/photos/src/utils/file/index.ts
@@ -1,5 +1,5 @@
+import { downloadAndSaveFiles } from "@/services/save";
import type { AddSaveGroup } from "ente-gallery/components/utils/save-groups";
-import { downloadAndSaveFiles } from "ente-gallery/services/save";
import type { EnteFile } from "ente-media/file";
import { fileFileName, ItemVisibility } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
diff --git a/web/packages/new/photos/utils/native-fs.ts b/web/apps/photos/src/utils/native-fs.ts
similarity index 100%
rename from web/packages/new/photos/utils/native-fs.ts
rename to web/apps/photos/src/utils/native-fs.ts
diff --git a/web/packages/new/photos/pages/duplicates.tsx b/web/packages/new/photos/pages/duplicates.tsx
deleted file mode 100644
index 98507d8999..0000000000
--- a/web/packages/new/photos/pages/duplicates.tsx
+++ /dev/null
@@ -1,665 +0,0 @@
-import ArrowBackIcon from "@mui/icons-material/ArrowBack";
-import DoneIcon from "@mui/icons-material/Done";
-import RemoveCircleOutlinedIcon from "@mui/icons-material/RemoveCircleOutlined";
-import SortIcon from "@mui/icons-material/Sort";
-import {
- Box,
- Checkbox,
- Divider,
- IconButton,
- LinearProgress,
- Stack,
- styled,
- Tooltip,
- Typography,
-} from "@mui/material";
-import { useRedirectIfNeedsCredentials } from "ente-accounts/components/utils/use-redirect";
-import { CenteredFill, SpacedRow } from "ente-base/components/containers";
-import { ActivityErrorIndicator } from "ente-base/components/ErrorIndicator";
-import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import {
- OverflowMenu,
- OverflowMenuOption,
-} from "ente-base/components/OverflowMenu";
-import { Ellipsized2LineTypography } from "ente-base/components/Typography";
-import { useBaseContext } from "ente-base/context";
-import log from "ente-base/log";
-import { formattedByteSize } from "ente-gallery/utils/units";
-import { t } from "i18next";
-import { useRouter } from "next/router";
-import React, {
- memo,
- useCallback,
- useEffect,
- useMemo,
- useReducer,
-} from "react";
-import Autosizer from "react-virtualized-auto-sizer";
-import {
- areEqual,
- VariableSizeList,
- type ListChildComponentProps,
-} from "react-window";
-import {
- DuplicateItemTile,
- ItemCard,
- TileBottomTextOverlay,
-} from "../components/Tiles";
-import {
- computeThumbnailGridLayoutParams,
- type ThumbnailGridLayoutParams,
-} from "../components/utils/thumbnail-grid-layout";
-import {
- deduceDuplicates,
- removeSelectedDuplicateGroups,
- type DuplicateGroup,
-} from "../services/dedup";
-
-const Page: React.FC = () => {
- const { onGenericError } = useBaseContext();
-
- const [state, dispatch] = useReducer(dedupReducer, initialDedupState);
-
- useRedirectIfNeedsCredentials("/duplicates");
-
- useEffect(() => {
- dispatch({ type: "analyze" });
- void deduceDuplicates()
- .then((duplicateGroups) =>
- dispatch({ type: "analysisCompleted", duplicateGroups }),
- )
- .catch((e: unknown) => {
- log.error("Failed to detect duplicates", e);
- dispatch({ type: "analysisFailed" });
- });
- }, []);
-
- const handleRemoveDuplicates = useCallback(() => {
- dispatch({ type: "dedupe" });
- void removeSelectedDuplicateGroups(
- state.duplicateGroups,
- (progress: number) =>
- dispatch({ type: "setDedupeProgress", progress }),
- )
- .then((removedGroupIDs) =>
- dispatch({ type: "dedupeCompleted", removedGroupIDs }),
- )
-
- .catch((e: unknown) => {
- onGenericError(e);
- dispatch({ type: "dedupeFailed" });
- });
- }, [state.duplicateGroups, onGenericError]);
-
- const contents = (() => {
- switch (state.analysisStatus) {
- case undefined:
- case "started":
- return <Loading />;
- case "failed":
- return <LoadFailed />;
- case "completed":
- if (state.duplicateGroups.length == 0) {
- return <NoDuplicatesFound />;
- } else {
- return (
- <Duplicates
- duplicateGroups={state.duplicateGroups}
- sortOrder={state.sortOrder}
- onToggleSelection={(index) =>
- dispatch({ type: "toggleSelection", index })
- }
- prunableCount={state.prunableCount}
- prunableSize={state.prunableSize}
- dedupeProgress={state.dedupeProgress}
- onRemoveDuplicates={handleRemoveDuplicates}
- />
- );
- }
- }
- })();
-
- return (
- <Stack sx={{ height: "100vh" }}>
- <Navbar
- sortOrder={state.sortOrder}
- onChangeSortOrder={(sortOrder) =>
- dispatch({ type: "changeSortOrder", sortOrder })
- }
- onDeselectAll={() => dispatch({ type: "deselectAll" })}
- />
- {contents}
- </Stack>
- );
-};
-
-export default Page;
-
-type SortOrder = "prunableCount" | "prunableSize";
-
-interface DedupState {
- /** Status of the analysis ("loading") process. */
- analysisStatus: undefined | "started" | "failed" | "completed";
- /**
- * Groups of duplicates.
- *
- * These are groups of files that our algorithm has detected as exact
- * duplicates, augmented with UI state and various cached properties to make
- * them more amenable to be directly used by the UI component.
- *
- * These are sorted in order of display, reflecting the {@link sortType}
- * user preference.
- */
- duplicateGroups: DuplicateGroup[];
- /**
- * The attribute to use for sorting {@link duplicateGroups}.
- */
- sortOrder: SortOrder;
- /**
- * The number of files that will be pruned if the user decides to dedup the
- * current selection.
- */
- prunableCount: number;
- /**
- * The size (in bytes) that can be saved if the user decides to dedup the
- * current selection.
- */
- prunableSize: number;
- /**
- * If a dedupe is in progress, then this will indicate its progress
- * percentage (a number between 0 and 100).
- */
- dedupeProgress: number | undefined;
-}
-
-type DedupAction =
- | { type: "analyze" }
- | { type: "analysisFailed" }
- | { type: "analysisCompleted"; duplicateGroups: DuplicateGroup[] }
- | { type: "changeSortOrder"; sortOrder: SortOrder }
- | { type: "toggleSelection"; index: number }
- | { type: "deselectAll" }
- | { type: "dedupe" }
- | { type: "setDedupeProgress"; progress: number }
- | { type: "dedupeFailed" }
- | { type: "dedupeCompleted"; removedGroupIDs: Set<string> };
-
-const initialDedupState: DedupState = {
- analysisStatus: undefined,
- duplicateGroups: [],
- sortOrder: "prunableSize",
- prunableCount: 0,
- prunableSize: 0,
- dedupeProgress: undefined,
-};
-
-const dedupReducer: React.Reducer<DedupState, DedupAction> = (
- state,
- action,
-) => {
- switch (action.type) {
- case "analyze":
- return { ...state, analysisStatus: "started" };
- case "analysisFailed":
- return { ...state, analysisStatus: "failed" };
- case "analysisCompleted": {
- const duplicateGroups = sortedCopyOfDuplicateGroups(
- action.duplicateGroups,
- state.sortOrder,
- );
- const selected = duplicateGroups.map(() => true);
- const { prunableCount, prunableSize } =
- deducePrunableCountAndSize(duplicateGroups);
- return {
- ...state,
- analysisStatus: "completed",
- duplicateGroups,
- selected,
- prunableCount,
- prunableSize,
- };
- }
-
- case "changeSortOrder": {
- const sortOrder = action.sortOrder;
- const duplicateGroups = sortedCopyOfDuplicateGroups(
- state.duplicateGroups,
- sortOrder,
- );
- return { ...state, sortOrder, duplicateGroups };
- }
-
- case "toggleSelection": {
- const duplicateGroups = [...state.duplicateGroups];
- const duplicateGroup = duplicateGroups[action.index]!;
- duplicateGroup.isSelected = !duplicateGroup.isSelected;
- const { prunableCount, prunableSize } =
- deducePrunableCountAndSize(duplicateGroups);
- return { ...state, duplicateGroups, prunableCount, prunableSize };
- }
-
- case "deselectAll": {
- const duplicateGroups = state.duplicateGroups.map(
- (duplicateGroup) => ({ ...duplicateGroup, isSelected: false }),
- );
- const { prunableCount, prunableSize } =
- deducePrunableCountAndSize(duplicateGroups);
- return { ...state, duplicateGroups, prunableCount, prunableSize };
- }
-
- case "dedupe":
- return { ...state, dedupeProgress: 0 };
-
- case "setDedupeProgress": {
- return { ...state, dedupeProgress: action.progress };
- }
-
- case "dedupeFailed":
- return { ...state, dedupeProgress: undefined };
-
- case "dedupeCompleted": {
- const duplicateGroups = state.duplicateGroups.filter(
- ({ id }) => !action.removedGroupIDs.has(id),
- );
- const { prunableCount, prunableSize } =
- deducePrunableCountAndSize(duplicateGroups);
- return {
- ...state,
- duplicateGroups,
- prunableCount,
- prunableSize,
- dedupeProgress: undefined,
- };
- }
- }
-};
-
-/**
- * Return a copy of the given {@link duplicateGroups}, also sorting them as per
- * the given {@link sortOrder}.
- *
- * Helper method for the reducer.
- */
-const sortedCopyOfDuplicateGroups = (
- duplicateGroups: DuplicateGroup[],
- sortOrder: DedupState["sortOrder"],
-) =>
- [...duplicateGroups].sort((a, b) =>
- sortOrder == "prunableSize"
- ? b.prunableSize - a.prunableSize
- : b.prunableCount - a.prunableCount,
- );
-
-/** Helper method for the reducer. */
-const deducePrunableCountAndSize = (duplicateGroups: DuplicateGroup[]) => {
- const prunableCount = duplicateGroups.reduce(
- (sum, { prunableCount, isSelected }) =>
- sum + (isSelected ? prunableCount : 0),
- 0,
- );
- const prunableSize = duplicateGroups.reduce(
- (sum, { prunableSize, isSelected }) =>
- sum + (isSelected ? prunableSize : 0),
- 0,
- );
- return { prunableCount, prunableSize };
-};
-
-interface NavbarProps {
- /**
- * The current sort order.
- */
- sortOrder: SortOrder;
- /**
- * Called when the user changes the sort order using the sort order menu
- * visible via the navbar.
- */
- onChangeSortOrder: (sortOrder: SortOrder) => void;
- /**
- * Called when the user selects the deselect all option.
- */
- onDeselectAll: () => void;
-}
-
-const Navbar: React.FC<NavbarProps> = ({
- sortOrder,
- onChangeSortOrder,
- onDeselectAll,
-}) => {
- const router = useRouter();
-
- return (
- <Stack
- direction="row"
- sx={(theme) => ({
- alignItems: "center",
- justifyContent: "space-between",
- padding: "8px 4px",
- borderBottom: `1px solid ${theme.vars.palette.divider}`,
- })}
- >
- <Box sx={{ minWidth: "100px" /* 2 icons + gap */ }}>
- <IconButton onClick={router.back}>
- <ArrowBackIcon />
- </IconButton>
- </Box>
- <Typography variant="h6">{t("remove_duplicates")}</Typography>
- <Stack direction="row" sx={{ gap: "4px" }}>
- <SortMenu {...{ sortOrder, onChangeSortOrder }} />
- <OptionsMenu {...{ onDeselectAll }} />
- </Stack>
- </Stack>
- );
-};
-
-type SortMenuProps = Pick<NavbarProps, "sortOrder" | "onChangeSortOrder">;
-
-const SortMenu: React.FC<SortMenuProps> = ({
- sortOrder,
- onChangeSortOrder,
-}) => (
- <OverflowMenu
- ariaID="duplicates-sort"
- triggerButtonIcon={
- <Tooltip title={t("sort_by")}>
- <SortIcon />
- </Tooltip>
- }
- >
- <OverflowMenuOption
- endIcon={sortOrder == "prunableSize" ? <DoneIcon /> : undefined}
- onClick={() => onChangeSortOrder("prunableSize")}
- >
- {t("total_size")}
- </OverflowMenuOption>
- <OverflowMenuOption
- endIcon={sortOrder == "prunableCount" ? <DoneIcon /> : undefined}
- onClick={() => onChangeSortOrder("prunableCount")}
- >
- {t("count")}
- </OverflowMenuOption>
- </OverflowMenu>
-);
-
-type OptionsMenuProps = Pick<NavbarProps, "onDeselectAll">;
-
-const OptionsMenu: React.FC<OptionsMenuProps> = ({ onDeselectAll }) => (
- <OverflowMenu ariaID="duplicates-options">
- <OverflowMenuOption
- startIcon={<RemoveCircleOutlinedIcon />}
- onClick={onDeselectAll}
- >
- {t("deselect_all")}
- </OverflowMenuOption>
- </OverflowMenu>
-);
-
-const Loading: React.FC = () => (
- <CenteredFill>
- <ActivityIndicator />
- </CenteredFill>
-);
-
-const LoadFailed: React.FC = () => (
- <CenteredFill>
- <ActivityErrorIndicator />
- </CenteredFill>
-);
-
-const NoDuplicatesFound: React.FC = () => (
- <CenteredFill>
- <Typography sx={{ color: "text.muted", textAlign: "center" }}>
- {t("no_duplicates")}
- </Typography>
- </CenteredFill>
-);
-
-type DuplicatesProps = Pick<
- DuplicatesListProps,
- "duplicateGroups" | "sortOrder" | "onToggleSelection"
-> &
- DeduplicateButtonProps;
-
-const Duplicates: React.FC<DuplicatesProps> = ({
- duplicateGroups,
- sortOrder,
- onToggleSelection,
- ...deduplicateButtonProps
-}) => (
- <Stack sx={{ flex: 1 }}>
- <Box sx={{ flex: 1, overflow: "hidden", paddingBlockEnd: 1 }}>
- <Autosizer>
- {({ width, height }) => (
- <DuplicatesList
- {...{
- width,
- height,
- duplicateGroups,
- sortOrder,
- onToggleSelection,
- }}
- />
- )}
- </Autosizer>
- </Box>
- <Stack sx={{ margin: 1 }}>
- <DeduplicateButton {...deduplicateButtonProps} />
- </Stack>
- </Stack>
-);
-
-interface DuplicatesListProps {
- /**
- * The width (px) that the list should size itself to.
- */
- width: number;
- /**
- * The height (px) that the list should size itself to.
- */
- height: number;
- /**
- * Groups of duplicates. Guaranteed to be non-empty.
- */
- duplicateGroups: DuplicateGroup[];
- /**
- * The current {@link SortOrder} that is being used for sorting {@link duplicateGroups}.
- */
- sortOrder: SortOrder;
- /**
- * Called when the user toggles the selection for the duplicate group at the
- * given {@link index}.
- */
- onToggleSelection: (index: number) => void;
-}
-
-type DuplicatesListItemData = Pick<
- DuplicatesListProps,
- "duplicateGroups" | "onToggleSelection"
-> & { layoutParams: ThumbnailGridLayoutParams };
-
-const DuplicatesList: React.FC<DuplicatesListProps> = ({
- width,
- height,
- duplicateGroups,
- sortOrder,
- onToggleSelection,
-}) => {
- const layoutParams = useMemo(
- () => computeThumbnailGridLayoutParams(width),
- [width],
- );
-
- const itemData = { layoutParams, duplicateGroups, onToggleSelection };
- const itemCount = duplicateGroups.length;
- const itemSize = (index: number) => {
- // The height of the header is driven by the height of the Checkbox,
- // which is 42px high, and the divider, which is 1px. The rest of the
- // height comes from the fixed paddings, margins on the header, the
- // divider, and on the row itself.
- const fixedHeight = 24 + 42 + 4 + 1 + 20 + 16;
-
- const duplicateGroup = duplicateGroups[index]!;
- const rowCount = Math.ceil(
- duplicateGroup.items.length / layoutParams.columns,
- );
- const rowHeight = layoutParams.itemHeight + layoutParams.gap;
-
- return fixedHeight + rowCount * rowHeight;
- };
- const itemKey = (index: number, itemData: DuplicatesListItemData) =>
- itemData.duplicateGroups[index]!.id;
-
- // Derive a key based on aspects whose change should cause the list to be
- // recreated. This is the easiest way I've found to get react-window to
- // invalidate `itemSize` values when, say, the width changes.
- const key = `${width}-${sortOrder}`;
-
- return (
- <VariableSizeList
- key={key}
- style={
- {
- "--et-padding-inline": `${layoutParams.paddingInline}px`,
- } as React.CSSProperties
- }
- {...{ height, width, itemData, itemCount, itemSize, itemKey }}
- >
- {ListItem}
- </VariableSizeList>
- );
-};
-
-const ListItem: React.FC<ListChildComponentProps<DuplicatesListItemData>> =
- memo(({ index, style, data }) => {
- const { layoutParams, duplicateGroups, onToggleSelection } = data;
-
- // For smaller screens, hide to divider to reduce visual noise. For
- // larger screens, the divider is helpful in guiding the user's eyes to
- // the checkbox which is otherwise at the right end of the header.
- const hideDivider = layoutParams.isSmallerLayout;
-
- const duplicateGroup = duplicateGroups[index]!;
- const items = duplicateGroup.items;
- const count = items.length;
- const itemSize = formattedByteSize(duplicateGroup.itemSize);
- const checked = duplicateGroup.isSelected;
- const onChange = () => onToggleSelection(index);
-
- return (
- <Stack
- {...{ style }}
- sx={[
- { paddingBlockEnd: "16px" },
- checked ? { opacity: 1 } : { opacity: 0.8 },
- ]}
- >
- <SpacedRow
- sx={{
- mx: 1,
- paddingInline: "var(--et-padding-inline)",
- paddingBlock: "24px 0px",
- }}
- >
- <Typography
- sx={{ color: checked ? "text.base" : "text.muted" }}
- >
- {t("duplicate_group_description", { count, itemSize })}
- </Typography>
- {/* The size of this Checkbox is 42px. */}
- <Checkbox {...{ checked, onChange }} />
- </SpacedRow>
- <Divider
- variant="middle"
- sx={[
- { marginBlock: "4px 20px" },
- hideDivider ? { opacity: 0 } : { opacity: 0.8 },
- ]}
- />
- <ItemGrid {...{ layoutParams }}>
- {items.map((item, j) => (
- <ItemCard
- key={j}
- TileComponent={DuplicateItemTile}
- coverFile={item.file}
- >
- <TileBottomTextOverlay>
- <Ellipsized2LineTypography variant="small">
- {item.collectionName}
- </Ellipsized2LineTypography>
- </TileBottomTextOverlay>
- </ItemCard>
- ))}
- </ItemGrid>
- </Stack>
- );
- }, areEqual);
-
-type ItemGridProps = Pick<DuplicatesListItemData, "layoutParams">;
-
-const ItemGrid = styled("div", {
- shouldForwardProp: (prop) => prop != "layoutParams",
-})<ItemGridProps>(
- ({ layoutParams }) => `
- display: grid;
- padding-inline: ${layoutParams.paddingInline}px;
- grid-template-columns: repeat(${layoutParams.columns}, ${layoutParams.itemWidth}px);
- grid-auto-rows: ${layoutParams.itemHeight}px;
- gap: ${layoutParams.gap}px;
-`,
-);
-
-type DeduplicateButtonProps = Pick<
- DedupState,
- "prunableCount" | "prunableSize" | "dedupeProgress"
-> & {
- /**
- * Called when the user presses the button to remove duplicates.
- */
- onRemoveDuplicates: () => void;
-};
-
-const DeduplicateButton: React.FC<DeduplicateButtonProps> = ({
- prunableCount,
- prunableSize,
- dedupeProgress,
- onRemoveDuplicates,
-}) => (
- <FocusVisibleButton
- sx={{ minWidth: "min(100%, 320px)", margin: "auto" }}
- disabled={prunableCount == 0 || dedupeProgress !== undefined}
- onClick={onRemoveDuplicates}
- >
- <Stack
- sx={{
- gap: 1,
- // Prevent a layout shift by giving a minHeight that is larger
- // than all expected states.
- minHeight: "45px",
- justifyContent: "center",
- flex: 1,
- }}
- >
- {dedupeProgress !== undefined ? (
- <LinearProgress
- sx={{ borderRadius: "4px" }}
- variant={
- dedupeProgress === 0 ? "indeterminate" : "determinate"
- }
- value={dedupeProgress}
- />
- ) : (
- <>
- <Typography>
- {t("remove_duplicates_button_count", {
- count: prunableCount,
- })}
- </Typography>
- <Typography variant="small" sx={{ fontWeight: "regular" }}>
- {formattedByteSize(prunableSize)}
- </Typography>
- </>
- )}
- </Stack>
- </FocusVisibleButton>
-);