Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(largeFiles):listing-and-removing-large-files

Aswin Asok5fc5d80d0dcf
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 86b28f2984..f6e796b5fb 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -227,6 +227,11 @@ type HelpAction = Extract<
| "help.testUpload"
>;
+type FreeUpSpaceAction = Extract<
+ SidebarActionID,
+ "freeUpSpace.deduplicate" | "freeUpSpace.largeFiles"
+>;
+
export const Sidebar: React.FC<SidebarProps> = ({
open,
onClose,
@@ -239,12 +244,13 @@ export const Sidebar: React.FC<SidebarProps> = ({
onShowExport,
onAuthenticateUser,
}) => {
- const router = useRouter();
const { show: showHelp, props: helpVisibilityProps } = useModalVisibility();
const { show: showAccount, props: accountVisibilityProps } =
useModalVisibility();
const { show: showPreferences, props: preferencesVisibilityProps } =
useModalVisibility();
+ const { show: showFreeUpSpace, props: freeUpSpaceVisibilityProps } =
+ useModalVisibility();
const { watchFolderView, setWatchFolderView } = usePhotosAppContext();
const { showMiniDialog, logout } = useBaseContext();
@@ -253,6 +259,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
const [pendingPreferencesAction, setPendingPreferencesAction] =
useState<PreferencesAction>();
const [pendingHelpAction, setPendingHelpAction] = useState<HelpAction>();
+ const [pendingFreeUpSpaceAction, setPendingFreeUpSpaceAction] =
+ useState<FreeUpSpaceAction>();
const handleLogout = useCallback(
() =>
@@ -287,9 +295,9 @@ export const Sidebar: React.FC<SidebarProps> = ({
showAccount,
showPreferences,
showHelp,
+ showFreeUpSpace,
onShowExport,
onLogout: handleLogout,
- onRouteToDeduplicate: () => router.push("/duplicates"),
onShowWatchFolder: handleOpenWatchFolder,
pseudoIDs: {
uncategorized: uncategorizedCollectionSummaryID,
@@ -305,6 +313,10 @@ export const Sidebar: React.FC<SidebarProps> = ({
),
setPendingHelpAction: (a) =>
setPendingHelpAction(a as HelpAction | undefined),
+ setPendingFreeUpSpaceAction: (a) =>
+ setPendingFreeUpSpaceAction(
+ a as FreeUpSpaceAction | undefined,
+ ),
} as SidebarActionContext),
[
handleLogout,
@@ -313,8 +325,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
onShowCollectionSummary,
onShowPlanSelector,
onShowExport,
- router,
showAccount,
+ showFreeUpSpace,
showHelp,
showPreferences,
uncategorizedCollectionSummaryID,
@@ -368,6 +380,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
preferencesVisibilityProps,
showHelp,
helpVisibilityProps,
+ showFreeUpSpace,
+ freeUpSpaceVisibilityProps,
watchFolderView,
onShowWatchFolder: handleOpenWatchFolder,
onCloseWatchFolder: handleCloseWatchFolder,
@@ -377,9 +391,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
onPreferencesActionHandled: setPendingPreferencesAction,
pendingHelpAction,
onHelpActionHandled: setPendingHelpAction,
- onRouteToDeduplicate: () => {
- void router.push("/duplicates");
- },
+ pendingFreeUpSpaceAction,
+ onFreeUpSpaceActionHandled: setPendingFreeUpSpaceAction,
}}
/>
<Divider sx={{ my: "2px" }} />
@@ -758,6 +771,8 @@ type UtilitySectionProps = SectionProps &
preferencesVisibilityProps: ModalVisibilityProps;
showHelp: () => void;
helpVisibilityProps: ModalVisibilityProps;
+ showFreeUpSpace: () => void;
+ freeUpSpaceVisibilityProps: ModalVisibilityProps;
watchFolderView: boolean;
onShowWatchFolder: () => void;
onCloseWatchFolder: () => void;
@@ -767,7 +782,8 @@ type UtilitySectionProps = SectionProps &
onPreferencesActionHandled: (action?: PreferencesAction) => void;
pendingHelpAction?: HelpAction;
onHelpActionHandled: (action?: HelpAction) => void;
- onRouteToDeduplicate: () => void;
+ pendingFreeUpSpaceAction?: FreeUpSpaceAction;
+ onFreeUpSpaceActionHandled: (action?: FreeUpSpaceAction) => void;
};
const UtilitySection: React.FC<UtilitySectionProps> = ({
@@ -780,6 +796,8 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
preferencesVisibilityProps,
showHelp,
helpVisibilityProps,
+ showFreeUpSpace,
+ freeUpSpaceVisibilityProps,
watchFolderView,
onShowWatchFolder,
onCloseWatchFolder,
@@ -789,7 +807,8 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
onPreferencesActionHandled,
pendingHelpAction,
onHelpActionHandled,
- onRouteToDeduplicate,
+ pendingFreeUpSpaceAction,
+ onFreeUpSpaceActionHandled,
}) => {
const { showMiniDialog } = useBaseContext();
@@ -814,8 +833,8 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
)}
<RowButton
variant="secondary"
- label={t("deduplicate_files")}
- onClick={onRouteToDeduplicate}
+ label={t("free_up_space")}
+ onClick={showFreeUpSpace}
/>
<RowButton
variant="secondary"
@@ -862,6 +881,12 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({
pendingAction={pendingPreferencesAction}
onActionHandled={onPreferencesActionHandled}
/>
+ <FreeUpSpace
+ {...freeUpSpaceVisibilityProps}
+ onRootClose={onCloseSidebar}
+ pendingAction={pendingFreeUpSpaceAction}
+ onActionHandled={onFreeUpSpaceActionHandled}
+ />
</>
);
};
@@ -1719,3 +1744,74 @@ const Help: React.FC<HelpProps> = ({
</TitledNestedSidebarDrawer>
);
};
+
+type FreeUpSpaceProps = NestedSidebarDrawerVisibilityProps & {
+ pendingAction?: FreeUpSpaceAction;
+ onActionHandled?: (action?: FreeUpSpaceAction) => void;
+};
+
+const FreeUpSpace: React.FC<FreeUpSpaceProps> = ({
+ open,
+ onClose,
+ onRootClose,
+ pendingAction,
+ onActionHandled,
+}) => {
+ const router = useRouter();
+
+ const handleRootClose = useCallback(() => {
+ onClose();
+ onRootClose();
+ }, [onClose, onRootClose]);
+
+ const handleDeduplicate = useCallback(() => {
+ handleRootClose();
+ void router.push("/duplicates");
+ }, [handleRootClose, router]);
+
+ const handleLargeFiles = useCallback(() => {
+ handleRootClose();
+ void router.push("/large-files");
+ }, [handleRootClose, router]);
+
+ useEffect(() => {
+ if (!open || !pendingAction) return;
+ switch (pendingAction) {
+ case "freeUpSpace.deduplicate":
+ handleDeduplicate();
+ break;
+ case "freeUpSpace.largeFiles":
+ handleLargeFiles();
+ break;
+ }
+ onActionHandled?.();
+ }, [
+ handleDeduplicate,
+ handleLargeFiles,
+ open,
+ onActionHandled,
+ pendingAction,
+ ]);
+
+ return (
+ <TitledNestedSidebarDrawer
+ {...{ open, onClose }}
+ onRootClose={handleRootClose}
+ title={t("free_up_space")}
+ >
+ <Stack sx={{ px: 2, py: 1, gap: 3 }}>
+ <RowButtonGroup>
+ <RowButton
+ label={t("deduplicate_files")}
+ onClick={handleDeduplicate}
+ />
+ <RowButtonDivider />
+ <RowButton
+ label={t("large_files_title")}
+ onClick={handleLargeFiles}
+ />
+ </RowButtonGroup>
+ </Stack>
+ </TitledNestedSidebarDrawer>
+ );
+};
diff --git a/web/apps/photos/src/pages/large-files.tsx b/web/apps/photos/src/pages/large-files.tsx
new file mode 100644
index 0000000000..568d3a0319
--- /dev/null
+++ b/web/apps/photos/src/pages/large-files.tsx
@@ -0,0 +1,829 @@
+import ArrowBackIcon from "@mui/icons-material/ArrowBack";
+import CheckBoxIcon from "@mui/icons-material/CheckBox";
+import ImageIcon from "@mui/icons-material/Image";
+import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
+import SortIcon from "@mui/icons-material/Sort";
+import VideocamIcon from "@mui/icons-material/Videocam";
+import {
+ Box,
+ Chip,
+ IconButton,
+ LinearProgress,
+ Stack,
+ styled,
+ Tooltip,
+ Typography,
+} from "@mui/material";
+import { useRedirectIfNeedsCredentials } from "ente-accounts/components/utils/use-redirect";
+import { CenteredFill, Overlay } 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 { useBaseContext } from "ente-base/context";
+import log from "ente-base/log";
+import { formattedByteSize } from "ente-gallery/utils/units";
+import { ItemCard, LargeFileTileOverlay } from "ente-new/photos/components/Tiles";
+import { computeThumbnailGridLayoutParams, type ThumbnailGridLayoutParams } from "ente-new/photos/components/utils/thumbnail-grid-layout";
+import {
+ deleteSelectedLargeFiles,
+ findLargeFiles,
+ type LargeFileFilter,
+ type LargeFileItem,
+} from "ente-new/photos/services/large-files";
+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";
+
+type SortOrder = "desc" | "asc";
+
+const Page: React.FC = () => {
+ const { onGenericError } = useBaseContext();
+
+ const [state, dispatch] = useReducer(largeFilesReducer, initialState);
+
+ useRedirectIfNeedsCredentials("/large-files");
+
+ useEffect(() => {
+ dispatch({ type: "analyze" });
+ void findLargeFiles(state.filter)
+ .then((largeFiles) =>
+ dispatch({ type: "analysisCompleted", largeFiles }),
+ )
+ .catch((e: unknown) => {
+ log.error("Failed to find large files", e);
+ dispatch({ type: "analysisFailed" });
+ });
+ }, [state.filter]);
+
+ const handleDeleteFiles = useCallback(() => {
+ dispatch({ type: "delete" });
+ void deleteSelectedLargeFiles(state.largeFiles, (progress: number) =>
+ dispatch({ type: "setDeleteProgress", progress }),
+ )
+ .then((removedIDs) =>
+ dispatch({ type: "deleteCompleted", removedIDs }),
+ )
+ .catch((e: unknown) => {
+ onGenericError(e);
+ dispatch({ type: "deleteFailed" });
+ });
+ }, [state.largeFiles, onGenericError]);
+
+ const contents = (() => {
+ switch (state.analysisStatus) {
+ case undefined:
+ case "started":
+ return <Loading />;
+ case "failed":
+ return <LoadFailed />;
+ case "completed":
+ if (state.largeFiles.length == 0) {
+ return <NoLargeFilesFound />;
+ } else {
+ return (
+ <LargeFiles
+ largeFiles={state.largeFiles}
+ onToggleSelection={(index) =>
+ dispatch({ type: "toggleSelection", index })
+ }
+ selectedCount={state.selectedCount}
+ selectedSize={state.selectedSize}
+ deleteProgress={state.deleteProgress}
+ onDeleteFiles={handleDeleteFiles}
+ />
+ );
+ }
+ }
+ })();
+
+ return (
+ <Stack sx={{ height: "100vh" }}>
+ <Navbar
+ filter={state.filter}
+ onChangeFilter={(filter) =>
+ dispatch({ type: "changeFilter", filter })
+ }
+ sortOrder={state.sortOrder}
+ onChangeSortOrder={(sortOrder) =>
+ dispatch({ type: "changeSortOrder", sortOrder })
+ }
+ onDeselectAll={() => dispatch({ type: "deselectAll" })}
+ onSelectAll={() => dispatch({ type: "selectAll" })}
+ />
+ {contents}
+ </Stack>
+ );
+};
+
+export default Page;
+
+interface LargeFilesState {
+ /** Status of the analysis ("loading") process. */
+ analysisStatus: undefined | "started" | "failed" | "completed";
+ /**
+ * List of large files.
+ *
+ * These are sorted by file size based on sortOrder.
+ */
+ largeFiles: LargeFileItem[];
+ /**
+ * The current filter for file types.
+ */
+ filter: LargeFileFilter;
+ /**
+ * The current sort order (descending = largest first, ascending = smallest first).
+ */
+ sortOrder: SortOrder;
+ /**
+ * The number of files currently selected for deletion.
+ */
+ selectedCount: number;
+ /**
+ * The total size (in bytes) of files currently selected for deletion.
+ */
+ selectedSize: number;
+ /**
+ * If a deletion is in progress, this will indicate its progress
+ * percentage (a number between 0 and 100).
+ */
+ deleteProgress: number | undefined;
+}
+
+type LargeFilesAction =
+ | { type: "analyze" }
+ | { type: "analysisFailed" }
+ | { type: "analysisCompleted"; largeFiles: LargeFileItem[] }
+ | { type: "changeFilter"; filter: LargeFileFilter }
+ | { type: "changeSortOrder"; sortOrder: SortOrder }
+ | { type: "toggleSelection"; index: number }
+ | { type: "deselectAll" }
+ | { type: "selectAll" }
+ | { type: "delete" }
+ | { type: "setDeleteProgress"; progress: number }
+ | { type: "deleteFailed" }
+ | { type: "deleteCompleted"; removedIDs: Set<string> };
+
+const initialState: LargeFilesState = {
+ analysisStatus: undefined,
+ largeFiles: [],
+ filter: "all",
+ sortOrder: "desc",
+ selectedCount: 0,
+ selectedSize: 0,
+ deleteProgress: undefined,
+};
+
+const largeFilesReducer: React.Reducer<LargeFilesState, LargeFilesAction> = (
+ state,
+ action,
+) => {
+ switch (action.type) {
+ case "analyze":
+ return { ...state, analysisStatus: "started" };
+ case "analysisFailed":
+ return { ...state, analysisStatus: "failed" };
+ case "analysisCompleted": {
+ const largeFiles = action.largeFiles;
+ const { selectedCount, selectedSize } =
+ computeSelectedCountAndSize(largeFiles);
+ return {
+ ...state,
+ analysisStatus: "completed",
+ largeFiles,
+ selectedCount,
+ selectedSize,
+ };
+ }
+
+ case "changeFilter": {
+ // Reset state when filter changes, will trigger re-analysis.
+ return {
+ ...initialState,
+ filter: action.filter,
+ sortOrder: state.sortOrder,
+ };
+ }
+
+ case "changeSortOrder": {
+ const sortOrder = action.sortOrder;
+ const largeFiles = sortedCopyOfLargeFiles(
+ state.largeFiles,
+ sortOrder,
+ );
+ return { ...state, sortOrder, largeFiles };
+ }
+
+ case "toggleSelection": {
+ const largeFiles = [...state.largeFiles];
+ const item = largeFiles[action.index]!;
+ item.isSelected = !item.isSelected;
+ const { selectedCount, selectedSize } =
+ computeSelectedCountAndSize(largeFiles);
+ return { ...state, largeFiles, selectedCount, selectedSize };
+ }
+
+ case "deselectAll": {
+ const largeFiles = state.largeFiles.map((item) => ({
+ ...item,
+ isSelected: false,
+ }));
+ return { ...state, largeFiles, selectedCount: 0, selectedSize: 0 };
+ }
+
+ case "selectAll": {
+ const largeFiles = state.largeFiles.map((item) => ({
+ ...item,
+ isSelected: true,
+ }));
+ const { selectedCount, selectedSize } =
+ computeSelectedCountAndSize(largeFiles);
+ return { ...state, largeFiles, selectedCount, selectedSize };
+ }
+
+ case "delete":
+ return { ...state, deleteProgress: 0 };
+
+ case "setDeleteProgress":
+ return { ...state, deleteProgress: action.progress };
+
+ case "deleteFailed":
+ return { ...state, deleteProgress: undefined };
+
+ case "deleteCompleted": {
+ const largeFiles = state.largeFiles.filter(
+ ({ id }) => !action.removedIDs.has(id),
+ );
+ const { selectedCount, selectedSize } =
+ computeSelectedCountAndSize(largeFiles);
+ return {
+ ...state,
+ largeFiles,
+ selectedCount,
+ selectedSize,
+ deleteProgress: undefined,
+ };
+ }
+ }
+};
+
+const computeSelectedCountAndSize = (largeFiles: LargeFileItem[]) => {
+ const selectedCount = largeFiles.reduce(
+ (sum, { isSelected }) => sum + (isSelected ? 1 : 0),
+ 0,
+ );
+ const selectedSize = largeFiles.reduce(
+ (sum, { size, isSelected }) => sum + (isSelected ? size : 0),
+ 0,
+ );
+ return { selectedCount, selectedSize };
+};
+
+const sortedCopyOfLargeFiles = (
+ largeFiles: LargeFileItem[],
+ sortOrder: SortOrder,
+) =>
+ [...largeFiles].sort((a, b) =>
+ sortOrder === "desc" ? b.size - a.size : a.size - b.size,
+ );
+
+interface NavbarProps {
+ filter: LargeFileFilter;
+ onChangeFilter: (filter: LargeFileFilter) => void;
+ sortOrder: SortOrder;
+ onChangeSortOrder: (sortOrder: SortOrder) => void;
+ onDeselectAll: () => void;
+ onSelectAll: () => void;
+}
+
+const Navbar: React.FC<NavbarProps> = ({
+ filter,
+ onChangeFilter,
+ sortOrder,
+ onChangeSortOrder,
+ onDeselectAll,
+ onSelectAll,
+}) => {
+ const router = useRouter();
+
+ const handleToggleSortOrder = () => {
+ onChangeSortOrder(sortOrder === "desc" ? "asc" : "desc");
+ };
+
+ const sortTooltip =
+ sortOrder === "desc"
+ ? t("sort_largest_first")
+ : t("sort_smallest_first");
+
+ return (
+ <Stack
+ sx={(theme) => ({
+ borderBottom: `1px solid ${theme.vars.palette.divider}`,
+ })}
+ >
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between",
+ padding: "8px 4px",
+ }}
+ >
+ <Box sx={{ minWidth: "100px" }}>
+ <IconButton onClick={router.back}>
+ <ArrowBackIcon />
+ </IconButton>
+ </Box>
+ <Typography variant="h6">{t("large_files_title")}</Typography>
+ <Stack
+ direction="row"
+ sx={{
+ gap: "4px",
+ minWidth: "100px",
+ justifyContent: "flex-end",
+ }}
+ >
+ <Tooltip title={sortTooltip}>
+ <IconButton onClick={handleToggleSortOrder}>
+ <SortIcon
+ sx={{
+ transform:
+ sortOrder === "asc"
+ ? "scaleY(-1)"
+ : "none",
+ }}
+ />
+ </IconButton>
+ </Tooltip>
+ <OptionsMenu {...{ onDeselectAll, onSelectAll }} />
+ </Stack>
+ </Stack>
+ <FilterChips {...{ filter, onChangeFilter }} />
+ </Stack>
+ );
+};
+
+interface FilterChipsProps {
+ filter: LargeFileFilter;
+ onChangeFilter: (filter: LargeFileFilter) => void;
+}
+
+const FilterChips: React.FC<FilterChipsProps> = ({
+ filter,
+ onChangeFilter,
+}) => (
+ <Stack direction="row" sx={{ gap: 1, px: 3, pb: 1.5, flexWrap: "wrap" }}>
+ <Chip
+ label={t("all")}
+ variant={filter === "all" ? "filled" : "outlined"}
+ color={filter === "all" ? "primary" : "default"}
+ onClick={() => onChangeFilter("all")}
+ />
+ <Chip
+ icon={<ImageIcon sx={{ fontSize: "18px !important" }} />}
+ label={t("photos")}
+ variant={filter === "photos" ? "filled" : "outlined"}
+ color={filter === "photos" ? "primary" : "default"}
+ onClick={() => onChangeFilter("photos")}
+ sx={{ px: 1 }}
+ />
+ <Chip
+ icon={<VideocamIcon sx={{ fontSize: "18px !important" }} />}
+ label={t("videos")}
+ variant={filter === "videos" ? "filled" : "outlined"}
+ color={filter === "videos" ? "primary" : "default"}
+ onClick={() => onChangeFilter("videos")}
+ sx={{ px: 1 }}
+ />
+ </Stack>
+);
+
+interface OptionsMenuProps {
+ onDeselectAll: () => void;
+ onSelectAll: () => void;
+}
+
+const OptionsMenu: React.FC<OptionsMenuProps> = ({
+ onDeselectAll,
+ onSelectAll,
+}) => (
+ <OverflowMenu ariaID="large-files-options">
+ <OverflowMenuOption startIcon={<CheckBoxIcon />} onClick={onSelectAll}>
+ {t("select_all")}
+ </OverflowMenuOption>
+ <OverflowMenuOption
+ startIcon={<RemoveCircleOutlineIcon />}
+ onClick={onDeselectAll}
+ >
+ {t("deselect_all")}
+ </OverflowMenuOption>
+ </OverflowMenu>
+);
+
+const Loading: React.FC = () => (
+ <CenteredFill>
+ <ActivityIndicator />
+ </CenteredFill>
+);
+
+const LoadFailed: React.FC = () => (
+ <CenteredFill>
+ <ActivityErrorIndicator />
+ </CenteredFill>
+);
+
+const NoLargeFilesFound: React.FC = () => (
+ <CenteredFill>
+ <Typography color="text.muted" sx={{ textAlign: "center" }}>
+ {t("no_large_files")}
+ </Typography>
+ </CenteredFill>
+);
+
+interface LargeFilesProps {
+ largeFiles: LargeFileItem[];
+ onToggleSelection: (index: number) => void;
+ selectedCount: number;
+ selectedSize: number;
+ deleteProgress: number | undefined;
+ onDeleteFiles: () => void;
+}
+
+const LargeFiles: React.FC<LargeFilesProps> = ({
+ largeFiles,
+ onToggleSelection,
+ selectedCount,
+ selectedSize,
+ deleteProgress,
+ onDeleteFiles,
+}) => (
+ <Stack sx={{ flex: 1 }}>
+ <Box sx={{ flex: 1, overflow: "hidden", paddingBlockEnd: 1 }}>
+ <Autosizer>
+ {({ width, height }) => (
+ <LargeFilesGrid
+ {...{ width, height, largeFiles, onToggleSelection }}
+ />
+ )}
+ </Autosizer>
+ </Box>
+ <Stack sx={{ margin: 1 }}>
+ <DeleteButton
+ {...{
+ selectedCount,
+ selectedSize,
+ deleteProgress,
+ onDeleteFiles,
+ }}
+ />
+ </Stack>
+ </Stack>
+);
+
+interface LargeFilesGridProps {
+ width: number;
+ height: number;
+ largeFiles: LargeFileItem[];
+ onToggleSelection: (index: number) => void;
+}
+
+interface LargeFilesGridItemData {
+ largeFiles: LargeFileItem[];
+ onToggleSelection: (index: number) => void;
+ layoutParams: ThumbnailGridLayoutParams;
+}
+
+const LargeFilesGrid: React.FC<LargeFilesGridProps> = ({
+ width,
+ height,
+ largeFiles,
+ onToggleSelection,
+}) => {
+ const layoutParams = useMemo(
+ () => computeThumbnailGridLayoutParams(width),
+ [width],
+ );
+
+ const columns = layoutParams.columns;
+ const rowCount = Math.ceil(largeFiles.length / columns);
+
+ const itemData: LargeFilesGridItemData = {
+ largeFiles,
+ onToggleSelection,
+ layoutParams,
+ };
+
+ const itemSize = () => layoutParams.itemHeight + layoutParams.gap;
+
+ const itemKey = (index: number) => `row-${index}`;
+
+ // Key based on width to force re-render when layout changes
+ const key = `${width}`;
+
+ return (
+ <VariableSizeList
+ key={key}
+ style={
+ {
+ "--et-padding-inline": `${layoutParams.paddingInline}px`,
+ } as React.CSSProperties
+ }
+ {...{
+ height,
+ width,
+ itemData,
+ itemCount: rowCount,
+ itemSize,
+ itemKey,
+ }}
+ >
+ {GridRow}
+ </VariableSizeList>
+ );
+};
+
+const GridRow: React.FC<ListChildComponentProps<LargeFilesGridItemData>> = memo(
+ ({ index: rowIndex, style, data }) => {
+ const { largeFiles, onToggleSelection, layoutParams } = data;
+ const columns = layoutParams.columns;
+
+ // Calculate which items are in this row
+ const startIndex = rowIndex * columns;
+ const endIndex = Math.min(startIndex + columns, largeFiles.length);
+ const rowItems = largeFiles.slice(startIndex, endIndex);
+
+ return (
+ <ItemGrid layoutParams={layoutParams} style={style}>
+ {rowItems.map((item, colIndex) => {
+ const itemIndex = startIndex + colIndex;
+ return (
+ <GridItem
+ key={item.id}
+ item={item}
+ onToggle={() => onToggleSelection(itemIndex)}
+ />
+ );
+ })}
+ </ItemGrid>
+ );
+ },
+ areEqual,
+);
+
+interface GridItemProps {
+ item: LargeFileItem;
+ onToggle: () => void;
+}
+
+const GridItem: React.FC<GridItemProps> = memo(({ item, onToggle }) => {
+ const checked = item.isSelected;
+
+ const handleCheckboxChange: React.ChangeEventHandler<HTMLInputElement> = (
+ e,
+ ) => {
+ e.stopPropagation();
+ onToggle();
+ };
+
+ return (
+ <TileContainer onClick={onToggle}>
+ <ItemCard TileComponent={LargeFileTile} coverFile={item.file}>
+ <LargeFileTileOverlay>
+ <SizeLabel>{formattedByteSize(item.size)}</SizeLabel>
+ </LargeFileTileOverlay>
+ </ItemCard>
+ <Check
+ type="checkbox"
+ checked={checked}
+ onChange={handleCheckboxChange}
+ onClick={(e) => e.stopPropagation()}
+ />
+ {checked && <SelectedOverlay />}
+ <HoverOverlay className="hover-overlay" $checked={checked} />
+ </TileContainer>
+ );
+});
+
+interface ItemGridProps {
+ layoutParams: ThumbnailGridLayoutParams;
+ style?: React.CSSProperties;
+}
+
+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;
+`,
+);
+
+const TileContainer = styled("div")`
+ position: relative;
+ cursor: pointer;
+ border-radius: 4px;
+ overflow: hidden;
+ width: 100%;
+ height: 100%;
+ user-select: none;
+
+ @media (pointer: fine) {
+ &:hover {
+ input[type="checkbox"] {
+ visibility: visible;
+ opacity: 0.5;
+ }
+
+ .hover-overlay {
+ opacity: 1;
+ }
+ }
+ }
+`;
+
+const LargeFileTile = styled("div")`
+ display: flex;
+ position: relative;
+ border-radius: 4px;
+ overflow: hidden;
+ width: 100%;
+ height: 100%;
+ & > img {
+ object-fit: cover;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ }
+`;
+
+const SizeLabel = styled(Typography)`
+ position: absolute;
+ bottom: 4px;
+ left: 4px;
+ background-color: rgba(0, 0, 0, 0.6);
+ color: white;
+ padding: 2px 4px;
+ border-radius: 4px;
+ font-size: 0.65rem;
+`;
+
+const Check = styled("input")(
+ ({ theme }) => `
+ appearance: none;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ position: absolute;
+ z-index: 10;
+ top: 0;
+ left: 0;
+ outline: none;
+ cursor: pointer;
+ width: 31px;
+ height: 31px;
+ box-sizing: border-box;
+
+ @media (pointer: coarse) {
+ pointer-events: none;
+ }
+
+ &::before {
+ content: "";
+ display: block; /* Critical for Safari */
+ width: 19px;
+ height: 19px;
+ background-color: #ddd;
+ border-radius: 50%;
+ margin: 6px;
+ transition: background-color 0.3s ease, opacity 0.3s ease;
+ position: relative; /* Important for Safari */
+ }
+
+ &::after {
+ content: "";
+ display: block; /* Critical for Safari */
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 5px;
+ height: 11px;
+ border: solid #333;
+ border-width: 0 2px 2px 0;
+ transform: translate(-50%, -60%) rotate(45deg);
+ transition: border-color 0.3s ease, opacity 0.3s ease;
+ transform-origin: center;
+ }
+
+ /* Default state - hidden */
+ visibility: hidden;
+
+ /* Hover state - show with reduced opacity */
+ &:hover {
+ visibility: visible;
+ opacity: 0.7;
+ }
+
+ /* Checked state - fully visible and colored */
+ &:checked {
+ visibility: visible;
+ opacity: 1 !important;
+ }
+
+ &:checked::before {
+ background-color: ${theme.vars.palette.accent.main};
+ }
+
+ &:checked::after {
+ border-color: #ddd;
+ }
+`,
+);
+
+const SelectedOverlay = styled(Overlay)(
+ ({ theme }) => `
+ border: 2px solid ${theme.vars.palette.accent.main};
+ border-radius: 4px;
+ pointer-events: none;
+`,
+);
+
+const HoverOverlay = styled("div")<{ $checked: boolean }>`
+ opacity: 0;
+ left: 0;
+ top: 0;
+ outline: none;
+ height: 40%;
+ width: 100%;
+ position: absolute;
+ pointer-events: none;
+ ${(props) =>
+ !props.$checked &&
+ "background: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0));"}
+`;
+
+interface DeleteButtonProps {
+ selectedCount: number;
+ selectedSize: number;
+ deleteProgress: number | undefined;
+ onDeleteFiles: () => void;
+}
+
+const DeleteButton: React.FC<DeleteButtonProps> = ({
+ selectedCount,
+ selectedSize,
+ deleteProgress,
+ onDeleteFiles,
+}) => (
+ <FocusVisibleButton
+ sx={{ minWidth: "min(100%, 320px)", margin: "auto" }}
+ disabled={selectedCount == 0 || deleteProgress !== undefined}
+ color="critical"
+ onClick={onDeleteFiles}
+ >
+ <Stack
+ sx={{
+ gap: 1,
+ minHeight: "45px",
+ justifyContent: "center",
+ flex: 1,
+ }}
+ >
+ {deleteProgress !== undefined ? (
+ <LinearProgress
+ sx={{ borderRadius: "4px" }}
+ variant={
+ deleteProgress === 0 ? "indeterminate" : "determinate"
+ }
+ value={deleteProgress}
+ color="inherit"
+ />
+ ) : (
+ <>
+ <Typography>
+ {t("delete_files_button", { count: selectedCount })}
+ </Typography>
+ <Typography variant="small" fontWeight="regular">
+ {formattedByteSize(selectedSize)}
+ </Typography>
+ </>
+ )}
+ </Stack>
+ </FocusVisibleButton>
+);
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index 9675263bf4..028ba245b0 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -516,6 +516,7 @@
"file": "File",
"folder": "Folder",
"google_takeout": "Google takeout",
+ "free_up_space": "Free up space",
"deduplicate_files": "Deduplicate files",
"remove_duplicates": "Remove duplicates",
"total_size": "Total size",
@@ -524,6 +525,15 @@
"no_duplicates": "No duplicates",
"duplicate_group_description": "{{count}} items, {{itemSize}} each",
"remove_duplicates_button_count": "Delete {{count, number}} items",
+ "large_files_title": "Large files",
+ "no_large_files": "No large files found",
+ "sort_largest_first": "Largest first",
+ "sort_smallest_first": "Smallest first",
+ "delete_files_button": "Delete {{count, number}} files",
+ "all": "All",
+ "photos": "Photos",
+ "videos": "Videos",
+ "select_all": "Select all",
"stop_uploads_title": "Stop uploads?",
"stop_uploads_message": "Are you sure that you want to stop all the uploads in progress?",
"yes_stop_uploads": "Yes, stop uploads",
diff --git a/web/packages/new/photos/components/Tiles.tsx b/web/packages/new/photos/components/Tiles.tsx
index bf8318d832..f2b4e83286 100644
--- a/web/packages/new/photos/components/Tiles.tsx
+++ b/web/packages/new/photos/components/Tiles.tsx
@@ -258,3 +258,12 @@ export const TileBottomTextOverlay = styled(Overlay)`
background: linear-gradient(transparent 30%, 80%, rgba(0 0 0 / 0.7));
color: white;
`;
+
+/**
+ * An {@link Overlay} for use with large file tiles, providing a container
+ * for selection indicators and file size labels.
+ */
+export const LargeFileTileOverlay = styled(Overlay)`
+ display: flex;
+ pointer-events: none;
+`;
diff --git a/web/packages/new/photos/services/large-files.ts b/web/packages/new/photos/services/large-files.ts
new file mode 100644
index 0000000000..ce3ab4ed61
--- /dev/null
+++ b/web/packages/new/photos/services/large-files.ts
@@ -0,0 +1,168 @@
+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 {
+ createCollectionNameByID,
+ moveToTrash,
+ savedNormalCollections,
+} from "./collection";
+import { savedCollectionFiles } from "./photos-fdb";
+import { pullFiles } from "./pull";
+
+/**
+ * Minimum file size (in bytes) to be considered a "large" file.
+ *
+ * This matches the mobile implementation: 10 MB.
+ */
+export const MIN_LARGE_FILE_SIZE = 10 * 1024 * 1024;
+
+/**
+ * Filter type for large files.
+ */
+export type LargeFileFilter = "all" | "photos" | "videos";
+
+/**
+ * A large file as shown in the UI.
+ */
+export interface LargeFileItem {
+ /**
+ * A nanoid for this item.
+ *
+ * This can be used as the key when rendering the item in a list.
+ */
+ id: string;
+ /**
+ * The underlying file.
+ */
+ file: EnteFile;
+ /**
+ * The size of the file in bytes.
+ */
+ size: number;
+ /**
+ * The name of the collection to which this file belongs.
+ */
+ collectionName: string;
+ /**
+ * `true` if the user has marked this item for deletion.
+ */
+ isSelected: boolean;
+}
+
+/**
+ * Find files larger than {@link MIN_LARGE_FILE_SIZE} in the user's library.
+ *
+ * @param filter The type of files to include (all, photos, or videos).
+ *
+ * @returns An array of {@link LargeFileItem} sorted by file size (descending).
+ */
+export const findLargeFiles = async (
+ filter: LargeFileFilter,
+): Promise<LargeFileItem[]> => {
+ const userID = ensureLocalUser().id;
+
+ // Get collections and create a name lookup map.
+ const normalCollections = await savedNormalCollections();
+ const normalOwnedCollections = normalCollections.filter(
+ ({ owner }) => owner.id == userID,
+ );
+ const allowedCollectionIDs = new Set(
+ normalOwnedCollections.map(({ id }) => id),
+ );
+ const collectionNameByID = createCollectionNameByID(normalOwnedCollections);
+
+ // Get all collection files.
+ const collectionFiles = await savedCollectionFiles();
+
+ // Track files we've already added (by file ID) to avoid duplicates
+ // when the same file exists in multiple collections.
+ const seenFileIDs = new Set<number>();
+ const largeFiles: LargeFileItem[] = [];
+
+ for (const file of collectionFiles) {
+ // Skip files not in allowed collections.
+ if (!allowedCollectionIDs.has(file.collectionID)) continue;
+
+ // Skip files not owned by the user.
+ if (file.ownerID != userID) continue;
+
+ // Skip files already processed (same file in different collection).
+ if (seenFileIDs.has(file.id)) continue;
+
+ // Get file size.
+ const size = file.info?.fileSize;
+ if (!size || size < MIN_LARGE_FILE_SIZE) continue;
+
+ // Apply filter.
+ if (!matchesFilter(file, filter)) continue;
+
+ seenFileIDs.add(file.id);
+
+ const collectionName = collectionNameByID.get(file.collectionID) ?? "";
+
+ largeFiles.push({
+ id: newID("lf_"),
+ file,
+ size,
+ collectionName,
+ isSelected: false,
+ });
+ }
+
+ // Sort by size descending (largest first).
+ largeFiles.sort((a, b) => b.size - a.size);
+
+ return largeFiles;
+};
+
+/**
+ * Check if a file matches the given filter.
+ */
+const matchesFilter = (file: EnteFile, filter: LargeFileFilter): boolean => {
+ switch (filter) {
+ case "all":
+ return true;
+ case "photos":
+ return (
+ file.metadata.fileType === FileType.image ||
+ file.metadata.fileType === FileType.livePhoto
+ );
+ case "videos":
+ return file.metadata.fileType === FileType.video;
+ }
+};
+
+/**
+ * Delete selected large files by moving them to trash.
+ *
+ * @param largeFiles The list of large file items.
+ * @param onProgress A function called with progress percentage (0-100).
+ *
+ * @returns A set of IDs of the items that were deleted.
+ */
+export const deleteSelectedLargeFiles = async (
+ largeFiles: LargeFileItem[],
+ onProgress: (progress: number) => void,
+): Promise<Set<string>> => {
+ const selectedItems = largeFiles.filter((item) => item.isSelected);
+ const filesToTrash = selectedItems.map((item) => item.file);
+
+ if (filesToTrash.length === 0) {
+ return new Set();
+ }
+
+ let np = 0;
+ const ntotal = 2; // trash + sync
+ const tickProgress = () => onProgress((np++ / ntotal) * 100);
+
+ // Move files to trash.
+ await moveToTrash(filesToTrash);
+ tickProgress();
+
+ // Sync local state.
+ await pullFiles();
+ tickProgress();
+
+ return new Set(selectedItems.map((item) => item.id));
+};
diff --git a/web/packages/new/photos/services/search/sidebar-search-registry.ts b/web/packages/new/photos/services/search/sidebar-search-registry.ts
index 635bae2135..e3bec36c5b 100644
--- a/web/packages/new/photos/services/search/sidebar-search-registry.ts
+++ b/web/packages/new/photos/services/search/sidebar-search-registry.ts
@@ -24,10 +24,10 @@ export interface SidebarActionContext {
showAccount: () => void;
showPreferences: () => void;
showHelp: () => void;
+ showFreeUpSpace: () => void;
onShowExport: () => void;
onShowPlanSelector: () => void;
onLogout: () => void;
- onRouteToDeduplicate: () => Promise<unknown>;
onShowWatchFolder: () => void;
pseudoIDs: {
uncategorized: number;
@@ -40,6 +40,7 @@ export interface SidebarActionContext {
setPendingAccountAction: (a: SidebarActionID | undefined) => void;
setPendingPreferencesAction: (a: SidebarActionID | undefined) => void;
setPendingHelpAction: (a: SidebarActionID | undefined) => void;
+ setPendingFreeUpSpaceAction: (a: SidebarActionID | undefined) => void;
}
// Construct sidebar actions at call time so we always use initialized i18n
@@ -101,11 +102,31 @@ const sidebarActions = (): SidebarAction[] => {
available: () => isDesktop,
},
{
- id: "utility.deduplicate",
+ id: "utility.freeUpSpace",
+ label: t("free_up_space"),
+ path: [preferencesCategory, t("free_up_space")],
+ keywords: ["free", "space", "storage", "clean"],
+ },
+ {
+ id: "freeUpSpace.deduplicate",
label: t("deduplicate_files"),
- path: [preferencesCategory, t("deduplicate_files")],
+ path: [
+ preferencesCategory,
+ t("free_up_space"),
+ t("deduplicate_files"),
+ ],
keywords: ["duplicate", "dedupe"],
},
+ {
+ id: "freeUpSpace.largeFiles",
+ label: t("large_files_title"),
+ path: [
+ preferencesCategory,
+ t("free_up_space"),
+ t("large_files_title"),
+ ],
+ keywords: ["large", "big", "files", "size", "space"],
+ },
{
id: "utility.preferences",
label: t("preferences"),
@@ -332,8 +353,15 @@ export const performSidebarAction = async (
ctx.onShowWatchFolder();
return Promise.resolve();
- case "utility.deduplicate":
- return ctx.onRouteToDeduplicate().then(() => ctx.onClose());
+ case "utility.freeUpSpace":
+ ctx.showFreeUpSpace();
+ return Promise.resolve();
+
+ case "freeUpSpace.deduplicate":
+ case "freeUpSpace.largeFiles":
+ ctx.setPendingFreeUpSpaceAction(actionID);
+ ctx.showFreeUpSpace();
+ return Promise.resolve();
case "utility.preferences":
ctx.showPreferences();
diff --git a/web/packages/new/photos/services/search/types.ts b/web/packages/new/photos/services/search/types.ts
index c469418ec7..9a6eb25036 100644
--- a/web/packages/new/photos/services/search/types.ts
+++ b/web/packages/new/photos/services/search/types.ts
@@ -30,11 +30,13 @@ export type SidebarActionID =
| "shortcuts.trash"
| "utility.account"
| "utility.watchFolders"
- | "utility.deduplicate"
+ | "utility.freeUpSpace"
| "utility.preferences"
| "utility.help"
| "utility.export"
| "utility.logout"
+ | "freeUpSpace.deduplicate"
+ | "freeUpSpace.largeFiles"
| "account.subscription"
| "account.recoveryKey"
| "account.twoFactor"