Skip to content

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.

feat(webv2): move preview chrome into the header and dock the filmstrip

Josh Corbettc41a34a99d56
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 20a21c4505..5ca366125c 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1720,6 +1720,7 @@
"source:src/workbench/widgets/preview/PreviewActionStrip.tsx",
"source:src/workbench/widgets/preview/PreviewCompare.tsx",
"source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx",
+ "source:src/workbench/widgets/preview/PreviewDetailsPopover.tsx",
"source:src/workbench/widgets/preview/PreviewFilmstrip.tsx",
"source:src/workbench/widgets/preview/PreviewFooter.tsx",
"source:src/workbench/widgets/preview/PreviewFrame.tsx",
@@ -1728,6 +1729,7 @@
"source:src/workbench/widgets/preview/PreviewStage.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetView.tsx",
+ "source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",
"source:src/workbench/widgets/preview/implementation.ts",
"source:src/workbench/widgets/preview/livePreviewFollow.tsx",
"source:src/workbench/widgets/preview/loupeGestures.ts",
@@ -2913,6 +2915,7 @@
"source:src/workbench/widgets/preview/PreviewActionStrip.tsx",
"source:src/workbench/widgets/preview/PreviewCompare.tsx",
"source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx",
+ "source:src/workbench/widgets/preview/PreviewDetailsPopover.tsx",
"source:src/workbench/widgets/preview/PreviewFilmstrip.tsx",
"source:src/workbench/widgets/preview/PreviewFooter.tsx",
"source:src/workbench/widgets/preview/PreviewFrame.tsx",
@@ -2921,6 +2924,7 @@
"source:src/workbench/widgets/preview/PreviewStage.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetView.tsx",
+ "source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",
"source:src/workbench/widgets/preview/implementation.ts",
"source:src/workbench/widgets/preview/livePreviewFollow.tsx",
"source:src/workbench/widgets/preview/loupeGestures.ts",
@@ -4026,6 +4030,7 @@
"source:src/workbench/widgets/preview/PreviewActionStrip.tsx",
"source:src/workbench/widgets/preview/PreviewCompare.tsx",
"source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx",
+ "source:src/workbench/widgets/preview/PreviewDetailsPopover.tsx",
"source:src/workbench/widgets/preview/PreviewFilmstrip.tsx",
"source:src/workbench/widgets/preview/PreviewFooter.tsx",
"source:src/workbench/widgets/preview/PreviewFrame.tsx",
@@ -4034,6 +4039,7 @@
"source:src/workbench/widgets/preview/PreviewStage.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",
"source:src/workbench/widgets/preview/PreviewWidgetView.tsx",
+ "source:src/workbench/widgets/preview/PreviewZoomMenu.tsx",
"source:src/workbench/widgets/preview/implementation.ts",
"source:src/workbench/widgets/preview/livePreviewFollow.tsx",
"source:src/workbench/widgets/preview/loupeGestures.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 8d5dc1a9fa..4074635ea9 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2548,13 +2548,7 @@
"loadingMetadata": "Loading metadata",
"metadata": "Metadata",
"metadataJsonLabel": "Video metadata JSON",
- "nextItemInBoard": "Next item in board",
- "nextImageInBoard": "Next image in board",
"noGallerySelection": "No gallery selection",
- "previousItemInBoard": "Previous item in board",
- "recallNotAvailable": "Not recallable for this image",
- "previousImageInBoard": "Previous image in board",
- "resetZoom": "Reset zoom",
"showFilmstrip": "Show filmstrip",
"showInProgressDiffusion": "Show in-progress diffusion",
"sideBySide": "Side by Side",
@@ -2570,7 +2564,17 @@
"viewing": "Viewing",
"workflow": "Workflow",
"workflowJsonLabel": "Video workflow JSON",
- "showAllActivePreviews": "Show all active previews"
+ "showAllActivePreviews": "Show all active previews",
+ "zoom": "Zoom",
+ "zoomLevel": "Zoom {{percent}}%",
+ "zoomPercent": "{{percent}}%",
+ "zoomFit": "Fit to view",
+ "selectForCompare": "Select for Compare",
+ "imageActions": "Image actions",
+ "starImage": "Star image",
+ "unstarImage": "Unstar image",
+ "starVideo": "Star video",
+ "unstarVideo": "Unstar video"
},
"queue": {
"allScopedItemsRequested": "All scoped queue items were requested.",
@@ -2642,7 +2646,6 @@
"queued_one": "{{count}} queued",
"queued_other": "{{count}} queued",
"recallAll": "Recall All",
- "recallFromGallery": "Recall this generation from the gallery",
"recallUnavailable": "Nothing recallable for this item — select a supported Generate model first.",
"recallUnavailableCapabilities": "Nothing recallable yet — model capabilities have not loaded. If loading failed, retry from the Generate panel.",
"recallUnavailableForItem": "Nothing recallable for this item.",
diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx
index 12035d62d2..7e34cc816c 100644
--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.tsx
@@ -2,6 +2,8 @@ import { Tooltip as ChakraTooltip, Portal } from '@chakra-ui/react';
import {
cloneElement,
isValidElement,
+ useId,
+ useMemo,
type ComponentProps,
type ReactElement,
type ReactNode,
@@ -92,6 +94,18 @@ export interface TooltipProps extends ChakraTooltip.RootProps {
* `theme/recipes.ts`, so this wrapper only provides the trigger/portal
* structure and the `content` convenience API.
*/
+/**
+ * One trigger id for a menu or popover whose trigger a `Tooltip` wraps. Both
+ * machines render onto the same element and each wants to own its id; without
+ * sharing, the menu has no anchor and opens at the viewport origin. Pass the
+ * result as `ids` to the Menu/Popover root and to the Tooltip.
+ */
+export const useTooltipTriggerIds = (): { trigger: string } => {
+ const trigger = useId();
+
+ return useMemo(() => ({ trigger }), [trigger]);
+};
+
export const Tooltip = (props: TooltipProps) => {
const {
showArrow = true,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx
index 780f8e7c66..65ec4db70b 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/RecallActionButtons.tsx
@@ -1,5 +1,3 @@
-import { ButtonGroup, Icon } from '@chakra-ui/react';
-import { Button, Tooltip } from '@platform/ui';
import {
AsteriskIcon,
QuoteIcon,
@@ -9,7 +7,6 @@ import {
SproutIcon,
type LucideIcon,
} from 'lucide-react';
-import { useCallback, type ReactNode } from 'react';
import type { ImageRecallCapabilities, ImageRecallKind } from './imageRecall';
@@ -48,67 +45,3 @@ export const getImageRecallVerb = (kind: ImageRecallKind): { icon: LucideIcon; l
return { icon: item.icon, label: item.label };
};
-
-// The verb row is wide at max-content; `contain: inline-size` zeroes its
-// intrinsic width contribution so it can never stretch a host (queue row,
-// preview footer) past its panel — it fills the given width and wraps.
-const CONTAIN_INLINE_SIZE = { contain: 'inline-size' } as const;
-
-export const RecallActionButtons = ({
- capabilities,
- children,
- disabledReason,
- onRecall,
-}: {
- capabilities: ImageRecallCapabilities;
- /** Extra host-specific buttons rendered in the same group after the verbs. */
- children?: ReactNode;
- /** Tooltip for disabled verbs, explaining why recall is unavailable. */
- disabledReason?: string;
- onRecall: (kind: ImageRecallKind) => void;
-}) => (
- <ButtonGroup css={CONTAIN_INLINE_SIZE} flexWrap="wrap" minW="0" rowGap="1" size="2xs" variant="subtle" w="full">
- {RECALL_ACTION_ITEMS.map((item) => (
- <RecallActionButton
- key={item.kind}
- disabledReason={disabledReason}
- icon={item.icon}
- isEnabled={capabilities[item.capability]}
- kind={item.kind}
- label={item.label}
- onRecall={onRecall}
- />
- ))}
- {children}
- </ButtonGroup>
-);
-
-const RecallActionButton = ({
- disabledReason,
- icon,
- isEnabled,
- kind,
- label,
- onRecall,
-}: {
- disabledReason?: string;
- icon: LucideIcon;
- isEnabled: boolean;
- kind: ImageRecallKind;
- label: string;
- onRecall: (kind: ImageRecallKind) => void;
-}) => {
- const handleClick = useCallback(() => onRecall(kind), [kind, onRecall]);
- const button = (
- <Button disabled={!isEnabled} onClick={handleClick}>
- <Icon as={icon} boxSize="3" />
- {label}
- </Button>
- );
-
- if (!isEnabled && disabledReason) {
- return <Tooltip content={disabledReason}>{button}</Tooltip>;
- }
-
- return button;
-};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
index b1110b183b..64148040c0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
@@ -16,7 +16,7 @@ export {
type ImageRecallResult,
} from './imageRecall';
export { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
-export { getImageRecallVerb, IMAGE_RECALL_KINDS, RecallActionButtons } from './RecallActionButtons';
+export { getImageRecallVerb, IMAGE_RECALL_KINDS } from './RecallActionButtons';
export { getSelectedGalleryImage, getSelectedGalleryImageFromValues } from './selectedImage';
export { useImageActions, type ImageActions } from './useImageActions';
export { useDeletionConfirmation, type RequestDeletionConfirmation } from './useDeletionConfirmation';
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx
index 13332a65be..ba7077031f 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx
@@ -1,29 +1,22 @@
import type { QueueItemReadModel } from '@features/queue/contracts';
-import { Dialog, Icon, Portal } from '@chakra-ui/react';
-import { extractGenerationMeta } from '@features/queue/contracts';
+import { ButtonGroup, Dialog, Icon, Portal } from '@chakra-ui/react';
import { Button, CloseButton } from '@platform/ui/Button';
import { JsonPreview } from '@platform/ui/JsonPreview';
-import { RecallActionButtons } from '@workbench/image-actions';
import { useNotify } from '@workbench/useNotify';
import { FileTextIcon, WandSparklesIcon } from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useQueueItemRecall } from './useQueueItemRecall';
-
/**
- * Per-item actions for the RECENT details panel. Recall uses the shared
- * {@link RecallActionButtons} verbs (same look as the preview's metadata
- * panel) over {@link useQueueItemRecall}. "View JSON" opens the raw queue
- * item in a dialog.
+ * Per-item actions for the RECENT details panel. Recall lives in the image
+ * context menu and the Details rows, not in a button row here. "View JSON"
+ * opens the raw queue item in a dialog.
*/
export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {
const { t } = useTranslation();
const notify = useNotify();
const [jsonOpen, setJsonOpen] = useState(false);
- const meta = useMemo(() => extractGenerationMeta(item), [item]);
- const { capabilities, recall: onRecall } = useQueueItemRecall(item.origin, meta);
const onSendToCanvas = useCallback(
() => notify.info(t('widgets.queue.sendToCanvas'), t('widgets.queue.sendToCanvasComingSoon')),
@@ -35,11 +28,7 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {
return (
<>
- <RecallActionButtons
- capabilities={capabilities}
- disabledReason={t('widgets.queue.recallFromGallery')}
- onRecall={onRecall}
- >
+ <ButtonGroup flexWrap="wrap" minW="0" rowGap="1" size="2xs" variant="subtle" w="full">
<Button disabled variant="ghost" onClick={onSendToCanvas}>
<Icon as={WandSparklesIcon} boxSize="3" />
{t('widgets.queue.sendToCanvas')}
@@ -48,7 +37,7 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {
<Icon as={FileTextIcon} boxSize="3" />
{t('common.viewJson')}
</Button>
- </RecallActionButtons>
+ </ButtonGroup>
<Dialog.Root open={jsonOpen} scrollBehavior="inside" size="lg" onOpenChange={closeJson}>
<Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
index 9535f9dbde..be181f4e97 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
@@ -1,13 +1,15 @@
import type { GalleryItem } from '@features/gallery';
+import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
import type { ImageActions } from '@workbench/image-actions';
-import { HStack, Icon } from '@chakra-ui/react';
+import { HStack, Icon, Menu, Portal } from '@chakra-ui/react';
import { galleryImageItemToGalleryImage, isGalleryImageItem, toGalleryItemRef } from '@features/gallery/contracts';
-import { Button, IconButton, Tooltip } from '@platform/ui';
+import { Button, IconButton, MenuActionItem, MenuContent, Tooltip, useTooltipTriggerIds } from '@platform/ui';
+import { getGalleryCanvasImportMenuItems } from '@workbench/image-actions';
import {
+ ChevronDownIcon,
CopyIcon,
EllipsisVerticalIcon,
- FileJsonIcon,
ImagesIcon,
PencilIcon,
StarIcon,
@@ -18,18 +20,20 @@ import { useTranslation } from 'react-i18next';
import type { PreviewDensity } from './previewDensity';
+const CANVAS_ITEMS = getGalleryCanvasImportMenuItems(false);
+const CANVAS_MENU_POSITIONING = { placement: 'bottom-start' } as const;
+const STAR_LABEL_KEYS = {
+ image: { off: 'widgets.preview.starImage', on: 'widgets.preview.unstarImage' },
+ video: { off: 'widgets.preview.starVideo', on: 'widgets.preview.unstarVideo' },
+} as const;
+
/**
- * The header's always-visible action row: quick verbs one click away, plus an
- * "image actions" dropdown that opens the full right-click context menu
- * (anchored under the button) — one source of truth for every image verb,
+ * The header's always-visible action row: Edit leads (the one verb that moves
+ * the image into actual work — a menu of canvas layer destinations), then
+ * compare, star, and an "image actions" dropdown that opens the full
+ * right-click context menu — one source of truth for every image verb,
* mirroring the legacy viewer's menu button. Compact densities collapse to
- * star + the dropdown.
- *
- * The strip earns its space by holding what the dropdown cannot reach in one
- * click. Copy and Download sat here *and* in the dropdown's quick row, so they
- * cost a slot each to save nothing; editing on canvas — the one verb that
- * moves the image into actual work — had no button at all. Copy and Download
- * stay one click away in the dropdown.
+ * star + the dropdown. Details lives beside the toggles, not here.
*/
export const PreviewActionStrip = ({
actions,
@@ -37,7 +41,6 @@ export const PreviewActionStrip = ({
isVideoFrameCopyAvailable = false,
item,
onCopyCurrentFrame,
- onOpenDetails,
onOpenMenu,
}: {
actions: ImageActions;
@@ -45,7 +48,6 @@ export const PreviewActionStrip = ({
isVideoFrameCopyAvailable?: boolean;
item: GalleryItem;
onCopyCurrentFrame?: () => void;
- onOpenDetails?: () => void;
/** Opens the view's image context menu at viewport coordinates. */
onOpenMenu: ((x: number, y: number) => void) | null;
}) => {
@@ -56,9 +58,11 @@ export const PreviewActionStrip = ({
[actions, item]
);
const selectForCompare = useCallback(() => image && actions.selectForCompare(image), [actions, image]);
- const editOnCanvas = useCallback(() => image && void actions.sendToCanvas([image], 'raster'), [actions, image]);
+ const sendToCanvas = useCallback(
+ (destination: GalleryCanvasImportDestination) => image && void actions.sendToCanvas([image], destination),
+ [actions, image]
+ );
const copyCurrentFrame = useCallback(() => onCopyCurrentFrame?.(), [onCopyCurrentFrame]);
- const openDetails = useCallback(() => onOpenDetails?.(), [onOpenDetails]);
const openMenu = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -67,8 +71,7 @@ export const PreviewActionStrip = ({
},
[onOpenMenu]
);
- const itemKindLabel = item.kind === 'video' ? 'video' : 'image';
- const starLabel = `${item.starred ? 'Unstar' : 'Star'} ${itemKindLabel}`;
+ const starLabel = t(STAR_LABEL_KEYS[item.kind][item.starred ? 'on' : 'off']);
const starButton = (
<Tooltip content={starLabel}>
<IconButton aria-label={starLabel} color="fg.muted" size="2xs" variant="ghost" onClick={toggleStar}>
@@ -77,11 +80,7 @@ export const PreviewActionStrip = ({
</Tooltip>
);
const menuButton = onOpenMenu ? (
- <Tooltip content="Image actions">
- <IconButton aria-label="Image actions" color="fg.muted" size="2xs" variant="ghost" onClick={openMenu}>
- <Icon as={EllipsisVerticalIcon} boxSize="3.5" />
- </IconButton>
- </Tooltip>
+ <StripIconButton icon={EllipsisVerticalIcon} label={t('widgets.preview.imageActions')} onClick={openMenu} />
) : null;
if (density !== 'full') {
@@ -96,26 +95,16 @@ export const PreviewActionStrip = ({
return (
<HStack flexShrink={0} gap="0.5">
{/* First and worded, not another glyph in the row: it is the strip's one
- verb that moves the image into actual work. "Edit" like legacy's
- button; the aria-label keeps the destination. Videos have no canvas
- destination, so it simply is not offered for them — the same guard
- the context menu's image-only branch uses. */}
+ verb that moves the image into actual work, so it opens straight onto
+ the layer destinations. Videos have no canvas destination, so it is
+ not offered for them — the same guard the context menu uses. */}
{image ? (
- <Tooltip content={t('widgets.preview.editOnCanvas')}>
- <Button
- aria-label={t('widgets.preview.editOnCanvas')}
- color="fg.muted"
- size="2xs"
- variant="ghost"
- onClick={editOnCanvas}
- >
- <Icon as={PencilIcon} boxSize="3.5" />
- {t('common.edit')}
- </Button>
- </Tooltip>
+ <>
+ <EditOnCanvasMenu onSend={sendToCanvas} />
+ <StripIconButton icon={ImagesIcon} label={t('widgets.preview.selectForCompare')} onClick={selectForCompare} />
+ </>
) : null}
{starButton}
- {image ? <StripIconButton icon={ImagesIcon} label="Select for Compare" onClick={selectForCompare} /> : null}
{item.kind === 'video' && onCopyCurrentFrame ? (
<StripIconButton
disabled={!isVideoFrameCopyAvailable}
@@ -124,14 +113,62 @@ export const PreviewActionStrip = ({
onClick={copyCurrentFrame}
/>
) : null}
- {item.kind === 'video' && onOpenDetails ? (
- <StripIconButton icon={FileJsonIcon} label={t('widgets.preview.videoDetails')} onClick={openDetails} />
- ) : null}
{menuButton}
</HStack>
);
};
+/** "Edit" opens onto every canvas layer destination the context menu offers. */
+const EditOnCanvasMenu = ({ onSend }: { onSend: (destination: GalleryCanvasImportDestination) => void }) => {
+ const { t } = useTranslation();
+ const ids = useTooltipTriggerIds();
+
+ return (
+ <Menu.Root ids={ids} positioning={CANVAS_MENU_POSITIONING}>
+ <Tooltip content={t('widgets.preview.editOnCanvas')} ids={ids}>
+ <Menu.Trigger asChild>
+ <Button aria-label={t('widgets.preview.editOnCanvas')} color="fg.muted" size="2xs" variant="ghost">
+ <Icon as={PencilIcon} boxSize="3.5" />
+ {t('common.edit')}
+ <ChevronDownIcon size={12} />
+ </Button>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="14rem">
+ {CANVAS_ITEMS.map((item) => (
+ <CanvasDestinationItem
+ key={item.destination}
+ destination={item.destination}
+ label={t(item.label)}
+ value={item.value}
+ onSend={onSend}
+ />
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+const CanvasDestinationItem = ({
+ destination,
+ label,
+ onSend,
+ value,
+}: {
+ destination: GalleryCanvasImportDestination;
+ label: string;
+ onSend: (destination: GalleryCanvasImportDestination) => void;
+ value: string;
+}) => {
+ const handleSelect = useCallback(() => onSend(destination), [destination, onSend]);
+
+ return <MenuActionItem label={label} value={value} onSelect={handleSelect} />;
+};
+
const StripIconButton = ({
disabled,
icon,
@@ -141,7 +178,7 @@ const StripIconButton = ({
disabled?: boolean;
icon: LucideIcon;
label: string;
- onClick: () => void;
+ onClick: (event: MouseEvent<HTMLButtonElement>) => void;
}) => (
<Tooltip content={label}>
<IconButton aria-label={label} color="fg.muted" disabled={disabled} size="2xs" variant="ghost" onClick={onClick}>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
index de6a030608..e608a4db5a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
@@ -13,10 +13,11 @@ import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { PreviewFooter } from './PreviewFooter';
+import { PreviewDetailsPopover } from './PreviewDetailsPopover';
const galleryMocks = vi.hoisted(() => ({
imageMetadata: vi.fn(),
+ imageWorkflow: vi.fn(),
videoMetadata: vi.fn(),
videoWorkflow: vi.fn(),
}));
@@ -27,7 +28,11 @@ vi.mock('@features/gallery', async (importOriginal) => {
return {
...actual,
- galleryImages: { ...actual.galleryImages, metadata: galleryMocks.imageMetadata },
+ galleryImages: {
+ ...actual.galleryImages,
+ metadata: galleryMocks.imageMetadata,
+ workflow: galleryMocks.imageWorkflow,
+ },
galleryVideos: {
metadata: galleryMocks.videoMetadata,
workflow: galleryMocks.videoWorkflow,
@@ -157,37 +162,28 @@ const interact = (action: () => void, delay = 100): Promise<void> =>
});
});
-const buildItemMedia = (item: GalleryImageItem | GalleryVideoItem) =>
- ({
- actionImage: item.kind === 'image' ? actionImage : null,
- actions,
- item,
- kind: 'item',
- }) as const;
+const POSITION = { boardItemCount: 2, isLoadingBoard: false, selectedIndex: 0 };
-const renderFooter = async ({
+const renderDetails = async ({
isOpen,
item,
}: {
isOpen: boolean;
item: GalleryImageItem | GalleryVideoItem;
}): Promise<void> => {
- const media = buildItemMedia(item);
-
await interact(() => {
root?.render(
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <PreviewFooter
- boardItemCount={2}
- isLoadingBoard={false}
- isMetadataOpen={isOpen}
- media={media}
- selectedIndex={0}
- onNext={() => undefined}
- onPrevious={() => undefined}
- onToggleMetadata={() => undefined}
+ <PreviewDetailsPopover
+ actions={actions}
+ image={item.kind === 'image' ? actionImage : null}
+ isOpen={isOpen}
+ item={item}
+ position={POSITION}
+ stageElement={null}
+ onOpenChange={() => undefined}
/>
</ChakraProvider>
</I18nextProvider>
@@ -199,6 +195,7 @@ const renderFooter = async ({
beforeEach(() => {
identityMocks.accountEpoch = 7;
galleryMocks.imageMetadata.mockReset().mockResolvedValue(null);
+ galleryMocks.imageWorkflow.mockReset().mockResolvedValue({ graph: null, workflow: null });
galleryMocks.videoMetadata.mockReset().mockResolvedValue(null);
galleryMocks.videoWorkflow.mockReset().mockResolvedValue({ graph: null, workflow: null });
actions = {
@@ -224,11 +221,11 @@ afterEach(async () => {
describe('Preview query-driven Details', () => {
it('shows the video Details disclosure but starts no request while it is closed', async () => {
- await renderFooter({ isOpen: false, item: videoItem });
+ await renderDetails({ isOpen: false, item: videoItem });
expect(galleryMocks.videoMetadata).not.toHaveBeenCalled();
expect(galleryMocks.videoWorkflow).not.toHaveBeenCalled();
- expect(getButton('Details')).not.toBeNull();
+ expect(document.querySelector('button[aria-label="Details"]')).not.toBeNull();
});
it('keeps the disabled image recall skeleton mounted while Details is pending', async () => {
@@ -238,23 +235,24 @@ describe('Preview query-driven Details', () => {
})
);
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
- expect(host?.textContent).toContain('Loading metadata');
- expect(getButton('Recall All').disabled).toBe(true);
+ expect(document.body.textContent).toContain('Loading metadata');
});
it('aborts the sole image metadata transport on close without starting duplicate capability work', async () => {
const metadata = deferred<null>();
galleryMocks.imageMetadata.mockReturnValueOnce(metadata.promise);
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
const metadataSignal = galleryMocks.imageMetadata.mock.calls[0]?.[1] as AbortSignal;
expect(actions.getImageRecallCapabilities).not.toHaveBeenCalled();
- await renderFooter({ isOpen: false, item: imageItem });
+ await renderDetails({ isOpen: false, item: imageItem });
+ // The popover's exit runs through zag outside act; settle it before asserting.
+ await interact(() => undefined, 600);
expect(metadataSignal.aborted).toBe(true);
await interact(() => {
metadata.resolve(null);
@@ -267,7 +265,7 @@ describe('Preview query-driven Details', () => {
galleryMocks.videoMetadata.mockReturnValueOnce(metadata.promise);
galleryMocks.videoWorkflow.mockReturnValueOnce(workflow.promise);
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
expect(galleryMocks.videoMetadata).toHaveBeenCalledOnce();
expect(galleryMocks.videoWorkflow).toHaveBeenCalledOnce();
@@ -288,12 +286,14 @@ describe('Preview query-driven Details', () => {
const workflow = deferred<{ graph: string | null; workflow: string | null }>();
galleryMocks.videoMetadata.mockReturnValueOnce(metadata.promise);
galleryMocks.videoWorkflow.mockReturnValueOnce(workflow.promise);
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
const metadataSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
const workflowSignal = galleryMocks.videoWorkflow.mock.calls[0]?.[1] as AbortSignal;
- await renderFooter({ isOpen: false, item: videoItem });
+ await renderDetails({ isOpen: false, item: videoItem });
+ // The popover's exit runs through zag outside act; settle it before asserting.
+ await interact(() => undefined, 600);
expect(metadataSignal.aborted).toBe(true);
expect(workflowSignal.aborted).toBe(true);
expect(galleryMocks.videoMetadata).toHaveBeenCalledOnce();
@@ -311,7 +311,7 @@ describe('Preview query-driven Details', () => {
? oldWorkflow.promise
: Promise.resolve({ graph: '{"marker":"new-graph"}', workflow: '{"marker":"new-workflow"}' })
);
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
const oldSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
const nextItem = {
...videoItem,
@@ -320,19 +320,19 @@ describe('Preview query-driven Details', () => {
thumbnailUrl: '/thumbnails/next.webp',
};
- await renderFooter({ isOpen: true, item: nextItem });
+ await renderDetails({ isOpen: true, item: nextItem });
expect(oldSignal.aborted).toBe(true);
expect(galleryMocks.videoMetadata).toHaveBeenNthCalledWith(2, 'next.mp4', expect.any(AbortSignal));
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('new-item'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('new-item'));
});
await interact(() => {
oldMetadata.resolve({ marker: 'stale-item' });
oldWorkflow.resolve({ graph: '{"marker":"stale-graph"}', workflow: '{"marker":"stale-workflow"}' });
});
- expect(host?.textContent).not.toContain('stale-item');
+ expect(document.body.textContent).not.toContain('stale-item');
});
it('aborts and isolates stale account results behind the account epoch', async () => {
@@ -344,24 +344,26 @@ describe('Preview query-driven Details', () => {
galleryMocks.videoWorkflow
.mockReturnValueOnce(oldWorkflow.promise)
.mockResolvedValueOnce({ graph: '{"epoch":8}', workflow: '{"epoch":8}' });
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
const oldSignal = galleryMocks.videoMetadata.mock.calls[0]?.[1] as AbortSignal;
identityMocks.accountEpoch = 8;
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
+ // The popover's exit runs through zag outside act; settle it before asserting.
+ await interact(() => undefined, 600);
expect(oldSignal.aborted).toBe(true);
expect(galleryMocks.videoMetadata).toHaveBeenCalledTimes(2);
expect(queryClient.getQueryCache().find({ queryKey: ['preview', 'details', 8, 'video:clip.mp4'] })).toBeDefined();
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('new-account'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('new-account'));
});
await interact(() => {
oldMetadata.resolve({ marker: 'stale-account' });
oldWorkflow.resolve({ graph: '{"epoch":7}', workflow: '{"epoch":7}' });
});
- expect(host?.textContent).not.toContain('stale-account');
+ expect(document.body.textContent).not.toContain('stale-account');
});
it('renders raw Metadata, Workflow, and Graph JSON tabs without image recall controls', async () => {
@@ -371,21 +373,26 @@ describe('Preview query-driven Details', () => {
workflow: '{"name":"Video workflow"}',
});
- await renderFooter({ isOpen: true, item: videoItem });
+ await renderDetails({ isOpen: true, item: videoItem });
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('"codec": "h264"'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('"codec": "h264"'));
});
expect(getButton('Metadata')).not.toBeNull();
expect(getButton('Workflow')).not.toBeNull();
expect(getButton('Graph')).not.toBeNull();
- expect(host?.textContent).not.toContain('Recall All');
+ // Videos have no parsed rows, so no Details tab.
+ expect([...document.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent)).toEqual([
+ 'Metadata',
+ 'Workflow',
+ 'Graph',
+ ]);
await interact(() => getButton('Workflow').click());
- expect(host?.textContent).toContain('"name":"Video workflow"');
+ expect(document.body.textContent).toContain('"name":"Video workflow"');
await interact(() => getButton('Graph').click());
- expect(host?.textContent).toContain('"id":"video"');
- expect(host?.querySelector('[aria-label="Video graph JSON"]')).not.toBeNull();
+ expect(document.body.textContent).toContain('"id":"video"');
+ expect(document.querySelector('[aria-label="Video graph JSON"]')).not.toBeNull();
});
it('keeps parsed image rows, source run, and recall controls while moving the fetch to Query', async () => {
@@ -395,18 +402,18 @@ describe('Preview query-driven Details', () => {
seed: 42,
});
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
expect(galleryMocks.imageMetadata).toHaveBeenCalledWith('still.png', expect.any(AbortSignal));
expect(queryClient.getQueryCache().find({ queryKey: ['preview', 'details', 7, 'image:still.png'] })).toBeDefined();
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('query-driven prompt'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('query-driven prompt'));
});
- expect(host?.textContent).toContain('Test Model');
- expect(host?.textContent).toContain('queue-image');
+ expect(document.body.textContent).toContain('Test Model');
+ expect(document.body.textContent).toContain('queue-image');
- await interact(() => getButton('Recall All').click());
- expect(actions.recallImageData).toHaveBeenCalledWith(actionImage, 'all');
+ await interact(() => document.querySelector<HTMLButtonElement>('[aria-label="Use Prompt"]')?.click());
+ expect(actions.recallImageData).toHaveBeenCalledWith(actionImage, 'prompts');
});
it('recalls a single field from its metadata row', async () => {
@@ -416,22 +423,22 @@ describe('Preview query-driven Details', () => {
seed: 42,
});
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('row prompt'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('row prompt'));
});
// Only the row buttons carry aria-labels; the verb-row buttons are named
// by their visible text, so the attribute selector is unambiguous.
- const seedRecall = host?.querySelector<HTMLButtonElement>('[aria-label="Use Seed"]');
+ const seedRecall = document.querySelector<HTMLButtonElement>('[aria-label="Use Seed"]');
expect(seedRecall).not.toBeNull();
- expect(host?.querySelector('[aria-label="Use Prompt"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Use Prompt"]')).not.toBeNull();
// No size row was parsed, so no row carries the size verb even though the
// capability itself is available.
- expect(host?.querySelector('[aria-label="Use Size"]')).toBeNull();
+ expect(document.querySelector('[aria-label="Use Size"]')).toBeNull();
// The model row has no single-field verb — copy stays its only action.
- const modelRow = [...(host?.querySelectorAll('.chakra-data-list__item') ?? [])].find((row) =>
+ const modelRow = [...(document.querySelectorAll('.chakra-data-list__item') ?? [])].find((row) =>
row.textContent?.includes('Test Model')
);
expect(modelRow?.querySelectorAll('button')).toHaveLength(1);
@@ -445,35 +452,35 @@ describe('Preview query-driven Details', () => {
actions.deriveImageRecallCapabilities = vi.fn(() => NO_RECALL_CAPABILITIES);
galleryMocks.imageMetadata.mockResolvedValueOnce({ seed: 42 });
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
await act(async () => {
- await vi.waitFor(() => expect(host?.textContent).toContain('42'));
+ await vi.waitFor(() => expect(document.body.textContent).toContain('42'));
});
- expect(host?.querySelector('[aria-label="Use Seed"]')).toBeNull();
+ expect(document.querySelector('[aria-label="Use Seed"]')).toBeNull();
});
- it('updates recall buttons when capability inputs change without refetching cached metadata', async () => {
+ it('updates row recall verbs when capability inputs change without refetching cached metadata', async () => {
galleryMocks.imageMetadata.mockResolvedValueOnce({ positive_prompt: 'cached prompt' });
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
await act(async () => {
- await vi.waitFor(() => expect(getButton('Recall All').disabled).toBe(false));
+ await vi.waitFor(() => expect(document.querySelector('[aria-label="Use Prompt"]')).not.toBeNull());
});
actions = {
...actions,
deriveImageRecallCapabilities: vi.fn(() => NO_RECALL_CAPABILITIES),
} as unknown as ImageActions;
- await renderFooter({ isOpen: true, item: imageItem });
+ await renderDetails({ isOpen: true, item: imageItem });
- expect(getButton('Recall All').disabled).toBe(true);
+ expect(document.querySelector('[aria-label="Use Prompt"]')).toBeNull();
expect(galleryMocks.imageMetadata).toHaveBeenCalledOnce();
});
});
const getButton = (text: string): HTMLButtonElement => {
- const button = Array.from((host ?? document).querySelectorAll<HTMLButtonElement>('button')).find(
+ const button = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(
(candidate) => candidate.textContent?.trim() === text
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx
new file mode 100644
index 0000000000..1b6da0ceb5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx
@@ -0,0 +1,269 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { GalleryImage, GalleryImageItem, GalleryVideoItem } from '@features/gallery';
+import type * as GalleryModule from '@features/gallery';
+import type * as IdentityModule from '@features/identity';
+import type { ImageActions } from '@workbench/image-actions';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { PreviewDetailsPopover } from './PreviewDetailsPopover';
+
+// Forty rows / a long payload: far taller than the stage below, so the cap is what keeps it inside.
+const TALL_RECORD = Object.fromEntries(Array.from({ length: 40 }, (_, index) => [`field_${index}`, `value ${index}`]));
+
+vi.mock('@features/gallery', async (importOriginal) => {
+ const actual = await importOriginal<typeof GalleryModule>();
+
+ return {
+ ...actual,
+ galleryImages: {
+ ...actual.galleryImages,
+ metadata: () => Promise.resolve({ ...TALL_RECORD, positive_prompt: 'a tall prompt', seed: 7 }),
+ workflow: () => Promise.resolve({ graph: null, workflow: '{"name":"image workflow"}' }),
+ },
+ galleryVideos: {
+ metadata: () => Promise.resolve(TALL_RECORD),
+ workflow: () => Promise.resolve({ graph: null, workflow: null }),
+ },
+ };
+});
+vi.mock('@features/identity', async (importOriginal) => {
+ const actual = await importOriginal<typeof IdentityModule>();
+
+ return { ...actual, useAuthSession: () => ({ accountEpoch: 1 }) };
+});
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { countOfTotal: '{{count}} of {{total}}', copy: 'Copy' },
+ widgets: {
+ preview: {
+ details: 'Details',
+ graph: 'Graph',
+ graphJsonLabel: 'Graph JSON',
+ loadingMetadata: 'Loading metadata',
+ metadata: 'Metadata',
+ metadataJsonLabel: 'Metadata JSON',
+ videoDuration: 'Duration {{duration}}',
+ workflow: 'Workflow',
+ workflowJsonLabel: 'Workflow JSON',
+ },
+ },
+ },
+ },
+ },
+});
+
+const imageItem: GalleryImageItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-09-21T00:00:00Z',
+ fullUrl: '/images/still.png',
+ height: 768,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'still.png',
+ starred: false,
+ thumbnailUrl: '/thumbnails/still.webp',
+ width: 512,
+};
+const image: GalleryImage = {
+ boardId: 'none',
+ height: 768,
+ imageCategory: 'general',
+ imageName: 'still.png',
+ imageUrl: '/images/still.png',
+ queuedAt: '2026-09-21T00:00:00Z',
+ sourceQueueItemId: 'run-1',
+ starred: false,
+ thumbnailUrl: '/thumbnails/still.webp',
+ width: 512,
+};
+const videoItem: GalleryVideoItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-09-21T00:00:00Z',
+ durationSeconds: 5,
+ fullUrl: '/videos/clip.mp4',
+ height: 1080,
+ isIntermediate: false,
+ kind: 'video',
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/thumbnails/clip.webp',
+ width: 1920,
+};
+const actions = {
+ deriveImageRecallCapabilities: () => ({
+ all: true,
+ clipSkip: false,
+ dimensions: false,
+ prompts: true,
+ remix: true,
+ seed: true,
+ workflow: false,
+ }),
+ recallImageData: vi.fn(),
+} as unknown as ImageActions;
+const POSITION = { boardItemCount: 3, isLoadingBoard: false, selectedIndex: 0 };
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement;
+let root: Root;
+const onOpenChange = vi.fn();
+
+const settle = (ms = 300) =>
+ act(
+ () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, ms);
+ })
+ );
+
+/** A widget: a header row holding the trigger, a short stage, and a filmstrip row under it. */
+const Widget = ({ item }: { item: GalleryImageItem | GalleryVideoItem }) => {
+ const [stage, setStage] = useState<HTMLDivElement | null>(null);
+
+ return (
+ <div role="region" style={{ display: 'flex', flexDirection: 'column', height: 360, width: 640 }}>
+ <div style={{ display: 'flex', height: 32, justifyContent: 'flex-end' }}>
+ <PreviewDetailsPopover
+ actions={actions}
+ image={item.kind === 'image' ? image : null}
+ isOpen
+ item={item}
+ position={POSITION}
+ stageElement={stage}
+ onOpenChange={onOpenChange}
+ />
+ </div>
+ <div ref={setStage} data-testid="stage" style={{ flex: 1, minHeight: 0 }} />
+ <div data-testid="filmstrip" style={{ height: 60 }} />
+ </div>
+ );
+};
+
+const render = async (item: GalleryImageItem | GalleryVideoItem) => {
+ await act(() =>
+ root.render(
+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Widget item={item} />
+ </ChakraProvider>
+ </I18nextProvider>
+ </QueryClientProvider>
+ )
+ );
+ await settle();
+};
+
+const popover = () => document.querySelector<HTMLElement>('[data-preview-details]')!;
+const stage = () => host.querySelector<HTMLElement>('[data-testid="stage"]')!;
+const filmstrip = () => host.querySelector<HTMLElement>('[data-testid="filmstrip"]')!;
+
+/** The popover sits under its trigger and ends on or above the stage's bottom edge, never over the strip. */
+const expectBoundedByStage = () => {
+ const rect = popover().getBoundingClientRect();
+ const stageRect = stage().getBoundingClientRect();
+
+ expect(rect.top).toBeGreaterThanOrEqual(stageRect.top - 1);
+ expect(rect.height).toBeGreaterThan(150);
+ expect(rect.bottom).toBeLessThanOrEqual(stageRect.bottom + 0.5);
+ expect(rect.bottom).toBeLessThanOrEqual(filmstrip().getBoundingClientRect().top + 0.5);
+};
+
+beforeEach(() => {
+ onOpenChange.mockReset();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+});
+
+describe('PreviewDetailsPopover', () => {
+ it('keeps long image details inside the stage, scrolling them above the filmstrip', async () => {
+ await render(imageItem);
+
+ await expect.element(page.getByText('a tall prompt')).toBeVisible();
+ expectBoundedByStage();
+ expect(document.body.textContent).toContain('1 of 3');
+ expect(document.body.textContent).toContain('512 × 768');
+
+ // Workflow-added keys are not parsed rows; they live in the raw record, whose
+ // forty lines overflow the cap and scroll inside it rather than past it.
+ await page.getByRole('tab', { name: 'Metadata' }).click();
+ const viewport = page.getByRole('region', { name: 'Metadata JSON' }).element();
+ await expect.element(page.getByRole('region', { name: 'Metadata JSON' })).toBeVisible();
+ expectBoundedByStage();
+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight + 40);
+ });
+
+ it('shows the raw metadata record and the workflow for an image, like the legacy viewer', async () => {
+ await render(imageItem);
+
+ await page.getByRole('tab', { name: 'Metadata' }).click();
+ await expect.element(page.getByRole('region', { name: 'Metadata JSON' })).toBeVisible();
+ expect(document.body.textContent).toContain('"field_39"');
+ expectBoundedByStage();
+
+ await page.getByRole('tab', { name: 'Workflow' }).click();
+ await expect.element(page.getByRole('region', { name: 'Workflow JSON' })).toBeVisible();
+ expect(document.body.textContent).toContain('image workflow');
+ // Nothing behind Graph, so it is not offered.
+ await expect.element(page.getByRole('tab', { name: 'Graph' })).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it('bounds video details by the stage too', async () => {
+ await render(videoItem);
+
+ await expect.element(page.getByRole('region', { name: 'Metadata JSON' })).toBeVisible();
+ expectBoundedByStage();
+ expect(document.body.textContent).toContain('1920 × 1080');
+ await expect.element(page.getByRole('tab', { name: 'Workflow' })).toHaveAttribute('aria-disabled', 'true');
+ await expect.element(page.getByRole('tab', { name: 'Graph' })).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it('stays open for interactions inside the preview widget and does not steal focus', async () => {
+ const before = document.activeElement;
+ await render(imageItem);
+
+ await expect.element(page.getByText('a tall prompt')).toBeVisible();
+ expect(popover().contains(document.activeElement)).toBe(false);
+ expect(document.activeElement).toBe(before);
+
+ await act(() => {
+ filmstrip().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' }));
+ filmstrip().dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'mouse' }));
+ filmstrip().dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+ await settle(100);
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ await act(() => {
+ document.body.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' }));
+ document.body.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'mouse' }));
+ });
+ await settle(100);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx
new file mode 100644
index 0000000000..a3848e659b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx
@@ -0,0 +1,151 @@
+import type { GalleryImage, GalleryItem } from '@features/gallery';
+import type { ImageActions } from '@workbench/image-actions';
+
+import { HStack, Icon, Popover, Portal, Text } from '@chakra-ui/react';
+import { formatGalleryVideoDuration } from '@features/gallery/contracts';
+import { useAuthSession } from '@features/identity';
+import { IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import { InfoIcon } from 'lucide-react';
+import { useCallback, useMemo, type ComponentProps } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { PreviewItemPosition } from './previewHeaderStore';
+
+import { PreviewDetails } from './PreviewMetadataPanel';
+
+type InteractOutsideHandler = NonNullable<ComponentProps<typeof Popover.Root>['onInteractOutside']>;
+
+/**
+ * The header's Details toggle and its popover: board position and dimensions
+ * on the first line, then the legacy tab set (parsed details for images, the
+ * raw metadata record, workflow, graph). Anchored bottom-end under its trigger
+ * at the header's far end and bounded by the media stage rather than the
+ * viewport, so however long the metadata runs it scrolls inside the image area
+ * and never lies over the filmstrip.
+ */
+export const PreviewDetailsPopover = ({
+ actions,
+ image,
+ isOpen,
+ item,
+ onOpenChange,
+ position,
+ stageElement,
+}: {
+ actions: ImageActions;
+ image: GalleryImage | null;
+ isOpen: boolean;
+ item: GalleryItem;
+ onOpenChange: (open: boolean) => void;
+ position: PreviewItemPosition | null;
+ stageElement: HTMLElement | null;
+}) => {
+ const { i18n, t } = useTranslation();
+ const accountEpoch = useAuthSession().accountEpoch;
+ const ids = useTooltipTriggerIds();
+ const positioning = useMemo(
+ () => ({
+ boundary: () => stageElement ?? document.body,
+ flip: false,
+ overflowPadding: 8,
+ placement: 'bottom-end' as const,
+ }),
+ [stageElement]
+ );
+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);
+ // Reading Details while browsing the board is the point: a click on the
+ // filmstrip or the stage keeps the popover up (the query re-keys to the new
+ // item), and focus stays on the preview so the arrow keys keep walking.
+ const handleInteractOutside = useCallback<InteractOutsideHandler>(
+ (event) => {
+ const widget = stageElement?.closest('[role="region"]');
+ const target = event.detail.originalEvent.target;
+
+ if (widget && target instanceof Node && widget.contains(target)) {
+ event.preventDefault();
+ }
+ },
+ [stageElement]
+ );
+ const positionLabel =
+ position === null
+ ? null
+ : position.isLoadingBoard
+ ? t('widgets.preview.loadingBoard')
+ : position.selectedIndex === -1
+ ? t('widgets.preview.itemCount', { count: position.boardItemCount })
+ : t('common.countOfTotal', { count: position.selectedIndex + 1, total: position.boardItemCount });
+ const fps =
+ item.kind === 'video' && item.fps !== undefined
+ ? new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }).format(item.fps)
+ : null;
+ const mediaLabel = [
+ `${item.width} × ${item.height}`,
+ ...(item.kind === 'video'
+ ? [t('widgets.preview.videoDuration', { duration: formatGalleryVideoDuration(item.durationSeconds) })]
+ : []),
+ ...(fps === null ? [] : [t('widgets.preview.framesPerSecond', { count: fps })]),
+ ].join(' · ');
+
+ return (
+ <Popover.Root
+ autoFocus={false}
+ ids={ids}
+ lazyMount
+ open={isOpen}
+ positioning={positioning}
+ unmountOnExit
+ onInteractOutside={handleInteractOutside}
+ onOpenChange={handleOpenChange}
+ >
+ {/* Reads like the toggles beside it: the filled variant and `aria-pressed`
+ carry "open" the way they carry "on" for the filmstrip. */}
+ <Tooltip content={t('widgets.preview.details')} ids={ids}>
+ <Popover.Trigger asChild>
+ <IconButton
+ aria-label={t('widgets.preview.details')}
+ aria-pressed={isOpen}
+ color={isOpen ? undefined : 'fg.muted'}
+ size="2xs"
+ variant={isOpen ? 'solid' : 'ghost'}
+ >
+ <Icon as={InfoIcon} boxSize="3.5" />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent
+ data-preview-details
+ display="flex"
+ flexDirection="column"
+ maxH="var(--available-height)"
+ showArrow={false}
+ w="24rem"
+ >
+ <Popover.Body display="flex" flexDirection="column" gap="2" minH="0" p="2.5">
+ <HStack gap="1" minW="0">
+ {positionLabel === null ? null : (
+ <>
+ <Text color="fg.muted" flexShrink={0} fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {positionLabel}
+ </Text>
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
+ ·
+ </Text>
+ </>
+ )}
+ <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums" truncate>
+ {mediaLabel}
+ </Text>
+ </HStack>
+ <PreviewDetails accountEpoch={accountEpoch} actions={actions} image={image} item={item} />
+ </Popover.Body>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
index 6de8483b58..22fdc73471 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx
@@ -5,29 +5,34 @@ import { useDraggable } from '@dnd-kit/core';
import { toGalleryItemKey, toGalleryItemRef } from '@features/gallery/contracts';
import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';
import { Scrollable } from '@platform/ui/Scrollable';
-import { useCallback, useMemo } from 'react';
+import { useCallback, useMemo, type MouseEvent } from 'react';
import type { PreviewDensity } from './previewDensity';
/**
- * A floating strip of the current board's thumbnails above the footer — the
- * same `boardImages` the "N of M" counter is derived from, made spatial. It
- * overlays the fitted media rather than reserving height from it, so it
- * carries the same opaque island fill as the footer to stay legible over any
- * image. Thumbs are standard all-image gallery-item drag sources, so they
- * work with every existing drop target (canvas zones, boards,
- * drop-to-compare).
+ * The current board's thumbnails as a row docked under the stage — the same
+ * `boardImages` the Details position counter is derived from, made spatial.
+ * It takes its own height rather than floating over the media, so the fitted
+ * frame is never covered and Details has a clean edge to stop above. Thumbs
+ * are standard all-image gallery-item drag sources, so they work with every
+ * existing drop target (canvas zones, boards, drop-to-compare).
*/
export const PreviewFilmstrip = ({
density,
items,
selectedItemKey,
+ onCompare,
+ onContextMenu,
onSelect,
}: {
density: PreviewDensity;
items: GalleryItem[];
selectedItemKey: GalleryItemKey | null;
+ /** Alt-click: arm this thumb for comparison against the selection. */
+ onCompare?: (item: GalleryItem) => void;
+ /** Right-click: the image context menu for this thumb, at viewport coordinates. */
+ onContextMenu?: (item: GalleryItem, x: number, y: number) => void;
onSelect: (item: GalleryItem) => void;
}) => {
const thumbSize = density === 'full' ? '12' : '8';
@@ -46,16 +51,15 @@ export const PreviewFilmstrip = ({
<Scrollable
bg="bg.subtle"
borderColor="border.subtle"
- borderWidth="1px"
+ borderTopWidth="1px"
contentProps={FILMSTRIP_CONTENT_PROPS}
css={FILMSTRIP_CONTAIN_CSS}
+ data-preview-filmstrip
flexShrink={0}
h={density === 'full' ? '3.75rem' : '2.75rem'}
minW="0"
orientation="horizontal"
- px="1.5"
- rounded="md"
- shadow="sm"
+ px="2"
w="full"
>
<HStack align="center" gap="1" h="full">
@@ -68,6 +72,8 @@ export const PreviewFilmstrip = ({
item={item}
isSelected={itemKey === selectedItemKey}
size={thumbSize}
+ onCompare={onCompare}
+ onContextMenu={onContextMenu}
onSelect={onSelect}
/>
);
@@ -81,11 +87,15 @@ const FilmstripThumb = ({
item,
isSelected,
size,
+ onCompare,
+ onContextMenu,
onSelect,
}: {
item: GalleryItem;
isSelected: boolean;
size: string;
+ onCompare?: (item: GalleryItem) => void;
+ onContextMenu?: (item: GalleryItem, x: number, y: number) => void;
onSelect: (item: GalleryItem) => void;
}) => {
const itemRef = useMemo(() => toGalleryItemRef(item), [item]);
@@ -95,7 +105,26 @@ const FilmstripThumb = ({
data: dragData,
id: getGalleryItemDragId(itemRef, 'preview-filmstrip'),
});
- const handleClick = useCallback(() => onSelect(item), [item, onSelect]);
+ const handleClick = useCallback(
+ (event: MouseEvent<HTMLElement>) => {
+ if (event.altKey && onCompare) {
+ onCompare(item);
+ return;
+ }
+
+ onSelect(item);
+ },
+ [item, onCompare, onSelect]
+ );
+ const handleContextMenu = useCallback(
+ (event: MouseEvent<HTMLElement>) => {
+ if (onContextMenu) {
+ event.preventDefault();
+ onContextMenu(item, event.clientX, event.clientY);
+ }
+ },
+ [item, onContextMenu]
+ );
// Ref callbacks re-run when `isSelected` changes, keeping the selected thumb
// in view without an effect.
const scrollIntoView = useCallback(
@@ -130,6 +159,7 @@ const FilmstripThumb = ({
// browser claims it); dragging still works after a sustained hold.
touchAction="pan-x"
onClick={handleClick}
+ onContextMenu={onContextMenu ? handleContextMenu : undefined}
>
{thumbnailSrc ? (
<img alt={item.name} loading="lazy" src={thumbnailSrc} style={FILMSTRIP_IMG_STYLE} />
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
index 4fae43dbbb..c5947257d5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFooter.tsx
@@ -1,33 +1,9 @@
-import type { GalleryImage, GalleryItem } from '@features/gallery';
-import type { ImageActions } from '@workbench/image-actions';
import type { ReactNode } from 'react';
-import { HStack, Icon, Stack, Text } from '@chakra-ui/react';
-import { formatGalleryVideoDuration } from '@features/gallery/contracts';
-import { Button } from '@platform/ui';
-import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
+import { HStack, Stack, Text } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
-import { PreviewMetadataPanel } from './PreviewMetadataPanel';
-
-/**
- * What the footer is describing: a selected gallery item, or the image slot a
- * live generation is filling. The live shape carries the slot's requested
- * output dimensions — the denoise preview frames arrive at other sizes, and a
- * dimensions readout that ticks while rendering reads as noise.
- */
-export type PreviewFooterMedia =
- | { actionImage: GalleryImage | null; actions: ImageActions; item: GalleryItem; kind: 'item' }
- | { height: number; kind: 'live'; width: number };
-
-/**
- * The opaque island a preview footer sits in.
- *
- * Shared rather than restyled per surface: a live session and a finished item
- * must present the same frame and the same bar, so that the moment generation
- * ends nothing about the layout moves. Every preview surface that carries a
- * footer — single, multi-session tile, compare — renders it through this.
- */
+/** The opaque island a multi-session tile's status footer floats in over its stage. */
export const PreviewFooterIsland = ({ children }: { children: ReactNode }) => (
<Stack bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" gap="2" minW="0" p="3" rounded="md" shadow="sm">
{children}
@@ -66,115 +42,3 @@ export const PreviewTileFooter = ({ deviceLabel, percent }: { deviceLabel: strin
</PreviewFooterIsland>
);
};
-
-/**
- * The preview's slim status bar: board position and dimensions on one quiet
- * row with prev/next, plus the Details expander. Identity (board / image name)
- * lives in the widget header; image actions live in the header's actions slot
- * — never here.
- *
- * It floats over the dot-grid surface rather than partitioning it, so it
- * carries its own opaque panel fill — the grid runs behind and past it.
- *
- * It renders while a generation is live too, with the same geometry: the
- * moment denoising finishes is exactly when the fitted frame must not move,
- * so the bar never appears or disappears across that boundary.
- */
-export const PreviewFooter = ({
- boardItemCount,
- isLoadingBoard,
- isMetadataOpen,
- media,
- onNext,
- onPrevious,
- onToggleMetadata,
- selectedIndex,
-}: {
- boardItemCount: number;
- isLoadingBoard: boolean;
- isMetadataOpen: boolean;
- media: PreviewFooterMedia;
- onNext: () => void;
- onPrevious: () => void;
- onToggleMetadata: () => void;
- selectedIndex: number;
-}) => {
- const { i18n, t } = useTranslation();
- const positionLabel =
- media.kind === 'live'
- ? t('common.generating')
- : isLoadingBoard
- ? t('widgets.preview.loadingBoard')
- : selectedIndex === -1
- ? t('widgets.preview.itemCount', { count: boardItemCount })
- : t('common.countOfTotal', { count: selectedIndex + 1, total: boardItemCount });
- const item = media.kind === 'item' ? media.item : null;
- const fps =
- item?.kind === 'video' && item.fps !== undefined
- ? new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 3 }).format(item.fps)
- : null;
- const { height, width } = media.kind === 'item' ? media.item : media;
-
- return (
- <PreviewFooterIsland>
- <HStack align="center" justify="space-between">
- <HStack gap="1" minW="0">
- <Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums" truncate>
- {positionLabel}
- </Text>
- <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
- ·
- </Text>
- <Text color="fg.muted" flexShrink={0} fontSize="2xs" fontVariantNumeric="tabular-nums">
- {width} × {height}
- {item?.kind === 'video'
- ? ` · ${t('widgets.preview.videoDuration', {
- duration: formatGalleryVideoDuration(item.durationSeconds),
- })}${fps === null ? '' : ` · ${t('widgets.preview.framesPerSecond', { count: fps })}`}`
- : ''}
- </Text>
- </HStack>
- {media.kind === 'item' ? (
- <HStack flexShrink={0} gap="1">
- <Button
- aria-label={t('widgets.preview.previousItemInBoard')}
- disabled={selectedIndex <= 0}
- size="2xs"
- variant="outline"
- onClick={onPrevious}
- >
- <ChevronLeftIcon />
- </Button>
- <Button
- aria-label={t('widgets.preview.nextItemInBoard')}
- disabled={selectedIndex === -1 || selectedIndex >= boardItemCount - 1}
- size="2xs"
- variant="outline"
- onClick={onNext}
- >
- <ChevronRightIcon />
- </Button>
- </HStack>
- ) : null}
- </HStack>
- {media.kind === 'item' ? (
- <PreviewMetadataPanel
- actions={media.actions}
- image={media.actionImage}
- isOpen={isMetadataOpen}
- item={media.item}
- onToggle={onToggleMetadata}
- />
- ) : (
- // The Details row an in-flight image cannot answer yet, at the exact
- // geometry of the live one, so completion swaps content — never layout.
- <HStack aria-disabled="true" color="fg.subtle" gap="1" w="fit-content">
- <Icon as={ChevronRightIcon} boxSize="3" />
- <Text fontSize="2xs" fontWeight="700" textTransform="uppercase">
- {t('widgets.preview.details')}
- </Text>
- </HStack>
- )}
- </PreviewFooterIsland>
- );
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
index 2fdf663d80..b1b74b5f18 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx
@@ -35,7 +35,7 @@ import {
publishVideoSpanPlaybackState,
subscribeVideoSpanPlaybackRequests,
} from './spanPlaybackRequest';
-import { usePreviewLoupe, type PreviewLoupeControls } from './usePreviewLoupe';
+import { usePreviewLoupe, type PreviewLoupeControls, type PreviewZoomState } from './usePreviewLoupe';
export type PreviewMediaSource =
| { itemKey: GalleryItemKey; kind: 'image'; source: StreamingImageSource }
@@ -63,6 +63,7 @@ interface PreviewFrameProps {
isLive: boolean;
loupeControlsRef?: Ref<PreviewLoupeControls>;
onContextMenu?: (x: number, y: number) => void;
+ onZoomChange?: (state: PreviewZoomState) => void;
onVideoCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
padding?: string;
paddingBottom?: string;
@@ -104,6 +105,7 @@ const PreviewImageFrame = ({
loupeControlsRef,
onContextMenu,
onSourceLoaded,
+ onZoomChange,
padding,
paddingBottom,
shouldAntialiasLiveImage,
@@ -112,12 +114,13 @@ const PreviewImageFrame = ({
}: Omit<PreviewFrameProps, 'isItemCurrent' | 'onVideoCopyAvailabilityChange' | 'source' | 'videoControllerRef'> & {
source: StreamingImageSource | null;
}) => {
- const { t } = useTranslation();
const loupe = usePreviewLoupe({
controlsRef: loupeControlsRef,
enabled: variant === 'framed' && !isLive,
naturalWidth: frameWidth,
+ onZoomChange,
});
+ const { contentRefCallback, stageRefCallback } = loupe;
const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);
const isDragDisabled = !dragItem || isLive || loupe.isZoomed;
const disabledDragId = useId();
@@ -134,13 +137,10 @@ const PreviewImageFrame = ({
(element: HTMLDivElement | null) => {
setDragNodeRef(element);
- if (loupe.contentRef) {
- loupe.contentRef.current = element;
- }
+ return contentRefCallback?.(element);
},
- [loupe.contentRef, setDragNodeRef]
+ [contentRefCallback, setDragNodeRef]
);
-
// Reset zoom in place when the displayed image changes (or goes live) — a
// remount would flash the frame on every selection.
loupe.syncDisplayedSource(variant === 'framed' && !isLive && source ? source.src : null);
@@ -254,7 +254,7 @@ const PreviewImageFrame = ({
return (
<PreviewStage
- ref={loupe.stageRefCallback}
+ ref={stageRefCallback}
cursor={loupe.isZoomed ? 'grab' : undefined}
fill="flex"
padding={padding}
@@ -284,22 +284,6 @@ const PreviewImageFrame = ({
>
{media}
</FittedFrame>
- {loupe.zoomPercent !== null ? (
- <Badge
- aria-label={t('widgets.preview.resetZoom')}
- as="button"
- bottom="2"
- position="absolute"
- right="2"
- size="xs"
- title={t('widgets.preview.resetZoom')}
- variant="solid"
- zIndex="1"
- onClick={loupe.reset}
- >
- {loupe.zoomPercent}%
- </Badge>
- ) : null}
</PreviewStage>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
index 1c312e28db..35caf5eabb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
@@ -1,4 +1,6 @@
+import type * as IdentityModule from '@features/identity';
import type { WidgetViewProps } from '@workbench/widgetContracts';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
@@ -7,6 +9,7 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
import { PreviewHeaderActions } from './PreviewHeaderActions';
@@ -24,6 +27,15 @@ void i18n.use(initReactI18next).init({
hideInProgressDiffusion: 'Hide in-progress diffusion',
showFilmstrip: 'Show filmstrip',
showInProgressDiffusion: 'Show in-progress diffusion',
+ details: 'Details',
+ editOnCanvas: 'Edit on Canvas',
+ imageActions: 'Image actions',
+ selectForCompare: 'Select for Compare',
+ starImage: 'Star image',
+ zoom: 'Zoom',
+ zoomFit: 'Fit to view',
+ zoomLevel: 'Zoom {{percent}}%',
+ zoomPercent: '{{percent}}%',
},
},
},
@@ -31,27 +43,52 @@ void i18n.use(initReactI18next).init({
},
});
-const state = vi.hoisted(() => ({ filmstripVisible: true, showProgressImagesInViewer: true }));
+const state = vi.hoisted(() => ({
+ actionItem: null as null | Record<string, unknown>,
+ filmstripVisible: true,
+ showProgressImagesInViewer: true,
+ zoom: null as null | {
+ fitPercent: number | null;
+ isZoomed: boolean;
+ percent: number | null;
+ reset: () => void;
+ zoomTo: (actualZoom: number) => void;
+ },
+}));
const patchValues = vi.hoisted(() => vi.fn());
const updateProjectPreferences = vi.hoisted(() => vi.fn());
vi.mock('@features/queue/react', () => ({ useProgressImage: () => null }));
+vi.mock('@features/identity', async (importOriginal) => ({
+ ...(await importOriginal<typeof IdentityModule>()),
+ useAuthSession: () => ({ accountEpoch: 1 }),
+}));
vi.mock('./previewHeaderStore', () => ({
+ usePreviewStageContext: () => ({
+ stageElement: null,
+ zoom: state.zoom && {
+ fitPercent: state.zoom.fitPercent,
+ isZoomed: state.zoom.isZoomed,
+ percent: state.zoom.percent,
+ },
+ }),
usePreviewHeaderContext: () => ({
- actionItem: null,
- actions: null,
+ actionItem: state.actionItem,
+ actions: state.actionItem ? { selectForCompare: vi.fn(), sendToCanvas: vi.fn(), setItemsStarred: vi.fn() } : null,
copyCurrentVideoFrame: null,
isVideoFrameCopyAvailable: false,
openItemMenu: vi.fn(),
- openVideoDetails: null,
+ position: null,
+ zoom: state.zoom && { reset: state.zoom.reset, zoomTo: state.zoom.zoomTo },
}),
}));
vi.mock('@workbench/widgetState', () => ({
- getProjectWidgetValues: () => ({ filmstripVisible: state.filmstripVisible }),
+ getProjectWidgetValues: () => ({ filmstripVisible: state.filmstripVisible, metadataOpen: false }),
}));
-vi.mock('@workbench/WorkbenchContext', () => ({
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
useActiveProjectSelector: (select: (project: unknown) => unknown) =>
select({ settings: { showProgressImagesInViewer: state.showProgressImagesInViewer } }),
useWorkbenchCommands: () => ({
@@ -92,8 +129,10 @@ const button = (label: string): HTMLButtonElement =>
host!.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
beforeEach(() => {
+ state.actionItem = null;
state.filmstripVisible = true;
state.showProgressImagesInViewer = true;
+ state.zoom = null;
patchValues.mockClear();
updateProjectPreferences.mockClear();
});
@@ -138,3 +177,69 @@ describe('preview header toggles', () => {
vi.mock('./livePreviewFollow', () => ({
useLivePreviewFollow: () => ({ sessions: [], pinnedSessionId: null, pin: vi.fn(), showAll: vi.fn() }),
}));
+
+describe('preview zoom menu', () => {
+ it('reads the fitted percent, offers only presets above fit, and routes fit/presets to the loupe', async () => {
+ const reset = vi.fn();
+ const zoomTo = vi.fn();
+ state.zoom = { fitPercent: 88, isZoomed: false, percent: 88, reset, zoomTo };
+ await render();
+
+ const trigger = button('Zoom 88%');
+ expect(trigger.textContent).toContain('88%');
+ await settle(() => trigger.click());
+
+ const item = (label: string) => page.getByRole('menuitem', { name: label });
+ // Fit is where the image already is; 100% and 200% are above the 88% fit, 400% too.
+ await expect.element(item('Fit to view')).toHaveAttribute('aria-disabled', 'true');
+ await expect.element(item('100%')).not.toHaveAttribute('aria-disabled');
+ await item('200%').click();
+ expect(zoomTo).toHaveBeenCalledExactlyOnceWith(2);
+
+ state.zoom = { fitPercent: 120, isZoomed: true, percent: 200, reset, zoomTo };
+ await render();
+ await settle(() => button('Zoom 200%').click());
+ // A fit above 100% leaves the 100% preset nowhere to go; the current level is not re-offered.
+ await expect.element(item('100%')).toHaveAttribute('aria-disabled', 'true');
+ await expect.element(item('200%')).toHaveAttribute('aria-disabled', 'true');
+ await item('Fit to view').click();
+ expect(reset).toHaveBeenCalledOnce();
+ });
+
+ it('shows the zoom control in compact regions only while zoomed', async () => {
+ state.zoom = { fitPercent: 88, isZoomed: false, percent: 88, reset: vi.fn(), zoomTo: vi.fn() };
+ await render('right');
+ expect(host!.querySelector('button[aria-label="Zoom 88%"]')).toBeNull();
+
+ state.zoom = { fitPercent: 88, isZoomed: true, percent: 200, reset: vi.fn(), zoomTo: vi.fn() };
+ await render('right');
+ expect(host!.querySelector('button[aria-label="Zoom 200%"]')).not.toBeNull();
+ });
+});
+
+describe('preview header details toggle', () => {
+ it('sits last, after the filmstrip toggle, and reads as a toggle that opens the popover', async () => {
+ state.actionItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-09-21T00:00:00Z',
+ fullUrl: '/images/still.png',
+ height: 8,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'still.png',
+ starred: false,
+ thumbnailUrl: '/thumbnails/still.webp',
+ width: 8,
+ };
+ await render();
+
+ const labels = [...host!.querySelectorAll<HTMLButtonElement>('button')].map((b) => b.getAttribute('aria-label'));
+ expect(labels.slice(-3)).toEqual(['Hide in-progress diffusion', 'Hide filmstrip', 'Details']);
+ expect(labels[0]).toBe('Edit on Canvas');
+ expect(button('Details').getAttribute('aria-pressed')).toBe('false');
+
+ await settle(() => button('Details').click());
+ expect(patchValues).toHaveBeenCalledWith('preview', { metadataOpen: true });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
index 59b3425d60..98452632af 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx
@@ -1,35 +1,50 @@
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { Box, HStack } from '@chakra-ui/react';
+import { galleryImageItemToGalleryImage, isGalleryImageItem } from '@features/gallery/contracts';
import { ToggleIconButton } from '@platform/ui';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { GalleryThumbnailsIcon, HourglassIcon } from 'lucide-react';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useLivePreviewFollow } from './livePreviewFollow';
import { PreviewActionStrip } from './PreviewActionStrip';
-import { usePreviewHeaderContext } from './previewHeaderStore';
-import { getPreviewFilmstripVisible } from './previewSettings';
+import { PreviewDetailsPopover } from './PreviewDetailsPopover';
+import { usePreviewHeaderContext, usePreviewStageContext, type PreviewZoomControls } from './previewHeaderStore';
+import { getPreviewFilmstripVisible, getPreviewMetadataOpen } from './previewSettings';
+import { PreviewZoomMenu } from './PreviewZoomMenu';
+
+const Divider = () => <Box bg="border.subtle" flexShrink={0} h="4" w="1px" />;
/**
- * The preview widget's header actions: the image action strip for the current
- * selection (published by the view via `previewHeaderStore`) plus the
- * in-progress diffusion toggle. Actions live here — in the frame's standard
- * header slot — like every other widget, not in the widget body.
+ * The preview widget's header actions, left to right: the zoom readout, the
+ * image action strip for the current selection (both published by the view
+ * via `previewHeaderStore`), then the in-progress diffusion and filmstrip
+ * toggles and the Details toggle, at the far end so its popover hangs off the
+ * header's right edge. Actions live here — in the frame's standard header
+ * slot — like every other widget, not in the widget body.
*/
export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
const { t } = useTranslation();
const livePreview = useLivePreviewFollow();
const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
const hasProgressImage = livePreview.sessions.length > 0;
- const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, openVideoDetails } =
+ const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, position, zoom } =
usePreviewHeaderContext();
- const isFilmstripVisible = useActiveProjectSelector((project) =>
- getPreviewFilmstripVisible(getProjectWidgetValues(project, 'preview'))
+ const { stageElement, zoom: zoomReadout } = usePreviewStageContext();
+ const zoomControls = useMemo<PreviewZoomControls | null>(
+ () => (zoom && zoomReadout ? { ...zoom, ...zoomReadout } : null),
+ [zoom, zoomReadout]
);
+ const { isDetailsOpen, isFilmstripVisible } = useActiveProjectSelector((project) => {
+ const values = getProjectWidgetValues(project, 'preview');
+
+ return { isDetailsOpen: getPreviewMetadataOpen(values), isFilmstripVisible: getPreviewFilmstripVisible(values) };
+ });
const { account, widgets } = useWorkbenchCommands();
+ const isFull = region === 'center';
const label = showProgressImagesInViewer
? t('widgets.preview.hideInProgressDiffusion')
: t('widgets.preview.showInProgressDiffusion');
@@ -42,32 +57,37 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
() => widgets.patchValues('preview', { filmstripVisible: !isFilmstripVisible }),
[isFilmstripVisible, widgets]
);
+ const setDetailsOpen = useCallback(
+ (open: boolean) => widgets.patchValues('preview', { metadataOpen: open }),
+ [widgets]
+ );
return (
<HStack gap="1">
+ {/* Compact chrome has no room for a readout at fit, but a zoomed image must
+ still say so and offer the way back. */}
+ {zoomControls && (isFull || zoomControls.isZoomed) ? (
+ <>
+ <PreviewZoomMenu zoom={zoomControls} />
+ <Divider />
+ </>
+ ) : null}
{actionItem && actions ? (
<>
<PreviewActionStrip
actions={actions}
- density={region === 'center' ? 'full' : 'compact'}
+ density={isFull ? 'full' : 'compact'}
isVideoFrameCopyAvailable={isVideoFrameCopyAvailable}
item={actionItem}
onCopyCurrentFrame={copyCurrentVideoFrame ?? undefined}
- onOpenDetails={openVideoDetails ?? undefined}
onOpenMenu={openItemMenu}
/>
- <Box bg="border.subtle" flexShrink={0} h="4" w="1px" />
+ <Divider />
</>
) : null}
{/* Both toggles go through `ToggleIconButton` so they read as one control
type: the filled variant carries "on", `aria-pressed` carries it for
assistive tech, and the label doubles as the tooltip. */}
- <ToggleIconButton
- checked={isFilmstripVisible}
- icon={GalleryThumbnailsIcon}
- label={filmstripLabel}
- onCheckedChange={toggleFilmstrip}
- />
<ToggleIconButton
checked={showProgressImagesInViewer}
icon={HourglassIcon}
@@ -77,6 +97,23 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {
opacity={hasProgressImage || showProgressImagesInViewer ? 1 : 0.7}
onCheckedChange={toggleProgressImages}
/>
+ <ToggleIconButton
+ checked={isFilmstripVisible}
+ icon={GalleryThumbnailsIcon}
+ label={filmstripLabel}
+ onCheckedChange={toggleFilmstrip}
+ />
+ {actionItem && actions ? (
+ <PreviewDetailsPopover
+ actions={actions}
+ image={isGalleryImageItem(actionItem) ? galleryImageItemToGalleryImage(actionItem) : null}
+ isOpen={isDetailsOpen}
+ item={actionItem}
+ position={position}
+ stageElement={stageElement}
+ onOpenChange={setDetailsOpen}
+ />
+ ) : null}
</HStack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx
index 434c070aff..03a7a16f55 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx
@@ -3,7 +3,7 @@ import type { GalleryImageItem, GalleryVideoItem } from '@features/gallery';
import type * as queueDevicesModule from '@features/queue/devices';
import type { ImageActions } from '@workbench/image-actions';
-import { Box, ChakraProvider, Text } from '@chakra-ui/react';
+import { Box, ChakraProvider } from '@chakra-ui/react';
import { DndContext, PointerSensor, useDndMonitor, useSensor, useSensors, type DragStartEvent } from '@dnd-kit/core';
import { system } from '@theme/system';
import { createInstance } from 'i18next';
@@ -11,10 +11,10 @@ import { act, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
import { PreviewActionStrip } from './PreviewActionStrip';
import { PreviewFilmstrip } from './PreviewFilmstrip';
-import { PreviewFooter } from './PreviewFooter';
import { LivePreviewTile } from './PreviewWidgetView';
const sharedImage: GalleryImageItem = {
@@ -95,15 +95,21 @@ void i18n.use(initReactI18next).init({
translation: {
common: { countOfTotal: '{{count}} of {{total}}', edit: 'Edit', generating: 'Generating' },
widgets: {
+ canvas: { import: { control: 'Control Layer', raster: 'Raster Layer' } },
preview: {
copyCurrentFrame: 'Copy Current Frame',
+ details: 'Details',
editOnCanvas: 'Edit on Canvas',
framesPerSecond: '{{count}} fps',
+ imageActions: 'Image actions',
itemCount_one: '{{count}} item',
itemCount_other: '{{count}} items',
- nextItemInBoard: 'Next item in board',
- previousItemInBoard: 'Previous item in board',
- videoDetails: 'Video Details',
+ selectForCompare: 'Select for Compare',
+ sendToCanvas: 'Send to Canvas',
+ starImage: 'Star image',
+ starVideo: 'Star video',
+ unstarImage: 'Unstar image',
+ unstarVideo: 'Unstar video',
videoDuration: 'Duration {{duration}}',
},
queue: {
@@ -268,6 +274,38 @@ describe('PreviewFilmstrip mixed media', () => {
expect(onSelect).toHaveBeenCalledWith(sharedVideo);
});
+ it('opens the image context menu for a thumb and arms a comparison on alt-click', async () => {
+ const onSelect = vi.fn();
+ const onCompare = vi.fn();
+ const onContextMenu = vi.fn();
+
+ await render(
+ <DndContext>
+ <PreviewFilmstrip
+ density="full"
+ items={[sharedImage, sharedVideo]}
+ selectedItemKey="video:shared"
+ onCompare={onCompare}
+ onContextMenu={onContextMenu}
+ onSelect={onSelect}
+ />
+ </DndContext>
+ );
+ const imageButton = host!.querySelector<HTMLButtonElement>('[aria-label="shared"]')!;
+
+ const contextEvent = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 40, clientY: 50 });
+ await interact(() => imageButton.dispatchEvent(contextEvent));
+ expect(contextEvent.defaultPrevented).toBe(true);
+ expect(onContextMenu).toHaveBeenCalledExactlyOnceWith(sharedImage, 40, 50);
+
+ await interact(() => imageButton.dispatchEvent(new MouseEvent('click', { altKey: true, bubbles: true })));
+ expect(onCompare).toHaveBeenCalledExactlyOnceWith(sharedImage);
+ expect(onSelect).not.toHaveBeenCalled();
+
+ await interact(() => imageButton.click());
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(sharedImage);
+ });
+
it('drags a video poster with a qualified filmstrip id and video ref payload', async () => {
await render(<FilmstripDragHarness />);
@@ -318,80 +356,13 @@ describe('PreviewFilmstrip mixed media', () => {
});
});
-describe('Preview mixed media footer and actions', () => {
- it('uses the readable muted foreground for compact image and video footer text', async () => {
- for (const item of [sharedImage, sharedVideo]) {
- await render(
- <>
- <Text color="fg.muted" data-testid="expected-muted">
- Expected muted
- </Text>
- <PreviewFooter
- boardItemCount={3}
- isLoadingBoard={false}
- isMetadataOpen={false}
- media={{ actionImage: null, actions: {} as ImageActions, item, kind: 'item' }}
- selectedIndex={1}
- onNext={() => undefined}
- onPrevious={() => undefined}
- onToggleMetadata={() => undefined}
- />
- </>
- );
-
- const position = Array.from(host!.querySelectorAll<HTMLElement>('p')).find((element) =>
- element.textContent?.includes('2 of 3')
- );
- const dimensions = Array.from(host!.querySelectorAll<HTMLElement>('p')).find((element) =>
- element.textContent?.includes(`${item.width} × ${item.height}`)
- );
- const details = host!.querySelector<HTMLElement>('button[aria-expanded="false"]');
- const mutedColor = getComputedStyle(host!.querySelector<HTMLElement>('[data-testid="expected-muted"]')!).color;
-
- expect(getComputedStyle(position!).color).toBe(mutedColor);
- expect(getComputedStyle(dimensions!).color).toBe(mutedColor);
- expect(getComputedStyle(details!).color).toBe(mutedColor);
- }
- });
-
- it('shows mixed position, dimensions, duration, and localized fps with tabular numerals', async () => {
- await render(
- <PreviewFooter
- boardItemCount={3}
- isLoadingBoard={false}
- isMetadataOpen={false}
- media={{ actionImage: null, actions: {} as ImageActions, item: sharedVideo, kind: 'item' }}
- selectedIndex={1}
- onNext={() => undefined}
- onPrevious={() => undefined}
- onToggleMetadata={() => undefined}
- />
- );
-
- expect(host?.textContent).toContain('2 of 3');
- expect(host?.textContent).toContain('1920 × 1080');
- expect(host?.textContent).toContain('Duration 1:06');
- expect(host?.textContent).toContain('23.976 fps');
-
- const status = Array.from(host!.querySelectorAll<HTMLElement>('p')).find((element) =>
- element.textContent?.includes('1920 × 1080')
- );
- const position = Array.from(host!.querySelectorAll<HTMLElement>('p')).find((element) =>
- element.textContent?.includes('2 of 3')
- );
- expect(status ? getComputedStyle(status).fontVariantNumeric : '').toContain('tabular-nums');
- expect(position ? getComputedStyle(position).fontVariantNumeric : '').toContain('tabular-nums');
- expect(host?.querySelector('[aria-label="Previous item in board"]')).not.toBeNull();
- expect(host?.querySelector('[aria-label="Next item in board"]')).not.toBeNull();
- });
-
- it('keeps common video actions, adds Preview-only frame/details actions, and hides image-only actions', async () => {
+describe('Preview mixed media actions', () => {
+ it('keeps common video actions, adds the Preview-only frame copy, and hides image-only actions', async () => {
const actions = {
downloadItem: vi.fn(() => Promise.resolve()),
setItemsStarred: vi.fn(() => Promise.resolve()),
} as unknown as ImageActions;
const onCopyCurrentFrame = vi.fn();
- const onOpenDetails = vi.fn();
await render(
<PreviewActionStrip
@@ -400,7 +371,6 @@ describe('Preview mixed media footer and actions', () => {
isVideoFrameCopyAvailable={false}
item={sharedVideo}
onCopyCurrentFrame={onCopyCurrentFrame}
- onOpenDetails={onOpenDetails}
onOpenMenu={() => undefined}
/>
);
@@ -411,17 +381,15 @@ describe('Preview mixed media footer and actions', () => {
expect(host?.querySelector('[aria-label="Edit on Canvas"]')).toBeNull();
const copyFrame = host?.querySelector<HTMLButtonElement>('[aria-label="Copy Current Frame"]');
- const details = host?.querySelector<HTMLButtonElement>('[aria-label="Video Details"]');
const star = host?.querySelector<HTMLButtonElement>('[aria-label="Unstar video"]');
expect(copyFrame).not.toBeNull();
expect(copyFrame?.disabled).toBe(true);
- expect(details).not.toBeNull();
+ // Details lives beside the header toggles now, not in the strip.
+ expect(host?.querySelector('[aria-label="Details"]')).toBeNull();
expect(star).not.toBeNull();
- await interact(() => details?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
await interact(() => star?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
- expect(onOpenDetails).toHaveBeenCalledOnce();
expect(onCopyCurrentFrame).not.toHaveBeenCalled();
expect(actions.setItemsStarred).toHaveBeenCalledWith([{ kind: 'video', name: 'shared' }], false);
@@ -432,7 +400,6 @@ describe('Preview mixed media footer and actions', () => {
isVideoFrameCopyAvailable
item={sharedVideo}
onCopyCurrentFrame={onCopyCurrentFrame}
- onOpenDetails={onOpenDetails}
onOpenMenu={() => undefined}
/>
);
@@ -443,7 +410,7 @@ describe('Preview mixed media footer and actions', () => {
expect(onCopyCurrentFrame).toHaveBeenCalledOnce();
});
- it('sends an image to the canvas as a raster layer', async () => {
+ it('opens Edit onto the canvas layer destinations and sends the image to the chosen one', async () => {
const actions = {
copyImage: vi.fn(() => Promise.resolve()),
downloadItem: vi.fn(() => Promise.resolve()),
@@ -462,8 +429,11 @@ describe('Preview mixed media footer and actions', () => {
expect(host?.querySelector('button')).toBe(editOnCanvas);
expect(editOnCanvas?.textContent).toContain('Edit');
expect(host?.querySelector('[aria-label="Copy Current Frame"]')).toBeNull();
- await interact(() => editOnCanvas?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));
- expect(actions.sendToCanvas).toHaveBeenCalledWith([expect.objectContaining({ imageName: 'shared' })], 'raster');
+
+ await page.getByRole('button', { name: 'Edit on Canvas' }).click();
+ await expect.element(page.getByRole('menuitem', { name: 'Raster Layer' })).toBeVisible();
+ await page.getByRole('menuitem', { name: 'Control Layer' }).click();
+ expect(actions.sendToCanvas).toHaveBeenCalledWith([expect.objectContaining({ imageName: 'shared' })], 'control');
});
// Both remain one click away in the dropdown's quick row, which is why they
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
index 3daef0c586..f07523d3d1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
@@ -3,7 +3,6 @@ import type { GalleryImage, GalleryImageMetadata, GalleryItem, GalleryItemKey }
import { DataList, HStack, Icon, Stack, Tabs, Text } from '@chakra-ui/react';
import { galleryImages, galleryVideos } from '@features/gallery';
import { toGalleryItemKey } from '@features/gallery/contracts';
-import { useAuthSession } from '@features/identity';
import { IconButton, Scrollable, Tooltip } from '@platform/ui';
import { JsonPreview } from '@platform/ui/JsonPreview';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
@@ -11,24 +10,23 @@ import { useQuery } from '@tanstack/react-query';
import {
EMPTY_IMAGE_RECALL_CAPABILITIES,
getImageRecallVerb,
- RecallActionButtons,
type ImageActions,
type ImageRecallCapabilities,
type ImageRecallKind,
} from '@workbench/image-actions';
-import { ChevronDownIcon, ChevronRightIcon, CopyIcon } from 'lucide-react';
-import { useCallback } from 'react';
+import { CopyIcon } from 'lucide-react';
+import { useCallback, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { parsePreviewMetadata, type PreviewMetadataEntry } from './previewMetadata';
/**
- * The footer's collapsible "Details" section: how the image was made (prompt,
- * seed, model, sampler settings) as quiet label/value rows with per-row copy
- * and the recall verbs wired to the existing recall machinery. Video Details
- * expose the backend's raw metadata/workflow/graph payloads instead. The query
- * child exists only while expanded and is keyed by account + qualified item
- * identity, so closing or changing identity aborts supported transports.
+ * The Details popover's body: how the image was made (prompt, seed, model,
+ * sampler settings) as quiet label/value rows with per-row copy and the recall
+ * verbs wired to the existing recall machinery. Video Details expose the
+ * backend's raw metadata/workflow/graph payloads instead. The query child is
+ * keyed by account + qualified item identity, so a closed popover (which
+ * unmounts it) or a changed identity aborts supported transports.
*/
const GROUP_HOVER_VISIBLE = { opacity: 1 };
@@ -48,49 +46,38 @@ const ENTRY_RECALL_KINDS: Partial<
size: { capability: 'dimensions', kind: 'dimensions' },
};
-export const PreviewMetadataPanel = ({
+export const PreviewDetails = ({
+ accountEpoch,
actions,
image,
- isOpen,
item,
- onToggle,
}: {
+ /** Read by the caller, outside the popover's presence boundary, so an account change re-keys the query. */
+ accountEpoch: number;
actions: ImageActions;
image: GalleryImage | null;
- isOpen: boolean;
item: GalleryItem;
- onToggle: () => void;
}) => {
- const { t } = useTranslation();
- const accountEpoch = useAuthSession().accountEpoch;
const itemKey = toGalleryItemKey(item);
return (
- <Stack gap="2">
- <HStack as="button" aria-expanded={isOpen} color="fg.muted" gap="1" w="fit-content" onClick={onToggle}>
- <Icon as={isOpen ? ChevronDownIcon : ChevronRightIcon} boxSize="3" />
- <Text fontSize="2xs" fontWeight="700" textTransform="uppercase">
- {t('widgets.preview.details')}
- </Text>
- </HStack>
- {isOpen ? (
- <PreviewDetailsQuery
- key={`${accountEpoch}:${itemKey}`}
- accountEpoch={accountEpoch}
- actions={actions}
- image={image}
- item={item}
- itemKey={itemKey}
- />
- ) : null}
- </Stack>
+ <PreviewDetailsQuery
+ key={`${accountEpoch}:${itemKey}`}
+ accountEpoch={accountEpoch}
+ actions={actions}
+ image={image}
+ item={item}
+ itemKey={itemKey}
+ />
);
};
type PreviewDetailsData =
| {
+ graph: string | null;
kind: 'image';
metadata: GalleryImageMetadata | null;
+ workflow: string | null;
}
| {
graph: string | null;
@@ -117,12 +104,17 @@ const PreviewDetailsQuery = ({
queryFn: async ({ signal }): Promise<PreviewDetailsData> => {
if (item.kind === 'image') {
if (!image) {
- return { kind: 'image', metadata: null };
+ return { graph: null, kind: 'image', metadata: null, workflow: null };
}
- const metadata = await galleryImages.metadata(item.name, signal);
+ // Metadata carries whatever a workflow's metadata nodes added, so the
+ // raw record is shown whole alongside the parsed rows, like legacy.
+ const [metadata, workflow] = await Promise.all([
+ galleryImages.metadata(item.name, signal),
+ galleryImages.workflow(item.name, signal),
+ ]);
- return { kind: 'image', metadata };
+ return { graph: workflow.graph, kind: 'image', metadata, workflow: workflow.workflow };
}
const [metadata, workflow] = await Promise.all([
@@ -148,7 +140,7 @@ const PreviewDetailsQuery = ({
const details = isVideoDetails(detailsQuery.data) ? detailsQuery.data : null;
return (
- <VideoDetails
+ <DetailsTabs
graph={details?.graph ?? null}
metadata={details?.metadata ?? null}
workflow={details?.workflow ?? null}
@@ -161,13 +153,19 @@ const PreviewDetailsQuery = ({
image && details ? actions.deriveImageRecallCapabilities(image, details.metadata) : EMPTY_IMAGE_RECALL_CAPABILITIES;
return (
- <ImageDetails
- actions={actions}
- capabilities={capabilities}
- image={image}
- isLoading={detailsQuery.isPending}
+ <DetailsTabs
+ graph={details?.graph ?? null}
metadata={details?.metadata ?? null}
- />
+ workflow={details?.workflow ?? null}
+ >
+ <ImageDetails
+ actions={actions}
+ capabilities={capabilities}
+ image={image}
+ isLoading={detailsQuery.isPending}
+ metadata={details?.metadata ?? null}
+ />
+ </DetailsTabs>
);
};
@@ -207,7 +205,7 @@ const ImageDetails = ({
);
return (
- <Scrollable maxH="40cqh">
+ <Scrollable flex="1" minH="0">
<Stack gap="2" pe="1">
{isLoading ? (
<Text color="fg.subtle" fontSize="2xs">
@@ -229,47 +227,73 @@ const ImageDetails = ({
})}
</DataList.Root>
)}
- <RecallActionButtons
- capabilities={capabilities}
- disabledReason={t('widgets.preview.recallNotAvailable')}
- onRecall={handleRecall}
- />
</Stack>
</Scrollable>
);
};
-const VideoDetails = ({
+/**
+ * The legacy metadata viewer's tab set: parsed details (images only), then the
+ * raw metadata record — where workflow metadata nodes land — and the source
+ * workflow and graph. Each tab body fills the popover's remaining height and
+ * scrolls inside it.
+ */
+const DetailsTabs = ({
+ children: details,
graph,
metadata,
workflow,
}: {
+ /** The parsed rows + recall verbs; images only. */
+ children?: ReactNode;
graph: string | null;
metadata: Record<string, unknown> | null;
workflow: string | null;
}) => {
const { t } = useTranslation();
+ // A tab with nothing behind it is disabled rather than opening onto an empty
+ // pane, so the first tab with content is where the popover opens.
+ const defaultValue = details ? 'details' : metadata !== null ? 'metadata' : workflow !== null ? 'workflow' : 'graph';
return (
- <Tabs.Root defaultValue="metadata" lazyMount size="sm" unmountOnExit variant="outline">
- <Tabs.List>
- <Tabs.Trigger fontSize="2xs" value="metadata">
+ <Tabs.Root
+ defaultValue={defaultValue}
+ display="flex"
+ flexDirection="column"
+ lazyMount
+ minH="0"
+ size="sm"
+ unmountOnExit
+ variant="outline"
+ >
+ <Tabs.List flexShrink={0}>
+ {details ? (
+ <Tabs.Trigger fontSize="2xs" value="details">
+ {t('widgets.preview.details')}
+ </Tabs.Trigger>
+ ) : null}
+ <Tabs.Trigger disabled={metadata === null} fontSize="2xs" value="metadata">
{t('widgets.preview.metadata')}
</Tabs.Trigger>
- <Tabs.Trigger fontSize="2xs" value="workflow">
+ <Tabs.Trigger disabled={workflow === null} fontSize="2xs" value="workflow">
{t('widgets.preview.workflow')}
</Tabs.Trigger>
- <Tabs.Trigger fontSize="2xs" value="graph">
+ <Tabs.Trigger disabled={graph === null} fontSize="2xs" value="graph">
{t('widgets.preview.graph')}
</Tabs.Trigger>
</Tabs.List>
- <Tabs.Content value="metadata">
- <JsonPreview label={t('widgets.preview.metadataJsonLabel')} maxH="40cqh" value={metadata} />
+ {details ? (
+ <Tabs.Content display="flex" flexDirection="column" minH="0" value="details">
+ {details}
+ </Tabs.Content>
+ ) : null}
+ <Tabs.Content display="flex" flexDirection="column" minH="0" value="metadata">
+ <JsonPreview label={t('widgets.preview.metadataJsonLabel')} maxH="100%" value={metadata} />
</Tabs.Content>
- <Tabs.Content value="workflow">
+ <Tabs.Content display="flex" flexDirection="column" minH="0" value="workflow">
<RawJsonPreview label={t('widgets.preview.workflowJsonLabel')} text={workflow} />
</Tabs.Content>
- <Tabs.Content value="graph">
+ <Tabs.Content display="flex" flexDirection="column" minH="0" value="graph">
<RawJsonPreview label={t('widgets.preview.graphJsonLabel')} text={graph} />
</Tabs.Content>
</Tabs.Root>
@@ -278,9 +302,9 @@ const VideoDetails = ({
const RawJsonPreview = ({ label, text }: { label: string; text: string | null }) =>
text === null ? (
- <JsonPreview label={label} maxH="40cqh" value={null} />
+ <JsonPreview label={label} maxH="100%" value={null} />
) : (
- <JsonPreview label={label} maxH="40cqh" text={text} />
+ <JsonPreview label={label} maxH="100%" text={text} />
);
/**
@@ -310,7 +334,7 @@ const MetadataRow = ({
return (
<DataList.Item alignItems="start" className="group">
<DataList.ItemLabel fontSize="2xs">{entry.label}</DataList.ItemLabel>
- <DataList.ItemValue fontSize="2xs" minW="0">
+ <DataList.ItemValue alignItems="flex-start" fontSize="2xs" minW="0">
{entry.isMultiline ? (
<Text flex="1" fontSize="2xs" minW="0" whiteSpace="pre-wrap">
{entry.value}
@@ -319,6 +343,7 @@ const MetadataRow = ({
<MiddleTruncate flex="1" fontSize="2xs" minW="0" text={entry.value} />
)}
<HStack
+ alignSelf="flex-start"
flexShrink={0}
gap="0"
opacity={0}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index f5acb56a9a..bcc2a1eff2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -285,8 +285,6 @@ await i18n.use(initReactI18next).init({
framesPerSecond: '{{count}} fps',
itemCount_one: '{{count}} item',
itemCount_other: '{{count}} items',
- nextItemInBoard: 'Next item in board',
- previousItemInBoard: 'Previous item in board',
videoDuration: 'Duration {{duration}}',
},
},
@@ -536,6 +534,10 @@ afterEach(async () => {
root = null;
});
+/** The filmstrip's current thumb: the one visible trace of where the navigation cursor sits. */
+const selectedThumb = (): string | null | undefined =>
+ host?.querySelector<HTMLButtonElement>('button[aria-current]')?.getAttribute('aria-label');
+
describe('preview keyboard navigation boundary', () => {
it('walks the starred strip into the unstarred listing and back, as the grid lays them out', async () => {
const starredTop = { ...createImageItem('starred-top', '2026-07-23T00:00:00.000Z'), starred: true };
@@ -551,7 +553,7 @@ describe('preview keyboard navigation boundary', () => {
// The listing stays the unstarred one; the strip supplies the starred neighbors.
expect(mocks.galleryItemFilters.length).toBeGreaterThan(0);
expect(mocks.galleryItemFilters.every((query) => query.starred === false)).toBe(true);
- await expect.poll(() => host?.textContent).toContain('2 of 4');
+ await expect.poll(() => selectedThumb()).toBe('starred-next');
expect(mocks.galleryStripFetches.length).toBeGreaterThan(0);
await pressArrow('ArrowRight');
@@ -592,7 +594,7 @@ describe('preview keyboard navigation boundary', () => {
});
await render();
- await expect.poll(() => host?.textContent).toContain('1 of 2');
+ await expect.poll(() => selectedThumb()).toBe('newest');
await pressArrow('ArrowRight');
expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ name: 'oldest' }),
@@ -633,7 +635,7 @@ describe('preview keyboard navigation boundary', () => {
starredOnly: true,
});
await render();
- await expect.poll(() => host?.textContent).toContain('2 of 2');
+ await expect.poll(() => selectedThumb()).toBe('starred-deep');
expect(mocks.galleryStripFetches).toHaveLength(0);
expect(mocks.galleryItemFilters.every((query) => query.starred === true)).toBe(true);
await pressArrow('ArrowLeft');
@@ -1582,10 +1584,6 @@ describe('preview keyboard navigation boundary', () => {
await render();
// Live status reports the requested size without suggesting board navigation.
- expect(host?.textContent).toContain('64 × 64');
- expect(host?.querySelector('button[aria-label="Next item in board"]')).toBeNull();
- expect(host?.textContent).toContain('Generating');
- expect(host?.textContent).not.toContain('0 items');
expect(host?.querySelector<HTMLImageElement>('img[src^="data:image/png"]')).not.toBeNull();
});
@@ -1636,7 +1634,6 @@ describe('preview keyboard navigation boundary', () => {
await render();
expect(host?.querySelectorAll<HTMLImageElement>('img[src^="data:image/png"]')).toHaveLength(1);
- expect(host?.textContent).toContain('64 × 64');
});
it("shows the followed slot's own frame even when the store-wide latest frame is gone", async () => {
@@ -1774,10 +1771,6 @@ describe('preview keyboard navigation boundary', () => {
await act(() => followControls.pin('queue-item-live:1'));
const boundary = host!.querySelector<HTMLElement>('[role="region"]')!;
expect(boundary.getBoundingClientRect().bottom).toBeLessThanOrEqual(host!.getBoundingClientRect().bottom);
- expect(host!.querySelector('button[aria-label="Next item in board"]')).toBeNull();
- expect(host!.querySelector('button[aria-label="Previous item in board"]')).toBeNull();
- expect(host!.textContent).not.toContain('0 items');
- expect(host!.textContent).toContain('Generating');
});
it('does not consume arrow keys in comparison mode', async () => {
(mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage = {
@@ -1820,10 +1813,6 @@ describe('preview keyboard navigation boundary', () => {
expect(video?.getAttribute('src')).toBe(sameNameVideo.fullUrl);
expect(video?.getAttribute('poster')).toBe(sameNameVideo.thumbnailUrl);
expect(filmstripPosters).toHaveLength(3);
- expect(host?.textContent).toContain('2 of 3');
- expect(host?.textContent).toContain('1920 × 1080');
- expect(host?.textContent).toContain('Duration 1:06');
- expect(host?.textContent).toContain('23.976 fps');
expect(host?.textContent).not.toContain('Drop to compare');
await pressArrow('ArrowLeft');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index ff2e4e00a3..82c354bc0b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -7,7 +7,6 @@ import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';
import {
galleryImages,
type GalleryBoard,
- type GalleryImage,
type GalleryImageItem,
type GalleryItem,
type GalleryItemKey,
@@ -52,7 +51,6 @@ import {
ImageContextMenu,
useDeletionConfirmation,
useImageActions,
- type ImageActions,
type ImageContextMenuTarget,
} from '@workbench/image-actions';
import { QueueProgressRail } from '@workbench/queue-integration/QueueProgressRail';
@@ -74,25 +72,18 @@ import { PreviewCompare } from './PreviewCompare';
import { resolvePreviewCompareDrop } from './previewCompareDnd';
import { usePreviewDensity, type PreviewDensity } from './previewDensity';
import { PreviewFilmstrip } from './PreviewFilmstrip';
-import { PreviewFooter, type PreviewFooterMedia, PreviewTileFooter } from './PreviewFooter';
+import { PreviewTileFooter } from './PreviewFooter';
import {
PreviewFrame,
type PreviewMediaSource,
type PreviewVideoFrameController,
type PreviewVideoFrameCopyResult,
} from './PreviewFrame';
-import { previewHeaderStore } from './previewHeaderStore';
-import {
- getPreviewComparisonMode,
- getPreviewFilmstripVisible,
- getPreviewMetadataOpen,
- type PreviewComparisonMode,
-} from './previewSettings';
+import { previewHeaderStore, previewStageStore, type PreviewZoomCommands } from './previewHeaderStore';
+import { getPreviewComparisonMode, getPreviewFilmstripVisible, type PreviewComparisonMode } from './previewSettings';
import { usePreviewNavigation } from './usePreviewNavigation';
/** For the live footer's Details slot, which renders disabled and never fires. */
-const noop = (): void => {};
-
const VIDEO_FRAME_COPY_FAILURE_KEYS = {
'clipboard-failed': 'widgets.preview.copyCurrentFrameWriteFailed',
'draw-failed': 'widgets.preview.copyCurrentFrameDrawFailed',
@@ -154,19 +145,10 @@ const getBoardName = (
const selectGenerateRecallValues = createGenerateFormValuesSelector();
/**
- * Bottom padding the grid surface reserves for the overlaid details island —
- * its collapsed height plus the 2-unit inset and gap. The filmstrip
- * deliberately reserves nothing: it is a floating overlay above the media's
- * lower edge, so toggling it never reflows the fitted image. An expanded
- * Details panel grows over the grid on purpose; it is self-capped at `40cqh`
- * and closes back down.
- */
-const PREVIEW_OVERLAY_RESERVE = '5.5rem';
-
-/**
- * A tile carries a footer but never a filmstrip, so it reserves the one island
- * instead of the pair. Its stage padding stays compact for the same reason the
- * grid exists at all: at four sessions each cell is a quarter of the widget.
+ * A multi-session tile floats its status island over its stage and reserves
+ * that much bottom padding for it. Its stage padding stays compact for the
+ * same reason the grid exists at all: at four sessions each cell is a quarter
+ * of the widget.
*/
const PREVIEW_TILE_OVERLAY_RESERVE = '3.25rem';
const PREVIEW_TILE_STAGE_PADDING = '3';
@@ -237,7 +219,16 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
};
}, []);
const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);
+ // The header's zoom commands close over the controls ref, so they are stable
+ // per mount; the readout itself streams through `previewStageStore`.
const videoControllerRef = useRef<PreviewVideoFrameController | null>(null);
+ const zoomCommands = useMemo<PreviewZoomCommands>(
+ () => ({
+ reset: () => loupeControlsRef.current?.reset(),
+ zoomTo: (actualZoom: number) => loupeControlsRef.current?.zoomTo(actualZoom),
+ }),
+ []
+ );
const [copyAvailableItemKey, setCopyAvailableItemKey] = useState<GalleryItemKey | null>(null);
const boardsQuery = useQuery({
@@ -265,7 +256,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
getSelectionPage,
handleNavigationKeyDown,
isLoadingBoard,
- navigate,
navigationCursor,
navigationQueryKey,
selectPreviewItem,
@@ -315,11 +305,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
return boardItems.find((item) => toGalleryItemKey(item) === selectedItemKey) ?? selectedItem;
}, [boardItems, selectedItem, selectedItemKey]);
- const actionImage = useMemo<GalleryImage | null>(
- () =>
- contextMenuItem && isGalleryImageItem(contextMenuItem) ? galleryImageItemToGalleryImage(contextMenuItem) : null,
- [contextMenuItem]
- );
const exitCompare = useCallback(() => gallery.setCompareItem(null), [gallery]);
// The page the item now in the compare slot was selected at, when Preview
// put it there by swapping. The window may not hold that item any more —
@@ -379,11 +364,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
(comparisonMode: PreviewComparisonMode) => widgets.patchValues('preview', { comparisonMode }),
[widgets]
);
- const isMetadataOpen = getPreviewMetadataOpen(previewValues);
- const toggleMetadata = useCallback(
- () => widgets.patchValues('preview', { metadataOpen: !isMetadataOpen }),
- [isMetadataOpen, widgets]
- );
const openVideoDetails = useCallback(() => widgets.patchValues('preview', { metadataOpen: true }), [widgets]);
const handleVideoCopyAvailabilityChange = useCallback((itemKey: GalleryItemKey, isAvailable: boolean) => {
setCopyAvailableItemKey((current) => (isAvailable ? itemKey : current === itemKey ? null : current));
@@ -472,6 +452,19 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[boardItems, gallery, notifications, selectedItem]
);
useDndMonitor({ onDragEnd: handleCompareDrop });
+ const openFilmstripItemContextMenu = useCallback(
+ (item: GalleryItem, x: number, y: number) =>
+ setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y }),
+ []
+ );
+ const compareFilmstripItem = useCallback(
+ (item: GalleryItem) => {
+ if (isGalleryImageItem(item)) {
+ imageActions.selectForCompare(galleryImageItemToGalleryImage(item));
+ }
+ },
+ [imageActions]
+ );
const openItemContextMenu = useCallback(
(x: number, y: number) => {
if (contextMenuItem) {
@@ -485,8 +478,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
},
[contextMenuItem]
);
- const selectNextItem = useCallback(() => navigate(1), [navigate]);
- const selectPreviousItem = useCallback(() => navigate(-1), [navigate]);
const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);
const headerItemName = shouldFollowLive ? null : (selectedItem?.name ?? null);
@@ -494,6 +485,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
// action strip's image + actions) for the widget frame; the chrome renders
// outside this view, so an external store is the sync channel. Cleared on
// unmount so stale chrome never outlives us.
+ const hasHeaderItem = !shouldFollowLive && contextMenuItem !== null;
useEffect(() => {
previewHeaderStore.set({
actionItem: shouldFollowLive ? null : contextMenuItem,
@@ -503,21 +495,37 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
isVideoFrameCopyAvailable: !shouldFollowLive && isVideoFrameCopyAvailable,
itemName: headerItemName,
openItemMenu: shouldFollowLive ? null : openItemContextMenu,
- openVideoDetails: !shouldFollowLive && contextMenuItem?.kind === 'video' ? openVideoDetails : null,
+ position: hasHeaderItem
+ ? { boardItemCount: boardItems.length, isLoadingBoard, selectedIndex: navigationCursor }
+ : null,
+ // Only the single image frame carries a loupe: videos have none and
+ // compare has its own synced pair.
+ zoom: hasHeaderItem && !isComparing && contextMenuItem.kind === 'image' ? zoomCommands : null,
});
}, [
+ boardItems.length,
boardName,
contextMenuItem,
copyCurrentVideoFrame,
+ hasHeaderItem,
headerItemName,
imageActions,
+ isComparing,
+ isLoadingBoard,
isVideoFrameCopyAvailable,
+ navigationCursor,
openItemContextMenu,
- openVideoDetails,
shouldFollowLive,
+ zoomCommands,
]);
- useEffect(() => () => previewHeaderStore.clear(), []);
+ useEffect(
+ () => () => {
+ previewHeaderStore.clear();
+ previewStageStore.clear();
+ },
+ []
+ );
const executeViewerHotkey = useEffectEvent((commandId: string) => {
if (commandId === 'viewer.swapImages' && selectedItem?.kind === 'image' && compareImage) {
@@ -617,15 +625,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
/>
) : shouldFollowLive && activeGalleryPlaceholder ? (
<LivePreview
- boardItemCount={0}
density={density}
filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}
- isLoadingBoard={isLoadingBoard}
placeholder={activeGalleryPlaceholder}
- selectedIndex={-1}
shouldAntialiasProgressImage={antialiasProgressImages}
- onNext={selectNextItem}
- onPrevious={selectPreviousItem}
onSelectItem={selectPreviewItem}
/>
) : selectedItem ? (
@@ -642,43 +645,29 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
/>
) : selectedItem.kind === 'image' ? (
<SelectedImagePreview
- actionImage={actionImage}
- actions={imageActions}
- boardItemCount={boardItems.length}
density={density}
filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}
isItemCurrent={isItemCurrent}
- isLoadingBoard={isLoadingBoard}
- isMetadataOpen={isMetadataOpen}
item={selectedItem}
loupeControlsRef={loupeControlsRef}
- selectedIndex={navigationCursor}
shouldAntialiasProgressImage={antialiasProgressImages}
+ onCompareItem={compareFilmstripItem}
onContextMenu={openItemContextMenu}
- onNext={selectNextItem}
- onPrevious={selectPreviousItem}
+ onItemContextMenu={openFilmstripItemContextMenu}
onSelectItem={selectPreviewItem}
- onToggleMetadata={toggleMetadata}
/>
) : (
<SelectedVideoPreview
- actionImage={null}
- actions={imageActions}
- boardItemCount={boardItems.length}
density={density}
filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}
isItemCurrent={isItemCurrent}
- isLoadingBoard={isLoadingBoard}
- isMetadataOpen={isMetadataOpen}
item={selectedItem}
videoControllerRef={videoControllerRef}
- selectedIndex={navigationCursor}
onContextMenu={openItemContextMenu}
onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}
- onNext={selectNextItem}
- onPrevious={selectPreviousItem}
+ onCompareItem={compareFilmstripItem}
+ onItemContextMenu={openFilmstripItemContextMenu}
onSelectItem={selectPreviewItem}
- onToggleMetadata={toggleMetadata}
/>
)}
<ImageContextMenu
@@ -775,35 +764,27 @@ const SelectedVideoPreview = ({
};
interface SelectedMediaPreviewProps {
- actionImage: GalleryImage | null;
- actions: ImageActions;
- boardItemCount: number;
density: PreviewDensity;
/** Board thumbnails for the filmstrip, or null when the strip is hidden. */
filmstripItems: GalleryItem[] | null;
isItemCurrent: (itemKey: GalleryItemKey) => boolean;
- isLoadingBoard: boolean;
- isMetadataOpen: boolean;
item: GalleryItem;
loupeControlsRef?: Ref<PreviewLoupeControls>;
onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;
- selectedIndex: number;
+ onCompareItem: (item: GalleryItem) => void;
onContextMenu: (x: number, y: number) => void;
- onNext: () => void;
- onPrevious: () => void;
+ onItemContextMenu: (item: GalleryItem, x: number, y: number) => void;
onSelectItem: (item: GalleryItem) => void;
- onToggleMetadata: () => void;
videoControllerRef?: Ref<PreviewVideoFrameController>;
}
/**
* The one media arrangement, shared by selected items and the live preview:
- * the stage fills, and the filmstrip + footer float above its lower edge in a
- * single island stack. The stage reserves bottom padding for the footer island
- * only, so the fitted media is never tucked under it; the filmstrip floats
- * over the media itself and steals no height. Live and finished renders MUST
- * pass through the same scaffold — the denoise→done boundary may change only
- * the pixels inside the frame, never the geometry around it.
+ * the stage fills, and the filmstrip docks under it as a row of its own, so
+ * toggling the strip refits the media rather than covering it. Live and
+ * finished renders MUST pass through the same scaffold — the denoise→done
+ * boundary may change only the pixels inside the frame, never the geometry
+ * around it.
*/
const PreviewMediaScaffold = ({ children }: { children: ReactNode }) => (
<Flex direction="column" h="full" minH="0" position="relative" w="full">
@@ -811,7 +792,7 @@ const PreviewMediaScaffold = ({ children }: { children: ReactNode }) => (
</Flex>
);
-/** The floating island column the filmstrip and footer share. */
+/** The floating island a multi-session tile's status footer sits in. */
const PreviewOverlayStack = ({ children }: { children: ReactNode }) => (
<Stack bottom="2" gap="2" insetX="2" position="absolute" zIndex="1">
{children}
@@ -819,11 +800,9 @@ const PreviewOverlayStack = ({ children }: { children: ReactNode }) => (
);
const getMediaStagePadding = (density: PreviewDensity): string => (density === 'full' ? '6' : '3');
+const { setStageElement, setZoom: setZoomReadout } = previewStageStore;
const SelectedMediaPreview = ({
- actionImage,
- actions,
- boardItemCount,
density,
dragItem,
filmstripItems,
@@ -831,20 +810,16 @@ const SelectedMediaPreview = ({
frameWidth,
holdSource,
isItemCurrent,
- isLoadingBoard,
- isMetadataOpen,
item,
loupeControlsRef,
onCopyAvailabilityChange,
onSourceLoaded,
- selectedIndex,
shouldAntialiasHoldImage,
source,
+ onCompareItem,
onContextMenu,
- onNext,
- onPrevious,
+ onItemContextMenu,
onSelectItem,
- onToggleMetadata,
videoControllerRef,
}: SelectedMediaPreviewProps & {
dragItem?: GalleryItemRef;
@@ -854,14 +829,11 @@ const SelectedMediaPreview = ({
onSourceLoaded?: (src: string) => void;
shouldAntialiasHoldImage?: boolean;
source: Parameters<typeof PreviewFrame>[0]['source'];
-}) => {
- const media = useMemo<PreviewFooterMedia>(
- () => ({ actionImage, actions, item, kind: 'item' }),
- [actionImage, actions, item]
- );
-
- return (
- <PreviewMediaScaffold>
+}) => (
+ <PreviewMediaScaffold>
+ {/* The stage wrapper is the Details popover's boundary for images and
+ videos alike; the frame inside fills it, so their rects coincide. */}
+ <Flex ref={setStageElement} direction="column" flex="1" minH="0">
<PreviewFrame
dragItem={dragItem}
frameHeight={frameHeight}
@@ -872,66 +844,45 @@ const SelectedMediaPreview = ({
loupeControlsRef={loupeControlsRef}
onSourceLoaded={onSourceLoaded}
onVideoCopyAvailabilityChange={onCopyAvailabilityChange}
+ onZoomChange={setZoomReadout}
padding={getMediaStagePadding(density)}
- paddingBottom={PREVIEW_OVERLAY_RESERVE}
shouldAntialiasLiveImage={shouldAntialiasHoldImage ?? true}
source={source}
variant="framed"
videoControllerRef={videoControllerRef}
onContextMenu={onContextMenu}
/>
- <PreviewOverlayStack>
- {filmstripItems ? (
- <PreviewFilmstrip
- density={density}
- items={filmstripItems}
- selectedItemKey={toGalleryItemKey(item)}
- onSelect={onSelectItem}
- />
- ) : null}
- <PreviewFooter
- boardItemCount={boardItemCount}
- isLoadingBoard={isLoadingBoard}
- isMetadataOpen={isMetadataOpen}
- media={media}
- selectedIndex={selectedIndex}
- onNext={onNext}
- onPrevious={onPrevious}
- onToggleMetadata={onToggleMetadata}
- />
- </PreviewOverlayStack>
- </PreviewMediaScaffold>
- );
-};
+ </Flex>
+ {filmstripItems ? (
+ <PreviewFilmstrip
+ density={density}
+ items={filmstripItems}
+ selectedItemKey={toGalleryItemKey(item)}
+ onCompare={onCompareItem}
+ onContextMenu={onItemContextMenu}
+ onSelect={onSelectItem}
+ />
+ ) : null}
+ </PreviewMediaScaffold>
+);
/**
* The single-session live preview: the denoise stream rendered exactly like a
* finished item — same scaffold, same frame chrome, no badge — so the moment
- * generation completes, only the pixels change. The footer stays up
- * throughout, showing generation status and requested output dimensions.
- * Saved-image navigation remains in the filmstrip.
+ * generation completes, only the pixels change. Saved-image navigation
+ * remains in the filmstrip.
*/
const LivePreview = ({
- boardItemCount,
density,
filmstripItems,
- isLoadingBoard,
placeholder,
- selectedIndex,
shouldAntialiasProgressImage,
- onNext,
- onPrevious,
onSelectItem,
}: {
- boardItemCount: number;
density: PreviewDensity;
filmstripItems: GalleryItem[] | null;
- isLoadingBoard: boolean;
placeholder: QueueActiveSession;
- selectedIndex: number;
shouldAntialiasProgressImage: boolean;
- onNext: () => void;
- onPrevious: () => void;
onSelectItem: (item: GalleryItem) => void;
}) => {
// The followed slot's own frame, not the store-wide latest: with two slots
@@ -958,11 +909,6 @@ const LivePreview = ({
[placeholder.id, previewImage]
);
- const media = useMemo<PreviewFooterMedia>(
- () => ({ height: placeholder.height, kind: 'live', width: placeholder.width }),
- [placeholder.height, placeholder.width]
- );
-
return (
<PreviewMediaScaffold>
<PreviewFrame
@@ -970,26 +916,13 @@ const LivePreview = ({
frameWidth={previewImage?.width ?? placeholder.width}
isLive
padding={getMediaStagePadding(density)}
- paddingBottom={PREVIEW_OVERLAY_RESERVE}
shouldAntialiasLiveImage={shouldAntialiasProgressImage}
source={source}
variant="framed"
/>
- <PreviewOverlayStack>
- {filmstripItems ? (
- <PreviewFilmstrip density={density} items={filmstripItems} selectedItemKey={null} onSelect={onSelectItem} />
- ) : null}
- <PreviewFooter
- boardItemCount={boardItemCount}
- isLoadingBoard={isLoadingBoard}
- isMetadataOpen={false}
- media={media}
- selectedIndex={selectedIndex}
- onNext={onNext}
- onPrevious={onPrevious}
- onToggleMetadata={noop}
- />
- </PreviewOverlayStack>
+ {filmstripItems ? (
+ <PreviewFilmstrip density={density} items={filmstripItems} selectedItemKey={null} onSelect={onSelectItem} />
+ ) : null}
</PreviewMediaScaffold>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx
new file mode 100644
index 0000000000..1533444280
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx
@@ -0,0 +1,96 @@
+import { HStack, Menu, Portal, Text } from '@chakra-ui/react';
+import { Button } from '@platform/ui/Button';
+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import { ChevronDownIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { PreviewZoomControls } from './previewHeaderStore';
+
+const ZOOM_PRESETS = [100, 200, 400] as const;
+const MENU_POSITIONING = { placement: 'bottom-start' } as const;
+
+/**
+ * The header's zoom readout: the fitted image's percent of its own pixels, or
+ * the loupe's current zoom, with fit and the actual-pixel presets one click
+ * away. The stage keeps the gestures (wheel, pinch, double-click); this is the
+ * legible number and the keyboard route.
+ */
+export const PreviewZoomMenu = ({ zoom }: { zoom: PreviewZoomControls }) => {
+ const { t } = useTranslation();
+ const percent = zoom.percent;
+ const label = percent === null ? '—' : t('widgets.preview.zoomPercent', { percent });
+ const ids = useTooltipTriggerIds();
+
+ return (
+ <Menu.Root ids={ids} positioning={MENU_POSITIONING}>
+ <Tooltip content={t('widgets.preview.zoom')} ids={ids}>
+ <Menu.Trigger asChild>
+ <Button
+ aria-label={percent === null ? t('widgets.preview.zoom') : t('widgets.preview.zoomLevel', { percent })}
+ color="fg.muted"
+ fontVariantNumeric="tabular-nums"
+ minW="0"
+ px="1.5"
+ size="2xs"
+ variant="ghost"
+ >
+ <HStack gap="1">
+ <Text fontSize="xs" fontWeight="600">
+ {label}
+ </Text>
+ <ChevronDownIcon size={12} />
+ </HStack>
+ </Button>
+ </Menu.Trigger>
+ </Tooltip>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="9rem">
+ <MenuActionItem
+ disabled={!zoom.isZoomed}
+ label={t('widgets.preview.zoomFit')}
+ value="fit"
+ onSelect={zoom.reset}
+ />
+ {ZOOM_PRESETS.map((preset) => (
+ <ZoomPresetItem
+ key={preset}
+ // A preset the fit already exceeds would only snap back to fit.
+ disabled={zoom.fitPercent !== null && preset <= zoom.fitPercent}
+ isCurrent={zoom.isZoomed && percent === preset}
+ percent={preset}
+ onZoomTo={zoom.zoomTo}
+ />
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+const ZoomPresetItem = ({
+ disabled,
+ isCurrent,
+ onZoomTo,
+ percent,
+}: {
+ disabled: boolean;
+ isCurrent: boolean;
+ onZoomTo: (actualZoom: number) => void;
+ percent: number;
+}) => {
+ const { t } = useTranslation();
+ const handleSelect = useCallback(() => onZoomTo(percent / 100), [onZoomTo, percent]);
+
+ return (
+ <MenuActionItem
+ disabled={disabled || isCurrent}
+ label={t('widgets.preview.zoomPercent', { percent })}
+ value={`zoom-${percent}`}
+ onSelect={handleSelect}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
index ef0ef2bebe..b7d9bb1f13 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts
@@ -4,6 +4,32 @@ import type { ImageActions } from '@workbench/image-actions';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+/** The loupe's commands, published once per selection; the readout lives in `previewStageStore`. */
+export interface PreviewZoomCommands {
+ reset: () => void;
+ /** Zoom to a fraction of the image's own pixels (1 = 100%), never below fit. */
+ zoomTo: (actualZoom: number) => void;
+}
+
+/** What the header's zoom menu renders: the readout plus the commands. */
+export type PreviewZoomControls = PreviewZoomCommands & PreviewZoomReadout;
+
+/** What the loupe shows, as percents of the image's own pixels. */
+export interface PreviewZoomReadout {
+ /** What the fitted image shows, for the menu's presets. */
+ fitPercent: number | null;
+ isZoomed: boolean;
+ /** What is on screen right now. */
+ percent: number | null;
+}
+
+/** Where the selection sits in its board, for the Details popover's header line. */
+export interface PreviewItemPosition {
+ boardItemCount: number;
+ isLoadingBoard: boolean;
+ selectedIndex: number;
+}
+
/**
* Header context published by the preview view so the widget frame's chrome
* (label + header actions) can render the current selection without refetching
@@ -27,7 +53,9 @@ export interface PreviewHeaderContext {
* one source of truth for every image verb.
*/
openItemMenu: ((x: number, y: number) => void) | null;
- openVideoDetails: (() => void) | null;
+ position: PreviewItemPosition | null;
+ /** Null unless the selection is an image the loupe can zoom. */
+ zoom: PreviewZoomCommands | null;
}
const emptyContext: PreviewHeaderContext = {
@@ -38,7 +66,8 @@ const emptyContext: PreviewHeaderContext = {
isVideoFrameCopyAvailable: false,
itemName: null,
openItemMenu: null,
- openVideoDetails: null,
+ position: null,
+ zoom: null,
};
const store = createExternalStore<PreviewHeaderContext>(emptyContext);
@@ -58,3 +87,36 @@ registerAccountOwnedResource({
});
export const usePreviewHeaderContext = (): PreviewHeaderContext => store.useSelector((snapshot) => snapshot);
+
+/**
+ * The view's hot-path readouts, written straight from ref callbacks and the
+ * loupe so a wheel tick re-renders the header's zoom menu and nothing else —
+ * never the view, its filmstrip, or the context menu.
+ */
+export interface PreviewStageContext {
+ /** The media stage; the Details popover keeps within it, off the filmstrip. */
+ stageElement: HTMLElement | null;
+ zoom: PreviewZoomReadout | null;
+}
+
+const emptyStage: PreviewStageContext = { stageElement: null, zoom: null };
+const stageStore = createExternalStore<PreviewStageContext>(emptyStage);
+
+export const previewStageStore = {
+ clear(): void {
+ stageStore.patchSnapshot(emptyStage);
+ },
+ setStageElement(stageElement: HTMLElement | null): void {
+ stageStore.patchSnapshot({ stageElement });
+ },
+ setZoom(zoom: PreviewZoomReadout | null): void {
+ stageStore.patchSnapshot({ zoom });
+ },
+};
+
+registerAccountOwnedResource({
+ clear: previewStageStore.clear,
+ name: 'preview-stage',
+});
+
+export const usePreviewStageContext = (): PreviewStageContext => stageStore.useSelector((snapshot) => snapshot);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts
index 7bd96699e0..c02da887d0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/settingsContribution.ts
@@ -23,5 +23,7 @@ export const previewSettingsContribution: SettingsContribution = {
],
},
],
+ // Both fit the gear's popover; the full dialog stays one click further.
+ quick: ['filmstripVisible', 'comparisonMode'],
load: () => import('./settingsBindings'),
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
index 3cc8b8b734..0fc087b827 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
@@ -18,8 +18,9 @@ const interact = (action: () => void): Promise<void> =>
});
});
-const Harness = () => {
- const loupe = usePreviewLoupe({ enabled: true, naturalWidth: 200 });
+const Harness = ({ naturalWidth = 200, token = 'a' }: { naturalWidth?: number; token?: string }) => {
+ const loupe = usePreviewLoupe({ enabled: true, naturalWidth });
+ loupe.syncDisplayedSource(token);
return (
<div
@@ -36,7 +37,7 @@ const Harness = () => {
}}
{...loupe.stageProps}
>
- <div ref={loupe.contentRef} data-testid="content" style={{ height: 150, width: 200 }} />
+ <div ref={loupe.contentRefCallback} data-testid="content" style={{ height: 150, width: 200 }} />
</div>
);
};
@@ -228,3 +229,31 @@ describe('usePreviewLoupe', () => {
expect(content.style.transform).toBe(transformAtRelease);
});
});
+
+describe('usePreviewLoupe across image swaps', () => {
+ it('clears the old zoom when the displayed image changes, even though the image size changed with it', async () => {
+ const { content, stage } = await mountHarness();
+ const rect = stage.getBoundingClientRect();
+
+ await interact(() =>
+ stage.dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + 200,
+ clientY: rect.top + 150,
+ deltaY: -600,
+ })
+ )
+ );
+ expect(content.style.transform).not.toBe('');
+
+ // A new source with a different natural width: the reset scheduled for it
+ // must survive the gesture math changing identity.
+ await interact(() => root?.render(<Harness naturalWidth={400} token="b" />));
+ await interact(() => undefined);
+
+ expect(content.style.transform).toBe('');
+ expect(content.style.imageRendering).toBe('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
index 34f665244e..ec4f34b899 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
@@ -39,9 +39,18 @@ const PIXELATED_ACTUAL_ZOOM = 2;
export interface PreviewLoupeControls {
reset(): void;
+ /** Zoom to a fraction of the image's own pixels (1 = 100%) about the stage centre, never below fit. */
+ zoomTo(actualZoom: number): void;
zoomToActual(): void;
}
+/** What the loupe shows, for a readout outside the stage: percents of the image's own pixels. */
+export interface PreviewZoomState {
+ fitPercent: number | null;
+ isZoomed: boolean;
+ percent: number | null;
+}
+
interface LoupeTransform {
scale: number;
/** Stage-space translation applied to the content box (origin 0 0). */
@@ -78,10 +87,12 @@ export const usePreviewLoupe = ({
controlsRef,
enabled,
naturalWidth,
+ onZoomChange,
}: {
controlsRef?: Ref<PreviewLoupeControls>;
enabled: boolean;
naturalWidth: number;
+ onZoomChange?: (state: PreviewZoomState) => void;
}) => {
const stageRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
@@ -96,17 +107,60 @@ export const usePreviewLoupe = ({
/** Whether the touch session's first pointer landed on the draggable image. */
const dragCandidateRef = useRef(false);
const lastSourceTokenRef = useRef<string | null | undefined>(undefined);
- const [zoomPercent, setZoomPercent] = useState<number | null>(null);
+ const [zoomState, setZoomState] = useState<PreviewZoomState>(FIT_UNMEASURED);
+ const publishedRef = useRef<PreviewZoomState>(FIT_UNMEASURED);
+ // Live read ports, so the gesture math keeps one identity across images. A
+ // dependency instead would re-create the stage ref callback on every source
+ // swap, and its cleanup cancels the frame that clears the old transform —
+ // leaving the new image drawn zoomed while the readout said fit.
+ const naturalWidthRef = useRef(naturalWidth);
+ // eslint-disable-next-line react/refs
+ naturalWidthRef.current = naturalWidth;
+ const onZoomChangeRef = useRef(onZoomChange);
+ // eslint-disable-next-line react/refs
+ onZoomChangeRef.current = onZoomChange;
+
+ /** The fitted (untransformed) content's width as a fraction of the image's own pixels. */
+ const measureFitRatio = useCallback((): number | null => {
+ const renderedWidth = contentRef.current?.clientWidth ?? 0;
+ const width = naturalWidthRef.current;
+
+ return renderedWidth > 0 && width > 0 ? renderedWidth / width : null;
+ }, []);
- const getActualZoom = useCallback(
- (scale: number): number => {
- const renderedWidth = contentRef.current?.clientWidth ?? 0;
+ /** One place turns a transform into the readout, so the header and `isZoomed` never disagree. */
+ const publish = useCallback(
+ (scale: number) => {
+ const fitRatio = measureFitRatio();
+ const next: PreviewZoomState = {
+ fitPercent: fitRatio === null ? null : Math.round(fitRatio * 100),
+ isZoomed: scale !== 1,
+ percent: fitRatio === null ? null : Math.round(fitRatio * scale * 100),
+ };
+ const previous = publishedRef.current;
+
+ if (
+ previous.fitPercent === next.fitPercent &&
+ previous.isZoomed === next.isZoomed &&
+ previous.percent === next.percent
+ ) {
+ return;
+ }
- return renderedWidth > 0 && naturalWidth > 0 ? (scale * renderedWidth) / naturalWidth : scale;
+ publishedRef.current = next;
+ setZoomState(next);
+ onZoomChangeRef.current?.(next);
},
- [naturalWidth]
+ [measureFitRatio]
);
+ const getActualZoom = useCallback((scale: number): number => {
+ const renderedWidth = contentRef.current?.clientWidth ?? 0;
+ const width = naturalWidthRef.current;
+
+ return renderedWidth > 0 && width > 0 ? (scale * renderedWidth) / width : scale;
+ }, []);
+
const apply = useCallback(() => {
if (rafRef.current !== null) {
return;
@@ -134,9 +188,9 @@ export const usePreviewLoupe = ({
// reaches the img (whose own style leaves it unset while the loupe is
// enabled).
content.style.imageRendering = !isFit && actualZoom >= PIXELATED_ACTUAL_ZOOM ? 'pixelated' : '';
- setZoomPercent(isFit ? null : Math.round(actualZoom * 100));
+ publish(transform.scale);
});
- }, [getActualZoom]);
+ }, [getActualZoom, publish]);
/**
* Called during render with a token identifying the displayed image (or null
@@ -156,26 +210,11 @@ export const usePreviewLoupe = ({
// centre. Dropping it leaves the fresh fit alone until the fingers lift.
panPointerRef.current = null;
pinchRef.current = null;
-
- if (transformRef.current.scale === 1) {
- return;
- }
-
transformRef.current = { scale: 1, tx: 0, ty: 0 };
-
- if (rafRef.current === null) {
- rafRef.current = requestAnimationFrame(() => {
- rafRef.current = null;
- const content = contentRef.current;
-
- if (content) {
- content.style.transform = '';
- content.style.imageRendering = '';
- }
-
- setZoomPercent(null);
- });
- }
+ // Through `apply`, not a bespoke frame: the frame re-derives the style from
+ // the transform ref when it runs, so a wheel tick that lands before it
+ // still wins — and the new image's fit percent is measured once laid out.
+ apply();
};
const setTransform = useCallback(
@@ -203,15 +242,12 @@ export const usePreviewLoupe = ({
);
/** Never below fit, never past `MAX_ACTUAL_ZOOM` of the image's own pixels. */
- const constrainScale = useCallback(
- (scale: number): number => {
- const renderedWidth = contentRef.current?.clientWidth ?? 0;
- const maxScale = renderedWidth > 0 ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / renderedWidth) : 1;
+ const constrainScale = useCallback((scale: number): number => {
+ const renderedWidth = contentRef.current?.clientWidth ?? 0;
+ const maxScale = renderedWidth > 0 ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidthRef.current) / renderedWidth) : 1;
- return Math.max(1, Math.min(scale, maxScale));
- },
- [naturalWidth]
- );
+ return Math.max(1, Math.min(scale, maxScale));
+ }, []);
/** Zoom keeping the content point under the given stage-space coordinates fixed. */
const zoomAroundPoint = useCallback(
@@ -246,19 +282,51 @@ export const usePreviewLoupe = ({
setTransform({ scale: 1, tx: 0, ty: 0 });
}, [setTransform]);
- const zoomToActual = useCallback(() => {
- const stage = stageRef.current;
- const content = contentRef.current;
+ const zoomTo = useCallback(
+ (actualZoom: number) => {
+ const stage = stageRef.current;
+ const content = contentRef.current;
- if (!stage || !content || content.clientWidth === 0) {
- return;
- }
+ if (!stage || !content || content.clientWidth === 0) {
+ return;
+ }
- pinchRef.current = null;
- zoomAroundPoint(stage.clientWidth / 2, stage.clientHeight / 2, Math.max(1, naturalWidth / content.clientWidth));
- }, [naturalWidth, zoomAroundPoint]);
+ pinchRef.current = null;
+ zoomAroundPoint(
+ stage.clientWidth / 2,
+ stage.clientHeight / 2,
+ Math.max(1, (actualZoom * naturalWidthRef.current) / content.clientWidth)
+ );
+ },
+ [zoomAroundPoint]
+ );
+
+ const zoomToActual = useCallback(() => zoomTo(1), [zoomTo]);
+
+ useImperativeHandle(controlsRef, () => ({ reset, zoomTo, zoomToActual }), [reset, zoomTo, zoomToActual]);
- useImperativeHandle(controlsRef, () => ({ reset, zoomToActual }), [reset, zoomToActual]);
+ // The fitted size follows the stage, so the readout has to be re-measured
+ // whenever the content box is laid out at a new size. `apply` rather than
+ // `publish`: it re-derives the DOM transform from the transform ref too, so
+ // a re-attach can never leave the style and the readout disagreeing.
+ const contentRefCallback = useCallback(
+ (node: HTMLDivElement | null) => {
+ contentRef.current = node;
+
+ if (!node || typeof ResizeObserver === 'undefined') {
+ return;
+ }
+
+ const observer = new ResizeObserver(() => apply());
+
+ observer.observe(node);
+
+ return () => {
+ observer.disconnect();
+ };
+ },
+ [apply]
+ );
/** Starts a pan from the given pointer's current position, at the current transform. */
const beginPan = useCallback((pointerId: number, from: PanZoomPoint): void => {
@@ -549,19 +617,18 @@ export const usePreviewLoupe = ({
if (!enabled) {
return {
- contentRef: null,
+ contentRefCallback: null,
isZoomed: false,
reset,
stageProps: null,
stageRefCallback: null,
syncDisplayedSource,
- zoomPercent: null,
};
}
return {
- contentRef,
- isZoomed: zoomPercent !== null,
+ contentRefCallback,
+ isZoomed: zoomState.isZoomed,
reset,
stageProps: {
onDoubleClick: handleDoubleClick,
@@ -570,6 +637,7 @@ export const usePreviewLoupe = ({
},
stageRefCallback,
syncDisplayedSource,
- zoomPercent,
};
};
+
+const FIT_UNMEASURED: PreviewZoomState = { fitPercent: null, isZoomed: false, percent: null };