Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import {
galleryImageItemToGalleryImage,
galleryItems,
isGalleryImageItem,
legacyGeneratedImageToGalleryItem,
toGalleryItemKey,
} from '@features/gallery';
import {
getGalleryCompareImage,
getGalleryMoveTargets,
getSelectedGalleryItemFromValues,
} from '@features/gallery/contracts';
import { galleryKeys } from '@features/gallery/queries';
import { canCopyImage } from '@platform/browser/clipboard';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { MenuContent, MenuIconItem } from '@platform/ui';
import { MenuItem } from '@platform/ui/Menu';
import { useQuery } from '@tanstack/react-query';
import { formatHotkeyPartLabel } from '@workbench/hotkeys/keys';
import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
BoxIcon,
CopyIcon,
CrosshairIcon,
DownloadIcon,
ExternalLinkIcon,
EyeIcon,
FileJsonIcon,
FolderIcon,
ImagesIcon,
StarIcon,
Trash2Icon,
WorkflowIcon,
XIcon,
type LucideIcon,
} from 'lucide-react';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { ImageRecallCapabilities } from './imageRecall';
import type { ImageActions } from './useImageActions';
import { ContextSubMenu, IMAGE_MENU_CONTENT_PROPS } from './ContextSubMenu';
import { GalleryBoardDestinationGroups } from './GalleryBoardDestinationGroups';
import { ImageContinueGroup, ImageUseGroups, VideoUseGroups } from './ImageItemMenuGroups';
import { useImageRecallCapabilities } from './useImageRecallCapabilities';
export interface LegacyImageContextMenuTarget {
/** Right-clicked image first; more entries switch the menu into bulk mode. */
images: GalleryImage[];
x: number;
y: number;
}
export type ImageContextMenuTarget = LegacyImageContextMenuTarget | GalleryItemContextMenuTarget;
/**
* `housekeeping` leaves out the groups a host offers beside the menu (Preview's Edit and Use menus): what to continue
* working on with the image, and what to take from the image or video. Single items only; selections stay full.
*/
export type ImageContextMenuVariant = 'full' | 'housekeeping';
/**
* Extra actions of Preview's selected native video; other hosts omit this port, so grid menus never gain frame copy.
*/
export interface PreviewVideoContextActions {
isCopyCurrentFrameAvailable: boolean;
itemKey: GalleryItemKey;
onCopyCurrentFrame: () => void;
onOpenDetails: () => void;
}
const isUsableGalleryImage = (value: unknown): value is GalleryImage =>
Boolean(value) &&
typeof value === 'object' &&
typeof (value as GalleryImage).imageName === 'string' &&
typeof (value as GalleryImage).imageUrl === 'string' &&
typeof (value as GalleryImage).thumbnailUrl === 'string';
export const getImageContextMenuImages = (target: ImageContextMenuTarget | null): GalleryImage[] => {
if (target && 'itemRefs' in target) {
const loadedItemsByKey = new Map(target.items.map((item) => [toGalleryItemKey(item), item]));
const imageItems = target.itemRefs.flatMap((ref) => {
const item = loadedItemsByKey.get(toGalleryItemKey(ref));
return item && isGalleryImageItem(item) ? [item] : [];
});
return imageItems.length === target.itemRefs.length ? imageItems.map(galleryImageItemToGalleryImage) : [];
}
if (!Array.isArray(target?.images)) {
return [];
}
return target.images.filter(isUsableGalleryImage);
};
const toGalleryItemContextMenuTarget = (target: ImageContextMenuTarget | null): GalleryItemContextMenuTarget | null => {
if (!target) {
return null;
}
if ('itemRefs' in target) {
return target;
}
const images = getImageContextMenuImages(target);
const items = images.map(legacyGeneratedImageToGalleryItem);
return {
itemRefs: items.map(({ kind, name }) => ({ kind, name })),
items,
x: target.x,
y: target.y,
};
};
/** Shared image context menu anchored to a cursor rect; setting target opens it without a trigger element. */
export const ImageContextMenu = ({
actions,
boards,
previewVideoActions,
returnFocus: hostReturnFocus,
target,
variant = 'full',
onClose,
}: {
actions: ImageActions;
/** The host's board listing as it shows it: folded through `useHostGalleryBoards` where boards cannot be shared. */
boards: GalleryBoard[];
previewVideoActions?: PreviewVideoContextActions;
/**
* Where focus goes when a deletion confirmation the menu opened closes, unless the target names its own. Without
* either the dialog returns focus to what had it as it opened, which the deletion may have removed.
*/
returnFocus?: () => HTMLElement | null;
target: ImageContextMenuTarget | null;
variant?: ImageContextMenuVariant;
onClose: () => void;
}) => {
const itemTarget = toGalleryItemContextMenuTarget(target);
const images = getImageContextMenuImages(itemTarget);
const isCompleteImageTarget = Boolean(itemTarget && images.length === itemTarget.itemRefs.length);
const imageTarget = useMemo<LegacyImageContextMenuTarget | null>(
() => (itemTarget && isCompleteImageTarget ? { images, x: itemTarget.x, y: itemTarget.y } : null),
[images, isCompleteImageTarget, itemTarget]
);
const returnFocus = itemTarget?.returnFocus ?? hostReturnFocus;
const requestDeletion = useCallback(
(itemRefs: GalleryItemRef[]) => void actions.deleteItems(itemRefs, { returnFocus }),
[actions, returnFocus]
);
const requestImageDeletion = useCallback(
(imageNames: string[]) => requestDeletion(imageNames.map((name) => ({ kind: 'image', name }))),
[requestDeletion]
);
if (!itemTarget) {
return null;
}
return imageTarget ? (
<ImageContextMenuContent
key={`${images[0]?.imageName ?? 'image'}:${images.length}`}
actions={actions}
boards={boards}
image={images[0] ?? null}
images={images}
target={imageTarget}
variant={variant}
onClose={onClose}
onRequestDeletion={requestImageDeletion}
/>
) : (
<GalleryItemContextMenuContent
key={`${itemTarget.itemRefs[0] ? toGalleryItemKey(itemTarget.itemRefs[0]) : 'item'}:${itemTarget.itemRefs.length}`}
actions={actions}
boards={boards}
previewVideoActions={previewVideoActions}
target={itemTarget}
variant={variant}
onClose={onClose}
onRequestDeletion={requestDeletion}
/>
);
};
const GalleryItemContextMenuContent = ({
actions,
boards,
previewVideoActions,
target,
variant,
onClose,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
previewVideoActions?: PreviewVideoContextActions;
target: GalleryItemContextMenuTarget;
variant: ImageContextMenuVariant;
onClose: () => void;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
const targetRef = useRef(target);
const item = target.items[0] ?? null;
const itemRef = target.itemRefs[0] ?? null;
const isBulk = target.itemRefs.length > 1;
// eslint-disable-next-line react/refs
targetRef.current = target;
const positioning = useMemo(
() => ({
getAnchorRect: () => {
const currentTarget = targetRef.current;
return { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y };
},
placement: 'bottom-start' as const,
}),
[]
);
const handleOpenChange = useCallback(
(event: { open: boolean }) => {
if (!event.open) {
onClose();
}
},
[onClose]
);
if (!item || !itemRef) {
return null;
}
return (
<Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
<Portal>
<Menu.Positioner>
<MenuContent
{...IMAGE_MENU_CONTENT_PROPS}
maxH="min(28rem, calc(100vh - 2rem))"
minW="16rem"
overflowY="auto"
>
{isBulk ? (
<BulkItemMenuItems
actions={actions}
allStarred={target.allStarred}
boards={boards}
itemRefs={target.itemRefs}
listingBoardId={target.listingBoardId}
loadedItems={target.items}
primaryItem={item}
onRequestDeletion={onRequestDeletion}
/>
) : (
<SingleItemMenuItems
actions={actions}
boards={boards}
item={item}
itemRef={itemRef}
previewVideoActions={previewVideoActions}
variant={variant}
onRequestDeletion={onRequestDeletion}
/>
)}
</MenuContent>
</Menu.Positioner>
</Portal>
</Menu.Root>
);
};
const SingleItemMenuItems = ({
actions,
boards,
item,
itemRef,
previewVideoActions,
variant,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
item: GalleryItem;
itemRef: GalleryItemRef;
previewVideoActions?: PreviewVideoContextActions;
variant: ImageContextMenuVariant;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
const { t } = useTranslation();
const isVideo = item.kind === 'video';
const handleOpenInNewTab = useCallback(() => actions.openItemInNewTab(item), [actions, item]);
const handleDownload = useCallback(() => void actions.downloadItem(item), [actions, item]);
const handleOpenPreview = useCallback(() => actions.openItemInPreview(item), [actions, item]);
const handleToggleStarred = useCallback(
() => void actions.setItemsStarred([itemRef], !item.starred),
[actions, item.starred, itemRef]
);
const handleMove = useCallback(
(boardId: string) => void actions.moveItemsToBoard([itemRef], boardId),
[actions, itemRef]
);
const handleDelete = useCallback(() => onRequestDeletion([itemRef]), [itemRef, onRequestDeletion]);
const singleSourceBoardIds = useMemo(() => [item.boardId], [item.boardId]);
const owner = captureAccountScope();
const videoItem = item.kind === 'video' ? item : null;
const videoName = videoItem?.name ?? '';
// The record answers whether a workflow is embedded only when the listing did not say.
const readsVideoRecord = videoItem !== null && videoItem.hasWorkflow === undefined;
const videoHasWorkflowQuery = useQuery({
enabled: readsVideoRecord,
queryFn: async ({ signal }) => {
let hasWorkflow: boolean;
try {
const record = await galleryItems.resolve(
{ kind: 'video', name: videoName },
AbortSignal.any([signal, owner.signal])
);
hasWorkflow = record.kind === 'video' && record.hasWorkflow === true;
} catch (error: unknown) {
// The server no longer has the video: a final answer, not a failure.
if (!(error instanceof ApiError && error.status === 404)) {
throw error;
}
hasWorkflow = false;
}
assertAccountScopeCurrent(owner);
return hasWorkflow;
},
queryKey: galleryKeys.videoHasWorkflow(owner, videoName),
// One policy whoever starts the read, as for metadata; whether a video embeds a workflow never changes.
retry: false,
staleTime: Infinity,
});
const isLoadingVideoWorkflow = readsVideoRecord && videoHasWorkflowQuery.isPending;
const hasVideoWorkflow = readsVideoRecord ? videoHasWorkflowQuery.data === true : videoItem?.hasWorkflow === true;
const handleLoadVideoWorkflow = useCallback(() => {
if (item.kind === 'video') {
void actions.loadVideoWorkflow(item);
}
}, [actions, item]);
return (
<>
<HStack gap="1">
<MenuIconItem
icon={ExternalLinkIcon}
label={t('widgets.gallery.itemMenu.openInNewTab')}
value="open-in-new-tab"
onSelect={handleOpenInNewTab}
/>
<MenuIconItem
icon={DownloadIcon}
label={t(isVideo ? 'widgets.gallery.itemMenu.downloadVideo' : 'widgets.gallery.itemMenu.downloadImage')}
value="download-item"
onSelect={handleDownload}
/>
<MenuIconItem
icon={EyeIcon}
label={t('widgets.gallery.itemMenu.openInPreview')}
value="open-in-preview"
onSelect={handleOpenPreview}
/>
<MenuIconItem
icon={StarIcon}
iconFill={item.starred ? 'currentColor' : 'none'}
label={t(
isVideo
? item.starred
? 'widgets.preview.unstarVideo'
: 'widgets.preview.starVideo'
: item.starred
? 'widgets.preview.unstarImage'
: 'widgets.preview.starImage'
)}
value="toggle-starred"
onSelect={handleToggleStarred}
/>
</HStack>
<Menu.Separator borderColor="border.subtle" />
{item.kind === 'video' ? (
<>
<ContextMenuItem
disabled={isLoadingVideoWorkflow || !hasVideoWorkflow}
icon={WorkflowIcon}
label={t('widgets.gallery.itemActions.loadWorkflow.label')}
value="load-video-workflow"
onClick={handleLoadVideoWorkflow}
/>
{variant === 'full' ? (
<>
<Menu.Separator borderColor="border.subtle" />
<VideoUseGroups actions={actions} item={item} presentation="compact" />
<Menu.Separator borderColor="border.subtle" />
</>
) : null}
</>
) : null}
{item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (
<>
<ContextMenuItem
// Without a clipboard (plain HTTP) the item says why; a frame still loading only disables it.
disabled={!previewVideoActions.isCopyCurrentFrameAvailable}
icon={CopyIcon}
label={t('widgets.preview.copyCurrentFrame')}
unavailableReason={canCopyImage() ? undefined : t('common.copyUnavailable')}
value="copy-current-video-frame"
onClick={previewVideoActions.onCopyCurrentFrame}
/>
<ContextMenuItem
icon={FileJsonIcon}
label={t('widgets.preview.videoDetails')}
value="open-video-details"
onClick={previewVideoActions.onOpenDetails}
/>
<Menu.Separator borderColor="border.subtle" />
</>
) : null}
<FindInGalleryMenuItem itemRef={itemRef} />
<ChangeBoardSubMenu boards={boards} itemBoardIds={singleSourceBoardIds} onMove={handleMove} />
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
isDanger
icon={Trash2Icon}
label={t(isVideo ? 'widgets.gallery.itemMenu.deleteVideo' : 'widgets.gallery.itemMenu.deleteImage')}
value="delete-item"
onClick={handleDelete}
/>
</>
);
};
const BulkItemMenuItems = ({
actions,
allStarred: knownAllStarred,
boards,
itemRefs,
listingBoardId,
loadedItems,
primaryItem,
onRequestDeletion,
}: {
actions: ImageActions;
allStarred: boolean | undefined;
boards: GalleryBoard[];
itemRefs: GalleryItemRef[];
/** The board the listing the selection was made in reads, where items no page holds sit. */
listingBoardId: string | undefined;
loadedItems: GalleryItem[];
primaryItem: GalleryItem;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
const { t } = useTranslation();
const allStarred =
knownAllStarred ?? (loadedItems.length === itemRefs.length && loadedItems.every((item) => item.starred));
const handleOpenInNewTab = useCallback(() => actions.openItemInNewTab(primaryItem), [actions, primaryItem]);
const handleOpenPreview = useCallback(() => actions.openItemInPreview(primaryItem), [actions, primaryItem]);
const handleToggleStarred = useCallback(
() => void actions.setItemsStarred(itemRefs, !allStarred),
[actions, allStarred, itemRefs]
);
const handleDownload = useCallback(
() => void actions.downloadItems(itemRefs, loadedItems),
[actions, itemRefs, loadedItems]
);
const handleMove = useCallback(
(boardId: string) => void actions.moveItemsToBoard(itemRefs, boardId),
[actions, itemRefs]
);
const handleDelete = useCallback(() => onRequestDeletion(itemRefs), [itemRefs, onRequestDeletion]);
const itemBoardIds = useMemo(() => loadedItems.map((item) => item.boardId), [loadedItems]);
return (
<>
<Text color="fg.subtle" fontSize="xs" fontWeight="700" px="3" py="1.5" textTransform="uppercase">
{t('widgets.gallery.itemMenu.itemsSelected', { count: itemRefs.length })}
</Text>
<Menu.Separator borderColor="border.subtle" />
<HStack gap="1">
<MenuIconItem
icon={ExternalLinkIcon}
label={t('widgets.gallery.itemMenu.openInNewTab')}
value="open-primary-in-new-tab"
onSelect={handleOpenInNewTab}
/>
<MenuIconItem
icon={EyeIcon}
label={t('widgets.gallery.itemMenu.openInPreview')}
value="open-primary-in-preview"
onSelect={handleOpenPreview}
/>
</HStack>
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
icon={StarIcon}
iconFill={allStarred ? 'currentColor' : 'none'}
label={t(allStarred ? 'widgets.gallery.unstarSelection' : 'widgets.gallery.starSelection')}
value="toggle-starred-all"
onClick={handleToggleStarred}
/>
<ContextMenuItem
icon={DownloadIcon}
label={t('widgets.gallery.downloadSelection')}
value="download-selection"
onClick={handleDownload}
/>
<ChangeBoardSubMenu
boards={boards}
itemBoardIds={itemBoardIds}
listingBoardId={listingBoardId}
unloadedCount={itemRefs.length - loadedItems.length}
onMove={handleMove}
/>
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
isDanger
icon={Trash2Icon}
label={t('widgets.gallery.deleteSelection')}
value="delete-selection"
onClick={handleDelete}
/>
</>
);
};
const ImageContextMenuContent = ({
actions,
boards,
image,
images,
target,
variant,
onClose,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
image: GalleryImage;
images: GalleryImage[];
target: ImageContextMenuTarget;
variant: ImageContextMenuVariant;
onClose: () => void;
onRequestDeletion: (imageNames: string[]) => void;
}) => {
const targetRef = useRef(target);
// eslint-disable-next-line react/refs
targetRef.current = target;
const isBulk = images.length > 1;
const imageNames = useMemo(() => images.map((candidate) => candidate.imageName), [images]);
const { capabilities: recallCapabilities, isLoading: isLoadingRecallCapabilities } = useImageRecallCapabilities(
actions,
isBulk ? null : image
);
const positioning = useMemo(
() => ({
getAnchorRect: () => {
const currentTarget = targetRef.current;
return { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y };
},
placement: 'bottom-start' as const,
}),
[]
);
const handleOpenChange = useCallback(
(event: { open: boolean }) => {
if (!event.open) {
onClose();
}
},
[onClose]
);
return (
<Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
<Portal>
<Menu.Positioner>
<MenuContent
{...IMAGE_MENU_CONTENT_PROPS}
maxH="min(36rem, calc(100vh - 2rem))"
minW="16rem"
overflowY="auto"
>
{isBulk ? (
<BulkMenuItems
actions={actions}
boards={boards}
imageNames={imageNames}
images={images}
onRequestDeletion={onRequestDeletion}
/>
) : (
<SingleImageMenuItems
actions={actions}
boards={boards}
image={image}
images={images}
isLoadingRecallCapabilities={isLoadingRecallCapabilities}
recallCapabilities={recallCapabilities}
variant={variant}
onRequestDeletion={onRequestDeletion}
/>
)}
</MenuContent>
</Menu.Positioner>
</Portal>
</Menu.Root>
);
};
const SingleImageMenuItems = ({
actions,
boards,
image,
images,
isLoadingRecallCapabilities,
recallCapabilities,
variant,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
image: GalleryImage;
images: GalleryImage[];
isLoadingRecallCapabilities: boolean;
recallCapabilities: ImageRecallCapabilities;
variant: ImageContextMenuVariant;
onRequestDeletion: (imageNames: string[]) => void;
}) => {
const { t } = useTranslation();
const handleMove = useCallback(
(boardId: string) => void actions.moveImagesToBoard([image.imageName], boardId),
[actions, image.imageName]
);
const handleDelete = useCallback(() => onRequestDeletion([image.imageName]), [image.imageName, onRequestDeletion]);
const imageSourceBoardIds = useMemo(() => [image.boardId], [image.boardId]);
const imageItemRef = useMemo<GalleryItemRef>(() => ({ kind: 'image', name: image.imageName }), [image.imageName]);
const handleLoadWorkflow = useCallback(() => void actions.loadImageWorkflow(image), [actions, image]);
const handleGeneratePbrMaps = useCallback(() => void actions.generatePbrMaps(image), [actions, image]);
return (
<>
<HStack gap="1">
<OpenInNewTabQuickMenuItem image={image} />
<CopyQuickMenuItem actions={actions} image={image} />
<DownloadQuickMenuItem actions={actions} image={image} />
<OpenPreviewQuickMenuItem actions={actions} image={image} />
<ToggleStarQuickMenuItem actions={actions} image={image} />
</HStack>
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
disabled={isLoadingRecallCapabilities || !recallCapabilities.workflow}
icon={WorkflowIcon}
label={t('widgets.gallery.itemActions.loadWorkflow.label')}
value="load-workflow"
onClick={handleLoadWorkflow}
/>
{variant === 'full' ? (
<>
<Menu.Separator borderColor="border.subtle" />
<ImageContinueGroup actions={actions} images={images} presentation="compact" />
<Menu.Separator borderColor="border.subtle" />
<ImageUseGroups
actions={actions}
capabilities={recallCapabilities}
image={image}
isLoadingCapabilities={isLoadingRecallCapabilities}
presentation="compact"
/>
<Menu.Separator borderColor="border.subtle" />
</>
) : null}
<SelectForCompareMenuItem actions={actions} image={image} />
<ContextMenuItem
icon={BoxIcon}
label={t('widgets.gallery.itemActions.pbrMaps.label')}
value="generate-pbr-maps"
onClick={handleGeneratePbrMaps}
/>
<Menu.Separator borderColor="border.subtle" />
<FindInGalleryMenuItem itemRef={imageItemRef} />
<ChangeBoardSubMenu boards={boards} itemBoardIds={imageSourceBoardIds} onMove={handleMove} />
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
isDanger
icon={Trash2Icon}
label={t('widgets.gallery.itemMenu.deleteImage')}
value="delete-image"
onClick={handleDelete}
/>
</>
);
};
const OpenInNewTabQuickMenuItem = ({ image }: { image: GalleryImage }) => {
const { t } = useTranslation();
const handleClick = useCallback(() => window.open(image.imageUrl, '_blank', 'noopener'), [image.imageUrl]);
return (
<MenuIconItem
icon={ExternalLinkIcon}
label={t('widgets.gallery.itemMenu.openInNewTab')}
value="open-in-new-tab"
onSelect={handleClick}
/>
);
};
const CopyQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {
const { t } = useTranslation();
const handleClick = useCallback(() => void actions.copyImage(image), [actions, image]);
return (
<MenuIconItem
icon={CopyIcon}
label={t('widgets.gallery.itemMenu.copyToClipboard')}
unavailableReason={canCopyImage() ? undefined : t('common.copyUnavailable')}
value="copy-to-clipboard"
onSelect={handleClick}
/>
);
};
const DownloadQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {
const { t } = useTranslation();
const handleClick = useCallback(() => void actions.downloadImage(image), [actions, image]);
return (
<MenuIconItem
icon={DownloadIcon}
label={t('widgets.gallery.itemMenu.downloadImage')}
value="download-image"
onSelect={handleClick}
/>
);
};
const OpenPreviewQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {
const { t } = useTranslation();
const handleClick = useCallback(() => actions.openImageInPreview(image), [actions, image]);
return (
<MenuIconItem
icon={EyeIcon}
label={t('widgets.gallery.itemMenu.openInPreview')}
value="open-in-preview"
onSelect={handleClick}
/>
);
};
const ToggleStarQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {
const { t } = useTranslation();
const handleClick = useCallback(
() => void actions.setImagesStarred([image.imageName], !image.starred),
[actions, image.imageName, image.starred]
);
return (
<MenuIconItem
icon={StarIcon}
iconFill={image.starred ? 'currentColor' : 'none'}
label={t(image.starred ? 'widgets.preview.unstarImage' : 'widgets.preview.starImage')}
value="toggle-starred"
onSelect={handleClick}
/>
);
};
const BulkMenuItems = ({
actions,
boards,
imageNames,
images,
onRequestDeletion,
}: {
actions: ImageActions;
boards: GalleryBoard[];
imageNames: string[];
images: GalleryImage[];
onRequestDeletion: (imageNames: string[]) => void;
}) => {
const { t } = useTranslation();
const allStarred = images.every((image) => image.starred);
const sourceBoardIds = useMemo(() => images.map((image) => image.boardId), [images]);
const handleToggleStarred = useCallback(
() => void actions.setImagesStarred(imageNames, !allStarred),
[actions, allStarred, imageNames]
);
const handleDownload = useCallback(() => void actions.downloadImages(imageNames), [actions, imageNames]);
const handleMove = useCallback(
(boardId: string) => void actions.moveImagesToBoard(imageNames, boardId),
[actions, imageNames]
);
const handleDelete = useCallback(() => onRequestDeletion(imageNames), [imageNames, onRequestDeletion]);
return (
<>
<Text color="fg.subtle" fontSize="xs" fontWeight="700" px="3" py="1.5" textTransform="uppercase">
{t('widgets.gallery.itemMenu.imagesSelected', { count: images.length })}
</Text>
<Menu.Separator borderColor="border.subtle" />
<ImageContinueGroup actions={actions} images={images} presentation="compact" />
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
icon={StarIcon}
iconFill={allStarred ? 'currentColor' : 'none'}
label={t(allStarred ? 'widgets.gallery.unstarSelection' : 'widgets.gallery.starSelection')}
value="toggle-starred-all"
onClick={handleToggleStarred}
/>
<ContextMenuItem
icon={DownloadIcon}
label={t('widgets.gallery.downloadSelection')}
value="download-selection"
onClick={handleDownload}
/>
<ChangeBoardSubMenu boards={boards} itemBoardIds={sourceBoardIds} onMove={handleMove} />
<Menu.Separator borderColor="border.subtle" />
<ContextMenuItem
isDanger
icon={Trash2Icon}
label={t('widgets.gallery.deleteSelection')}
value="delete-selection"
onClick={handleDelete}
/>
</>
);
};
const FindInGalleryMenuItem = ({ itemRef }: { itemRef: GalleryItemRef }) => {
const { t } = useTranslation();
const findGalleryItem = useFindGalleryItem();
const handleClick = useCallback(() => findGalleryItem(itemRef), [findGalleryItem, itemRef]);
return (
<ContextMenuItem
icon={CrosshairIcon}
label={t('widgets.gallery.findInGallery')}
value="find-in-gallery"
onClick={handleClick}
/>
);
};
/** The move targets the selection bar offers too (`getGalleryMoveTargets`), for the items' boards as known. */
const ChangeBoardSubMenu = ({
boards,
itemBoardIds,
listingBoardId,
unloadedCount = 0,
onMove,
}: {
boards: GalleryBoard[];
itemBoardIds: readonly string[];
listingBoardId?: string;
unloadedCount?: number;
onMove: (boardId: string) => void;
}) => {
const { t } = useTranslation();
const handleRemoveFromBoard = useCallback(() => onMove('none'), [onMove]);
const handleSelectBoard = useCallback((board: GalleryBoard) => onMove(board.id), [onMove]);
const { boards: destinations, canRemoveFromBoard } = useMemo(
() => getGalleryMoveTargets(boards, { itemBoardIds, listingBoardId, unloadedCount }),
[boards, itemBoardIds, listingBoardId, unloadedCount]
);
return (
<ContextSubMenu icon={FolderIcon} label={t('widgets.gallery.changeBoard')}>
{canRemoveFromBoard && (
<ContextMenuItem
icon={FolderIcon}
label={t('widgets.gallery.removeFromBoard')}
value="remove-from-board"
onClick={handleRemoveFromBoard}
/>
)}
<GalleryBoardDestinationGroups boards={destinations} onSelect={handleSelectBoard} />
</ContextSubMenu>
);
};
/** The image Select for compare is waiting with, if any: the comparison image that is also the selection. */
const selectArmedCompareImageName = (values: Record<string, unknown>): string | null => {
const compareImage = getGalleryCompareImage(values);
const selectedItem = getSelectedGalleryItemFromValues(values);
return compareImage && selectedItem?.kind === 'image' && selectedItem.name === compareImage.imageName
? compareImage.imageName
: null;
};
/**
* Select for compare, or on the image it is already waiting with, the way to call it off, as the Preview toggle does.
* It reads the comparison itself, so the shared actions stay independent of the selection.
*/
const SelectForCompareMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {
const { t } = useTranslation();
const { gallery } = useWorkbenchCommands();
const isArmedWithImage = useWidgetValuesSelector('gallery', selectArmedCompareImageName) === image.imageName;
const handleClick = useCallback(
() => (isArmedWithImage ? gallery.setCompareItem(null) : actions.selectForCompare(image)),
[actions, gallery, image, isArmedWithImage]
);
return isArmedWithImage ? (
<ContextMenuItem
icon={XIcon}
label={t('widgets.preview.cancelCompare')}
value="cancel-compare"
onClick={handleClick}
/>
) : (
<ContextMenuItem
// The grid's shortcut for the same action, otherwise found only by accident.
detail={t('widgets.gallery.itemMenu.compareShortcut', { key: formatHotkeyPartLabel('alt') })}
icon={ImagesIcon}
label={t('widgets.preview.selectForCompare')}
value="select-for-compare"
onClick={handleClick}
/>
);
};
const ContextMenuItem = ({
detail,
disabled,
icon,
iconFill,
isDanger,
label,
unavailableReason,
value,
onClick,
}: {
/** A short hint after the label, such as the pointer shortcut for the same action. */
detail?: string;
disabled?: boolean;
icon: LucideIcon;
/** Lucide icons are stroke-only, so `'currentColor'` is how an on state reads. */
iconFill?: string;
isDanger?: boolean;
label: string;
/** Why the item cannot act now; see `MenuItem`. */
unavailableReason?: string;
value: string;
onClick?: () => void;
}) => (
<MenuItem
data-danger={isDanger ? '' : undefined}
disabled={disabled}
unavailableReason={unavailableReason}
value={value}
onClick={onClick}
>
<HStack gap="2" minW="0" w="full">
<Icon as={icon} boxSize="3.5" color={isDanger ? undefined : 'fg.subtle'} fill={iconFill} flexShrink={0} />
<Text flex="1" fontSize="md">
{label}
</Text>
{detail ? (
<Text color="fg.muted" flexShrink={0} fontSize="sm">
{detail}
</Text>
) : null}
</HStack>
</MenuItem>
);