π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Trim public album viewer code
Anand Baburajan185e9c712672
diff --git a/web/apps/albums/src/pages/index.tsx b/web/apps/albums/src/pages/index.tsxindex 0e85a6fce3..280692c051 100644--- a/web/apps/albums/src/pages/index.tsx+++ b/web/apps/albums/src/pages/index.tsx@@ -681,8 +681,6 @@ export default function PublicCollectionGallery() {selected={selected}setSelected={setSelected}activeCollectionID={PseudoCollectionID.all}- onRemotePull={publicAlbumsRemotePull}- onVisualFeedback={handleVisualFeedback}onAddSaveGroup={onAddSaveGroup}publicAlbumsCredentials={credentials.current}collectionKey={collectionKey.current}diff --git a/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsxindex 0a7e043efc..91c57a68e4 100644--- a/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx+++ b/web/apps/albums/vendor/ente-gallery/components/FileInfo.tsx@@ -1,42 +1,58 @@import CalendarTodayIcon from "@mui/icons-material/CalendarToday";+import CameraOutlinedIcon from "@mui/icons-material/CameraOutlined";import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";-import PersonOutlineIcon from "@mui/icons-material/PersonOutline";import PhotoOutlinedIcon from "@mui/icons-material/PhotoOutlined";import TextSnippetOutlinedIcon from "@mui/icons-material/TextSnippetOutlined";import VideocamOutlinedIcon from "@mui/icons-material/VideocamOutlined";import {+ Box,Link,Stack,styled,Typography,+ type DialogProps,} from "@mui/material";-import type { Location } from "ente-base/types";+import { LinkButtonUndecorated } from "ente-base/components/LinkButton";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";import {SidebarDrawer,SidebarDrawerTitlebar,} from "ente-base/components/mui/SidebarDrawer";-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { EllipsizedTypography } from "ente-base/components/Typography";+import {+ useModalVisibility,+ type ModalVisibilityProps,+} from "ente-base/components/utils/modal";import { formattedDate, formattedTime } from "ente-base/i18n-date";+import type { Location } from "ente-base/types";import { CopyButton } from "ente-gallery/components/FileInfoComponents";-import type { RawExifTags } from "ente-gallery/services/exif";+import { tagNumericValue, type RawExifTags } from "ente-gallery/services/exif";import { formattedByteSize } from "ente-gallery/utils/units";import type { EnteFile } from "ente-media/file";import {fileCreationPhotoDate,- fileDurationString,fileFileName,fileLocation,type ParsedMetadata,} from "ente-media/file-metadata";import { FileType } from "ente-media/file-type";import { t } from "i18next";-import type { ReactNode } from "react";+import React, { useMemo } from "react";export interface FileInfoExif {tags: RawExifTags | undefined;parsed: ParsedMetadata | undefined;}+type FileInfoAnnotatedExif = Required<FileInfoExif> & {+ resolution?: string;+ megaPixels?: string;+ takenOnDevice?: string;+ fNumber?: string;+ exposureTime?: string;+ iso?: string;+};+export type FileInfoProps = ModalVisibilityProps & {file: EnteFile;exif: FileInfoExif | undefined;@@ -57,56 +73,50 @@ export const FileInfo: React.FC<FileInfoProps> = ({file,exif,}) => {+ const { show: showRawExif, props: rawExifVisibilityProps } =+ useModalVisibility();+const caption = file.pubMagicMetadata?.data.caption ?? exif?.parsed?.description;const location = fileLocation(file) ?? exif?.parsed?.location;const uploaderName = file.pubMagicMetadata?.data.uploaderName;- const date = fileCreationPhotoDate(file);- const mediaDetails = mediaDetailsCaption(file, exif?.parsed);+ const annotatedExif = useMemo(() => annotateExif(exif), [exif]);return (- <FileInfoSidebar anchor="right" {...{ open, onClose }}>+ <FileInfoSidebar {...{ open, onClose }}><SidebarDrawerTitlebaronClose={onClose}onRootClose={onClose}title={t("info")}/>- <Stack sx={{ px: 1, pt: 1, pb: 3, gap: "16px" }}>- <InfoRow- icon={- file.metadata.fileType === FileType.video ? (- <VideocamOutlinedIcon />- ) : (- <PhotoOutlinedIcon />- )- }- title={fileFileName(file)}- caption={[- fileTypeLabel(file),- mediaDetails,- ]- .filter(Boolean)- .join(" β’ ")}- action={<CopyButton text={fileFileName(file)} size="small" />}- />-- <InfoRow- icon={<CalendarTodayIcon />}- title={formattedDate(date)}- caption={formattedTime(date)}- />-- {caption && (- <InfoRow- icon={<TextSnippetOutlinedIcon />}- title={caption}- caption="Caption"+ <Stack sx={{ pt: 1, pb: 3, gap: "20px" }}>+ {caption ? (+ <Box sx={{ px: 1 }}>+ <Typography+ sx={{ whiteSpace: "pre-wrap", wordBreak: "break-word" }}+ >+ {caption}+ </Typography>+ </Box>+ ) : (+ <Box sx={{ minHeight: 2 }} />+ )}+ <CreationTime file={file} />+ <FileName file={file} annotatedExif={annotatedExif} />+ {annotatedExif?.takenOnDevice && (+ <InfoItem+ icon={<CameraOutlinedIcon />}+ title={annotatedExif.takenOnDevice}+ caption={createMultipartCaption(+ annotatedExif.fNumber,+ annotatedExif.exposureTime,+ annotatedExif.iso,+ )}/>)}-{location && (- <InfoRow+ <InfoItemicon={<LocationOnOutlinedIcon />}- title={locationLabel(location)}+ title={t("location")}caption={<Linkhref={openStreetMapLink(location)}@@ -117,96 +127,289 @@ export const FileInfo: React.FC<FileInfoProps> = ({{t("view_on_map")}</Link>}- action={+ trailingButton={<CopyButton+ size="medium"text={openStreetMapLink(location)}- size="small"/>}/>)}-+ <InfoItem+ icon={<TextSnippetOutlinedIcon />}+ title={t("details")}+ caption={+ !exif ? (+ <ActivityIndicator size={12} />+ ) : !exif.tags ? (+ t("no_exif")+ ) : (+ <LinkButtonUndecorated onClick={showRawExif}>+ {t("view_exif")}+ </LinkButtonUndecorated>+ )+ }+ />{uploaderName && (- <InfoRow- icon={<PersonOutlineIcon />}- title={uploaderName}- caption="Uploader"- />+ <Typography+ variant="small"+ sx={{ m: 2, textAlign: "right", color: "text.muted" }}+ >+ {t("added_by_name", { name: uploaderName })}+ </Typography>)}</Stack>+ <RawExif+ {...rawExifVisibilityProps}+ onInfoClose={onClose}+ tags={exif?.tags}+ fileName={fileFileName(file)}+ /></FileInfoSidebar>);};-const fileTypeLabel = (file: EnteFile) => {- switch (file.metadata.fileType) {- case FileType.video:- return t("video");- case FileType.livePhoto:- return t("live_photo");- case FileType.image:- default:- return t("image");+const annotateExif = (+ fileInfoExif: FileInfoExif | undefined,+): FileInfoAnnotatedExif | undefined => {+ if (!fileInfoExif || !fileInfoExif.tags || !fileInfoExif.parsed) {+ return undefined;+ }++ const annotatedExif: FileInfoAnnotatedExif = { ...fileInfoExif };+ const { width, height } = fileInfoExif.parsed;+ if (width && height) {+ annotatedExif.resolution = `${width} x ${height}`;+ const megaPixels = Math.round((width * height) / 1_000_000);+ if (megaPixels) annotatedExif.megaPixels = `${megaPixels}MP`;}-};-const mediaDetailsCaption = (- file: EnteFile,- parsed: ParsedMetadata | undefined,-) =>- [- parsed?.width && parsed?.height- ? `${parsed.width} Γ ${parsed.height}`- : undefined,- file.info?.fileSize- ? formattedByteSize(file.info.fileSize)- : undefined,- fileDurationString(file),- ]- .filter(Boolean)- .join(" β’ ");--const locationLabel = ({ latitude, longitude }: Location) =>- `${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;+ const { exif } = fileInfoExif.tags;+ if (!exif) return annotatedExif;-const openStreetMapLink = ({ latitude, longitude }: Location) =>- `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}#map=15/${latitude}/${longitude}`;+ if (exif.Make && exif.Model) {+ annotatedExif.takenOnDevice = `${exif.Make.description} ${exif.Model.description}`;+ }+ if (exif.FNumber) annotatedExif.fNumber = exif.FNumber.description;+ if (exif.ExposureTime) {+ annotatedExif.exposureTime = exif.ExposureTime.description;+ }+ if (exif.ISOSpeedRatings) {+ annotatedExif.iso = `ISO${tagNumericValue(exif.ISOSpeedRatings)}`;+ }++ return annotatedExif;+};-const FileInfoSidebar = styled(SidebarDrawer)({+const FileInfoSidebar = styled(+ (props: Pick<DialogProps, "open" | "onClose" | "children">) => (+ <SidebarDrawer+ {...props}+ anchor="right"+ disableRestoreFocus={true}+ closeAfterTransition={true}+ />+ ),+)(({ theme }) => ({"& .MuiDrawer-paper": {overflowX: "hidden",},-});--const InfoRow: React.FC<{- icon: ReactNode;- title: ReactNode;- caption?: ReactNode;- action?: ReactNode;-}> = ({ icon, title, caption, action }) => (- <Stack direction="row" sx={{ gap: 1.5, alignItems: "flex-start" }}>- <IconContainer>{icon}</IconContainer>- <Stack sx={{ minWidth: 0, flex: 1, gap: 0.25 }}>- <Typography sx={{ wordBreak: "break-word", fontWeight: "medium" }}>- {title}- </Typography>- {caption && (+ ...theme.applyStyles("light", {+ ".MuiBackdrop-root": {+ backgroundColor: theme.vars.palette.backdrop.faint,+ },+ }),+}));++interface InfoItemProps {+ icon: React.ReactNode;+ title?: string;+ caption?: React.ReactNode;+ trailingButton?: React.ReactNode;+}++const InfoItem: React.FC<React.PropsWithChildren<InfoItemProps>> = ({+ icon,+ title,+ caption,+ trailingButton,+ children,+}) => (+ <Stack+ direction="row"+ sx={{ alignItems: "flex-start", flex: 1, gap: "12px" }}+ >+ <InfoItemIconContainer>{icon}</InfoItemIconContainer>+ {children ? (+ <Box sx={{ flex: 1, mt: "4px" }}>{children}</Box>+ ) : (+ <Stack sx={{ flex: 1, mt: "4px", gap: "4px" }}>+ <Typography sx={{ wordBreak: "break-all" }}>{title}</Typography><Typographyvariant="small"- sx={{ color: "text.muted", wordBreak: "break-word" }}+ {...(typeof caption != "string" && { component: "div" })}+ sx={{ color: "text.muted" }}>{caption}</Typography>+ </Stack>+ )}+ {trailingButton}+ </Stack>+);++const InfoItemIconContainer = styled("div")(+ ({ theme }) => `+ width: 48px;+ aspect-ratio: 1;+ display: flex;+ justify-content: center;+ align-items: center;+ color: ${theme.vars.palette.stroke.muted}+`,+);++const CreationTime: React.FC<{ file: EnteFile }> = ({ file }) => {+ const date = fileCreationPhotoDate(file);+ return (+ <InfoItem+ icon={<CalendarTodayIcon />}+ title={formattedDate(date)}+ caption={formattedTime(date)}+ />+ );+};++const FileName: React.FC<{+ file: EnteFile;+ annotatedExif: FileInfoAnnotatedExif | undefined;+}> = ({ file, annotatedExif }) => {+ const icon =+ file.metadata.fileType === FileType.video ? (+ <VideocamOutlinedIcon />+ ) : (+ <PhotoOutlinedIcon />+ );+ const fileSize = file.info?.fileSize;++ return (+ <InfoItem+ icon={icon}+ title={fileFileName(file)}+ caption={createMultipartCaption(+ annotatedExif?.megaPixels,+ annotatedExif?.resolution,+ fileSize ? formattedByteSize(fileSize) : undefined,)}- </Stack>- {action}+ />+ );+};++const createMultipartCaption = (+ p1: string | undefined,+ p2: string | undefined,+ p3: string | undefined,+) => (+ <Stack direction="row" sx={{ gap: 1, flexWrap: "wrap" }}>+ {p1 && <div>{p1}</div>}+ {p2 && <div>{p2}</div>}+ {p3 && <div>{p3}</div>}</Stack>);-const IconContainer = styled("div")(({ theme }) => ({- display: "flex",- alignItems: "center",- justifyContent: "center",- color: theme.vars.palette.text.muted,- paddingTop: "2px",-}));+const openStreetMapLink = ({ latitude, longitude }: Location) =>+ `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}#map=15/${latitude}/${longitude}`;++interface RawExifProps {+ open: boolean;+ onClose: () => void;+ onInfoClose: () => void;+ tags: RawExifTags | undefined;+ fileName: string;+}++const RawExif: React.FC<RawExifProps> = ({+ open,+ onClose,+ onInfoClose,+ tags,+ fileName,+}) => {+ if (!tags) return <></>;++ const handleRootClose = () => {+ onClose();+ onInfoClose();+ };++ const items: (readonly [string, string, string, string])[] = Object.entries(+ tags,+ )+ .map(([namespace, namespaceTags]) =>+ Object.entries(namespaceTags).map(([tagName, tag]) => {+ const key = `${namespace}:${tagName}`;+ let description = "<...>";+ if (typeof tag == "string") {+ description = tag;+ } else if (typeof tag == "number") {+ description = `${tag}`;+ } else if (+ tag &&+ typeof tag == "object" &&+ "description" in tag &&+ typeof tag.description == "string"+ ) {+ description = tag.description;+ }++ return [key, namespace, tagName, description] as const;+ }),+ )+ .flat()+ .filter(([, , , description]) => description);++ return (+ <FileInfoSidebar open={open} onClose={onClose}>+ <SidebarDrawerTitlebar+ onClose={onClose}+ onRootClose={handleRootClose}+ title={t("exif")}+ caption={fileName}+ actionButton={+ <CopyButton size="small" text={JSON.stringify(tags)} />+ }+ />+ <Stack sx={{ gap: 2, py: 3, px: 1 }}>+ {items.map(([key, namespace, tagName, description]) => (+ <ExifItem key={key}>+ <Stack direction="row" sx={{ gap: 1 }}>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {tagName}+ </Typography>+ <Typography+ variant="tiny"+ sx={{ color: "text.faint" }}+ >+ {namespace}+ </Typography>+ </Stack>+ <EllipsizedTypography sx={{ width: "100%" }}>+ {description}+ </EllipsizedTypography>+ </ExifItem>+ ))}+ </Stack>+ </FileInfoSidebar>+ );+};++const ExifItem = styled("div")`+ padding-left: 8px;+ padding-right: 8px;+ display: flex;+ flex-direction: column;+ gap: 4px;+`;diff --git a/web/apps/albums/vendor/ente-gallery/components/Upload.tsx b/web/apps/albums/vendor/ente-gallery/components/Upload.tsxdeleted file mode 100644index 7f723875cf..0000000000--- a/web/apps/albums/vendor/ente-gallery/components/Upload.tsx+++ /dev/null@@ -1,7 +0,0 @@-/**- * The upload can be triggered by different buttons and flows in the UI, each of- * which is referred to as an "intent".- *- * The "intent" does not change the eventual upload outcome, only the UX flow.- */-export type UploadTypeSelectorIntent = "upload" | "import" | "collect";diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsxindex 1eb3f6b610..fe0957002e 100644--- a/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx+++ b/web/apps/albums/vendor/ente-gallery/components/viewer/FileViewer.tsx@@ -1,44 +1,27 @@-import { Navigation03Icon } from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";-import AddIcon from "@mui/icons-material/Add";-import ArchiveOutlinedIcon from "@mui/icons-material/ArchiveOutlined";import ContentCopyIcon from "@mui/icons-material/ContentCopy";-import DeleteIcon from "@mui/icons-material/Delete";-import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";import FullscreenExitOutlinedIcon from "@mui/icons-material/FullscreenExitOutlined";import FullscreenOutlinedIcon from "@mui/icons-material/FullscreenOutlined";-import UnArchiveIcon from "@mui/icons-material/Unarchive";import {Dialog,DialogContent,DialogTitle,Menu,MenuItem,- Stack,styled,Typography,- type ModalProps,} from "@mui/material";-import type { LocalUser } from "ente-accounts/services/user";import { SpacedRow } from "ente-base/components/containers";-import { InlineErrorIndicator } from "ente-base/components/ErrorIndicator";-import { TitledMiniDialog } from "ente-base/components/MiniDialog";import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { LoadingButton } from "ente-base/components/mui/LoadingButton";import { useInterval, useIsSmallWidth } from "ente-base/components/utils/hooks";import { type ModalVisibilityProps } from "ente-base/components/utils/modal";import { useBaseContext } from "ente-base/context";import type { PublicAlbumsCredentials } from "ente-base/http";import { formattedListJoin, ut } from "ente-base/i18n";import log from "ente-base/log";-import { isOfficialAlbumsApp } from "ente-base/origins";import {FileInfo,type FileInfoExif,- type FileInfoProps,} from "ente-gallery/components/FileInfo";-import { ItemVisibility } from "ente-media/file-metadata";import { FileType } from "ente-media/file-type";import type { EnteFile } from "ente-media/file.js";import {@@ -50,31 +33,18 @@ import {getPublicSocialDiff,getStoredAnonIdentity,} from "ente-new/albums/services/public-reaction";-import { getCollectionByID } from "ente-new/photos/services/collection";-import type { CollectionSummaries } from "ente-new/photos/services/collection-summary";import { type Comment } from "ente-new/photos/services/comment";-import { addReaction, deleteReaction } from "ente-new/photos/services/reaction";-import {- getAnonProfiles,- getUnifiedSocialDiff,- type UnifiedReaction,-} from "ente-new/photos/services/social";+import { type UnifiedReaction } from "ente-new/photos/services/social";import { t } from "i18next";import React, {useCallback,useEffect,- useMemo,useRef,useState,} from "react";import { AddNameModal } from "./AddNameModal";import { CommentsSidebar } from "./CommentsSidebar";-import {- fileInfoExifForFile,- updateItemDataAlt,- type ItemData,-} from "./data-source";-import { LikeAlbumSelectorModal } from "./LikeAlbumSelectorModal";+import { fileInfoExifForFile, type ItemData } from "./data-source";import { LikesSidebar } from "./LikesSidebar";import {FileViewerPhotoSwipe,@@ -107,44 +77,12 @@ const hasFileViewerBackStateMarker = (state: unknown, marker: string) =>* This is recomputed on-demand each time the slide changes.*/export interface FileViewerFileAnnotation {- /**- * The id of the file whose annotation this is.- */fileID: number;- /**- * `true` if this file is owned by the logged in user (if any).- */- isOwnFile: boolean;- /**- * `true` if the toggle favorite action should be shown for this file.- */showFavorite: boolean;- /**- * Set if the download action should be shown for this file.- *- * - When "bar", the action button is shown among the bar icons.- *- * - When "menu", the action is shown as a more menu entry.- *- * Note: "bar" should only be set if {@link haveUser} is also true.- */- showDownload: "bar" | "menu" | undefined;- /**- * `true` if the delete action should be shown for this file.- */+ showDownload: "bar" | undefined;showDelete: boolean;- /**- * `true` if the toggle archive action should be shown for this file.- */showArchive: boolean;- /**- * `true` if the copy image action should be shown for this file.- */showCopyImage: boolean;- /**- * `true` if this is an image which can be edited, _and_ editing is- * possible, and the edit action should therefore be shown for this file.- */}/**@@ -160,232 +98,22 @@ export interface FileViewerAnnotatedFile {export type FileViewerInitialSidebar = "likes" | "comments";export type FileViewerProps = ModalVisibilityProps & {- /**- * The currently logged in user, if any.- *- * - If we're running in the context of the photos app, then this should be- * set to the currently logged in user.- *- * - If we're running in the context of the public albums app, then this- * should not be set.- *- * See: [Note: Gallery children can assume user]- */- user?: LocalUser;- /**- * The list of files that are currently being displayed in the context in- * which the file viewer was invoked.- *- * Although the file viewer is called on to display a particular file- * (specified by the {@link initialIndex} prop), the viewer is always used- * in the context of a an album, or search results, or some other arbitrary- * list of files. The {@link files} prop sets this underlying list of files.- *- * After the initial file has been shown, the user can navigate through the- * other files from within the viewer by using the arrow buttons.- */files: EnteFile[];- /**- * The index of the file that should be initially shown.- *- * Subsequently the user may navigate between files by using the controls- * provided within the file viewer itself.- */initialIndex: number;- /**- * If set, the specified sidebar will be opened when the file viewer opens.- */initialSidebar?: FileViewerInitialSidebar;- /**- * If set, the comments sidebar will scroll to and highlight this comment.- * Only used when initialSidebar is "comments".- */highlightCommentID?: string;- /**- * If true then the viewer does not show controls for downloading the file.- */disableDownload?: boolean;- /**- * If true then the fullscreen button is shown as a primary action button- * in the toolbar instead of being hidden in the more menu.- */showFullscreenButton?: boolean;- /**- * `true` when we are viewing files in an album that the user does not own.- */- isInIncomingSharedCollection?: boolean;- /**- * `true` when we are viewing files in the Trash.- */- isInTrashSection?: boolean;- /**- * `true` when we are viewing files in the hidden section.- */- isInHiddenSection?: boolean;- /**- * File IDs of all the files that the user has marked as a favorite.- *- * See also {@link onToggleFavorite}.- */- favoriteFileIDs?: Set<number>;- /**- * File IDs of for which an update of its favorite status is pending (e.g.- * due to a toggle favorite action in the file viewer).- *- * See also {@link favoriteFileIDs} and {@link onToggleFavorite}.- */- pendingFavoriteUpdates?: Set<number>;- /**- * File IDs of for which an update of its visibility is pending (e.g. due to- * a toggle archived action in the file viewer).- *- * See also {@link onFileVisibilityUpdate}.- */- pendingVisibilityUpdates?: Set<number>;- /**- * A mapping from file IDs to the IDs of the normal (non-hidden) collections- * that they are a part of.- */- fileNormalCollectionIDs?: FileInfoProps["fileCollectionIDs"];- /**- * Collection summaries indexed by their IDs.- */- collectionSummaries?: CollectionSummaries;- /**- * Called when there was some update performed within the file viewer that- * necessitates us to pull the latest updates with remote.- *- * This is called when the file viewer is closing if any changes were made- * in the file info panel of the file viewer for any of the files that the- * user was viewing (e.g. if they changed the caption).- *- * Those changes have already been applied to both remote, and likely- * already also to our local state via {@link onRemoteFilesPull}. This this- * callback is to trigger a full pull so that any discrepancies in local- * database also gets up to speed if needed.- *- * If we're in a context where edits are not possible, e.g. {@link user} is- * not defined, then this prop is not used and need not be provided.- */- onTriggerRemotePull?: () => void;- /**- * Called when an action in the file viewer requires us to pull the local- * files and collections with remote.- *- * Unlike {@link onTriggerRemotePull}, which is a trigger, this function- * returns a promise that will settle once the pull has completed, and thus- * can be used in interactive operations that indicate activity to the user.- *- * See also: [Note: Full remote pull vs files pull]- */- onRemoteFilesPull?: () => Promise<void>;- /**- * Called when the user performs an action which does not otherwise have any- * immediate visual impact, to acknowledge it.- *- * See: [Note: Visual feedback to acknowledge user actions]- */- onVisualFeedback: () => void;- /**- * Called when the favorite status of given {@link file} should be toggled- * from its current value.- *- * The favorite toggle button is shown only if all three of- * {@link favoriteFileIDs}, {@link pendingFavoriteUpdates} and- * {@link onToggleFavorite} are provided.- */- onToggleFavorite?: (file: EnteFile) => Promise<void>;- /**- * Called when {@link visibility} of the given {@link file} should be- * updated (when the user activates toggle archived action).- *- * The toggle archived action is shown only if both- * {@link pendingVisibilityUpdates} and {@link onFileVisibilityUpdate} are- * provided.- */- onFileVisibilityUpdate?: (- file: EnteFile,- visibility: ItemVisibility,- ) => Promise<void>;- /**- * Called when the given {@link file} should be downloaded.- *- * If this is not provided then the download action will not be shown.- */onDownload?: (file: EnteFile) => void;- /**- * Called when the given {@link file} should be shared via quick link.- *- * If this is not provided then the send link action will not be shown.- */- onSendLink?: (file: EnteFile) => void;- /**- * Called when the given {@link file} should be deleted.- *- * If this is not provided then the delete action will not be shown.- */- onDelete?: (file: EnteFile) => Promise<void>;- onAddFileToCollection?: (- file: EnteFile,- sourceCollectionSummaryID?: number,- ) => void;- /**- * The ID of the currently active collection, if any (e.g., when viewing an album).- */activeCollectionID?: number;- /**- * Public album credentials for anonymous reactions/comments.- * Required when viewing a public album (no logged in user).- */publicAlbumsCredentials?: PublicAlbumsCredentials;- /**- * If set, overrides whether browser back should be consumed to close the- * viewer.- *- * By default this is enabled in public album context, and disabled- * otherwise.- */shouldCloseOnBrowserBack?: boolean;- /**- * If `true`, disables closing the viewer with the Escape key.- */disableEscapeClose?: boolean;- /**- * The decrypted collection key (base64 encoded) for encrypting reactions.- * Required when viewing a public album (no logged in user).- */collectionKey?: string;- /**- * Called when user clicks "Join album to like" in the public like modal.- * Should trigger the join album flow (with mobile deep link fallback).- */onJoinAlbum?: () => void;- /**- * `true` if comments are enabled on the public link.- *- * When `false`, the comment button and comments sidebar will be hidden.- * Defaults to `true`.- */enableComment?: boolean;- /**- * `true` if the comments and reactions feature is enabled for the user.- *- * When `false`, the like and comment buttons will be hidden for logged-in- * users. Defaults to `true`.- */- isCommentsFeatureEnabled?: boolean;- /**- * `true` if the "Join album" option is enabled for this public link.- *- * When `false`, the "Join album and like/comment" button will be hidden- * in the public like/comment modals.- * Defaults to `true`.- */enableJoin?: boolean;-} & Pick<- FileInfoProps,- "collectionNameByID" | "onSelectCollection" | "onSelectPerson"- >;+};/*** A PhotoSwipe based image, live photo and video viewer.@@ -393,33 +121,13 @@ export type FileViewerProps = ModalVisibilityProps & {export const FileViewer: React.FC<FileViewerProps> = ({open,onClose,- user,files,initialIndex,initialSidebar,highlightCommentID,disableDownload,showFullscreenButton,- isInIncomingSharedCollection,- isInTrashSection,- isInHiddenSection,- favoriteFileIDs,- pendingFavoriteUpdates,- pendingVisibilityUpdates,- fileNormalCollectionIDs,- collectionSummaries,- collectionNameByID,- onTriggerRemotePull,- onRemoteFilesPull,- onVisualFeedback,- onToggleFavorite,- onFileVisibilityUpdate,onDownload,- onSendLink,- onDelete,- onSelectCollection,- onSelectPerson,- onAddFileToCollection,activeCollectionID,publicAlbumsCredentials,shouldCloseOnBrowserBack: shouldCloseOnBrowserBackOverride,@@ -427,12 +135,10 @@ export const FileViewer: React.FC<FileViewerProps> = ({collectionKey,onJoinAlbum,enableComment = true,- isCommentsFeatureEnabled = true,enableJoin = true,}) => {const { onGenericError } = useBaseContext();- const shouldCloseOnBrowserBack =- shouldCloseOnBrowserBackOverride ?? !!publicAlbumsCredentials;+ const shouldCloseOnBrowserBack = shouldCloseOnBrowserBackOverride ?? true;// There are 3 things involved in this dance://@@ -478,12 +184,10 @@ export const FileViewer: React.FC<FileViewerProps> = ({const [openFileInfo, setOpenFileInfo] = useState(false);const [openComments, setOpenComments] = useState(false);const [openLikes, setOpenLikes] = useState(false);- const [openLikeAlbumSelector, setOpenLikeAlbumSelector] = useState(false);const [openPublicLikeModal, setOpenPublicLikeModal] = useState(false);const [openAddNameModal, setOpenAddNameModal] = useState(false);const [moreMenuAnchorEl, setMoreMenuAnchorEl] =useState<HTMLElement | null>(null);- const [openConfirmDelete, setOpenConfirmDelete] = useState(false);const [openShortcuts, setOpenShortcuts] = useState(false);const [isFullscreen, setIsFullscreen] = useState(false);@@ -512,44 +216,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({new Map(),);- // Ref for fileComments to use in callbacks- const fileCommentsRef = useRef(fileComments);- useEffect(() => {- fileCommentsRef.current = fileComments;- }, [fileComments]);-// Ref for allReactions to use in callbacksconst allReactionsRef = useRef(allReactions);useEffect(() => {allReactionsRef.current = allReactions;}, [allReactions]);- // Ref for collectionSummaries to use in callbacks without causing recreations- const collectionSummariesRef = useRef(collectionSummaries);- useEffect(() => {- collectionSummariesRef.current = collectionSummaries;- }, [collectionSummaries]);-- // Ref for fileNormalCollectionIDs to use in callbacks without causing recreations- const fileNormalCollectionIDsRef = useRef(fileNormalCollectionIDs);- useEffect(() => {- fileNormalCollectionIDsRef.current = fileNormalCollectionIDs;- }, [fileNormalCollectionIDs]);-- // Cache for collection keys to avoid refetching during polling- const collectionCacheRef = useRef<- Map<- number,- {- key: string;- ownerID: number;- ownerEmail?: string;- sharees: { id: number; email?: string }[];- hasPublicURLs: boolean;- }- >- >(new Map());-// Track whether we've already opened the initial sidebar for this openconst hasOpenedInitialSidebarRef = useRef(false);@@ -569,76 +241,19 @@ export const FileViewer: React.FC<FileViewerProps> = ({}}, [open, initialSidebar]);- // Helper to get current user's file reactions from allReactions- const getUserFileReactions = useCallback(- (fileId: number): { collectionId: number; reactionId: string }[] => {- const fileReactionsMap = allReactionsRef.current.get(fileId);- if (!fileReactionsMap) return [];-- const userReactions: {- collectionId: number;- reactionId: string;- }[] = [];- for (const [collectionId, reactions] of fileReactionsMap) {- // Get stored anonymous identity for this specific collection- const storedAnonIdentity = getStoredAnonIdentity(collectionId);-- const userFileReaction = reactions.find((r) => {- if (- r.commentID ||- r.fileID !== fileId ||- r.reactionType !== "green_heart"- )- return false;- // Check for logged-in user- if (user?.id && r.userID === user.id) return true;- // Check for anonymous user- if (- storedAnonIdentity &&- r.anonUserID === storedAnonIdentity.anonUserID- )- return true;- return false;- });- if (userFileReaction) {- userReactions.push({- collectionId,- reactionId: userFileReaction.id,- });- }- }- return userReactions;- },- [user?.id],- );-- // If `true`, then we need to trigger a pull from remote when we close.- const [, setNeedsRemotePull] = useState(false);-- const handleNeedsRemotePull = useCallback(- () => setNeedsRemotePull(true),- [],- );-const handleClose = useCallback(() => {if (document.fullscreenElement) void document.exitFullscreen();- setNeedsRemotePull((needsPull) => {- if (needsPull) onTriggerRemotePull?.();- return false;- });setOpenFileInfo(false);setOpenComments(false);setOpenLikes(false);- setOpenLikeAlbumSelector(false);setOpenPublicLikeModal(false);// No need to `resetMoreMenuButtonOnMenuClose` since we're closing// anyway and it'll be removed from the DOM.setMoreMenuAnchorEl(null);- setOpenConfirmDelete(false);setOpenShortcuts(false);setIsFullscreen(false);onClose();- }, [onTriggerRemotePull, onClose]);+ }, [onClose]);// Keep the latest close callback available to non-react event handlers// without forcing effects that register handlers to re-run.@@ -768,440 +383,83 @@ export const FileViewer: React.FC<FileViewerProps> = ({const activeAnnotatedFileRef = useRef(activeAnnotatedFile);activeAnnotatedFileRef.current = activeAnnotatedFile;- const isPublicAlbum = isOfficialAlbumsApp || !!publicAlbumsCredentials;+ const haveUser = false;+ const isPublicAlbum = true;- // Called when the like button (heart) is clicked.- // - If public album: toggle like (unlike if already liked, else show modal)- // - If gallery view: show album selector (like) OR unlike selector/direct delete- // - If collection view: toggle like in that collection+ // Called when the like button (heart) is clicked in public album mode.const handleLikeClick = useCallback(() => {- if (isPublicAlbum) {- const file = activeAnnotatedFileRef.current?.file;- if (!file || !publicAlbumsCredentials) {- setOpenPublicLikeModal(true);- return;- }-- const fileId = file.id;- const collectionId = file.collectionID;- const storedAnonIdentity = getStoredAnonIdentity(collectionId);-- // Check if already liked by current anon user (file-level only, not comment likes)- const fileReactionsMap = allReactionsRef.current.get(fileId);- const collectionReactions =- fileReactionsMap?.get(collectionId) ?? [];- const existingReaction = collectionReactions.find(- (r) =>- r.reactionType === "green_heart" &&- !r.commentID &&- storedAnonIdentity &&- r.anonUserID === storedAnonIdentity.anonUserID,- );-- if (existingReaction) {- // Already liked - unlike (delete reaction)- void (async () => {- try {- await deletePublicReaction(- publicAlbumsCredentials,- collectionId,- existingReaction.id,- );-- // Update local state- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<- number,- UnifiedReaction[]- >(prev.get(fileId) ?? new Map());- const updatedReactions = (- fileReactionsMap.get(collectionId) ?? []- ).filter((r) => r.id !== existingReaction.id);- fileReactionsMap.set(- collectionId,- updatedReactions,- );- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to delete public reaction", e);- }- })();- } else if (storedAnonIdentity) {- // Has identity but not liked - add reaction directly- void (async () => {- try {- if (!collectionKey) {- log.error(- "Missing collection key for public reaction",- );- return;- }- const reactionId = await addPublicReaction(- publicAlbumsCredentials,- collectionId,- fileId,- "green_heart",- collectionKey,- );-- // Update local state- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<- number,- UnifiedReaction[]- >(prev.get(fileId) ?? new Map());- const collectionReactions =- fileReactionsMap.get(collectionId) ?? [];- fileReactionsMap.set(collectionId, [- ...collectionReactions,- {- id: reactionId,- collectionID: collectionId,- fileID: fileId,- reactionType: "green_heart",- userID: 0,- anonUserID: storedAnonIdentity.anonUserID,- isDeleted: false,- createdAt: Date.now() * 1000,- updatedAt: Date.now() * 1000,- },- ]);- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to add public reaction", e);- }- })();- } else {- // No identity - show modal to get name- setOpenPublicLikeModal(true);- }+ const file = activeAnnotatedFileRef.current?.file;+ if (!file || !publicAlbumsCredentials) {+ setOpenPublicLikeModal(true);return;}- const file = activeAnnotatedFileRef.current?.file;- if (!file) return;-const fileId = file.id;- const reactions = getUserFileReactions(fileId);- const isGalleryView = !activeCollectionID || activeCollectionID === 0;-- if (isGalleryView) {- // Gallery view - only consider shared collections- const allCollectionIDs =- fileNormalCollectionIDsRef.current?.get(fileId) ?? [];- const collectionIDs = allCollectionIDs.filter((id) =>- collectionSummariesRef.current- ?.get(id)- ?.attributes.has("shared"),- );-- if (reactions.length === 0) {- // Not liked in any collection- if (collectionIDs.length === 1) {- // Single album - like directly without showing modal- const collectionId = collectionIDs[0]!;- void (async () => {- try {- const collection =- await getCollectionByID(collectionId);- const reactionId = await addReaction(- collectionId,- fileId,- "green_heart",- collection.key,- );- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<- number,- UnifiedReaction[]- >(prev.get(fileId) ?? new Map());- const collectionReactions =- fileReactionsMap.get(collectionId) ?? [];- fileReactionsMap.set(collectionId, [- ...collectionReactions,- {- id: reactionId,- collectionID: collectionId,- fileID: fileId,- reactionType: "green_heart",- userID: user?.id ?? 0,- isDeleted: false,- createdAt: Date.now() * 1000,- updatedAt: Date.now() * 1000,- },- ]);- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to add reaction", e);- }- })();- } else {- // Multiple albums - show album selector- setOpenLikeAlbumSelector(true);- }- } else {- // Liked in one or more collections - unlike from all- void (async () => {- try {- const deletedReactionIds = new Set<string>();- for (const reaction of reactions) {- await deleteReaction(reaction.reactionId);- deletedReactionIds.add(reaction.reactionId);- }- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = prev.get(fileId);- if (fileReactionsMap) {- const updatedMap = new Map(fileReactionsMap);- for (const [- collectionId,- collectionReactions,- ] of updatedMap) {- updatedMap.set(- collectionId,- collectionReactions.filter(- (r) =>- !deletedReactionIds.has(r.id),- ),- );- }- next.set(fileId, updatedMap);- }- return next;- });- } catch (e) {- log.error("Failed to delete reactions", e);- }- })();- }- } else {- // Collection view - toggle like in this specific collection- const existingReaction = reactions.find(- (r) => r.collectionId === activeCollectionID,- );-- if (existingReaction) {- // Already liked in this collection - delete- void (async () => {- try {- await deleteReaction(existingReaction.reactionId);- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = prev.get(fileId);- if (fileReactionsMap) {- const updatedMap = new Map(fileReactionsMap);- const collectionReactions =- updatedMap.get(activeCollectionID) ?? [];- updatedMap.set(- activeCollectionID,- collectionReactions.filter(- (r) =>- r.id !==- existingReaction.reactionId,- ),- );- next.set(fileId, updatedMap);- }- return next;- });- } catch (e) {- log.error("Failed to delete reaction", e);- }- })();- } else {- // Not liked in this collection - add- void (async () => {- try {- const collection =- await getCollectionByID(activeCollectionID);- const reactionId = await addReaction(- activeCollectionID,- fileId,- "green_heart",- collection.key,- );- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<- number,- UnifiedReaction[]- >(prev.get(fileId) ?? new Map());- const collectionReactions =- fileReactionsMap.get(activeCollectionID) ?? [];- fileReactionsMap.set(activeCollectionID, [- ...collectionReactions,- {- id: reactionId,- collectionID: activeCollectionID,- fileID: fileId,- reactionType: "green_heart",- userID: user?.id ?? 0,- isDeleted: false,- createdAt: Date.now() * 1000,- updatedAt: Date.now() * 1000,- },- ]);- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to add reaction", e);- }- })();- }- }- }, [- activeCollectionID,- getUserFileReactions,- user?.id,- isPublicAlbum,- publicAlbumsCredentials,- collectionKey,- ]);-- const handleLikeAlbumSelectorClose = useCallback(- () => setOpenLikeAlbumSelector(false),- [],- );-- const handleToggleAlbumLike = useCallback(- (albumId: number, isCurrentlyLiked: boolean) => {- const file = activeAnnotatedFileRef.current?.file;- if (!file) return;-- const fileId = file.id;+ const collectionId = file.collectionID;+ const storedAnonIdentity = getStoredAnonIdentity(collectionId);++ // Check if already liked by current anon user (file-level only, not comment likes)+ const fileReactionsMap = allReactionsRef.current.get(fileId);+ const collectionReactions = fileReactionsMap?.get(collectionId) ?? [];+ const existingReaction = collectionReactions.find(+ (r) =>+ r.reactionType === "green_heart" &&+ !r.commentID &&+ storedAnonIdentity &&+ r.anonUserID === storedAnonIdentity.anonUserID,+ );- if (isCurrentlyLiked) {- // Unlike - delete the reaction- const reactions = getUserFileReactions(fileId);- const reactionToDelete = reactions.find(- (r) => r.collectionId === albumId,- );+ if (existingReaction) {+ // Already liked - unlike (delete reaction)+ void (async () => {+ try {+ await deletePublicReaction(+ publicAlbumsCredentials,+ collectionId,+ existingReaction.id,+ );- if (reactionToDelete) {- void (async () => {- try {- await deleteReaction(reactionToDelete.reactionId);- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = prev.get(fileId);- if (fileReactionsMap) {- const updatedMap = new Map(- fileReactionsMap,- );- const collectionReactions =- updatedMap.get(albumId) ?? [];- updatedMap.set(- albumId,- collectionReactions.filter(- (r) =>- r.id !==- reactionToDelete.reactionId,- ),- );- next.set(fileId, updatedMap);- }- return next;- });- } catch (e) {- log.error("Failed to delete reaction", e);- }- })();+ // Update local state+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());+ const updatedReactions = (+ fileReactionsMap.get(collectionId) ?? []+ ).filter((r) => r.id !== existingReaction.id);+ fileReactionsMap.set(collectionId, updatedReactions);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to delete public reaction", e);}- } else {- // Like - add a reaction- void (async () => {- try {- const collection = await getCollectionByID(albumId);- const reactionId = await addReaction(- albumId,- fileId,- "green_heart",- collection.key,- );- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<- number,- UnifiedReaction[]- >(prev.get(fileId) ?? new Map());- const collectionReactions =- fileReactionsMap.get(albumId) ?? [];- fileReactionsMap.set(albumId, [- ...collectionReactions,- {- id: reactionId,- collectionID: albumId,- fileID: fileId,- reactionType: "green_heart",- userID: user?.id ?? 0,- isDeleted: false,- createdAt: Date.now() * 1000,- updatedAt: Date.now() * 1000,- },- ]);- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to add reaction", e);+ })();+ } else if (storedAnonIdentity) {+ // Has identity but not liked - add reaction directly+ void (async () => {+ try {+ if (!collectionKey) {+ log.error("Missing collection key for public reaction");+ return;}- })();- }- // Don't close - user might want to toggle more albums- },- [getUserFileReactions, user?.id],- );-- const handleLikeAll = useCallback(() => {- const file = activeAnnotatedFileRef.current?.file;- if (!file) return;-- const fileId = file.id;- const collectionIDs = fileNormalCollectionIDs?.get(fileId) ?? [];- const existingReactions = getUserFileReactions(fileId);- const likedCollectionIDs = new Set(- existingReactions.map((r) => r.collectionId),- );-- // Filter to only shared collections not already liked- const collectionsToLike = collectionIDs.filter(- (id) =>- !likedCollectionIDs.has(id) &&- collectionSummaries?.get(id)?.attributes.has("shared"),- );-- void (async () => {- try {- const newReactions: {- collectionId: number;- reactionId: string;- }[] = [];- for (const collectionId of collectionsToLike) {- const collection = await getCollectionByID(collectionId);- const reactionId = await addReaction(+ const reactionId = await addPublicReaction(+ publicAlbumsCredentials,collectionId,fileId,"green_heart",- collection.key,- );- newReactions.push({ collectionId, reactionId });- }- setAllReactions((prev) => {- const next = new Map(prev);- const fileReactionsMap = new Map<number, UnifiedReaction[]>(- prev.get(fileId) ?? new Map(),+ collectionKey,);- for (const { collectionId, reactionId } of newReactions) {++ // Update local state+ setAllReactions((prev) => {+ const next = new Map(prev);+ const fileReactionsMap = new Map<+ number,+ UnifiedReaction[]+ >(prev.get(fileId) ?? new Map());const collectionReactions =fileReactionsMap.get(collectionId) ?? [];fileReactionsMap.set(collectionId, [@@ -1211,27 +469,25 @@ export const FileViewer: React.FC<FileViewerProps> = ({collectionID: collectionId,fileID: fileId,reactionType: "green_heart",- userID: user?.id ?? 0,+ userID: 0,+ anonUserID: storedAnonIdentity.anonUserID,isDeleted: false,createdAt: Date.now() * 1000,updatedAt: Date.now() * 1000,},]);- }- next.set(fileId, fileReactionsMap);- return next;- });- } catch (e) {- log.error("Failed to add reactions", e);- }- })();- setOpenLikeAlbumSelector(false);- }, [- fileNormalCollectionIDs,- getUserFileReactions,- user?.id,- collectionSummaries,- ]);+ next.set(fileId, fileReactionsMap);+ return next;+ });+ } catch (e) {+ log.error("Failed to add public reaction", e);+ }+ })();+ } else {+ // No identity - show modal to get name+ setOpenPublicLikeModal(true);+ }+ }, [publicAlbumsCredentials, collectionKey]);const handlePublicLikeModalClose = useCallback(() => setOpenPublicLikeModal(false),@@ -1355,24 +611,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({[onDownload],);- // Callback invoked when the download action is triggered by activating the- // download menu item in the more menu.- //- // Not memoized since it uses the frequently changing `activeAnnotatedFile`.- const handleDownloadMenuAction = () => {- handleMoreMenuCloseIfNeeded();- onDownload!(activeAnnotatedFile!.file);- };-- // Callback invoked when the send link action is triggered by activating the- // send link menu item in the more menu.- //- // Not memoized since it uses the frequently changing `activeAnnotatedFile`.- const handleSendLinkMenuAction = () => {- handleMoreMenuCloseIfNeeded();- onSendLink!(activeAnnotatedFile!.file);- };-const handleMore = useCallback((buttonElement: HTMLElement) => setMoreMenuAnchorEl(buttonElement),[],@@ -1385,27 +623,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({});}, []);- const handleConfirmDelete = useMemo(() => {- return onDelete- ? () => {- handleMoreMenuCloseIfNeeded();- setOpenConfirmDelete(true);- }- : undefined;- }, [onDelete, handleMoreMenuCloseIfNeeded]);-- const handleConfirmDeleteClose = useCallback(- () => setOpenConfirmDelete(false),- [],- );-- // Not memoized since it uses the frequently changing `activeAnnotatedFile`.- const handleDelete = async () => {- const file = activeAnnotatedFile!.file;- await onDelete!(file);- handleNeedsRemotePull();- };-// Not memoized since it uses the frequently changing `activeAnnotatedFile`.const handleCopyImage = useCallback(() => {handleMoreMenuCloseIfNeeded();@@ -1424,53 +641,11 @@ export const FileViewer: React.FC<FileViewerProps> = ({.catch(onGenericError);}, [onGenericError, handleMoreMenuCloseIfNeeded, activeAnnotatedFile]);- const handleAddFileToCollection = useMemo(() => {- if (!onAddFileToCollection || !activeAnnotatedFile) return undefined;- return () => {- handleMoreMenuCloseIfNeeded();- const sourceSummaryID = fileNormalCollectionIDs- ?.get(activeAnnotatedFile.file.id)- ?.find((id) => id === activeCollectionID);- onAddFileToCollection(activeAnnotatedFile.file, sourceSummaryID);- };- }, [- onAddFileToCollection,- handleMoreMenuCloseIfNeeded,- fileNormalCollectionIDs,- activeAnnotatedFile,- activeCollectionID,- ]);-const handleAnnotate = useCallback((file: EnteFile, itemData: ItemData): FileViewerAnnotatedFile => {const fileID = file.id;- const isOwnFile = file.ownerID == user?.id;-- const canModify =- isOwnFile && !isInTrashSection && !isInHiddenSection;-- const showFavorite = canModify;-- const showArchive = canModify;-- const showDelete =- !!handleConfirmDelete &&- isOwnFile &&- !isInTrashSection &&- !isInIncomingSharedCollection;-- const showDownload = (() => {- if (disableDownload) return undefined;- if (!onDownload) return undefined;- if (user) {- // Logged in users see the download option in the more menu.- return "menu";- } else {- // In public albums, the download option is shown in the bar- // buttons, in lieu of the favorite option.- return "bar";- }- })();+ const showDownload =+ disableDownload || !onDownload ? undefined : "bar";const showCopyImage = (() => {if (disableDownload) return false;@@ -1485,11 +660,10 @@ export const FileViewer: React.FC<FileViewerProps> = ({const annotation: FileViewerFileAnnotation = {fileID,- isOwnFile,- showFavorite,+ showFavorite: false,showDownload,- showDelete,- showArchive,+ showDelete: false,+ showArchive: false,showCopyImage,};@@ -1497,186 +671,23 @@ export const FileViewer: React.FC<FileViewerProps> = ({setActiveAnnotatedFile(annotatedFile);return annotatedFile;},- [- user,- disableDownload,- isInIncomingSharedCollection,- isInTrashSection,- isInHiddenSection,- onDownload,- handleConfirmDelete,- ],- );-- const handleSelectCollection = useMemo(() => {- return onSelectCollection- ? (collectionID: number) => {- onSelectCollection(collectionID);- handleClose();- }- : undefined;- }, [onSelectCollection, handleClose]);-- const handleSelectPerson = useMemo(() => {- return onSelectPerson- ? (personID: string) => {- onSelectPerson(personID);- handleClose();- }- : undefined;- }, [onSelectPerson, handleClose]);-- const haveUser = !!user;-- // Determine if social buttons (like, comment) should be shown.- // They're shown for public albums or when viewing a shared collection.- const showSocialButtons = useMemo(() => {- // Show for public albums (no logged-in user).- if (!haveUser) return true;- // For logged-in users, check if the comments feature is enabled.- if (!isCommentsFeatureEnabled) return false;- // In collection view: check if that specific collection is shared.- if (- activeCollectionID &&- activeCollectionID !== 0 &&- collectionSummaries- ) {- const collectionSummary =- collectionSummaries.get(activeCollectionID);- if (collectionSummary?.attributes.has("shared")) return true;- }- return false;- }, [- haveUser,- isCommentsFeatureEnabled,- activeCollectionID,- collectionSummaries,- ]);-- // Check if a file belongs to any shared collection (for gallery view).- const isFileInSharedCollection = useCallback(- (fileID: number): boolean => {- if (!collectionSummaries || !fileNormalCollectionIDs) return false;- const collectionIDs = fileNormalCollectionIDs.get(fileID) ?? [];- return collectionIDs.some((collectionID) => {- const summary = collectionSummaries.get(collectionID);- return summary?.attributes.has("shared");- });- },- [collectionSummaries, fileNormalCollectionIDs],+ [disableDownload, onDownload],);+ const showSocialButtons = true;// Delegate callback to check if social buttons should be shown for a file.const shouldShowSocialButtons_ = useCallback(- ({ file }: FileViewerAnnotatedFile): boolean => {- // If showSocialButtons is already true (public album or in shared- // collection view), this won't be called. This callback is only- // for gallery view where we need to check per-file.- //- // For logged-in users, require the comments feature to be enabled.- if (!isCommentsFeatureEnabled) return false;- //- // If we're in a specific collection context (not gallery view),- // return false - the collection's shared status is what matters,- // not whether the file happens to be in some other shared album.- const isGalleryView =- !activeCollectionID || activeCollectionID === 0;- if (!isGalleryView) return false;-- return isFileInSharedCollection(file.id);- },- [- isCommentsFeatureEnabled,- isFileInSharedCollection,- activeCollectionID,- ],+ (): boolean => false,+ [],);- // Compute shared albums the file belongs to and which are liked for the modal- const { allAlbumsForFile, likedAlbumIDs } = useMemo(() => {- const file = activeAnnotatedFile?.file;- if (!file)- return { allAlbumsForFile: [], likedAlbumIDs: new Set<number>() };-- // Get all collections the file belongs to, filtered to only shared ones- const collectionIDs = fileNormalCollectionIDs?.get(file.id) ?? [];- const allAlbumsForFile = collectionIDs- .filter((id) =>- collectionSummaries?.get(id)?.attributes.has("shared"),- )- .map((id) => ({- id,- name: collectionNameByID?.get(id) ?? `Album ${id}`,- }));-- // Get the set of liked album IDs from allReactions- const fileReactionsMap = allReactions.get(file.id);- const likedAlbumIDs = new Set<number>();-- if (fileReactionsMap) {- for (const [collectionId, reactions] of fileReactionsMap) {- // Get stored anonymous identity for this specific collection- const storedAnonIdentity = getStoredAnonIdentity(collectionId);-- const hasUserLike = reactions.some((r) => {- if (r.commentID || r.reactionType !== "green_heart")- return false;- // Check for logged-in user- if (user?.id && r.userID === user.id) return true;- // Check for anonymous user- if (- storedAnonIdentity &&- r.anonUserID === storedAnonIdentity.anonUserID- )- return true;- return false;- });- if (hasUserLike) {- likedAlbumIDs.add(collectionId);- }- }- }-- return { allAlbumsForFile, likedAlbumIDs };- }, [- activeAnnotatedFile,- collectionNameByID,- collectionSummaries,- fileNormalCollectionIDs,- allReactions,- user?.id,- ]);-const getFiles = useCallback(() => files, [files]);- const isFavorite = useCallback(- ({ file }: FileViewerAnnotatedFile) => {- if (- !haveUser ||- !favoriteFileIDs ||- !pendingFavoriteUpdates ||- !onToggleFavorite- ) {- return undefined;- }- return favoriteFileIDs.has(file.id);- },- [haveUser, favoriteFileIDs, pendingFavoriteUpdates, onToggleFavorite],- );+ const isFavorite = useCallback(() => undefined, []);- const isFavoritePending = useCallback(- ({ file }: FileViewerAnnotatedFile) =>- !!pendingFavoriteUpdates?.has(file.id),- [pendingFavoriteUpdates],- );+ const isFavoritePending = useCallback(() => false, []);- const toggleFavorite = useCallback(- ({ file }: FileViewerAnnotatedFile) =>- onToggleFavorite!(file)- .catch(onGenericError)- .finally(handleNeedsRemotePull),- [onToggleFavorite, onGenericError, handleNeedsRemotePull],- );+ const toggleFavorite = useCallback(async () => undefined, []);const isLiked = useCallback(({ file }: FileViewerAnnotatedFile) => {@@ -1691,8 +702,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({const hasUserLike = reactions.some((r) => {if (r.commentID || r.reactionType !== "green_heart")return false;- // Check for logged-in user- if (user?.id && r.userID === user.id) return true;// Check for anonymous userif (storedAnonIdentity &&@@ -1705,7 +714,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({}return false;},- [allReactions, user?.id],+ [allReactions],);const getCommentCount = useCallback(@@ -1758,10 +767,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({openFileInfo ||openComments ||openLikes ||- openLikeAlbumSelector ||openPublicLikeModal ||!!moreMenuAnchorEl ||- openConfirmDelete ||openShortcuts) {return true;@@ -1790,10 +797,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({openFileInfo,openComments,openLikes,- openLikeAlbumSelector,openPublicLikeModal,moreMenuAnchorEl,- openConfirmDelete,openShortcuts,]);@@ -1804,73 +809,14 @@ export const FileViewer: React.FC<FileViewerProps> = ({[activeAnnotatedFile],);- const { isArchived, isPendingToggleArchive, toggleArchived } =- useMemo(() => {- let isArchived: boolean | undefined;- let isPendingToggleArchive: boolean | undefined;- let toggleArchived: (() => void) | undefined;-- const file = activeAnnotatedFile?.file;-- if (- pendingVisibilityUpdates &&- onFileVisibilityUpdate &&- file &&- activeAnnotatedFile.annotation.showArchive- ) {- switch (file.magicMetadata?.data.visibility) {- case undefined:- case ItemVisibility.visible:- isArchived = false;- break;- case ItemVisibility.archived:- isArchived = true;- break;- }-- isPendingToggleArchive = pendingVisibilityUpdates.has(file.id);-- toggleArchived = () => {- handleMoreMenuCloseIfNeeded();- void onFileVisibilityUpdate(- file,- isArchived- ? ItemVisibility.visible- : ItemVisibility.archived,- )- .then(handleNeedsRemotePull)- .catch(onGenericError);- };- }-- return { isArchived, isPendingToggleArchive, toggleArchived };- }, [- pendingVisibilityUpdates,- onFileVisibilityUpdate,- onGenericError,- handleNeedsRemotePull,- handleMoreMenuCloseIfNeeded,- activeAnnotatedFile,- ]);-const performKeyAction = useCallback<FileViewerPhotoSwipeDelegate["performKeyAction"]>((action) => {switch (action) {case "delete":- if (activeAnnotatedFile?.annotation.showDelete)- handleConfirmDelete?.();break;case "toggle-archive":- if (!isPendingToggleArchive) {- // Provide extra visual feedback when the toggle archive- // action is invoked via a keyboard shortcut since there- // is no corresponding screen control visible (the more- // menu might not be visible).- onVisualFeedback();- toggleArchived?.();- }break;case "copy":if (canCopyImage()) handleCopyImage();@@ -1884,14 +830,9 @@ export const FileViewer: React.FC<FileViewerProps> = ({}},[- onVisualFeedback,- handleConfirmDelete,handleCopyImage,handleToggleFullscreen,handleShortcuts,- activeAnnotatedFile,- isPendingToggleArchive,- toggleArchived,canCopyImage,],);@@ -1935,9 +876,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({performKeyAction,]);- // Handle updates to files.- //- // See: [Note: Updates to the files prop for FileViewer]useEffect(() => {if (!files.length) {// If there are no more files left, close the viewer.@@ -1950,20 +888,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({}}, [handleClose, files, open, activeAnnotatedFile]);- useEffect(() => {- // This effect might get triggered when the none of the files that were- // being shown are eligible to be shown anymore. e.g. suppose we are the- // archiveItems pseudo-collection, and the only archived file there is- // marked as unarchived by the user within the file viewer.- //- // In such cases, don't attempt to refresh since that causes various- // invariants (like the existence of a "currentFile") to get broken- // inside the `FileViewerPhotoSwipe` implementation.- if (open && files.length) {- psRef.current?.refreshCurrentSlideFavoriteButtonIfNeeded();- }- }, [favoriteFileIDs, pendingFavoriteUpdates, files, open]);-// Refresh like button when allReactions changes.useEffect(() => {if (open && files.length) {@@ -1971,145 +895,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({}}, [allReactions, files, open]);- // Fetch comments and reactions for the current file (only for shared albums).const activeFileID = activeAnnotatedFile?.file.id;- useEffect(() => {- if (!open || !activeFileID) return;-- // Only fetch social data if social buttons should be shown.- // In collection view, use showSocialButtons (based on that collection).- // In gallery view, check if the file is in any shared collection.- const isGalleryView = !activeCollectionID || activeCollectionID === 0;- const shouldFetch =- showSocialButtons ||- (isCommentsFeatureEnabled &&- isGalleryView &&- isFileInSharedCollection(activeFileID));- if (!shouldFetch) return;-- void (async () => {- try {- const commentsMap = new Map<number, Comment[]>();- const reactionsMap = new Map<number, UnifiedReaction[]>();- const newUserIDToEmail = new Map<number, string>();- const newAnonUserNames = new Map<string, string>();-- const collectionIDs = isGalleryView- ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])- : [activeCollectionID];-- for (const collectionId of collectionIDs) {- try {- const collection =- await getCollectionByID(collectionId);-- // Cache collection data for polling refresh- collectionCacheRef.current.set(collectionId, {- key: collection.key,- ownerID: collection.owner.id,- ownerEmail: collection.owner.email,- sharees: collection.sharees.map((s) => ({- id: s.id,- email: s.email,- })),- hasPublicURLs: collection.publicURLs.length > 0,- });-- // Build user ID to email map from collection owner and sharees- if (collection.owner.email) {- newUserIDToEmail.set(- collection.owner.id,- collection.owner.email,- );- }- for (const sharee of collection.sharees) {- if (sharee.email) {- newUserIDToEmail.set(sharee.id, sharee.email);- }- }-- const { comments, reactions } =- await getUnifiedSocialDiff(- collectionId,- activeFileID,- collection.key,- );-- commentsMap.set(collectionId, comments);- reactionsMap.set(collectionId, reactions);-- // Fetch anonymous user profiles only if collection has public links- if (collection.publicURLs.length > 0) {- try {- const anonProfiles = await getAnonProfiles(- collectionId,- collection.key,- );- for (const [- anonUserID,- userName,- ] of anonProfiles) {- newAnonUserNames.set(anonUserID, userName);- }- } catch {- // Ignore anon profiles fetch failures- }- }- } catch {- // Skip collections that fail to fetch- }- }-- setFileComments((prev) => {- const next = new Map(prev);- next.set(activeFileID, commentsMap);- return next;- });-- setAllReactions((prev) => {- const next = new Map(prev);- next.set(activeFileID, reactionsMap);- return next;- });-- setUserIDToEmail((prev) => {- const next = new Map(prev);- for (const [id, email] of newUserIDToEmail) {- next.set(id, email);- }- return next;- });-- setAnonUserNames((prev) => {- const next = new Map(prev);- for (const [id, name] of newAnonUserNames) {- next.set(id, name);- }- return next;- });- } catch (e) {- log.error("Failed to fetch social data", e);- setFileComments((prev) => {- const next = new Map(prev);- next.delete(activeFileID);- return next;- });- setAllReactions((prev) => {- const next = new Map(prev);- next.delete(activeFileID);- return next;- });- }- })();- }, [- open,- activeFileID,- activeCollectionID,- fileNormalCollectionIDs,- showSocialButtons,- isFileInSharedCollection,- isCommentsFeatureEnabled,- ]);// Fetch social data (comments + reactions) for public albums (when viewing as anonymous user).useEffect(() => {@@ -2235,94 +1021,8 @@ export const FileViewer: React.FC<FileViewerProps> = ({}}, [fileComments, files, open]);- // Polling interval for refreshing social data (5 seconds)const SOCIAL_REFRESH_INTERVAL_MS = 5_000;- // Refresh social data for logged-in users (uses cached collection keys)- const refreshSocialData = useCallback(async () => {- if (!activeFileID) return;-- const isGalleryView = !activeCollectionID || activeCollectionID === 0;- const shouldFetch =- showSocialButtons ||- (isCommentsFeatureEnabled &&- isGalleryView &&- isFileInSharedCollection(activeFileID));- if (!shouldFetch) return;-- try {- const commentsMap = new Map<number, Comment[]>();- const reactionsMap = new Map<number, UnifiedReaction[]>();- const newAnonUserNames = new Map<string, string>();-- const collectionIDs = isGalleryView- ? (fileNormalCollectionIDs?.get(activeFileID) ?? [])- : [activeCollectionID];-- for (const collectionId of collectionIDs) {- // Use cached collection data (populated during initial fetch)- const cached = collectionCacheRef.current.get(collectionId);- if (!cached) continue; // Skip if not in cache-- try {- const { comments, reactions } = await getUnifiedSocialDiff(- collectionId,- activeFileID,- cached.key,- );-- commentsMap.set(collectionId, comments);- reactionsMap.set(collectionId, reactions);-- if (cached.hasPublicURLs) {- try {- const anonProfiles = await getAnonProfiles(- collectionId,- cached.key,- );- for (const [anonUserID, userName] of anonProfiles) {- newAnonUserNames.set(anonUserID, userName);- }- } catch {- // Ignore- }- }- } catch {- // Skip failed collections- }- }-- setFileComments((prev) => {- const next = new Map(prev);- next.set(activeFileID, commentsMap);- return next;- });-- setAllReactions((prev) => {- const next = new Map(prev);- next.set(activeFileID, reactionsMap);- return next;- });-- setAnonUserNames((prev) => {- const next = new Map(prev);- for (const [id, name] of newAnonUserNames) {- next.set(id, name);- }- return next;- });- } catch (e) {- log.error("Failed to refresh social data", e);- }- }, [- activeFileID,- activeCollectionID,- fileNormalCollectionIDs,- showSocialButtons,- isFileInSharedCollection,- isCommentsFeatureEnabled,- ]);-// Refresh social data for public albumsconst refreshPublicSocialData = useCallback(async () => {if (@@ -2416,14 +1116,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({files,]);- // Poll for social data when comments or likes sidebar is open (logged-in users)- useInterval(- refreshSocialData,- (openComments || openLikes) && !publicAlbumsCredentials- ? SOCIAL_REFRESH_INTERVAL_MS- : null,- );-// Poll for social data when comments or likes sidebar is open (public albums)useInterval(refreshPublicSocialData,@@ -2475,20 +1167,16 @@ export const FileViewer: React.FC<FileViewerProps> = ({//// Note: showSocialButtons and enableComment are intentionally NOT included// here even though they're passed to the constructor. The delegate's- // shouldShowSocialButtons handles dynamic visibility, and these values only- // change based on collectionSummaries which we don't want to trigger a full- // recreation.+ // public-album branch is static, and these values should not trigger a+ // full recreation.// eslint-disable-next-line react-hooks/exhaustive-deps}, [open,onClose,- user,initialIndex,disableDownload,showFullscreenButton,disableEscapeClose,- haveUser,- isPublicAlbum,handleClose,handleAnnotate,handleViewInfo,@@ -2534,24 +1222,7 @@ export const FileViewer: React.FC<FileViewerProps> = ({};}, [open, shouldCloseOnBrowserBack]);- const handleFileMetadataUpdate = useMemo(() => {- return onRemoteFilesPull- ? async () => {- // Wait for the files pull to complete.- await onRemoteFilesPull();- // Set the flag to trigger the full pull later.- handleNeedsRemotePull();- }- : undefined;- }, [onRemoteFilesPull, handleNeedsRemotePull]);-- const handleUpdateCaption = useCallback(- (fileID: number, newCaption: string) => {- updateItemDataAlt(fileID, newCaption);- psRef.current!.refreshCurrentSlideContent();- },- [],- );+ const handleUpdateCaption = useCallback(() => undefined, []);useEffect(updateFullscreenStatus, [updateFullscreenStatus]);@@ -2566,24 +1237,13 @@ export const FileViewer: React.FC<FileViewerProps> = ({onClose={handleFileInfoClose}file={activeAnnotatedFile.file}exif={activeFileExif}- allowEdits={!!activeAnnotatedFile.annotation.isOwnFile}- allowMap={haveUser}- showCollections={haveUser && !isInHiddenSection}- fileCollectionIDs={fileNormalCollectionIDs}- onFileMetadataUpdate={handleFileMetadataUpdate}onUpdateCaption={handleUpdateCaption}- onSelectCollection={handleSelectCollection}- onSelectPerson={handleSelectPerson}- {...{ collectionNameByID }}/><CommentsSidebaropen={openComments}onClose={handleCommentsClose}file={activeAnnotatedFile.file}activeCollectionID={activeCollectionID}- fileNormalCollectionIDs={fileNormalCollectionIDs}- collectionSummaries={collectionSummaries}- currentUserID={user?.id}prefetchedComments={fileComments.get(activeAnnotatedFile.file.id,)}@@ -2607,23 +1267,12 @@ export const FileViewer: React.FC<FileViewerProps> = ({onClose={handleLikesClose}file={activeAnnotatedFile.file}activeCollectionID={activeCollectionID}- fileNormalCollectionIDs={fileNormalCollectionIDs}- collectionSummaries={collectionSummaries}- currentUserID={user?.id}prefetchedReactions={allReactions.get(activeAnnotatedFile.file.id,)}prefetchedUserIDToEmail={userIDToEmail}anonUserNames={anonUserNames}/>- <LikeAlbumSelectorModal- open={openLikeAlbumSelector}- onClose={handleLikeAlbumSelectorClose}- albums={allAlbumsForFile}- likedAlbumIDs={likedAlbumIDs}- onToggleAlbum={handleToggleAlbumLike}- onLikeAll={handleLikeAll}- /><PublicLikeModalopen={openPublicLikeModal}onClose={handlePublicLikeModalClose}@@ -2644,50 +1293,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({disableAutoFocusItemslotProps={{ list: { "aria-labelledby": moreButtonID } }}>- {activeAnnotatedFile.annotation.showDownload == "menu" && (- <MoreMenuItem onClick={handleDownloadMenuAction}>- <MoreMenuItemTitle>{t("download")}</MoreMenuItemTitle>- <FileDownloadOutlinedIcon />- </MoreMenuItem>- )}- {activeAnnotatedFile.annotation.isOwnFile &&- !isInTrashSection &&- onSendLink && (- <MoreMenuItem onClick={handleSendLinkMenuAction}>- <MoreMenuItemTitle>Send link</MoreMenuItemTitle>- <HugeiconsIcon icon={Navigation03Icon} size={20} />- </MoreMenuItem>- )}- {activeAnnotatedFile.annotation.showDelete && (- <MoreMenuItem onClick={handleConfirmDelete}>- <MoreMenuItemTitle>{t("delete")}</MoreMenuItemTitle>- <DeleteIcon />- </MoreMenuItem>- )}- {isArchived !== undefined && (- <MoreMenuItem- onClick={toggleArchived}- disabled={isPendingToggleArchive}- >- <MoreMenuItemTitle>- {isArchived ? t("unarchive") : t("archive")}- </MoreMenuItemTitle>- {isArchived ? (- <UnArchiveIcon />- ) : (- <ArchiveOutlinedIcon />- )}- </MoreMenuItem>- )}- {handleAddFileToCollection &&- activeAnnotatedFile.annotation.isOwnFile && (- <MoreMenuItem onClick={handleAddFileToCollection}>- <MoreMenuItemTitle>- {t("add_to_album")}- </MoreMenuItemTitle>- <AddIcon />- </MoreMenuItem>- )}{canCopyImage() && (<MoreMenuItem onClick={handleCopyImage}><MoreMenuItemTitle>@@ -2700,11 +1305,15 @@ export const FileViewer: React.FC<FileViewerProps> = ({<MoreMenuItemonClick={handleToggleFullscreen}- dividersx={{- borderColor: "fixed.dark.divider",- /* 12px + 2px */- pb: "14px",+ ...(canCopyImage()+ ? {+ borderTop: 1,+ borderColor: "fixed.dark.divider",+ mt: "2px",+ pt: "14px",+ }+ : undefined),}}><MoreMenuItemTitle>@@ -2724,11 +1333,6 @@ export const FileViewer: React.FC<FileViewerProps> = ({</Typography></MoreMenuItem></MoreMenu>- <ConfirmDeleteFileDialog- open={openConfirmDelete}- onClose={handleConfirmDeleteClose}- onConfirm={handleDelete}- /><Shortcutsopen={openShortcuts}onClose={handleShortcutsClose}@@ -2781,93 +1385,6 @@ const MoreMenuItemTitle: React.FC<React.PropsWithChildren> = ({ children }) => (<Typography sx={{ fontWeight: "medium" }}>{children}</Typography>);-type ConfirmDeleteFileDialogProps = ModalVisibilityProps & {- /**- * Called when the user confirms the deletion.- *- * The delete button will show an activity indicator until this async- * operation completes.- */- onConfirm: () => Promise<void>;-};--/**- * A bespoke variant of AttributedMiniDialog for use by the delete file- * confirmation prompt that we show in the file viewer.- *- * - It auto focuses the primary action.- * - It uses a lighter backdrop in light mode.- */-const ConfirmDeleteFileDialog: React.FC<ConfirmDeleteFileDialogProps> = ({- open,- onClose,- onConfirm,-}) => {- const [phase, setPhase] = useState<"loading" | "failed" | undefined>();-- const resetPhaseAndClose = () => {- setPhase(undefined);- onClose();- };-- const handleClick = async () => {- setPhase("loading");- try {- await onConfirm();- resetPhaseAndClose();- } catch (e) {- log.error(e);- setPhase("failed");- }- };-- const handleClose: ModalProps["onClose"] = (_, reason) => {- // Ignore backdrop clicks when we're processing the user request.- if (reason == "backdropClick" && phase == "loading") return;- resetPhaseAndClose();- };-- return (- <TitledMiniDialog- open={open}- onClose={handleClose}- title={t("trash_file_title")}- sx={(theme) => ({- // See: [Note: Lighter backdrop for overlays on photo viewer]- ...theme.applyStyles("light", {- ".MuiBackdrop-root": {- backgroundColor: theme.vars.palette.backdrop.faint,- },- }),- })}- >- <Typography sx={{ color: "text.muted" }}>- {t("trash_file_message")}- </Typography>- <Stack sx={{ pt: 3, gap: 1 }}>- {phase == "failed" && <InlineErrorIndicator />}- <LoadingButton- loading={phase == "loading"}- fullWidth- color="critical"- autoFocus- onClick={handleClick}- >- {t("move_to_trash")}- </LoadingButton>- <FocusVisibleButton- fullWidth- color="secondary"- disabled={phase == "loading"}- onClick={resetPhaseAndClose}- >- {t("cancel")}- </FocusVisibleButton>- </Stack>- </TitledMiniDialog>- );-};-type ShortcutsProps = ModalVisibilityProps &Pick<FileViewerProps, "disableDownload"> & {/**diff --git a/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsx b/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsxdeleted file mode 100644index d76f41d9dc..0000000000--- a/web/apps/albums/vendor/ente-gallery/components/viewer/LikeAlbumSelectorModal.tsx+++ /dev/null@@ -1,429 +0,0 @@-import CloseIcon from "@mui/icons-material/Close";-import { Box, Dialog, IconButton, styled, Typography } from "@mui/material";-import { type ModalVisibilityProps } from "ente-base/components/utils/modal";-import { t } from "i18next";-import React from "react";--// =============================================================================-// Icons-// =============================================================================--const HeartFilledIcon: React.FC<{ size?: number; color?: string }> = ({- size = 18,- color = "#08C225",-}) => (- <svg- width={size}- height={(size * 15) / 18}- viewBox="0 0 18 15"- fill="none"- xmlns="http://www.w3.org/2000/svg"- style={{ display: "block" }}- >- <path- d="M7.40825 13.8538C5.15122 12.1661 0.679688 8.30753 0.679688 4.83524C0.679688 2.54019 2.3639 0.679688 4.67969 0.679688C5.87969 0.679688 7.07969 1.07969 8.67969 2.67969C10.2797 1.07969 11.4797 0.679688 12.6797 0.679688C14.9954 0.679688 16.6797 2.54019 16.6797 4.83524C16.6797 8.30753 12.2082 12.1661 9.95113 13.8538C9.19161 14.4218 8.16777 14.4218 7.40825 13.8538Z"- fill={color}- stroke={color}- strokeWidth="1.36"- strokeLinecap="round"- strokeLinejoin="round"- />- </svg>-);--const HeartOutlineIcon: React.FC<{ size?: number; color?: string }> = ({- size = 18,- color = "#08C225",-}) => (- <svg- width={size}- height={(size * 15) / 18}- viewBox="0 0 18 15"- fill="none"- xmlns="http://www.w3.org/2000/svg"- style={{ display: "block" }}- >- <path- d="M7.40825 13.8538C5.15122 12.1661 0.679688 8.30753 0.679688 4.83524C0.679688 2.54019 2.3639 0.679688 4.67969 0.679688C5.87969 0.679688 7.07969 1.07969 8.67969 2.67969C10.2797 1.07969 11.4797 0.679688 12.6797 0.679688C14.9954 0.679688 16.6797 2.54019 16.6797 4.83524C16.6797 8.30753 12.2082 12.1661 9.95113 13.8538C9.19161 14.4218 8.16777 14.4218 7.40825 13.8538Z"- stroke={color}- strokeWidth="1.36"- strokeLinecap="round"- strokeLinejoin="round"- />- </svg>-);--const LikePhotoIllustration: React.FC = () => (- <svg- width="126"- height="121"- viewBox="0 0 126 121"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- <path- d="M84.7129 23.0781C96.7222 23.0784 105.29 32.8476 105.29 44.499C105.29 53.3449 99.7258 62.2116 93.4453 69.4932C87.0622 76.8936 79.4391 83.2238 74.3574 87.0557C69.973 90.3616 64.031 90.3614 59.6465 87.0557C54.5648 83.2238 46.9408 76.8937 40.5576 69.4932C34.2771 62.2116 28.7129 53.3449 28.7129 44.499C28.713 32.8474 37.2813 23.0781 49.291 23.0781C54.9545 23.0782 60.4297 24.9062 67.001 30.9004C73.5726 24.9056 79.0491 23.0781 84.7129 23.0781Z"- fill="#08C225"- stroke="#232323"- strokeWidth="5.73358"- strokeLinecap="round"- strokeLinejoin="round"- />- <mask- id="mask0_643_19218"- style={{ maskType: "alpha" }}- maskUnits="userSpaceOnUse"- x="31"- y="25"- width="72"- height="62"- >- <path- d="M61.3721 84.7662C51.3787 77.2306 31.5801 60.0026 31.5801 44.4993C31.5801 34.2522 39.0372 25.9453 49.2909 25.9453C54.6041 25.9453 59.9173 27.7313 67.0016 34.8751C74.086 27.7313 79.3992 25.9453 84.7124 25.9453C94.9659 25.9453 102.423 34.2522 102.423 44.4993C102.423 60.0026 82.6247 77.2306 72.6312 84.7662C69.2683 87.3019 64.735 87.3019 61.3721 84.7662Z"- fill="#08C225"- />- </mask>- <g mask="url(#mask0_643_19218)">- <path- d="M47.5975 41.0431C46.8515 39.3306 47.9859 37.1849 50.1312 36.2504C52.2765 35.316 54.6203 35.9467 55.3662 37.6591C56.1121 39.3716 54.9777 41.5173 52.8324 42.4518C50.6872 43.3862 48.3434 42.7555 47.5975 41.0431Z"- fill="white"- />- <path- d="M44.5677 45.0545C44.3136 44.4712 44.7025 43.7391 45.4364 43.4194C46.1704 43.0997 46.9713 43.3135 47.2254 43.8968C47.4795 44.4802 47.0906 45.2123 46.3567 45.532C45.6227 45.8517 44.8218 45.6379 44.5677 45.0545Z"- fill="white"- />- <path- d="M102.994 32.271C101.622 55.1395 78.9821 78.0073 50.9683 82.581C49.2531 88.2982 42.3926 93.7861 42.3926 95.1582C42.3926 96.5303 48.1097 107.926 50.9683 113.453L89.8447 101.447L115 66.5725C113.094 57.9969 106.196 31.3563 102.994 32.271Z"- fill="#46A030"- />- <path- d="M59.7039 28.2666C34.9591 23.1218 29.8137 47.7054 32.6723 55.1377L23.1143 51.7074C21.3992 47.3243 18.1976 37.9863 19.1123 35.6995C20.0271 33.4126 22.1615 16.833 23.1143 8.829L55.1302 3.68359L96.8651 13.9744C97.6274 18.1664 98.4659 26.8936 95.7217 28.2666C80.2855 22.5506 66.5644 33.9826 66.5644 33.4109C66.5644 32.9535 68.4701 30.5523 69.423 29.4089C66.3738 29.0281 60.1612 28.2666 59.7039 28.2666Z"- fill="white"- />- </g>- <path- d="M20.9639 58.8477C14.9399 61.182 10.9104 66.0874 11.263 71.48C10.9104 66.0874 6.28324 61.7544 -9.80907e-05 60.2184C6.02383 57.884 10.0533 52.9787 9.70073 47.5861C10.0533 52.9787 14.6805 57.3117 20.9639 58.8477Z"- fill="#08C225"- />- <path- d="M119.579 91.9746C111.591 92.7003 105.114 97.1692 103.689 103.722C105.114 97.1692 101.077 90.4145 94.1117 86.438C102.099 85.7122 108.576 81.2434 110.001 74.6902C108.576 81.2434 112.613 87.9981 119.579 91.9746Z"- fill="#08C225"- />- <path- d="M112.728 9.21189C108.334 9.91374 104.912 12.6353 104.37 16.3181C104.912 12.6353 102.421 9.04853 98.4114 7.10627C102.806 6.40442 106.228 3.68284 106.77 7.55054e-05C106.228 3.68284 108.719 7.26962 112.728 9.21189Z"- fill="#08C225"- />- </svg>-);--// =============================================================================-// Types-// =============================================================================--interface Album {- id: number;- name: string;- coverURL?: string;-}--export interface LikeAlbumSelectorModalProps extends ModalVisibilityProps {- /**- * List of albums containing this file that user can like in.- */- albums: Album[];- /**- * Set of album IDs where the photo is currently liked.- */- likedAlbumIDs: Set<number>;- /**- * Called when user clicks on an album to toggle like status.- * @param albumId The album ID- * @param isCurrentlyLiked Whether the album is currently liked- */- onToggleAlbum: (albumId: number, isCurrentlyLiked: boolean) => void;- /**- * Called when user clicks "Like all" to like in all albums.- */- onLikeAll: () => void;-}--/**- * Modal dialog for selecting which album to like a photo in.- * Shown when the like button is clicked and the photo was opened from- * gallery view (not from a specific collection).- */-export const LikeAlbumSelectorModal: React.FC<LikeAlbumSelectorModalProps> = ({- open,- onClose,- albums,- likedAlbumIDs,- onToggleAlbum,- onLikeAll,-}) => {- const likedCount = likedAlbumIDs.size;- const allLiked = likedCount === albums.length && albums.length > 0;-- return (- <StyledDialog open={open} onClose={onClose}>- <DialogWrapper>- <CloseButton onClick={onClose}>- <CloseIcon sx={{ fontSize: 20 }} />- </CloseButton>-- <ContentContainer>- <IllustrationWrapper>- <LikePhotoIllustration />- </IllustrationWrapper>-- <TitleSection>- <Title>{t("like_photo")}</Title>- <Subtitle>{t("select_album_to_like")}</Subtitle>- </TitleSection>-- <AlbumsSection>- <AlbumsHeader>- <AlbumsCount>- {t("albums_count", { count: albums.length })}- </AlbumsCount>- <LikeAllButton- onClick={!allLiked ? onLikeAll : undefined}- sx={{- opacity: !allLiked ? 1 : 0.5,- cursor: !allLiked ? "pointer" : "default",- pointerEvents: !allLiked ? "auto" : "none",- }}- >- <Typography- sx={(theme) => ({- fontWeight: 500,- fontSize: 14,- color: "#000",- ...theme.applyStyles("dark", {- color: "#fff",- }),- })}- >- {t("like_all")}- </Typography>- {allLiked ? (- <HeartFilledIcon- size={16}- color="var(--mui-palette-text-base)"- />- ) : (- <HeartOutlineIcon- size={16}- color="var(--mui-palette-text-base)"- />- )}- </LikeAllButton>- </AlbumsHeader>-- <AlbumsList>- {albums.map((album) => {- const isLiked = likedAlbumIDs.has(album.id);- return (- <AlbumItem key={album.id}>- <AlbumName>{album.name}</AlbumName>- <HeartButton- onClick={() =>- onToggleAlbum(album.id, isLiked)- }- >- {isLiked ? (- <HeartFilledIcon />- ) : (- <HeartOutlineIcon />- )}- </HeartButton>- </AlbumItem>- );- })}- </AlbumsList>- </AlbumsSection>- </ContentContainer>- </DialogWrapper>- </StyledDialog>- );-};--// =============================================================================-// Styled Components-// =============================================================================--const StyledDialog = styled(Dialog)(({ theme }) => ({- "& .MuiDialog-paper": {- width: 381,- maxWidth: "calc(100% - 32px)",- borderRadius: 28,- backgroundColor: "#fff",- padding: 0,- margin: 16,- overflow: "visible",- boxShadow: "none",- border: "1px solid #E0E0E0",- ...theme.applyStyles("dark", {- backgroundColor: "#1b1b1b",- border: "1px solid rgba(255, 255, 255, 0.18)",- }),- },- "& .MuiBackdrop-root": { backgroundColor: "rgba(0, 0, 0, 0.5)" },-}));--const DialogWrapper = styled(Box)(() => ({- position: "relative",- padding: "58px 24px 24px 24px",-}));--const CloseButton = styled(IconButton)(({ theme }) => ({- position: "absolute",- top: 11,- right: 12,- backgroundColor: "#FAFAFA",- color: "#000",- padding: 10,- "&:hover": { backgroundColor: "#F0F0F0" },- ...theme.applyStyles("dark", {- backgroundColor: "rgba(255, 255, 255, 0.12)",- color: "#fff",- "&:hover": { backgroundColor: "rgba(255, 255, 255, 0.16)" },- }),-}));--const ContentContainer = styled(Box)(() => ({- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: 16,-}));--const IllustrationWrapper = styled(Box)(() => ({- display: "flex",- justifyContent: "center",- alignItems: "center",- marginBottom: -12,-}));--const TitleSection = styled(Box)(() => ({- display: "flex",- flexDirection: "column",- alignItems: "center",- gap: 9,- textAlign: "center",- marginBottom: 14,-}));--const Title = styled(Typography)(({ theme }) => ({- fontWeight: 600,- fontSize: 24,- lineHeight: "22px",- letterSpacing: "-0.48px",- color: "#000",- ...theme.applyStyles("dark", { color: "#fff" }),-}));--const Subtitle = styled(Typography)(({ theme }) => ({- fontWeight: 500,- fontSize: 14,- lineHeight: "17px",- color: "#666666",- maxWidth: 295,- ...theme.applyStyles("dark", { color: "rgba(255, 255, 255, 0.7)" }),-}));--const AlbumsSection = styled(Box)(({ theme }) => ({- width: "100%",- backgroundColor: "rgba(162, 162, 162, 0.12)",- borderRadius: 27,- padding: "16px 0 0 0",- maxHeight: 313,- display: "flex",- flexDirection: "column",- overflow: "hidden",- ...theme.applyStyles("dark", {- backgroundColor: "rgba(162, 162, 162, 0.12)",- }),-}));--const AlbumsHeader = styled(Box)(() => ({- display: "flex",- justifyContent: "space-between",- alignItems: "center",- padding: "0 16px 0 25px",- marginBottom: 16,-}));--const AlbumsCount = styled(Typography)(({ theme }) => ({- fontWeight: 500,- fontSize: 14,- lineHeight: "17px",- color: "#000",- ...theme.applyStyles("dark", { color: "#fff" }),-}));--const LikeAllButton = styled(Box)(({ theme }) => ({- display: "flex",- alignItems: "center",- gap: 10,- padding: 10,- backgroundColor: "#fff",- borderRadius: 14,- cursor: "pointer",- "&:hover": { backgroundColor: "#EBEBEB" },- ...theme.applyStyles("dark", {- backgroundColor: "#1b1b1b",- "&:hover": { backgroundColor: "#252525" },- }),-}));--const AlbumsList = styled(Box)(({ theme }) => ({- display: "flex",- flexDirection: "column",- gap: 6,- padding: "0 12px 12px 12px",- overflowY: "auto",- maxHeight: 241,- "&::-webkit-scrollbar": { width: 6 },- "&::-webkit-scrollbar-track": { background: "transparent" },- "&::-webkit-scrollbar-thumb": {- background: "rgba(0, 0, 0, 0.2)",- borderRadius: 3,- },- ...theme.applyStyles("dark", {- "&::-webkit-scrollbar-thumb": {- background: "rgba(255, 255, 255, 0.2)",- },- }),-}));--const AlbumItem = styled(Box)(({ theme }) => ({- display: "flex",- alignItems: "center",- justifyContent: "space-between",- gap: 12,- padding: "10px 10px 10px 16px",- backgroundColor: "#fff",- borderRadius: 16,- ...theme.applyStyles("dark", { backgroundColor: "#212121" }),-}));--const AlbumName = styled(Typography)(({ theme }) => ({- fontWeight: 500,- fontSize: 14,- lineHeight: "17px",- color: "#000",- flex: 1,- ...theme.applyStyles("dark", { color: "#fff" }),-}));--const HeartButton = styled(Box)(() => ({- width: 32,- height: 32,- display: "flex",- alignItems: "center",- justifyContent: "center",- backgroundColor: "rgba(8, 194, 37, 0.06)",- borderRadius: 9.6,- cursor: "pointer",- "&:hover": { backgroundColor: "rgba(8, 194, 37, 0.12)" },-}));diff --git a/web/apps/albums/vendor/photos/components/FileListWithViewer.tsx b/web/apps/albums/vendor/photos/components/FileListWithViewer.tsxindex 20b2eb7683..7801c2f890 100644--- a/web/apps/albums/vendor/photos/components/FileListWithViewer.tsx+++ b/web/apps/albums/vendor/photos/components/FileListWithViewer.tsx@@ -30,11 +30,6 @@ export type FileListWithViewerProps = {*/files: EnteFile[];enableDownload?: boolean;- /**- * Called when an action in the file viewer requires us to perform a full- * pull from remote.- */- onRemotePull: () => Promise<void>;/*** If set, the file viewer will open to this file index on mount/update.* Set to undefined after the navigation is complete.@@ -69,7 +64,6 @@ export type FileListWithViewerProps = {> &Pick<ComponentProps<typeof FileViewer>,- | "onVisualFeedback"| "publicAlbumsCredentials"| "collectionKey"| "onJoinAlbum"@@ -92,8 +86,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({selected,setSelected,activeCollectionID,- onRemotePull,- onVisualFeedback,onAddSaveGroup,pendingFileIndex,pendingFileSidebar,@@ -151,11 +143,6 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({setOpenFileViewer(true);}, []);- const handleTriggerRemotePull = useCallback(- () => void onRemotePull(),- [onRemotePull],- );-const handleDownload = useCallback((file: EnteFile) =>downloadAndSaveFiles([file], fileFileName(file), onAddSaveGroup),@@ -190,14 +177,12 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({disableDownload={!enableDownload}{...{files,- onVisualFeedback,publicAlbumsCredentials,collectionKey,onJoinAlbum,enableComment,enableJoin,}}- onTriggerRemotePull={handleTriggerRemotePull}onDownload={handleDownload}activeCollectionID={activeCollectionID}/>diff --git a/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsx b/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsxindex 84c0eb9f26..bd5626edcc 100644--- a/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsx+++ b/web/apps/albums/vendor/photos/components/PublicAlbumSingleFileViewer.tsx@@ -498,7 +498,6 @@ export const PublicAlbumSingleFileViewer: React.FC<disableEscapeClosedisableDownload={!enableDownload}onDownload={enableDownload ? handleDownload : undefined}- onVisualFeedback={onVisualFeedback}publicAlbumsCredentials={publicAlbumsCredentials}shouldCloseOnBrowserBack={false}collectionKey={collectionKey}diff --git a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.ts b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.tsindex b58ff27142..99904802d7 100644--- a/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.ts+++ b/web/apps/albums/vendor/photos/components/TripLayout/hooks/useFileViewer.ts@@ -6,13 +6,11 @@ import type { JourneyPoint } from "../types";interface UseFileViewerProps {files: EnteFile[];onSetOpenFileViewer?: (open: boolean) => void;- onRemotePull?: () => Promise<void>;}export const useFileViewer = ({files,onSetOpenFileViewer,- onRemotePull,}: UseFileViewerProps) => {const [openFileViewer, setOpenFileViewer] = useState(false);const [currentFileIndex, setCurrentFileIndex] = useState(0);@@ -55,10 +53,6 @@ export const useFileViewer = ({onSetOpenFileViewer?.(false);}, [onSetOpenFileViewer]);- const handleTriggerRemotePull = useCallback(() => {- return onRemotePull?.() || Promise.resolve();- }, [onRemotePull]);-return {// StateopenFileViewer,@@ -67,6 +61,5 @@ export const useFileViewer = ({// HandlershandleOpenFileViewer,handleCloseFileViewer,- handleTriggerRemotePull,};};diff --git a/web/apps/albums/vendor/photos/components/TripLayout/index.tsx b/web/apps/albums/vendor/photos/components/TripLayout/index.tsxindex cee4133053..b1a35d8105 100644--- a/web/apps/albums/vendor/photos/components/TripLayout/index.tsx+++ b/web/apps/albums/vendor/photos/components/TripLayout/index.tsx@@ -43,11 +43,8 @@ interface TripLayoutProps {files: EnteFile[];collection?: Collection;albumTitle?: string;- user?: { id: number; email: string; token: string; [key: string]: unknown }; // User object for FileViewer- // FileViewer related props (optional, can be added as needed)enableDownload?: boolean;onSetOpenFileViewer?: (open: boolean) => void;- onRemotePull?: () => Promise<void>;onAddPhotos?: () => void; // Callback for add photos button// Join album propsaccessToken?: string;@@ -69,10 +66,8 @@ export const TripLayout: React.FC<TripLayoutProps> = ({files,collection,albumTitle,- user,enableDownload,onSetOpenFileViewer,- onRemotePull,onAddPhotos,accessToken,collectionKey,@@ -107,8 +102,7 @@ export const TripLayout: React.FC<TripLayoutProps> = ({viewerFiles,handleOpenFileViewer,handleCloseFileViewer,- handleTriggerRemotePull,- } = useFileViewer({ files, onSetOpenFileViewer, onRemotePull });+ } = useFileViewer({ files, onSetOpenFileViewer });// Join album hook for file viewer's public like modalconst { handleJoinAlbum } = useJoinAlbum({@@ -590,13 +584,7 @@ export const TripLayout: React.FC<TripLayoutProps> = ({initialSidebar={initialSidebar}highlightCommentID={highlightCommentID}files={viewerFiles}- user={user}disableDownload={!enableDownload}- onTriggerRemotePull={handleTriggerRemotePull}- onRemoteFilesPull={handleTriggerRemotePull}- onVisualFeedback={() => {- // No-op: Trip viewer is read-only and doesn't need visual feedback- }}publicAlbumsCredentials={credentials?.current}collectionKey={collectionKey}onJoinAlbum={handleJoinAlbum}