Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(FileContextMenu):initial-implementation-added

Aswin Asokf78d915e6209
diff --git a/web/apps/photos/src/components/FileList.tsx b/web/apps/photos/src/components/FileList.tsx
index 9e094f94ee..16e19b7b55 100644
--- a/web/apps/photos/src/components/FileList.tsx
+++ b/web/apps/photos/src/components/FileList.tsx
@@ -12,6 +12,10 @@ import { downloadManager } from "ente-gallery/services/download";
import type { EnteFile } from "ente-media/file";
import { fileDurationString } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
+import {
+ FileContextMenu,
+ type ContextMenuPosition,
+} from "ente-new/photos/components/FileContextMenu";
import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";
import { StarIcon } from "ente-new/photos/components/icons/StarIcon";
import {
@@ -24,7 +28,14 @@ import {
thumbnailGap,
type ThumbnailGridLayoutParams,
} from "ente-new/photos/components/utils/thumbnail-grid-layout";
-import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
+import {
+ PseudoCollectionID,
+ type CollectionSummary,
+} from "ente-new/photos/services/collection-summary";
+import {
+ getAvailableFileActions,
+ type FileContextAction,
+} from "ente-new/photos/utils/file-actions";
import { batch } from "ente-utils/array";
import { t } from "i18next";
import React, {
@@ -245,6 +256,22 @@ export interface FileListProps {
* Called when the visible date at the top of the viewport changes.
*/
onVisibleDateChange?: (date: string | undefined) => void;
+ /**
+ * The collection summary for the current view.
+ *
+ * Used to determine available context menu actions.
+ */
+ collectionSummary?: CollectionSummary;
+ /**
+ * Called when a context menu action is triggered on a file.
+ *
+ * @param action The action that was triggered.
+ */
+ onContextMenuAction?: (action: FileContextAction) => void;
+ /**
+ * Whether to show the "Add Person" action in the context menu.
+ */
+ showAddPersonAction?: boolean;
}
/**
@@ -271,6 +298,9 @@ export const FileList: React.FC<FileListProps> = ({
onItemClick,
onScroll,
onVisibleDateChange,
+ collectionSummary,
+ onContextMenuAction,
+ showAddPersonAction,
}) => {
const [_items, setItems] = useState<FileListItem[]>([]);
const items = useDeferredValue(_items);
@@ -288,6 +318,13 @@ export const FileList: React.FC<FileListProps> = ({
// Show back-to-top button when scrolled past threshold
const [showBackToTop, setShowBackToTop] = useState(false);
+ // Context menu state
+ const [contextMenu, setContextMenu] = useState<{
+ position: ContextMenuPosition;
+ file: EnteFile;
+ fileIndex: number;
+ } | null>(null);
+
const listRef = useRef<VariableSizeList | null>(null);
const outerRef = useRef<HTMLDivElement | null>(null);
@@ -584,6 +621,78 @@ export const FileList: React.FC<FileListProps> = ({
if (selected.count == 0) setRangeStartIndex(undefined);
}, [selected]);
+ // Compute available context menu actions based on stable context
+ // Note: We don't include contextMenu in deps since actions only depend on
+ // the gallery mode/context, not on whether the menu is open
+ const contextMenuActions = useMemo(() => {
+ if (!onContextMenuAction) return [];
+ return getAvailableFileActions({
+ barMode: mode,
+ isInSearchMode: modePlus === "search",
+ collectionSummary,
+ showAddPerson: !!showAddPersonAction,
+ });
+ }, [
+ onContextMenuAction,
+ mode,
+ modePlus,
+ collectionSummary,
+ showAddPersonAction,
+ ]);
+
+ // Handle context menu open
+ const handleContextMenu = useCallback(
+ (event: React.MouseEvent, file: EnteFile, fileIndex: number) => {
+ if (!onContextMenuAction) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ // Handle selection behavior on right-click
+ if (!selected[file.id]) {
+ // File not selected: clear selection and select only this file
+ const isOwnFile = file.ownerID === user?.id;
+ const context =
+ mode === "people" && activePersonID
+ ? { mode: "people" as const, personID: activePersonID }
+ : {
+ mode: (mode ?? "albums") as
+ | "albums"
+ | "hidden-albums",
+ collectionID: activeCollectionID,
+ };
+ setSelected({
+ [file.id]: true,
+ ownCount: isOwnFile ? 1 : 0,
+ count: 1,
+ collectionID: activeCollectionID,
+ context,
+ });
+ }
+ // If file is already selected, keep current multi-selection
+
+ setContextMenu({
+ position: { top: event.clientY, left: event.clientX },
+ file,
+ fileIndex,
+ });
+ },
+ [
+ onContextMenuAction,
+ selected,
+ setSelected,
+ user,
+ activeCollectionID,
+ activePersonID,
+ mode,
+ ],
+ );
+
+ // Handle context menu close
+ const handleContextMenuClose = useCallback(() => {
+ setContextMenu(null);
+ }, []);
+
const renderListItem = useCallback(
(item: FileListItem, isScrolling: boolean) => {
const haveSelection = selected.count > 0;
@@ -666,6 +775,16 @@ export const FileList: React.FC<FileListProps> = ({
onRangeSelect={() =>
handleRangeSelect(index)
}
+ onContextMenu={
+ onContextMenuAction
+ ? (e) =>
+ handleContextMenu(
+ e,
+ file,
+ index,
+ )
+ : undefined
+ }
/>
);
}),
@@ -683,12 +802,14 @@ export const FileList: React.FC<FileListProps> = ({
checkedTimelineDateStrings,
emailByUserID,
favoriteFileIDs,
+ handleContextMenu,
handleRangeSelect,
handleSelect,
hoverIndex,
isShiftKeyPressed,
mode,
onChangeSelectAllCheckBox,
+ onContextMenuAction,
onItemClick,
rangeStartIndex,
enableSelect,
@@ -807,6 +928,16 @@ export const FileList: React.FC<FileListProps> = ({
<KeyboardArrowUpIcon />
</BackToTopButton>
)}
+ {onContextMenuAction && (
+ <FileContextMenu
+ open={contextMenu !== null}
+ anchorPosition={contextMenu?.position}
+ onClose={handleContextMenuClose}
+ actions={contextMenuActions}
+ onAction={onContextMenuAction}
+ selectedCount={selected.count}
+ />
+ )}
</Box>
);
};
@@ -972,6 +1103,7 @@ type FileThumbnailProps = {
onSelect: (checked: boolean) => void;
onHover: () => void;
onRangeSelect: () => void;
+ onContextMenu?: (event: React.MouseEvent) => void;
} & Pick<FileListProps, "user" | "emailByUserID" | "enableSelect">;
const FileThumbnail: React.FC<FileThumbnailProps> = ({
@@ -990,6 +1122,7 @@ const FileThumbnail: React.FC<FileThumbnailProps> = ({
onSelect,
onHover,
onRangeSelect,
+ onContextMenu,
}) => {
const [imageURL, setImageURL] = useState<string | undefined>(undefined);
const [isLongPressing, setIsLongPressing] = useState(false);
@@ -1064,6 +1197,7 @@ const FileThumbnail: React.FC<FileThumbnailProps> = ({
<FileThumbnail_
key={`thumb-${file.id}}`}
onClick={handleClick}
+ onContextMenu={onContextMenu}
onMouseEnter={handleHover}
disabled={!imageURL}
{...(enableSelect && longPressHandlers)}
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index ba81af1836..d363fd641c 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -108,6 +108,8 @@ export type FileListWithViewerProps = {
| "favoriteFileIDs"
| "emailByUserID"
| "listBorderRadius"
+ | "onContextMenuAction"
+ | "showAddPersonAction"
> &
Pick<
FileViewerProps,
@@ -157,6 +159,8 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
favoriteFileIDs,
emailByUserID,
listBorderRadius,
+ onContextMenuAction,
+ showAddPersonAction,
isInIncomingSharedCollection,
isInHiddenSection,
fileNormalCollectionIDs,
@@ -350,6 +354,9 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
listBorderRadius,
onScroll,
onVisibleDateChange,
+ collectionSummary: activeCollectionSummary,
+ onContextMenuAction,
+ showAddPersonAction,
}}
onItemClick={handleThumbnailClick}
/>
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 7fbf7448fc..5c2668a4a0 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -53,6 +53,7 @@ import {
hasPendingAlbumToJoin,
processPendingAlbumJoin,
} from "ente-new/albums/services/join-album";
+import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
import {
CollectionSelector,
type CollectionSelectorAttributes,
@@ -103,7 +104,10 @@ import {
} from "ente-new/photos/services/collection-summary";
import exportService from "ente-new/photos/services/export";
import { updateFilesVisibility } from "ente-new/photos/services/file";
-import { addManualFileAssignmentsToPerson } from "ente-new/photos/services/ml";
+import {
+ addManualFileAssignmentsToPerson,
+ isMLEnabled,
+} from "ente-new/photos/services/ml";
import {
savedCollectionFiles,
savedCollections,
@@ -129,6 +133,7 @@ import {
verifyStripeSubscription,
} from "ente-new/photos/services/user-details";
import { usePhotosAppContext } from "ente-new/photos/types/context";
+import type { FileContextAction } from "ente-new/photos/utils/file-actions";
import { PromiseQueue } from "ente-utils/promise";
import { t } from "i18next";
import { useRouter, type NextRouter } from "next/router";
@@ -225,6 +230,25 @@ const Page: React.FC = () => {
const userDetails = useUserDetailsSnapshot();
const peopleState = usePeopleStateSnapshot();
+ // Modal visibility for the context menu "Add Person" action
+ const {
+ show: showContextMenuAssignPerson,
+ props: contextMenuAssignPersonProps,
+ } = useModalVisibility();
+
+ // Named people available for assignment (used by context menu)
+ const namedPeople = useMemo(
+ () =>
+ (peopleState?.visiblePeople ?? []).filter(
+ (p) => p.type == "cgroup" && !!p.name,
+ ),
+ [peopleState],
+ );
+ const showAddPersonAction = useMemo(
+ () => isMLEnabled() && namedPeople.length > 0,
+ [namedPeople],
+ );
+
const { saveGroups, onAddSaveGroup, onRemoveSaveGroup } = useSaveGroups();
const [, setPostCreateAlbumOp] = useState<CollectionOp | undefined>(
undefined,
@@ -930,6 +954,15 @@ const Page: React.FC = () => {
[selected, filteredFiles, clearSelection],
);
+ // Handler for selecting a person from the context menu assign person dialog
+ const handleContextMenuSelectPerson = useCallback(
+ (personID: string) => {
+ contextMenuAssignPersonProps.onClose();
+ void handleAddPersonToSelectedFiles(personID);
+ },
+ [contextMenuAssignPersonProps, handleAddPersonToSelectedFiles],
+ );
+
const handleSelectSearchOption = (
searchOption: SearchOption | undefined,
options?: { shouldExitSearchMode?: boolean },
@@ -1138,6 +1171,118 @@ const Page: React.FC = () => {
[],
);
+ /**
+ * Handle a context menu action on a file.
+ *
+ * This handler is called when the user right-clicks on a file thumbnail
+ * and selects an action from the context menu.
+ */
+ const handleContextMenuAction = useCallback(
+ (action: FileContextAction) => {
+ // The selection should already be set by FileList's handleContextMenu
+ // We just need to invoke the appropriate action handler
+ switch (action) {
+ case "download":
+ createFileOpHandler("download")();
+ break;
+ case "favorite":
+ createFileOpHandler("favorite")();
+ break;
+ case "archive":
+ createFileOpHandler("archive")();
+ break;
+ case "unarchive":
+ createFileOpHandler("unarchive")();
+ break;
+ case "hide":
+ createFileOpHandler("hide")();
+ break;
+ case "fixTime":
+ createFileOpHandler("fixTime")();
+ break;
+ case "trash":
+ showMiniDialog({
+ title: t("trash_files_title"),
+ message: t("trash_files_message"),
+ continue: {
+ text: t("move_to_trash"),
+ color: "critical",
+ action: createFileOpHandler("trash"),
+ },
+ });
+ break;
+ case "deletePermanently":
+ showMiniDialog({
+ title: t("delete_files_title"),
+ message: t("delete_files_message"),
+ continue: {
+ text: t("delete"),
+ color: "critical",
+ action: createFileOpHandler("deletePermanently"),
+ },
+ });
+ break;
+ case "restore":
+ handleOpenCollectionSelector({
+ action: "restore",
+ onCreateCollection:
+ createOnCreateForCollectionOp("restore"),
+ onSelectCollection:
+ createOnSelectForCollectionOp("restore"),
+ });
+ break;
+ case "addToAlbum":
+ handleOpenCollectionSelector({
+ action: "add",
+ sourceCollectionSummaryID: activeCollectionSummary?.id,
+ onCreateCollection:
+ createOnCreateForCollectionOp("add"),
+ onSelectCollection:
+ createOnSelectForCollectionOp("add"),
+ });
+ break;
+ case "moveToAlbum":
+ handleOpenCollectionSelector({
+ action: "move",
+ sourceCollectionSummaryID: activeCollectionSummary?.id,
+ onCreateCollection:
+ createOnCreateForCollectionOp("move"),
+ onSelectCollection:
+ createOnSelectForCollectionOp("move"),
+ });
+ break;
+ case "removeFromAlbum":
+ if (activeCollection) {
+ handleRemoveFilesFromCollection(activeCollection);
+ }
+ break;
+ case "unhide":
+ handleOpenCollectionSelector({
+ action: "unhide",
+ onCreateCollection:
+ createOnCreateForCollectionOp("unhide"),
+ onSelectCollection:
+ createOnSelectForCollectionOp("unhide"),
+ });
+ break;
+ case "addPerson":
+ showContextMenuAssignPerson();
+ break;
+ }
+ },
+ [
+ createFileOpHandler,
+ createOnCreateForCollectionOp,
+ createOnSelectForCollectionOp,
+ handleOpenCollectionSelector,
+ handleRemoveFilesFromCollection,
+ showMiniDialog,
+ showContextMenuAssignPerson,
+ activeCollectionSummary,
+ activeCollection,
+ ],
+ );
+
const handleCloseCollectionSelector = useCallback(
() => setOpenCollectionSelector(false),
[],
@@ -1294,8 +1439,8 @@ const Page: React.FC = () => {
createOnCreateForCollectionOp,
createOnSelectForCollectionOp,
createFileOpHandler,
- onAddPersonToSelectedFiles:
- handleAddPersonToSelectedFiles,
+ onShowAssignPersonDialog:
+ showContextMenuAssignPerson,
}}
/>
) : barMode == "hidden-albums" ? (
@@ -1395,6 +1540,12 @@ const Page: React.FC = () => {
onAuthenticateUser={authenticateUser}
/>
<WhatsNew {...whatsNewVisibilityProps} />
+ <AssignPersonDialog
+ {...contextMenuAssignPersonProps}
+ people={namedPeople}
+ title={t("add_a_person")}
+ onSelectPerson={handleContextMenuSelectPerson}
+ />
{!isInSearchMode &&
!isFirstLoad &&
!state.collectionFiles.length &&
@@ -1430,6 +1581,8 @@ const Page: React.FC = () => {
"sharedIncoming",
)}
isInHiddenSection={barMode == "hidden-albums"}
+ onContextMenuAction={handleContextMenuAction}
+ showAddPersonAction={showAddPersonAction}
{...{
favoriteFileIDs,
collectionNameByID,
diff --git a/web/packages/new/photos/components/FileContextMenu.tsx b/web/packages/new/photos/components/FileContextMenu.tsx
new file mode 100644
index 0000000000..fcad23e79f
--- /dev/null
+++ b/web/packages/new/photos/components/FileContextMenu.tsx
@@ -0,0 +1,188 @@
+import ClockIcon from "@mui/icons-material/AccessTime";
+import AddIcon from "@mui/icons-material/Add";
+import ArchiveIcon from "@mui/icons-material/ArchiveOutlined";
+import MoveIcon from "@mui/icons-material/ArrowForward";
+import DeleteIcon from "@mui/icons-material/Delete";
+import DownloadIcon from "@mui/icons-material/Download";
+import PersonAddIcon from "@mui/icons-material/PersonAdd";
+import RemoveIcon from "@mui/icons-material/RemoveCircleOutline";
+import RestoreIcon from "@mui/icons-material/Restore";
+import UnArchiveIcon from "@mui/icons-material/Unarchive";
+import VisibilityOffOutlinedIcon from "@mui/icons-material/VisibilityOffOutlined";
+import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
+import type { SvgIconProps } from "@mui/material";
+import {
+ Box,
+ Divider,
+ ListItemIcon,
+ ListItemText,
+ Menu,
+ MenuItem,
+ Typography,
+ styled,
+} from "@mui/material";
+import { StarBorderIcon } from "ente-new/photos/components/icons/StarIcon";
+import type { FileContextAction } from "ente-new/photos/utils/file-actions";
+import { t } from "i18next";
+import React, { memo, useCallback, useMemo } from "react";
+
+/**
+ * Position for anchoring the context menu.
+ */
+export interface ContextMenuPosition {
+ top: number;
+ left: number;
+}
+
+interface FileContextMenuProps {
+ /** Whether the menu is open. */
+ open: boolean;
+ /** The position to anchor the menu at. */
+ anchorPosition: ContextMenuPosition | undefined;
+ /** Callback when the menu should close. */
+ onClose: () => void;
+ /** The actions to display in the menu. */
+ actions: FileContextAction[];
+ /** Callback when an action is selected. */
+ onAction: (action: FileContextAction) => void;
+ /** Number of files currently selected. */
+ selectedCount: number;
+}
+
+interface ActionConfig {
+ label: string;
+ Icon: React.ComponentType<SvgIconProps>;
+ isDestructive?: boolean;
+}
+
+const actionConfigs: Record<FileContextAction, ActionConfig> = {
+ download: { label: "download", Icon: DownloadIcon },
+ fixTime: { label: "fix_creation_time", Icon: ClockIcon },
+ favorite: { label: "favorite", Icon: StarBorderIcon },
+ archive: { label: "archive", Icon: ArchiveIcon },
+ unarchive: { label: "unarchive", Icon: UnArchiveIcon },
+ hide: { label: "hide", Icon: VisibilityOffOutlinedIcon },
+ unhide: { label: "unhide", Icon: VisibilityOutlinedIcon },
+ trash: { label: "delete", Icon: DeleteIcon, isDestructive: true },
+ deletePermanently: {
+ label: "delete_permanently",
+ Icon: DeleteIcon,
+ isDestructive: true,
+ },
+ restore: { label: "restore", Icon: RestoreIcon },
+ addToAlbum: { label: "add", Icon: AddIcon },
+ moveToAlbum: { label: "move", Icon: MoveIcon },
+ removeFromAlbum: { label: "remove", Icon: RemoveIcon },
+ addPerson: { label: "add_a_person", Icon: PersonAddIcon },
+};
+
+/**
+ * Context menu for file operations, displayed on right-click of file
+ * thumbnails.
+ *
+ * This component renders a single Menu instance that is positioned based on
+ * mouse coordinates. It should be rendered once at the FileList level, not per
+ * thumbnail.
+ */
+export const FileContextMenu: React.FC<FileContextMenuProps> = memo(
+ ({ open, anchorPosition, onClose, actions, onAction, selectedCount }) => {
+ const handleActionClick = useCallback(
+ (action: FileContextAction) => {
+ onClose();
+ onAction(action);
+ },
+ [onClose, onAction],
+ );
+
+ // Separate primary and destructive actions in a single pass
+ const [primaryActions, destructiveActions] = useMemo(() => {
+ const primary: FileContextAction[] = [];
+ const destructive: FileContextAction[] = [];
+ for (const action of actions) {
+ if (actionConfigs[action].isDestructive) {
+ destructive.push(action);
+ } else {
+ primary.push(action);
+ }
+ }
+ return [primary, destructive];
+ }, [actions]);
+
+ return (
+ <StyledMenu
+ open={open}
+ onClose={onClose}
+ anchorReference="anchorPosition"
+ anchorPosition={anchorPosition}
+ slotProps={{
+ root: {
+ onContextMenu: (e: React.MouseEvent) =>
+ e.preventDefault(),
+ },
+ }}
+ >
+ {primaryActions.map((action) => {
+ const { label, Icon } = actionConfigs[action];
+ return (
+ <StyledMenuItem
+ key={action}
+ onClick={() => handleActionClick(action)}
+ >
+ <ListItemIcon>
+ <Icon fontSize="small" />
+ </ListItemIcon>
+ <ListItemText>{t(label)}</ListItemText>
+ </StyledMenuItem>
+ );
+ })}
+ {destructiveActions.length > 0 && primaryActions.length > 0 && (
+ <Divider />
+ )}
+ {destructiveActions.map((action) => {
+ const { label, Icon } = actionConfigs[action];
+ return (
+ <StyledMenuItem
+ key={action}
+ onClick={() => handleActionClick(action)}
+ sx={{ color: "critical.main" }}
+ >
+ <ListItemIcon sx={{ color: "inherit" }}>
+ <Icon fontSize="small" />
+ </ListItemIcon>
+ <ListItemText>{t(label)}</ListItemText>
+ </StyledMenuItem>
+ );
+ })}
+ {selectedCount > 1 && (
+ <Box sx={{ px: 2, pt: 0, pb: 0.5 }}>
+ <Typography
+ variant="small"
+ sx={{
+ color: "text.faint",
+ fontSize: "0.65rem",
+ opacity: 0.7,
+ }}
+ >
+ {t("selected_count", { selected: selectedCount })}
+ </Typography>
+ </Box>
+ )}
+ </StyledMenu>
+ );
+ },
+);
+
+FileContextMenu.displayName = "FileContextMenu";
+
+const StyledMenu = styled(Menu)(({ theme }) => ({
+ "& .MuiPaper-root": {
+ minWidth: 180,
+ borderRadius: 8,
+ boxShadow: theme.shadows[8],
+ },
+}));
+
+const StyledMenuItem = styled(MenuItem)(({ theme }) => ({
+ padding: theme.spacing(1, 2),
+ "& .MuiListItemIcon-root": { minWidth: 32 },
+}));
diff --git a/web/packages/new/photos/components/SelectedFileOptions.tsx b/web/packages/new/photos/components/SelectedFileOptions.tsx
index 42e70d1cda..cf20ef8c81 100644
--- a/web/packages/new/photos/components/SelectedFileOptions.tsx
+++ b/web/packages/new/photos/components/SelectedFileOptions.tsx
@@ -14,22 +14,16 @@ import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import { IconButton, Tooltip, Typography } from "@mui/material";
import { SpacedRow } from "ente-base/components/containers";
import type { ButtonishProps } from "ente-base/components/mui";
-import { useModalVisibility } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
import type { Collection } from "ente-media/collection";
-import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
import type { CollectionSelectorAttributes } from "ente-new/photos/components/CollectionSelector";
import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";
import { StarBorderIcon } from "ente-new/photos/components/icons/StarIcon";
-import { usePeopleStateSnapshot } from "ente-new/photos/components/utils/use-snapshot";
import {
PseudoCollectionID,
type CollectionSummary,
} from "ente-new/photos/services/collection-summary";
-import { isMLEnabled } from "ente-new/photos/services/ml";
import { t } from "i18next";
-import { useMemo } from "react";
-import { useWrapAsyncOperation } from "./utils/use-wrap-async";
/**
* Operations on selected files.
@@ -141,10 +135,15 @@ interface SelectedFileOptionsProps {
*/
createFileOpHandler: (op: FileOp) => () => void;
/**
- * If set, then an option to manually associate the selected file(s) with a
- * person will be shown (when ML is enabled and there are named people).
+ * Callback to show the assign person dialog.
+ *
+ * Similar to {@link onOpenCollectionSelector}, this opens a shared dialog
+ * defined in the parent component where the user can select a person to
+ * associate with the selected files.
+ *
+ * If not set, the "Add Person" option will not be shown.
*/
- onAddPersonToSelectedFiles?: (personID: string) => Promise<void>;
+ onShowAssignPersonDialog?: () => void;
}
/**
@@ -164,31 +163,10 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
createOnCreateForCollectionOp,
createOnSelectForCollectionOp,
createFileOpHandler,
- onAddPersonToSelectedFiles,
+ onShowAssignPersonDialog,
}) => {
const { showMiniDialog } = useBaseContext();
- const peopleState = usePeopleStateSnapshot();
- const namedPeople = useMemo(
- () =>
- (peopleState?.visiblePeople ?? []).filter(
- (p) => p.type == "cgroup" && !!p.name,
- ),
- [peopleState],
- );
- const shouldShowAddPerson =
- !!onAddPersonToSelectedFiles && isMLEnabled() && namedPeople.length > 0;
-
- const { show: showAssignPerson, props: assignPersonVisibilityProps } =
- useModalVisibility();
- const handleSelectPerson = useWrapAsyncOperation(
- async (personID: string) => {
- assignPersonVisibilityProps.onClose();
- if (!onAddPersonToSelectedFiles) return;
- await onAddPersonToSelectedFiles(personID);
- },
- );
-
const isUserFavorites =
!!collectionSummary?.attributes.has("userFavorites");
@@ -336,8 +314,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
<AddToCollectionButton
onClick={handleAddToCollection}
/>
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
<ArchiveButton onClick={handleArchive} />
<HideButton onClick={handleHide} />
@@ -350,8 +328,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
<AddToCollectionButton
onClick={handleAddToCollection}
/>
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
<ArchiveButton onClick={handleArchive} />
<HideButton onClick={handleHide} />
@@ -367,8 +345,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
) : collectionSummary?.attributes.has("uncategorized") ? (
<>
<DownloadButton onClick={handleDownload} />
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
<MoveToCollectionButton
onClick={handleMoveToCollection}
@@ -378,8 +356,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
) : collectionSummary?.attributes.has("sharedIncoming") ? (
<>
<DownloadButton onClick={handleDownload} />
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
<RemoveFromCollectionButton
onClick={handleRemoveFromCollection}
@@ -388,8 +366,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
) : barMode == "hidden-albums" ? (
<>
<DownloadButton onClick={handleDownload} />
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
<UnhideButton onClick={handleUnhide} />
<DeleteButton onClick={handleDelete} />
@@ -406,8 +384,8 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
<AddToCollectionButton
onClick={handleAddToCollection}
/>
- {shouldShowAddPerson && (
- <AddPersonButton onClick={showAssignPerson} />
+ {!!onShowAssignPersonDialog && (
+ <AddPersonButton onClick={onShowAssignPersonDialog} />
)}
{collectionSummary?.id === PseudoCollectionID.all ? (
<ArchiveButton onClick={handleArchive} />
@@ -431,15 +409,6 @@ export const SelectedFileOptions: React.FC<SelectedFileOptionsProps> = ({
</>
)}
</SpacedRow>
-
- {shouldShowAddPerson && (
- <AssignPersonDialog
- {...assignPersonVisibilityProps}
- people={namedPeople}
- title={t("add_a_person")}
- onSelectPerson={handleSelectPerson}
- />
- )}
</>
);
};
diff --git a/web/packages/new/photos/utils/file-actions.ts b/web/packages/new/photos/utils/file-actions.ts
new file mode 100644
index 0000000000..0b8e07d311
--- /dev/null
+++ b/web/packages/new/photos/utils/file-actions.ts
@@ -0,0 +1,171 @@
+import type { GalleryBarMode } from "ente-new/photos/components/gallery/reducer";
+import {
+ PseudoCollectionID,
+ type CollectionSummary,
+} from "ente-new/photos/services/collection-summary";
+
+/**
+ * Actions that can be performed on files via the context menu.
+ *
+ * These correspond to the same operations available in SelectedFileOptions.
+ */
+export type FileContextAction =
+ | "download"
+ | "fixTime"
+ | "favorite"
+ | "archive"
+ | "unarchive"
+ | "hide"
+ | "unhide"
+ | "trash"
+ | "deletePermanently"
+ | "restore"
+ | "addToAlbum"
+ | "moveToAlbum"
+ | "removeFromAlbum"
+ | "addPerson";
+
+/**
+ * Context needed to determine which file actions should be available.
+ */
+export interface FileActionContext {
+ /** The current bar mode (albums, hidden-albums, people). */
+ barMode?: GalleryBarMode;
+ /** Whether we're in search mode. */
+ isInSearchMode: boolean;
+ /**
+ * The collection summary for the current view.
+ *
+ * Will be undefined if we're in people section or showing search results.
+ */
+ collectionSummary: CollectionSummary | undefined;
+ /**
+ * Whether to show the "Add Person" action.
+ *
+ * This depends on ML being enabled and having named people.
+ */
+ showAddPerson: boolean;
+}
+
+/**
+ * Returns the list of available file actions based on the current context.
+ *
+ * This function encapsulates the conditional logic from SelectedFileOptions
+ * to enable reuse in both the selection bar and the context menu.
+ */
+export function getAvailableFileActions(
+ context: FileActionContext,
+): FileContextAction[] {
+ const { barMode, isInSearchMode, collectionSummary, showAddPerson } =
+ context;
+
+ const actions = getBaseActions(barMode, isInSearchMode, collectionSummary);
+
+ // Insert "addPerson" before modification actions if enabled
+ // (not applicable for trash since you can't add people to trashed files)
+ if (showAddPerson && collectionSummary?.id !== PseudoCollectionID.trash) {
+ insertAddPersonBeforeModifications(actions);
+ }
+
+ return actions;
+}
+
+/**
+ * Returns base actions without the "addPerson" action.
+ */
+function getBaseActions(
+ barMode: GalleryBarMode | undefined,
+ isInSearchMode: boolean,
+ collectionSummary: CollectionSummary | undefined,
+): FileContextAction[] {
+ // Search mode actions
+ if (isInSearchMode) {
+ return [
+ "favorite",
+ "fixTime",
+ "download",
+ "addToAlbum",
+ "archive",
+ "hide",
+ "trash",
+ ];
+ }
+
+ // People mode actions
+ if (barMode === "people") {
+ return ["favorite", "download", "addToAlbum", "archive", "hide", "trash"];
+ }
+
+ // Trash actions
+ if (collectionSummary?.id === PseudoCollectionID.trash) {
+ return ["restore", "deletePermanently"];
+ }
+
+ // Uncategorized actions
+ if (collectionSummary?.attributes.has("uncategorized")) {
+ return ["download", "moveToAlbum", "trash"];
+ }
+
+ // Shared incoming actions
+ if (collectionSummary?.attributes.has("sharedIncoming")) {
+ return ["download", "removeFromAlbum"];
+ }
+
+ // Hidden albums mode actions
+ if (barMode === "hidden-albums") {
+ return ["download", "unhide", "trash"];
+ }
+
+ // Default (normal albums) actions
+ const isUserFavorites =
+ !!collectionSummary?.attributes.has("userFavorites");
+ const isArchiveItems =
+ collectionSummary?.id === PseudoCollectionID.archiveItems;
+
+ const actions: FileContextAction[] = [];
+
+ // Favorite button only shown when not in favorites and not in archive
+ if (!isUserFavorites && !isArchiveItems) {
+ actions.push("favorite");
+ }
+
+ actions.push("fixTime", "download", "addToAlbum");
+
+ if (collectionSummary?.id === PseudoCollectionID.all) {
+ actions.push("archive");
+ } else if (isArchiveItems) {
+ actions.push("unarchive");
+ } else if (!isUserFavorites) {
+ actions.push("moveToAlbum", "removeFromAlbum");
+ }
+
+ actions.push("hide", "trash");
+
+ return actions;
+}
+
+/**
+ * Actions that modify file visibility or location.
+ * "addPerson" is inserted before the first of these actions.
+ */
+const modificationActions: FileContextAction[] = [
+ "archive",
+ "unarchive",
+ "hide",
+ "unhide",
+ "trash",
+ "moveToAlbum",
+ "removeFromAlbum",
+];
+
+/**
+ * Inserts "addPerson" before the first modification action in the array.
+ */
+function insertAddPersonBeforeModifications(actions: FileContextAction[]): void {
+ const insertIndex = actions.findIndex((a) => modificationActions.includes(a));
+ if (insertIndex !== -1) {
+ actions.splice(insertIndex, 0, "addPerson");
+ } else {
+ actions.push("addPerson");
+ }
+}