π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
refactor(photos):embed-large-files-in-gallery
Aswin Asokbc79eecbdd1c
diff --git a/web/apps/photos/src/pages/large-files.tsx b/web/apps/photos/src/components/gallery/LargeFilesView.tsxsimilarity index 97%rename from web/apps/photos/src/pages/large-files.tsxrename to web/apps/photos/src/components/gallery/LargeFilesView.tsxindex 5e123e6592..6e8221a624 100644--- a/web/apps/photos/src/pages/large-files.tsx+++ b/web/apps/photos/src/components/gallery/LargeFilesView.tsx@@ -18,7 +18,6 @@ import {styled,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";@@ -37,7 +36,6 @@ import {} from "ente-new/photos/components/utils/thumbnail-grid-layout";import { usePhotosAppContext } from "ente-new/photos/types/context";import { t } from "i18next";-import { useRouter } from "next/router";import React, {memo,useCallback,@@ -53,7 +51,15 @@ import {type ListChildComponentProps,} from "react-window";-const Page: React.FC = () => {+interface LargeFilesViewProps {+ onBack: () => void;+ onRemoteFilesPull: () => Promise<void>;+}++export function LargeFilesView({+ onBack,+ onRemoteFilesPull,+}: LargeFilesViewProps) {const { showMiniDialog, onGenericError } = useBaseContext();const { setIsFileViewerOpen } = usePhotosAppContext();@@ -64,8 +70,6 @@ const Page: React.FC = () => {const [openFileViewer, setOpenFileViewer] = useState(false);const [currentIndex, setCurrentIndex] = useState(0);- useRedirectIfNeedsCredentials("/large-files");-useEffect(() => {let isCurrent = true;@@ -101,6 +105,7 @@ const Page: React.FC = () => {state.largeFiles,(progress: number) =>dispatch({ type: "setDeleteProgress", progress }),+ onRemoteFilesPull,).then((removedIDs) =>dispatch({ type: "deleteCompleted", removedIDs }),@@ -112,7 +117,7 @@ const Page: React.FC = () => {},},});- }, [showMiniDialog, onGenericError, state.largeFiles]);+ }, [showMiniDialog, onGenericError, state.largeFiles, onRemoteFilesPull]);const handleOpenViewer = useCallback((index: number) => {@@ -172,8 +177,9 @@ const Page: React.FC = () => {})();return (- <Stack sx={{ height: "100vh" }}>+ <Stack sx={{ flex: 1, minHeight: 0 }}><Navbar+ onBack={onBack}filter={state.filter}onChangeFilter={(filter) =>dispatch({ type: "changeFilter", filter })@@ -191,18 +197,15 @@ const Page: React.FC = () => {/></Stack>);-};--export default Page;+}interface NavbarProps {+ onBack: () => void;filter: LargeFileFilter;onChangeFilter: (filter: LargeFileFilter) => void;}-const Navbar: React.FC<NavbarProps> = ({ filter, onChangeFilter }) => {- const router = useRouter();-+const Navbar: React.FC<NavbarProps> = ({ filter, onChangeFilter, onBack }) => {return (<Stack><Stack@@ -215,7 +218,7 @@ const Navbar: React.FC<NavbarProps> = ({ filter, onChangeFilter }) => {})}><Box sx={{ minWidth: "100px" }}>- <IconButton onClick={router.back}>+ <IconButton onClick={onBack} aria-label={t("go_back")}><ArrowBackIcon /></IconButton></Box>diff --git a/web/apps/photos/src/components/sidebar/FreeUpSpace.tsx b/web/apps/photos/src/components/sidebar/FreeUpSpace.tsxindex a28a25f086..c4eaef7427 100644--- a/web/apps/photos/src/components/sidebar/FreeUpSpace.tsx+++ b/web/apps/photos/src/components/sidebar/FreeUpSpace.tsx@@ -15,6 +15,7 @@ export type FreeUpSpaceAction = Extract<>;type FreeUpSpaceProps = NestedSidebarDrawerVisibilityProps & {+ onShowLargeFiles: () => void;pendingAction?: FreeUpSpaceAction;onActionHandled?: (action?: FreeUpSpaceAction) => void;};@@ -25,6 +26,7 @@ export const FreeUpSpace: React.FC<FreeUpSpaceProps> = ({onRootClose,pendingAction,onActionHandled,+ onShowLargeFiles,}) => {const router = useRouter();@@ -40,8 +42,8 @@ export const FreeUpSpace: React.FC<FreeUpSpaceProps> = ({const handleLargeFiles = useCallback(() => {onRootClose();- void router.push("/large-files");- }, [onRootClose, router]);+ onShowLargeFiles();+ }, [onRootClose, onShowLargeFiles]);useEffect(() => {if (!open || !pendingAction) return;diff --git a/web/apps/photos/src/components/sidebar/Sidebar.tsx b/web/apps/photos/src/components/sidebar/Sidebar.tsxindex 08a89065bd..36c1efebe5 100644--- a/web/apps/photos/src/components/sidebar/Sidebar.tsx+++ b/web/apps/photos/src/components/sidebar/Sidebar.tsx@@ -91,6 +91,7 @@ type SidebarProps = ModalVisibilityProps & {uncategorizedCollectionSummaryID: number;pendingAction?: SidebarActionID;onActionHandled?: (actionID: SidebarActionID) => void;+ onShowLargeFiles: () => void;onShowPlanSelector: () => void;onShowCollectionSummary: (collectionSummaryID: number,@@ -112,6 +113,7 @@ export const Sidebar: React.FC<SidebarProps> = ({pendingAction,onActionHandled,onShowPlanSelector,+ onShowLargeFiles,onShowCollectionSummary,collectionNameByID,onAuthenticateUser,@@ -437,6 +439,7 @@ export const Sidebar: React.FC<SidebarProps> = ({)}{freeUpSpaceVisibilityProps.open && (<FreeUpSpace+ onShowLargeFiles={onShowLargeFiles}{...freeUpSpaceVisibilityProps}onRootClose={onClose}pendingAction={pendingFreeUpSpaceAction}diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex 1257b9e538..b140b58e11 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -173,11 +173,18 @@ import {import { usePhotosAppContext } from "ente-new/photos/types/context";import { PromiseQueue } from "ente-utils/promise";import { t } from "i18next";+import dynamic from "next/dynamic";import { useRouter, type NextRouter } from "next/router";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { FileWithPath } from "react-dropzone";import { Trans } from "react-i18next";+const LargeFilesView = dynamic(() =>+ import("@/components/gallery/LargeFilesView").then(+ (module) => module.LargeFilesView,+ ),+);+const Page: React.FC = () => {const { logout, showMiniDialog, onGenericError } = useBaseContext();const {@@ -190,6 +197,7 @@ const Page: React.FC = () => {const isOffline = useIsOffline();const [state, dispatch] = useGalleryReducer();+ const [isLargeFilesOpen, setIsLargeFilesOpen] = useState(false);const [isFirstLoad, setIsFirstLoad] = useState(false);const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);const [trashFilesDialog, setTrashFilesDialog] = useState<{@@ -825,11 +833,19 @@ const Page: React.FC = () => {});};- const keyboardShortcutHandlerRef = useRef({ selectAll, clearSelection });+ const keyboardShortcutHandlerRef = useRef({+ selectAll,+ clearSelection,+ isLargeFilesOpen,+ });useEffect(() => {- keyboardShortcutHandlerRef.current = { selectAll, clearSelection };- }, [selectAll, clearSelection]);+ keyboardShortcutHandlerRef.current = {+ selectAll,+ clearSelection,+ isLargeFilesOpen,+ };+ }, [selectAll, clearSelection, isLargeFilesOpen]);const showSessionExpiredDialog = useCallback(() => showMiniDialog(sessionExpiredDialogAttributes(logout)),@@ -916,6 +932,7 @@ const Page: React.FC = () => {const setupSelectAllKeyBoardShortcutHandler = () => {const handleKeyUp = (e: KeyboardEvent) => {+ if (keyboardShortcutHandlerRef.current.isLargeFilesOpen) return;switch (e.key) {case "Escape":keyboardShortcutHandlerRef.current.clearSelection();@@ -1388,6 +1405,7 @@ const Page: React.FC = () => {const handleShowCollectionSummaryWithID = useCallback((collectionSummaryID: number | undefined) => {+ setIsLargeFilesOpen(false);// Museum deletes collection contents asynchronously; pull on entry.if (collectionSummaryID == PseudoCollectionID.trash) {void remoteFilesPull();@@ -1423,6 +1441,24 @@ const Page: React.FC = () => {[authenticateUser, handleShowCollectionSummaryWithID, barMode],);+ const handleShowLargeFiles = useCallback(() => {+ setSelected({+ ownCount: 0,+ count: 0,+ collectionID: 0,+ context: undefined,+ });+ closeCollectionMap();+ closeSlideshow();+ dispatch({ type: "exitSearch", shouldExitSearchMode: true });+ setIsLargeFilesOpen(true);+ }, [closeCollectionMap, closeSlideshow]);++ const handleCloseLargeFiles = useCallback(() => {+ setIsLargeFilesOpen(false);+ dispatch({ type: "showAll" });+ }, []);+const handleSidebarShowCollectionSummary = showCollectionSummary;const handleDownloadStatusNotificationsShowCollectionSummary = useCallback(@@ -1899,7 +1935,7 @@ const Page: React.FC = () => {message={watchFolderView ? t("watch_folder_dropzone_hint") : undefined}- disabled={shouldDisableDropzone || !!slideshow}+ disabled={shouldDisableDropzone || !!slideshow || isLargeFilesOpen}onDrop={setDragAndDropFiles}>{blockingLoad && <TranslucentLoadingOverlay />}@@ -1935,112 +1971,126 @@ const Page: React.FC = () => {{...trashFilesDialog}/>)}- <NavbarBase- sx={[- {- mb: "12px",- px: "24px",- "@media (width < 720px)": { px: "4px" },- },- showSelectionBar && { borderColor: "accent.main" },- ]}- >- {showSelectionBar ? (- <SelectedFileOptions- barMode={barMode}- isInSearchMode={isInSearchMode}- collection={- isInSearchMode ? undefined : activeCollection+ {!isLargeFilesOpen && (+ <>+ <NavbarBase+ sx={[+ {+ mb: "12px",+ px: "24px",+ "@media (width < 720px)": { px: "4px" },+ },+ showSelectionBar && { borderColor: "accent.main" },+ ]}+ >+ {showSelectionBar ? (+ <SelectedFileOptions+ barMode={barMode}+ isInSearchMode={isInSearchMode}+ collection={+ isInSearchMode+ ? undefined+ : activeCollection+ }+ collectionSummary={+ isInSearchMode+ ? undefined+ : activeCollectionSummary+ }+ selectedFileCount={selected.count}+ selectedOwnFileCount={selected.ownCount}+ selectedFavoriteCount={selectedFavoriteCount}+ onClearSelection={clearSelection}+ onDelete={() => handleDeleteFiles()}+ onRemoveFilesFromCollection={+ handleRemoveFilesFromCollection+ }+ onOpenCollectionSelector={+ handleOpenCollectionSelector+ }+ onSelectAll={handleSelectAll}+ isAllSelected={isAllSelectedInView}+ {...{+ createOnCreateForCollectionOp,+ createOnSelectForCollectionOp,+ createFileOpHandler,+ onShowAssignPersonDialog:+ showAddPersonAction+ ? showContextMenuAssignPerson+ : undefined,+ }}+ onEditLocation={showEditLocation}+ />+ ) : barMode == "hidden-albums" ? (+ <SectionNavbarContents+ title={t("section_hidden")}+ onBack={() => dispatch({ type: "showAlbums" })}+ onUpload={openUploader}+ />+ ) : !isInSearchMode && isInArchiveSection ? (+ <SectionNavbarContents+ title={t("section_archive")}+ onBack={() => dispatch({ type: "showAlbums" })}+ onUpload={openUploader}+ />+ ) : (+ <NormalNavbarContents+ {...{ isInSearchMode }}+ onSidebar={showSidebar}+ onUpload={openUploader}+ onSelectSearchOption={handleSelectSearchOption}+ onSelectPeople={() =>+ dispatch({ type: "showPeople" })+ }+ onSelectPerson={handleSelectPerson}+ />+ )}+ </NavbarBase>+ {isFirstLoad && <FirstLoadMessage />}+ {isOffline && <OfflineMessage />}++ <GalleryBarAndListHeader+ {...{+ user,+ // TODO: These are incorrect assertions, the types of the+ // component need to be updated.+ activeCollection: activeCollection!,+ activeCollectionID: activeCollectionID!,+ activePerson,+ setFileListHeader,+ saveGroups,+ canCreateAlbum: !isInArchiveSection,+ onAddSaveGroup,+ onEditAlbumDetails: showEditAlbumDetails,+ onShowMap: handleShowCollectionMap,+ onCollectionSlideshow: startSlideshow,+ }}+ mode={barMode}+ shouldHide={isInSearchMode}+ barCollectionSummaries={barCollectionSummaries}+ emailByUserID={state.emailByUserID}+ shareSuggestionEmails={state.shareSuggestionEmails}+ people={+ (state.view?.type == "people"+ ? state.view.visiblePeople+ : undefined) ?? []}- collectionSummary={- isInSearchMode ? undefined : activeCollectionSummary+ allPeople={+ (state.view?.type == "people"+ ? state.view.people+ : undefined) ?? []}- selectedFileCount={selected.count}- selectedOwnFileCount={selected.ownCount}- selectedFavoriteCount={selectedFavoriteCount}- onClearSelection={clearSelection}- onDelete={() => handleDeleteFiles()}- onRemoveFilesFromCollection={- handleRemoveFilesFromCollection+ onChangeMode={handleChangeBarMode}+ setBlockingLoad={setBlockingLoad}+ setActiveCollectionID={+ handleShowCollectionSummaryWithID}- onOpenCollectionSelector={handleOpenCollectionSelector}- onSelectAll={handleSelectAll}- isAllSelected={isAllSelectedInView}- {...{- createOnCreateForCollectionOp,- createOnSelectForCollectionOp,- createFileOpHandler,- onShowAssignPersonDialog: showAddPersonAction- ? showContextMenuAssignPerson- : undefined,- }}- onEditLocation={showEditLocation}- />- ) : barMode == "hidden-albums" ? (- <SectionNavbarContents- title={t("section_hidden")}- onBack={() => dispatch({ type: "showAlbums" })}- onUpload={openUploader}- />- ) : !isInSearchMode && isInArchiveSection ? (- <SectionNavbarContents- title={t("section_archive")}- onBack={() => dispatch({ type: "showAlbums" })}- onUpload={openUploader}- />- ) : (- <NormalNavbarContents- {...{ isInSearchMode }}- onSidebar={showSidebar}- onUpload={openUploader}- onSelectSearchOption={handleSelectSearchOption}- onSelectPeople={() => dispatch({ type: "showPeople" })}+ hasActiveFileSelection={hasActiveFileSelection}+ onRemotePull={remotePull}onSelectPerson={handleSelectPerson}/>- )}- </NavbarBase>- {isFirstLoad && <FirstLoadMessage />}- {isOffline && <OfflineMessage />}-- <GalleryBarAndListHeader- {...{- user,- // TODO: These are incorrect assertions, the types of the- // component need to be updated.- activeCollection: activeCollection!,- activeCollectionID: activeCollectionID!,- activePerson,- setFileListHeader,- saveGroups,- canCreateAlbum: !isInArchiveSection,- onAddSaveGroup,- onEditAlbumDetails: showEditAlbumDetails,- onShowMap: handleShowCollectionMap,- onCollectionSlideshow: startSlideshow,- }}- mode={barMode}- shouldHide={isInSearchMode}- barCollectionSummaries={barCollectionSummaries}- emailByUserID={state.emailByUserID}- shareSuggestionEmails={state.shareSuggestionEmails}- people={- (state.view?.type == "people"- ? state.view.visiblePeople- : undefined) ?? []- }- allPeople={- (state.view?.type == "people"- ? state.view.people- : undefined) ?? []- }- onChangeMode={handleChangeBarMode}- setBlockingLoad={setBlockingLoad}- setActiveCollectionID={handleShowCollectionSummaryWithID}- hasActiveFileSelection={hasActiveFileSelection}- onRemotePull={remotePull}- onSelectPerson={handleSelectPerson}- />-+ </>+ )}<Upload{...{user,@@ -2070,6 +2120,7 @@ const Page: React.FC = () => {<Sidebar{...sidebarVisibilityProps}onClose={handleSidebarClose}+ onShowLargeFiles={handleShowLargeFiles}normalCollectionSummaries={normalCollectionSummaries}uncategorizedCollectionSummaryID={state.uncategorizedCollectionSummaryID@@ -2091,10 +2142,15 @@ const Page: React.FC = () => {title={t("add_a_person")}onSelectPerson={handleContextMenuSelectPerson}/>- {!isInSearchMode &&- !isFirstLoad &&- !state.collectionFiles.length &&- activeCollectionID === PseudoCollectionID.all ? (+ {isLargeFilesOpen ? (+ <LargeFilesView+ onBack={handleCloseLargeFiles}+ onRemoteFilesPull={remoteFilesPull}+ />+ ) : !isInSearchMode &&+ !isFirstLoad &&+ !state.collectionFiles.length &&+ activeCollectionID === PseudoCollectionID.all ? (<GalleryEmptyStateisUploadInProgress={uploadManager.isUploadInProgress()}onUpload={openUploader}diff --git a/web/apps/photos/src/services/large-files.ts b/web/apps/photos/src/services/large-files.tsindex c84554d9e6..7c0432d97c 100644--- a/web/apps/photos/src/services/large-files.ts+++ b/web/apps/photos/src/services/large-files.ts@@ -7,7 +7,6 @@ import {savedNormalCollections,} from "ente-new/photos/services/collection";import { savedCollectionFiles } from "ente-new/photos/services/photos-fdb";-import { pullFiles } from "./pull";// Keep the 10 MB threshold aligned with mobile.const MIN_LARGE_FILE_SIZE = 10 * 1024 * 1024;@@ -78,6 +77,7 @@ const matchesFilter = (file: EnteFile, filter: LargeFileFilter): boolean => {export const deleteSelectedLargeFiles = async (largeFiles: LargeFileItem[],onProgress: (progress: number) => void,+ onRemoteFilesPull: () => Promise<void>,): Promise<Set<string>> => {const selectedItems = largeFiles.filter((item) => item.isSelected);const filesToTrash = selectedItems.map((item) => item.file);@@ -94,7 +94,7 @@ export const deleteSelectedLargeFiles = async (await moveToTrash(filesToTrash);tickProgress();- await pullFiles();+ await onRemoteFilesPull();tickProgress();return new Set(selectedItems.map((item) => item.id));diff --git a/web/apps/photos/tests/large-files.test.ts b/web/apps/photos/tests/large-files.test.tsnew file mode 100644index 0000000000..2a3cbca7a5--- /dev/null+++ b/web/apps/photos/tests/large-files.test.ts@@ -0,0 +1,78 @@+import type { EnteFile } from "ente-media/file";+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ deleteSelectedLargeFiles,+ type LargeFileItem,+} from "../src/services/large-files";++const { moveToTrash } = vi.hoisted(() => ({ moveToTrash: vi.fn() }));+vi.mock("ente-new/photos/services/collection", () => ({ moveToTrash }));+vi.mock("ente-new/photos/services/photos-fdb", () => ({}));+vi.mock("ente-accounts/services/user", () => ({}));++const item = (id: number, isSelected: boolean): LargeFileItem => ({+ id: `lf_${id}`,+ file: { id } as EnteFile,+ size: 20 * 1024 * 1024,+ isSelected,+});++describe("deleteSelectedLargeFiles", () => {+ beforeEach(() => vi.resetAllMocks());++ test("trashes only selected files and waits for gallery refresh before completing", async () => {+ const selected = item(1, true);+ const onProgress = vi.fn();+ let finishRefresh!: () => void;+ const refresh = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishRefresh = resolve;+ }),+ );+ const deletion = deleteSelectedLargeFiles(+ [selected, item(2, false)],+ onProgress,+ refresh,+ );+ await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce());+ expect(moveToTrash).toHaveBeenCalledExactlyOnceWith([selected.file]);+ expect(onProgress.mock.calls).toEqual([[50]]);+ finishRefresh();+ await expect(deletion).resolves.toEqual(new Set([selected.id]));+ expect(onProgress.mock.calls).toEqual([[50], [100]]);+ });++ test("does nothing when no files are selected", async () => {+ const onProgress = vi.fn();+ const refresh = vi.fn();+ await expect(+ deleteSelectedLargeFiles([item(1, false)], onProgress, refresh),+ ).resolves.toEqual(new Set());+ expect(moveToTrash).not.toHaveBeenCalled();+ expect(refresh).not.toHaveBeenCalled();+ expect(onProgress).not.toHaveBeenCalled();+ });++ test("propagates trash failures without starting a refresh", async () => {+ const failure = new Error("Trash failed");+ moveToTrash.mockRejectedValue(failure);+ const refresh = vi.fn();+ const onProgress = vi.fn();+ await expect(+ deleteSelectedLargeFiles([item(1, true)], onProgress, refresh),+ ).rejects.toBe(failure);+ expect(refresh).not.toHaveBeenCalled();+ expect(onProgress).not.toHaveBeenCalled();+ });++ test("propagates refresh failures without reporting completion", async () => {+ const failure = new Error("Refresh failed");+ const refresh = vi.fn().mockRejectedValue(failure);+ const onProgress = vi.fn();+ await expect(+ deleteSelectedLargeFiles([item(1, true)], onProgress, refresh),+ ).rejects.toBe(failure);+ expect(onProgress.mock.calls).toEqual([[50]]);+ });+});diff --git a/web/packages/gallery/components/FullScreenDropZone.tsx b/web/packages/gallery/components/FullScreenDropZone.tsxindex c01a6537e9..4f96932557 100644--- a/web/packages/gallery/components/FullScreenDropZone.tsx+++ b/web/packages/gallery/components/FullScreenDropZone.tsx@@ -47,10 +47,10 @@ export const FullScreenDropZone: React.FC<const handleDragEnter = useCallback((event: React.DragEvent<HTMLElement>) => {- if (!hasDraggedFiles(event.dataTransfer)) return;+ if (disabled || !hasDraggedFiles(event.dataTransfer)) return;setIsDragActive(true);},- [],+ [disabled],);const handleOverlayDrop = useCallback(@@ -86,7 +86,7 @@ export const FullScreenDropZone: React.FC<sx={{ flex: 1 }}{...getRootProps({ onDragEnter: handleDragEnter })}>- {(isDragActive || isDropPending) && (+ {!disabled && (isDragActive || isDropPending) && (<DropZoneOverlayonDrop={handleOverlayDrop}onDragLeave={handleDragLeave}