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(preview): add persisted comparison modes

joshistoast6f2fa3fb232a
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx
new file mode 100644
index 0000000000..1217412a14
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx
@@ -0,0 +1,201 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import type { GeneratedImageContract, WidgetRuntimeApi } from '@workbench/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+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, describe, expect, it, vi } from 'vitest';
+
+import type { PreviewComparisonMode } from './previewSettings';
+
+import { PreviewCompare } from './PreviewCompare';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initImmediate: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: { swap: 'Swap' },
+ widgets: {
+ preview: {
+ commands: { nextComparisonMode: 'Next comparison mode' },
+ compare: 'Compare',
+ exitCompare: 'Exit Compare',
+ hover: 'Hover',
+ hoverComparisonAriaLabel: 'Reveal comparison image on hover, focus, or touch',
+ sideBySide: 'Side by Side',
+ slider: 'Slider',
+ viewing: 'Viewing',
+ },
+ },
+ },
+ },
+ },
+});
+
+const createImage = (name: string, width: number, height: number): GeneratedImageContract => ({
+ height,
+ imageName: name,
+ imageUrl: `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`,
+ queuedAt: '2026-07-16T00:00:00.000Z',
+ sourceQueueItemId: 'queue-1',
+ thumbnailUrl: '',
+ width,
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 50);
+ });
+ });
+
+const waitForMotion = (): Promise<void> =>
+ act(async () => {
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 350);
+ });
+ });
+
+const renderComparison = async ({
+ baseImage = createImage('base', 1200, 800),
+ initialMode = 'hover',
+}: {
+ baseImage?: GeneratedImageContract;
+ initialMode?: PreviewComparisonMode;
+} = {}) => {
+ const commandHandlers = new Map<string, () => void>();
+ const onExit = vi.fn();
+ const onModeChange = vi.fn();
+ const onSwap = vi.fn();
+ const runtime = {
+ commands: {
+ register: ({ handler, id }: { handler: () => void; id: string }) => {
+ commandHandlers.set(id, handler);
+ return () => commandHandlers.delete(id);
+ },
+ },
+ hotkeys: { register: () => () => undefined },
+ } as unknown as WidgetRuntimeApi;
+ const compareImage = createImage('compare', 800, 1200);
+ const Harness = () => {
+ const [mode, setMode] = useState(initialMode);
+
+ return (
+ <PreviewCompare
+ baseImage={baseImage}
+ compareImage={compareImage}
+ mode={mode}
+ runtime={runtime}
+ onExit={onExit}
+ onModeChange={(nextMode) => {
+ setMode(nextMode);
+ onModeChange(nextMode);
+ }}
+ onSwap={onSwap}
+ />
+ );
+ };
+
+ host = document.createElement('div');
+ host.style.height = '500px';
+ host.style.width = '800px';
+ document.body.append(host);
+ root = createRoot(host);
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ return { commandHandlers, onExit, onModeChange, onSwap };
+};
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('PreviewCompare', () => {
+ it('reveals the comparison on focus and touch press, then restores the selected image', async () => {
+ await renderComparison();
+ const frame = host!.querySelector<HTMLElement>('[aria-label*="Reveal comparison"]')!;
+ const compareOverlay = host!.querySelector<HTMLImageElement>('img[alt="compare"]')?.parentElement as HTMLElement;
+
+ expect(getComputedStyle(compareOverlay).opacity).toBe('0');
+ await interact(() => frame.focus());
+ await waitForMotion();
+ expect(getComputedStyle(compareOverlay).opacity).toBe('1');
+ await interact(() => frame.blur());
+ await waitForMotion();
+ expect(getComputedStyle(compareOverlay).opacity).toBe('0');
+
+ Object.defineProperties(frame, {
+ hasPointerCapture: { value: () => true },
+ releasePointerCapture: { value: vi.fn() },
+ setPointerCapture: { value: vi.fn() },
+ });
+ await interact(() =>
+ frame.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerId: 7, pointerType: 'touch' }))
+ );
+ await waitForMotion();
+ expect(getComputedStyle(compareOverlay).opacity).toBe('1');
+ await interact(() =>
+ frame.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerId: 7, pointerType: 'touch' }))
+ );
+ await waitForMotion();
+ expect(getComputedStyle(compareOverlay).opacity).toBe('0');
+ expect(getComputedStyle(compareOverlay).transitionProperty).toContain('opacity');
+ });
+
+ it('cycles all modes through the M command and keeps swap and exit separate', async () => {
+ const { commandHandlers, onExit, onModeChange, onSwap } = await renderComparison({ initialMode: 'slider' });
+ const nextMode = commandHandlers.get('viewer.nextComparisonMode')!;
+
+ await interact(nextMode);
+ expect(onModeChange).toHaveBeenLastCalledWith('side-by-side');
+ await interact(nextMode);
+ expect(onModeChange).toHaveBeenLastCalledWith('hover');
+ await interact(nextMode);
+ expect(onModeChange).toHaveBeenLastCalledWith('slider');
+
+ const buttons = Array.from(host?.querySelectorAll<HTMLButtonElement>('button') ?? []);
+ await interact(() => buttons.find((button) => button.textContent?.includes('Swap'))?.click());
+ await interact(() => buttons.find((button) => button.textContent?.includes('Exit Compare'))?.click());
+ expect(onSwap).toHaveBeenCalledOnce();
+ expect(onExit).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ ['portrait', 400, 1600],
+ ['panorama', 1600, 400],
+ ['square', 900, 900],
+ ])('fits a %s image frame without overflow', async (_name, width, height) => {
+ await renderComparison({ baseImage: createImage('base', width, height), initialMode: 'slider' });
+ const frame = host?.querySelector<HTMLImageElement>('img[alt="base"]')?.parentElement as HTMLElement;
+ const stage = frame.parentElement!;
+ const frameRect = frame.getBoundingClientRect();
+ const stageRect = stage.getBoundingClientRect();
+
+ expect(frameRect.width).toBeLessThanOrEqual(stageRect.width);
+ expect(frameRect.height).toBeLessThanOrEqual(stageRect.height);
+ expect(frameRect.width / frameRect.height).toBeCloseTo(width / height, 1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
index 821ea7587d..48014e8657 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx
@@ -1,8 +1,8 @@
import type { GeneratedImageContract, WidgetRuntimeApi } from '@workbench/types';
-import { Badge, Box, Flex, HStack, Stack } from '@chakra-ui/react';
+import { Badge, Box, Flex, HStack, SegmentGroup, Stack, type SystemStyleObject } from '@chakra-ui/react';
import { Button } from '@workbench/components/ui';
-import { ArrowLeftRightIcon, Columns2Icon, XIcon } from 'lucide-react';
+import { ArrowLeftRightIcon, XIcon } from 'lucide-react';
import {
useCallback,
useEffect,
@@ -10,23 +10,49 @@ import {
useMemo,
useRef,
useState,
- type CSSProperties,
+ type FocusEvent,
type PointerEvent,
} from 'react';
import { useTranslation } from 'react-i18next';
-type CompareMode = 'slider' | 'side-by-side';
+import type { PreviewComparisonMode } from './previewSettings';
-const COMPARE_IMAGE_STYLE: CSSProperties = {
+const COMPARISON_MODES: { labelKey: string; value: PreviewComparisonMode }[] = [
+ { labelKey: 'widgets.preview.slider', value: 'slider' },
+ { labelKey: 'widgets.preview.sideBySide', value: 'side-by-side' },
+ { labelKey: 'widgets.preview.hover', value: 'hover' },
+];
+
+export const getNextPreviewComparisonMode = (mode: PreviewComparisonMode): PreviewComparisonMode => {
+ const index = COMPARISON_MODES.findIndex((item) => item.value === mode);
+
+ return COMPARISON_MODES[(index + 1) % COMPARISON_MODES.length]?.value ?? 'slider';
+};
+
+const getFittedFrameCss = (width: number, height: number): SystemStyleObject => ({
+ aspectRatio: `${width} / ${height}`,
+ height: 'auto',
+ maxHeight: '100%',
+ maxWidth: '100%',
+ width: `min(100cqw, calc(100cqh * ${width / height}))`,
+});
+
+const BASE_IMAGE_STYLE = {
+ display: 'block',
+ height: 'auto',
+ pointerEvents: 'none',
+ userSelect: 'none',
+ width: '100%',
+} as const;
+
+const OVERLAY_IMAGE_STYLE = {
display: 'block',
height: '100%',
- inset: 0,
objectFit: 'contain',
pointerEvents: 'none',
- position: 'absolute',
userSelect: 'none',
width: '100%',
-};
+} as const;
const previewGridCss = {
backgroundImage: 'radial-gradient(circle, currentColor 1px, transparent 1.5px)',
@@ -37,29 +63,29 @@ const previewGridCss = {
const sliderTouchStyle = { touchAction: 'none' } as const;
-/**
- * Two-image comparison: a draggable slider that reveals the compare image over
- * the selected one, or a side-by-side split.
- */
+/** Three-mode, project-persisted comparison surface. */
export const PreviewCompare = ({
baseImage,
compareImage,
+ mode,
onExit,
+ onModeChange,
onSwap,
runtime,
}: {
baseImage: GeneratedImageContract;
compareImage: GeneratedImageContract;
+ mode: PreviewComparisonMode;
onExit: () => void;
+ onModeChange: (mode: PreviewComparisonMode) => void;
onSwap: () => void;
runtime: WidgetRuntimeApi;
}) => {
const { t } = useTranslation();
- const [mode, setMode] = useState<CompareMode>('slider');
const [dividerPercent, setDividerPercent] = useState(50);
const containerRef = useRef<HTMLDivElement | null>(null);
const isDraggingRef = useRef(false);
- const nextMode = useEffectEvent(() => setMode((current) => (current === 'slider' ? 'side-by-side' : 'slider')));
+ const nextMode = useEffectEvent(() => onModeChange(getNextPreviewComparisonMode(mode)));
const nextComparisonModeLabel = t('widgets.preview.commands.nextComparisonMode');
useEffect(() => {
@@ -119,7 +145,14 @@ export const PreviewCompare = ({
isDraggingRef.current = false;
}, []);
- const toggleMode = useCallback(() => setMode((current) => (current === 'slider' ? 'side-by-side' : 'slider')), []);
+ const handleModeChange = useCallback(
+ (details: { value: string | null }) => {
+ if (details.value === 'slider' || details.value === 'side-by-side' || details.value === 'hover') {
+ onModeChange(details.value);
+ }
+ },
+ [onModeChange]
+ );
const clipStyle = useMemo(() => ({ clipPath: `inset(0 ${100 - dividerPercent}% 0 0)` }), [dividerPercent]);
return (
@@ -130,6 +163,7 @@ export const PreviewCompare = ({
borderWidth="1px"
borderColor="border.subtle"
color="fg.grid"
+ containerType="size"
css={previewGridCss}
flex="1"
justify="center"
@@ -142,26 +176,36 @@ export const PreviewCompare = ({
{mode === 'slider' ? (
<Box
ref={containerRef}
- bg="transparent"
+ borderColor="border.emphasized"
+ borderWidth="1px"
cursor="ew-resize"
- h="full"
+ css={getFittedFrameCss(baseImage.width, baseImage.height)}
overflow="hidden"
position="relative"
+ rounded="lg"
style={sliderTouchStyle}
- w="full"
+ onLostPointerCapture={endDrag}
+ onPointerCancel={endDrag}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={endDrag}
- onPointerCancel={endDrag}
- onLostPointerCapture={endDrag}
>
- <img alt={baseImage.imageName} draggable={false} src={baseImage.imageUrl} style={COMPARE_IMAGE_STYLE} />
+ <img
+ alt={baseImage.imageName}
+ draggable={false}
+ height={baseImage.height}
+ src={baseImage.imageUrl}
+ style={BASE_IMAGE_STYLE}
+ width={baseImage.width}
+ />
<Box bg="transparent" inset="0" pointerEvents="none" position="absolute" style={clipStyle}>
<img
alt={compareImage.imageName}
draggable={false}
+ height={compareImage.height}
src={compareImage.imageUrl}
- style={COMPARE_IMAGE_STYLE}
+ style={OVERLAY_IMAGE_STYLE}
+ width={compareImage.width}
/>
</Box>
<Box
@@ -174,13 +218,10 @@ export const PreviewCompare = ({
transform="translateX(-50%)"
w="2px"
/>
- <Badge left="2" pointerEvents="none" position="absolute" size="xs" top="2" variant="solid">
- {t('widgets.preview.compare')}
- </Badge>
- <Badge pointerEvents="none" position="absolute" right="2" size="xs" top="2" variant="solid">
- {t('widgets.preview.viewing')}
- </Badge>
+ <ComparisonBadges compareLabel={t('widgets.preview.compare')} viewingLabel={t('widgets.preview.viewing')} />
</Box>
+ ) : mode === 'hover' ? (
+ <HoverCompareFrame baseImage={baseImage} compareImage={compareImage} />
) : (
<HStack gap="2" h="full" minH="0" w="full">
<CompareSidePane image={compareImage} label={t('widgets.preview.compare')} />
@@ -189,10 +230,15 @@ export const PreviewCompare = ({
)}
</Flex>
<HStack flexShrink={0} gap="1" justify="center">
- <Button size="2xs" variant="outline" onClick={toggleMode}>
- <Columns2Icon />
- {mode === 'slider' ? t('widgets.preview.sideBySide') : t('widgets.preview.slider')}
- </Button>
+ <SegmentGroup.Root size="xs" value={mode} onValueChange={handleModeChange}>
+ <SegmentGroup.Indicator />
+ {COMPARISON_MODES.map((item) => (
+ <SegmentGroup.Item key={item.value} value={item.value}>
+ <SegmentGroup.ItemHiddenInput />
+ <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>
+ </SegmentGroup.Item>
+ ))}
+ </SegmentGroup.Root>
<Button size="2xs" variant="outline" onClick={onSwap}>
<ArrowLeftRightIcon />
{t('common.swap')}
@@ -206,11 +252,161 @@ export const PreviewCompare = ({
);
};
-const CompareSidePane = ({ image, label }: { image: GeneratedImageContract; label: string }) => (
- <Box bg="transparent" flex="1" h="full" minW="0" overflow="hidden" position="relative">
- <img alt={image.imageName} draggable={false} src={image.imageUrl} style={COMPARE_IMAGE_STYLE} />
+const HoverCompareFrame = ({
+ baseImage,
+ compareImage,
+}: {
+ baseImage: GeneratedImageContract;
+ compareImage: GeneratedImageContract;
+}) => {
+ const { t } = useTranslation();
+ const [isRevealed, setIsRevealed] = useState(false);
+ const interactionRef = useRef({ focused: false, hovered: false, pressed: false });
+ const syncRevealed = useCallback(() => {
+ const interaction = interactionRef.current;
+
+ setIsRevealed(interaction.focused || interaction.hovered || interaction.pressed);
+ }, []);
+ const handleFocus = useCallback(
+ (_event: FocusEvent<HTMLDivElement>) => {
+ interactionRef.current.focused = true;
+ syncRevealed();
+ },
+ [syncRevealed]
+ );
+ const handleBlur = useCallback(
+ (_event: FocusEvent<HTMLDivElement>) => {
+ interactionRef.current.focused = false;
+ syncRevealed();
+ },
+ [syncRevealed]
+ );
+ const handlePointerEnter = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (event.pointerType === 'mouse') {
+ interactionRef.current.hovered = true;
+ syncRevealed();
+ }
+ },
+ [syncRevealed]
+ );
+ const handlePointerLeave = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (event.pointerType === 'mouse') {
+ interactionRef.current.hovered = false;
+ syncRevealed();
+ }
+ },
+ [syncRevealed]
+ );
+ const handlePointerDown = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (event.pointerType !== 'mouse') {
+ event.preventDefault();
+ interactionRef.current.pressed = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ syncRevealed();
+ }
+ },
+ [syncRevealed]
+ );
+ const handlePointerEnd = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (event.pointerType !== 'mouse') {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ interactionRef.current.pressed = false;
+ syncRevealed();
+ }
+ },
+ [syncRevealed]
+ );
+
+ return (
+ <Box
+ aria-label={t('widgets.preview.hoverComparisonAriaLabel')}
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ css={getFittedFrameCss(baseImage.width, baseImage.height)}
+ cursor="pointer"
+ overflow="hidden"
+ position="relative"
+ rounded="lg"
+ tabIndex={0}
+ touchAction="none"
+ onBlur={handleBlur}
+ onFocus={handleFocus}
+ onLostPointerCapture={handlePointerEnd}
+ onPointerCancel={handlePointerEnd}
+ onPointerDown={handlePointerDown}
+ onPointerEnter={handlePointerEnter}
+ onPointerLeave={handlePointerLeave}
+ onPointerUp={handlePointerEnd}
+ >
+ <img
+ alt={baseImage.imageName}
+ draggable={false}
+ height={baseImage.height}
+ src={baseImage.imageUrl}
+ style={BASE_IMAGE_STYLE}
+ width={baseImage.width}
+ />
+ <Box
+ inset="0"
+ opacity={isRevealed ? 1 : 0}
+ pointerEvents="none"
+ position="absolute"
+ transitionDuration="var(--wb-motion-duration-fast)"
+ transitionProperty="opacity"
+ transitionTimingFunction="ease"
+ >
+ <img
+ alt={compareImage.imageName}
+ draggable={false}
+ height={compareImage.height}
+ src={compareImage.imageUrl}
+ style={OVERLAY_IMAGE_STYLE}
+ width={compareImage.width}
+ />
+ </Box>
+ <ComparisonBadges compareLabel={t('widgets.preview.compare')} viewingLabel={t('widgets.preview.viewing')} />
+ </Box>
+ );
+};
+
+const ComparisonBadges = ({ compareLabel, viewingLabel }: { compareLabel: string; viewingLabel: string }) => (
+ <>
<Badge left="2" pointerEvents="none" position="absolute" size="xs" top="2" variant="solid">
- {label}
+ {compareLabel}
</Badge>
- </Box>
+ <Badge pointerEvents="none" position="absolute" right="2" size="xs" top="2" variant="solid">
+ {viewingLabel}
+ </Badge>
+ </>
+);
+
+const CompareSidePane = ({ image, label }: { image: GeneratedImageContract; label: string }) => (
+ <Flex align="center" containerType="size" flex="1" h="full" justify="center" minW="0" overflow="hidden">
+ <Box
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ css={getFittedFrameCss(image.width, image.height)}
+ overflow="hidden"
+ position="relative"
+ rounded="lg"
+ >
+ <img
+ alt={image.imageName}
+ draggable={false}
+ height={image.height}
+ src={image.imageUrl}
+ style={BASE_IMAGE_STYLE}
+ width={image.width}
+ />
+ <Badge left="2" pointerEvents="none" position="absolute" size="xs" top="2" variant="solid">
+ {label}
+ </Badge>
+ </Box>
+ </Flex>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 40f911fd45..bb178bd7f8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -1,7 +1,7 @@
/* eslint-disable react/react-compiler */
import type { GeneratedImageContract, WidgetViewProps } from '@workbench/types';
-import { Badge, Box, Flex, HStack, Stack, Text } from '@chakra-ui/react';
+import { Badge, Box, Flex, HStack, Stack, Text, type SystemStyleObject } from '@chakra-ui/react';
import { useProgressImage, type ProgressImageSnapshot } from '@workbench/backend/progressImageStore';
import { Button } from '@workbench/components/ui';
import {
@@ -44,6 +44,7 @@ import {
import { useTranslation } from 'react-i18next';
import { PreviewCompare } from './PreviewCompare';
+import { getPreviewComparisonMode, type PreviewComparisonMode } from './previewSettings';
type PreviewImage = GeneratedImageContract & Partial<Pick<GalleryImage, 'boardId' | 'imageCategory' | 'starred'>>;
@@ -131,11 +132,20 @@ const previewGridCss = {
backgroundSize: '24px 24px',
} as const;
+const getFittedFrameCss = (width: number, height: number): SystemStyleObject => ({
+ aspectRatio: `${width} / ${height}`,
+ height: 'auto',
+ maxHeight: '100%',
+ maxWidth: '100%',
+ width: `min(100cqw, calc(100cqh * ${width / height}))`,
+});
+
const selectGenerateRecallValues = createGenerateFormValuesSelector();
export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const { t } = useTranslation();
const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
+ const previewValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'preview'));
const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);
const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector(
(project) => project.settings
@@ -144,6 +154,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const dispatch = useWorkbenchDispatch();
const selectedImage = useMemo(() => getSelectedImage(galleryValues), [galleryValues]);
const compareImage = getGalleryCompareImage(galleryValues);
+ const comparisonMode = getPreviewComparisonMode(previewValues);
const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : null;
const localImages = useMemo(() => getGalleryImages({ recentImages }), [recentImages]);
const imageBoardId = selectedImage ? getImageBoardId(selectedImage) : 'none';
@@ -352,6 +363,11 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
dispatch({ image: selectedImage, type: 'setGalleryCompareImage' });
}
}, [compareImage, dispatch, selectedImage]);
+ const setComparisonMode = useCallback(
+ (comparisonMode: PreviewComparisonMode) =>
+ dispatch({ type: 'patchWidgetValues', values: { comparisonMode }, widgetId: 'preview' }),
+ [dispatch]
+ );
const openImageContextMenu = useCallback(
(x: number, y: number) => {
if (contextMenuImage) {
@@ -404,8 +420,10 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
<PreviewCompare
baseImage={selectedImage}
compareImage={compareImage}
+ mode={comparisonMode}
runtime={runtime}
onExit={exitCompare}
+ onModeChange={setComparisonMode}
onSwap={swapCompareImages}
/>
) : (
@@ -503,23 +521,21 @@ const SelectedImagePreview = ({
const imageStyle = useMemo<CSSProperties>(
() => ({
display: 'block',
- height: '100%',
+ height: 'auto',
imageRendering: isProgressImage && !shouldAntialiasProgressImage ? 'pixelated' : 'auto',
- inset: 0,
- objectFit: 'contain',
- position: 'absolute',
width: '100%',
}),
[isProgressImage, shouldAntialiasProgressImage]
);
return (
- <Stack gap="3" h="full" minH="0" tabIndex={0} w="full" onKeyDown={handleKeyDown}>
+ <Stack gap="3" h="full" minH="0" outline="none" tabIndex={0} w="full" onKeyDown={handleKeyDown}>
<Flex
align="center"
borderWidth="1px"
borderColor="border.subtle"
color="fg.grid"
+ containerType="size"
css={previewGridCss}
flex="1"
justify="center"
@@ -530,21 +546,25 @@ const SelectedImagePreview = ({
w="full"
>
<Box
- aspectRatio={previewWidth / previewHeight}
bg="transparent"
borderWidth="1px"
borderColor={isProgressImage ? 'accent.solid' : 'border.emphasized'}
boxShadow="0 24px 80px rgba(0,0,0,0.42)"
- h={isCompact ? 'auto' : 'full'}
- maxH={isCompact ? undefined : 'full'}
- maxW="full"
+ css={getFittedFrameCss(previewWidth, previewHeight)}
overflow="hidden"
position="relative"
rounded="lg"
- w={isCompact ? 'full' : 'auto'}
onContextMenu={handleContextMenu}
>
- {previewImage ? <img alt={previewImage.alt} src={previewImage.src} style={imageStyle} /> : null}
+ {previewImage ? (
+ <img
+ alt={previewImage.alt}
+ height={previewHeight}
+ src={previewImage.src}
+ style={imageStyle}
+ width={previewWidth}
+ />
+ ) : null}
{isProgressImage ? (
<Badge left="2" pointerEvents="none" position="absolute" size="xs" top="2" variant="solid">
{t('common.generating')}
@@ -620,6 +640,7 @@ const EmptyPreview = ({
align="center"
backgroundColor="bg.inset"
color="fg.grid"
+ containerType="size"
css={previewGridCss}
h="full"
justify="center"
@@ -627,12 +648,10 @@ const EmptyPreview = ({
>
{previewImage ? (
<Box
- aspectRatio={(previewImage.width ?? 1) / (previewImage.height ?? 1)}
borderColor="accent.solid"
borderWidth="1px"
boxShadow="0 24px 80px rgba(0,0,0,0.42)"
- maxH="full"
- maxW="full"
+ css={getFittedFrameCss(previewImage.width ?? 1, previewImage.height ?? 1)}
overflow="hidden"
position="relative"
rounded="lg"
@@ -640,14 +659,15 @@ const EmptyPreview = ({
<img
alt={previewImage.alt}
draggable={false}
+ height={previewImage.height}
src={previewImage.src}
style={{
display: 'block',
- height: '100%',
+ height: 'auto',
imageRendering: shouldAntialiasProgressImage ? 'auto' : 'pixelated',
- objectFit: 'contain',
width: '100%',
}}
+ width={previewImage.width}
/>
<Badge left="2" pointerEvents="none" position="absolute" size="xs" top="2" variant="solid">
{t('common.generating')}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts
new file mode 100644
index 0000000000..43b9c73f1b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { getNextPreviewComparisonMode } from './PreviewCompare';
+import { DEFAULT_PREVIEW_COMPARISON_MODE, getPreviewComparisonMode } from './previewSettings';
+
+describe('preview comparison settings', () => {
+ it('defaults missing and invalid persisted modes to slider', () => {
+ expect(getPreviewComparisonMode({})).toBe(DEFAULT_PREVIEW_COMPARISON_MODE);
+ expect(getPreviewComparisonMode({ comparisonMode: 'invalid' })).toBe('slider');
+ });
+
+ it.each(['slider', 'side-by-side', 'hover'] as const)('restores the %s mode', (comparisonMode) => {
+ expect(getPreviewComparisonMode({ comparisonMode })).toBe(comparisonMode);
+ });
+
+ it('cycles all three comparison modes in order', () => {
+ expect(getNextPreviewComparisonMode('slider')).toBe('side-by-side');
+ expect(getNextPreviewComparisonMode('side-by-side')).toBe('hover');
+ expect(getNextPreviewComparisonMode('hover')).toBe('slider');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts
new file mode 100644
index 0000000000..95e6a8911d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewSettings.ts
@@ -0,0 +1,9 @@
+export type PreviewComparisonMode = 'slider' | 'side-by-side' | 'hover';
+
+export const DEFAULT_PREVIEW_COMPARISON_MODE: PreviewComparisonMode = 'slider';
+
+export const getPreviewComparisonMode = (values: Record<string, unknown>): PreviewComparisonMode => {
+ const mode = values.comparisonMode;
+
+ return mode === 'side-by-side' || mode === 'hover' ? mode : DEFAULT_PREVIEW_COMPARISON_MODE;
+};