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(canvas): restore eraser pressure width, layer quick switch, crop tools and middle-click open (#9808)

Josh Corbettcd9120a6645c
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
index c4e337fd7f..5b6afb8f11 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
@@ -107,6 +107,8 @@ To add one, click **Add reference image** and pick images from the Gallery or up
Hovering over a reference's thumbnail offers **Crop**, to use only part of the image, and **Use size**, to set the generation's size to match the reference. The switch on each card turns a reference off without removing it.
+In the crop dialog, drag the crop box or its handles, or pick an **Aspect ratio** (16:9, 3:2, 4:3, 1:1, 3:4, 2:3 or 9:16) to keep the box in proportion while you resize it. Scroll to zoom in on the image, hold **Space** (or use the middle mouse button) and drag to move the view, and use the **Fit image**, **Actual size**, **Zoom in** and **Zoom out** buttons. **Apply** uses the crop for the reference; **Save to Uploads** also stores the cropped image as an upload in the Gallery without changing the reference.
+
What a reference does, and what options it has, depends on the model family:
| Model family | How references work | Options |
diff --git a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx
index 8d954d225e..b20c1f209f 100644
--- a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx
+++ b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx
@@ -89,7 +89,7 @@ The gear button in the Gallery header opens its settings:
* **Show in-progress section** — shows generations that are still running at the top of the grid.
* **Pagination** — **Infinite** scrolling or numbered **Pages**.
-**All Gallery settings…** at the bottom opens the full settings. They also include **Send new results to the selected board** (under **Destination**), which is on by default; turn it off to keep sending results to the current destination board, which then becomes the **Auto** board. The full settings also include the sort order and the board visibility and sorting options from the [Filter & sort boards](/users-guide/gallery/introduction/#finding-filtering-and-sorting-boards) menu. All Gallery settings are saved with the project.
+**All Gallery settings…** at the bottom opens the full settings. They also include **Middle-click opens media in a new tab** (under **Thumbnails**), off by default, which makes a middle click on an image or video tile open it in a new browser tab, and **Send new results to the selected board** (under **Destination**), which is on by default; turn it off to keep sending results to the current destination board, which then becomes the **Auto** board. The full settings also include the sort order and the board visibility and sorting options from the [Filter & sort boards](/users-guide/gallery/introduction/#finding-filtering-and-sorting-boards) menu. All Gallery settings are saved with the project.
## Keyboard shortcuts
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 01246c552e..ceeb399f26 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -38,7 +38,7 @@ The Shape and Select buttons hold several tools. Click to use the current one, o
### Tool options
* **Brush** — **Size**, **Opacity** and **Hardness**; the **Foreground** color; and, under **Dynamics**, whether pen pressure affects the width or the opacity. **[** and **]** make the brush smaller or larger, and so does **Ctrl**+scroll.
-* **Eraser** — **Size**, **Opacity** and **Hardness**.
+* **Eraser** — **Size**, **Opacity** and **Hardness**; and, under **Dynamics**, whether pen pressure affects the width. Pressure never changes how strongly the eraser erases. Eraser settings are temporary and are not saved in the project; they can reset when the canvas is released or the page reloads.
* **Shape** — the **Kind** of shape; **Place on**, which draws on the **Selected layer** or on a **New layer** of its own; **Fill** and **Stroke**, each with a color; and the stroke **Width**. **Shift** constrains the proportions. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.
* **Gradient** — **Kind** (Linear or Radial), **Angle**, and the color **Stops**, which can be added and removed or follow the foreground and background colors. Dragging creates a gradient layer the size of the generation frame, or repositions the selected gradient layer.
* **Text** — the font **Family**, **Style** or **Weight**, **Size**, **Line height**, **Align** and **Fill** color. Click the canvas to start typing; **Ctrl+Enter** or clicking elsewhere finishes the text, and **Escape** cancels it. The text stays editable as a text layer.
@@ -212,7 +212,8 @@ These shortcuts work while the canvas has focus. On macOS, use **Cmd** in place
| **Ctrl+J** / **Ctrl+E** | Duplicate layer / merge layer down |
| **Ctrl+G** / **Ctrl+Shift+G** | Group / ungroup layers |
| **Ctrl+]** / **Ctrl+[** (add **Shift** for front / back) | Move layer forward / backward |
-| **Alt+[** / **Alt+]** | Previous / next layer, or staged result |
+| **Alt+[** / **Alt+]** | Previous / next layer (wrapping, in the order of the Layers panel), or staged result while results are staged |
+| **Q** | Switch to the layer bookmarked with **Bookmark for quick switch** in its menu, or back to the previously selected layer |
| **Shift+H** | Hide control, guidance and mask layers |
| **Shift+N** / **Shift+B** | Fit the generation frame to the layers / to the masks |
| **Enter** / **Escape** | Apply / cancel a transform, text or filter |
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index d9805e7dd3..bb27657b9b 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -82,7 +82,7 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw
* **Merge down**.
* **Copy to** — including **Copy layer to clipboard**, and copies to other layer types.
* **Crop layer to bbox** and **Save layer to uploads** (save it to the Gallery's Uploads).
- * **Disable layer**, **Lock layer** and **Color label**.
+ * **Disable layer**, **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is temporary and is not saved in the project. It can reset when the canvas is released, for example after switching away from its project, and resets on reload.
* **Delete layer**.
* **Raster layers:**
* **Transform**.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 2b8c859f96..ebc319488d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2383,8 +2383,15 @@
"copyValue": "Copy value",
"couldNotExpandPrompt": "Could not expand the prompt.",
"couldNotGeneratePromptFromImage": "Could not generate a prompt from the selected image.",
+ "cropActualSize": "Actual size",
+ "cropAspectRatioFree": "Free",
+ "cropFitView": "Fit image",
"cropReferenceImage": "Crop reference image",
- "cropReferenceImageHelp": "Drag the crop box to move it, or drag its handles to resize. Apply to create a cropped reference image.",
+ "cropReferenceImageHelp": "Drag the crop box to move it, or drag its handles to resize. Scroll to zoom and hold Space to drag the view. Apply to create a cropped reference image.",
+ "cropSaveToAssets": "Save to Uploads",
+ "cropSavedToAssets": "The crop was saved to Uploads.",
+ "cropZoomIn": "Zoom in",
+ "cropZoomOut": "Zoom out",
"deletePresetNamed": "Delete preset {{name}}",
"deletePromptHistoryItem": "Delete prompt history item",
"denoisingStrength": "Denoising strength",
@@ -3115,6 +3122,7 @@
"nudgeUpLarge": "Nudge layer up 10px",
"pasteImage": "Paste image",
"previousEntity": "Previous canvas entity",
+ "quickSwitch": "Quick switch to bookmarked or previous layer",
"redo": "Redo canvas edit",
"reorderLayer": "Reorder layer",
"resetSelected": "Clear selected mask",
@@ -3577,6 +3585,7 @@
"addRegionalReferenceImage": "Regional reference image",
"actionFailed": "Layer action failed",
"blendMode": "Blend mode",
+ "bookmarkForQuickSwitch": "Bookmark for quick switch",
"busy": "The canvas is busy. Try again when the current action finishes.",
"copyFailed": "The layer could not be copied.",
"copyLayerToClipboard": "Copy layer to clipboard",
@@ -3635,6 +3644,7 @@
"overBudget": "There is not enough canvas memory to make this change undoable, so nothing was changed.",
"stale": "The layer changed before this action finished, so nothing was changed. Try again.",
"rasterize": "Rasterize layer",
+ "removeQuickSwitchBookmark": "Remove quick switch bookmark",
"rename": "Rename layer",
"reorder": "Reorder layer",
"runWorkflow": "Run workflow",
@@ -4301,6 +4311,7 @@
"imageSize": "Image size",
"imageSort": "Image Sort",
"infinite": "Infinite",
+ "middleClickOpensInNewTab": "Middle-click opens media in a new tab",
"itemActions": {
"loadWorkflow": {
"editorUnavailable": "The workflow editor is not available in this layout.",
diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
index 60c649dcb3..6bc339aad5 100644
--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx
@@ -3,7 +3,7 @@ import type { QueueItem, QueueItemReadModel } from '@features/queue/contracts';
import type { ReadableExternalStore } from '@platform/state/projectedExternalStore';
import type { ReactNode } from 'react';
-import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
+import { getGalleryAutoAddBoardId, getSelectedGalleryImageFromValues } from '@features/gallery/contracts';
import { invalidateGallery } from '@features/gallery/queries';
import { galleryImageUrls } from '@features/gallery/utility';
import { GenerationUiProvider } from '@features/generation/react';
@@ -232,13 +232,17 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode
(imageName) => findGalleryItem({ kind: 'image', name: imageName }),
[findGalleryItem]
);
+ const uploadBoardId = useActiveProjectSelector(
+ (activeProject) => getGalleryAutoAddBoardId(getProjectWidgetValues(activeProject, 'gallery')) ?? 'none'
+ );
const galleryGroup = useMemo<GenerationUiAdapter['gallery']>(
() => ({
findImage,
selectedImage: selectedGalleryImage,
touchImages: () => void invalidateGallery(queryClient),
+ uploadBoardId,
}),
- [findImage, queryClient, selectedGalleryImage]
+ [findImage, queryClient, selectedGalleryImage, uploadBoardId]
);
const openInModelManager = useOpenModelInManager();
const modelsGroup = useMemo<GenerationUiAdapter['models']>(
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
index 1abc29a150..4e1bfd706b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts
@@ -35,6 +35,8 @@ export interface GallerySettings {
collapsedBoardSections: GalleryBoardSectionId[];
imageDensityPercent: number;
imageOrderDir: GalleryOrderDir;
+ /** Opt-in: a middle click on a tile opens the media in a new browser tab instead of the browser default. */
+ middleClickOpensInNewTab: boolean;
paginationMode: GalleryPaginationMode;
showArchivedBoards: boolean;
showDateBoards: boolean;
@@ -58,6 +60,7 @@ export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {
collapsedBoardSections: [],
imageDensityPercent: 50,
imageOrderDir: 'DESC',
+ middleClickOpensInNewTab: false,
paginationMode: 'infinite',
showArchivedBoards: false,
showDateBoards: false,
@@ -122,6 +125,7 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySett
? Math.min(100, Math.max(0, values.imageDensityPercent))
: DEFAULT_GALLERY_SETTINGS.imageDensityPercent,
imageOrderDir: isOrderDir(values.imageOrderDir) ? values.imageOrderDir : DEFAULT_GALLERY_SETTINGS.imageOrderDir,
+ middleClickOpensInNewTab: values.middleClickOpensInNewTab === true,
paginationMode,
showArchivedBoards:
typeof values.showArchivedBoards === 'boolean'
diff --git a/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts b/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts
index 6a46be869a..bec4491062 100644
--- a/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/settingsContribution.ts
@@ -42,6 +42,14 @@ export const gallerySettingsContribution: SettingsContribution = {
keywords: 'queue progress placeholders',
scope: 'instance',
},
+ {
+ id: 'middleClickOpensInNewTab',
+ kind: 'boolean',
+ label: (t) => t('widgets.gallery.middleClickOpensInNewTab'),
+ group: (t) => t('widgets.gallery.settingsThumbnails'),
+ keywords: 'mouse middle click wheel button open new tab',
+ scope: 'instance',
+ },
{
id: 'paginationMode',
kind: 'select',
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index 1780ed1039..1257dd51fe 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -1227,6 +1227,45 @@ describe('GalleryImageGrid mixed item cells', () => {
expect(imageActionMocks.openItemInPreview).not.toHaveBeenCalled();
});
+ describe.each([
+ { item: createItem('image', 'last.png'), label: 'Select last.png for preview' },
+ { item: createItem('video', 'shared'), label: 'Select video shared, duration 1:06, for preview' },
+ ])('browser middle-click on $item.kind', ({ item, label }) => {
+ it.each([false, true])(
+ 'respects middleClickOpensInNewTab=%s without selecting, previewing, or dragging',
+ async (enabled) => {
+ const gallery = createGallery({ items: [item], selectedItemKey: null, selectedItemKeys: [] });
+ await renderGallery({ ...gallery, settings: { ...gallery.settings, middleClickOpensInNewTab: enabled } });
+ const button = getButton(label);
+ const events: MouseEvent[] = [];
+ const recordEvent = (event: MouseEvent) => events.push(event);
+ // Keep the native events until React has handled them, even if it stops their propagation.
+ button.addEventListener('mousedown', recordEvent, { capture: true, once: true });
+ button.addEventListener('auxclick', recordEvent, { capture: true, once: true });
+
+ await act(() => userEvent.click(button, { button: 'middle' }));
+
+ expect(
+ events.map(({ type, button, isTrusted, defaultPrevented }) => ({ type, button, isTrusted, defaultPrevented }))
+ ).toEqual([
+ { type: 'mousedown', button: 1, isTrusted: true, defaultPrevented: enabled },
+ { type: 'auxclick', button: 1, isTrusted: true, defaultPrevented: enabled },
+ ]);
+ if (enabled) {
+ expect(imageActionMocks.openItemInNewTab).toHaveBeenCalledExactlyOnceWith(item);
+ } else {
+ expect(imageActionMocks.openItemInNewTab).not.toHaveBeenCalled();
+ }
+ expect(actionMocks.selectItem).not.toHaveBeenCalled();
+ expect(actionMocks.selectItemRange).not.toHaveBeenCalled();
+ expect(actionMocks.toggleItemInSelection).not.toHaveBeenCalled();
+ expect(actionMocks.setCompareItem).not.toHaveBeenCalled();
+ expect(imageActionMocks.openItemInPreview).not.toHaveBeenCalled();
+ expect(onDragStart).not.toHaveBeenCalled();
+ }
+ );
+ });
+
it('toggles the star on each click of a double-click without selecting or opening the item', async () => {
await renderGallery();
await act(() => userEvent.dblClick(getButton('Star first.png')));
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 584933ad96..ceb8fe8f84 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -431,6 +431,7 @@ export const GalleryImageGrid = () => {
const viewportRef = useRef<HTMLDivElement | null>(null);
const {
imageDensityPercent,
+ middleClickOpensInNewTab,
paginationMode,
progressSectionCollapsed,
showImageDimensions,
@@ -1654,6 +1655,7 @@ export const GalleryImageGrid = () => {
[itemActions]
);
const handleOpenItem = useCallback((item: GalleryItem) => itemActions.openItemInPreview(item), [itemActions]);
+ const handleOpenItemInNewTab = useCallback((item: GalleryItem) => itemActions.openItemInNewTab(item), [itemActions]);
// Releasing the anchor puts the window back over the top of the listing.
const handleReturnToBoardTop = useCallback(() => galleryCommands.setPage(0), [galleryCommands]);
@@ -1690,6 +1692,7 @@ export const GalleryImageGrid = () => {
onContextMenu={handleThumbnailContextMenu}
onFocusLost={restoreTileFocus}
onOpen={handleOpenItem}
+ onOpenInNewTab={middleClickOpensInNewTab ? handleOpenItemInNewTab : null}
onToggleStarred={handleToggleStarred}
selectionPage={selectionPage}
/>
@@ -1701,11 +1704,13 @@ export const GalleryImageGrid = () => {
getDragItems,
getReadyItemLabel,
handleOpenItem,
+ handleOpenItemInNewTab,
handleThumbnailClick,
handleThumbnailContextMenu,
handleToggleStarred,
isComparisonActive,
isFollowingLive,
+ middleClickOpensInNewTab,
region,
restoreTileFocus,
selectedItemKeys,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx
index e15a662b09..30970860e2 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.browser.test.tsx
@@ -26,6 +26,7 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
const STALE_TARGET = { projectId: 'old-project' };
const PICKED_BOARD_VALUES = { selectedBoardId: 'picked' };
+const NO_VALUES = {};
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const Harness = ({
@@ -105,6 +106,18 @@ describe('Gallery settings contribution bindings', () => {
expect(host?.querySelector('output')?.textContent).toContain('"showPendingItems":false');
});
+ it('binds the opt-in middle-click setting, off by default, through the settings command', async () => {
+ await act(() => root?.render(<Harness id="middleClickOpensInNewTab" initialValues={NO_VALUES} />));
+ const quick = host?.querySelector<HTMLInputElement>('[data-surface="quick"] input');
+ const dialog = host?.querySelector<HTMLInputElement>('[data-surface="dialog"] input');
+
+ expect(quick?.checked).toBe(false);
+ await act(() => dialog?.click());
+
+ expect(quick?.checked).toBe(true);
+ expect(host?.querySelector('output')?.textContent).toContain('"middleClickOpensInNewTab":true');
+ });
+
it('pins the current destination when results stop following the selected board', async () => {
await act(() => root?.render(<Harness id="followSelectedBoard" initialValues={PICKED_BOARD_VALUES} />));
const toggle = host?.querySelector<HTMLInputElement>('[data-surface="quick"] input');
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx
index 6973f020fe..2f728ae05c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySettingField.tsx
@@ -38,6 +38,7 @@ export const GallerySettingField = ({ field, surface, target }: SettingFieldProp
} else if (
(field.id === 'showImageDimensions' ||
field.id === 'showPendingItems' ||
+ field.id === 'middleClickOpensInNewTab' ||
field.id === 'showDateBoards' ||
field.id === 'showArchivedBoards' ||
field.id === 'showOtherProjectBoards') &&
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
index e1fb1d5fac..346494d794 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx
@@ -87,6 +87,7 @@ const GalleryThumbnail = ({
onContextMenu,
onFocusLost,
onOpen,
+ onOpenInNewTab,
onToggleStarred,
}: {
alwaysShowDimensions: boolean;
@@ -108,6 +109,8 @@ const GalleryThumbnail = ({
onFocusLost: (itemKey: GalleryItemKey) => void;
/** Double-click or Enter: show the item in the centre Preview. */
onOpen: (item: GalleryItem) => void;
+ /** Middle click, when the Gallery setting opts in; null leaves the browser's middle-click behaviour alone. */
+ onOpenInNewTab: ((item: GalleryItem) => void) | null;
onToggleStarred: (item: GalleryItem) => void;
}) => {
const { t } = useTranslation();
@@ -232,6 +235,27 @@ const GalleryThumbnail = ({
[item, onOpen]
);
+ // Middle button only; the primary button's click/double-click stay selection and open. Its mousedown default
+ // (autoscroll on some platforms) is suppressed so the release reliably delivers the auxclick.
+ const handleMiddleMouseDown = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ if (onOpenInNewTab && event.button === 1) {
+ event.preventDefault();
+ }
+ },
+ [onOpenInNewTab]
+ );
+ const handleAuxClick = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ if (onOpenInNewTab && event.button === 1) {
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenInNewTab(item);
+ }
+ },
+ [item, onOpenInNewTab]
+ );
+
// Enter opens and Space selects; neither starts a keyboard drag. Enter's default would click (select) first.
const handleActivationKeyDown = useCallback(
(event: KeyboardEvent<HTMLButtonElement>) => {
@@ -301,9 +325,11 @@ const GalleryThumbnail = ({
style={THUMBNAIL_BUTTON_STYLE}
tabIndex={isTabStop ? 0 : -1}
type="button"
+ onAuxClick={handleAuxClick}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
onKeyDown={handleActivationKeyDown}
+ onMouseDown={handleMiddleMouseDown}
>
<img
alt={item.name}
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index 165d7a191d..6754f3a622 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -169,6 +169,7 @@ describe('gallery state view', () => {
collapsedBoardSections: [],
imageDensityPercent: 50,
imageOrderDir: 'DESC',
+ middleClickOpensInNewTab: false,
paginationMode: 'infinite',
showArchivedBoards: false,
showDateBoards: false,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/referenceImage.ts b/invokeai/frontend/webv2/src/features/generation/core/referenceImage.ts
index 0d05093a2b..1b31983447 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/referenceImage.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/referenceImage.ts
@@ -183,3 +183,212 @@ export const applyReferenceImageCrop = (
export const clearReferenceImageCrop = (image: CroppableImageWithDims): CroppableImageWithDims => ({
original: { image: cloneImageWithDims(image.original.image) },
});
+
+// ---- Crop-box geometry for the reference image crop editor -------------------------------------------------------
+// Boxes are percentages of the original image, so an aspect ratio (width / height in pixels) becomes a width% per
+// height% factor through the image's own proportions.
+
+export type ReferenceCropAspectRatioId = 'free' | '16:9' | '3:2' | '4:3' | '1:1' | '3:4' | '2:3' | '9:16';
+
+/** The legacy cropper's presets, in its order; `null` leaves the box free. */
+export const REFERENCE_CROP_ASPECT_RATIOS: readonly { id: ReferenceCropAspectRatioId; ratio: number | null }[] = [
+ { id: 'free', ratio: null },
+ { id: '16:9', ratio: 16 / 9 },
+ { id: '3:2', ratio: 3 / 2 },
+ { id: '4:3', ratio: 4 / 3 },
+ { id: '1:1', ratio: 1 },
+ { id: '3:4', ratio: 3 / 4 },
+ { id: '2:3', ratio: 2 / 3 },
+ { id: '9:16', ratio: 9 / 16 },
+];
+
+export type ReferenceCropHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
+
+export type ReferenceCropDragMode = 'move' | ReferenceCropHandle;
+
+export interface ReferenceCropDrag {
+ /** The box when the drag started. */
+ box: ReferenceImageCropBoxPct;
+ mode: ReferenceCropDragMode;
+ /** The pointer position when the drag started, in image percent. */
+ x: number;
+ y: number;
+}
+
+export interface ReferenceCropConstraints {
+ /** The original image size, which maps pixel ratios onto percent boxes. */
+ image: { height: number; width: number };
+ /** Minimum crop edge, in image pixels. */
+ minDimensionPx: number;
+ /** Pixel width / height to hold, or null for a free box. */
+ ratio: number | null;
+}
+
+/** Tolerance when matching a box to a preset: a percent box rounded to pixels is never exact. */
+const RATIO_MATCH_TOLERANCE = 0.005;
+
+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+
+const minSizePct = ({ image, minDimensionPx }: ReferenceCropConstraints): { height: number; width: number } => ({
+ height: Math.min(100, (minDimensionPx / Math.max(1, image.height)) * 100),
+ width: Math.min(100, (minDimensionPx / Math.max(1, image.width)) * 100),
+});
+
+/** Width percent per height percent for a pixel ratio on this image. */
+const toPctRatio = (ratio: number, image: ReferenceCropConstraints['image']): number =>
+ (ratio * Math.max(1, image.height)) / Math.max(1, image.width);
+
+/** The preset whose pixel ratio the box has, or `free`. */
+export const matchReferenceCropAspectRatio = (
+ box: ReferenceImageCropBoxPct,
+ image: ReferenceCropConstraints['image']
+): ReferenceCropAspectRatioId => {
+ const pixelRatio = (box.width * image.width) / Math.max(1e-6, box.height * image.height);
+ const match = REFERENCE_CROP_ASPECT_RATIOS.find(
+ ({ ratio }) => ratio !== null && Math.abs(pixelRatio / ratio - 1) <= RATIO_MATCH_TOLERANCE
+ );
+ return match?.id ?? 'free';
+};
+
+/**
+ * A box of `pctRatio` whose width is at most `width`, at least the minimum edge, and that fits the image: the larger
+ * of the minimum edges wins, and overflow shrinks the box rather than breaking the ratio.
+ */
+const fitRatioBox = (
+ width: number,
+ pctRatio: number,
+ constraints: ReferenceCropConstraints
+): { height: number; width: number } => {
+ const min = minSizePct(constraints);
+ let w = Math.max(width, min.width, min.height * pctRatio);
+ w = Math.min(w, 100, 100 * pctRatio);
+ return { height: w / pctRatio, width: w };
+};
+
+/** Re-centers the box on `(cx, cy)` and slides it back inside the image when the center sits near an edge. */
+const placeAround = (cx: number, cy: number, size: { height: number; width: number }): ReferenceImageCropBoxPct => ({
+ height: size.height,
+ width: size.width,
+ x: clamp(cx - size.width / 2, 0, 100 - size.width),
+ y: clamp(cy - size.height / 2, 0, 100 - size.height),
+});
+
+/**
+ * Applies a preset to an existing box: the area and center are preserved where the image allows, as the legacy
+ * cropper did, so switching presets reshapes rather than relocates the crop. A null ratio returns the box as is.
+ */
+export const constrainReferenceCropBox = (
+ box: ReferenceImageCropBoxPct,
+ constraints: ReferenceCropConstraints
+): ReferenceImageCropBoxPct => {
+ if (constraints.ratio === null) {
+ return box;
+ }
+ const pctRatio = toPctRatio(constraints.ratio, constraints.image);
+ const size = fitRatioBox(Math.sqrt(box.width * box.height * pctRatio), pctRatio, constraints);
+ return placeAround(box.x + box.width / 2, box.y + box.height / 2, size);
+};
+
+const resolveFreeDrag = (
+ drag: ReferenceCropDrag,
+ point: { x: number; y: number },
+ constraints: ReferenceCropConstraints
+): ReferenceImageCropBoxPct => {
+ const dx = point.x - drag.x;
+ const dy = point.y - drag.y;
+ const { box, mode } = drag;
+ const min = minSizePct(constraints);
+ let left = box.x;
+ let top = box.y;
+ let right = box.x + box.width;
+ let bottom = box.y + box.height;
+
+ if (mode.includes('w')) {
+ left = clamp(left + dx, 0, right - min.width);
+ }
+ if (mode.includes('e')) {
+ right = clamp(right + dx, left + min.width, 100);
+ }
+ if (mode.includes('n')) {
+ top = clamp(top + dy, 0, bottom - min.height);
+ }
+ if (mode.includes('s')) {
+ bottom = clamp(bottom + dy, top + min.height, 100);
+ }
+ return { height: bottom - top, width: right - left, x: left, y: top };
+};
+
+/**
+ * A ratio-locked handle drag. Corners anchor the opposite corner and follow the larger ratio-normalized displacement;
+ * edges anchor the opposite edge, centering the other dimension until an image edge requires it to slide.
+ */
+const resolveRatioDrag = (
+ drag: ReferenceCropDrag,
+ point: { x: number; y: number },
+ constraints: ReferenceCropConstraints,
+ ratio: number
+): ReferenceImageCropBoxPct => {
+ const { box, mode } = drag;
+ const pctRatio = toPctRatio(ratio, constraints.image);
+ const free = resolveFreeDrag(drag, point, constraints);
+ const anchorLeft = mode.includes('w') ? box.x + box.width : box.x;
+ const anchorTop = mode.includes('n') ? box.y + box.height : box.y;
+ const horizontal = mode === 'e' || mode === 'w';
+ const vertical = mode === 'n' || mode === 's';
+
+ // The room between the anchor and the image edge on the growing side.
+ const roomWidth = mode.includes('w') ? anchorLeft : 100 - anchorLeft;
+ const roomHeight = mode.includes('n') ? anchorTop : 100 - anchorTop;
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+
+ let width: number;
+ if (vertical) {
+ width = free.height * pctRatio;
+ } else if (horizontal) {
+ width = free.width;
+ } else {
+ width =
+ Math.abs(free.width - box.width) >= Math.abs(free.height - box.height) * pctRatio
+ ? free.width
+ : free.height * pctRatio;
+ }
+ let size = fitRatioBox(width, pctRatio, constraints);
+ // Side handles may use the full orthogonal image dimension; placement below slides their center if needed.
+ const maxWidth = horizontal
+ ? Math.min(roomWidth, 100 * pctRatio)
+ : vertical
+ ? Math.min(roomHeight * pctRatio, 100)
+ : Math.min(roomWidth, roomHeight * pctRatio);
+ if (size.width > maxWidth) {
+ size = fitRatioBox(maxWidth, pctRatio, constraints);
+ }
+
+ const x = horizontal || !vertical ? (mode.includes('w') ? anchorLeft - size.width : anchorLeft) : cx - size.width / 2;
+ const y = vertical || !horizontal ? (mode.includes('n') ? anchorTop - size.height : anchorTop) : cy - size.height / 2;
+ return {
+ height: size.height,
+ width: size.width,
+ x: clamp(x, 0, 100 - size.width),
+ y: clamp(y, 0, 100 - size.height),
+ };
+};
+
+/** The box after moving the pointer to `point` during `drag`. */
+export const resolveReferenceCropDrag = (
+ drag: ReferenceCropDrag,
+ point: { x: number; y: number },
+ constraints: ReferenceCropConstraints
+): ReferenceImageCropBoxPct => {
+ if (drag.mode === 'move') {
+ const { box } = drag;
+ return {
+ ...box,
+ x: clamp(box.x + point.x - drag.x, 0, 100 - box.width),
+ y: clamp(box.y + point.y - drag.y, 0, 100 - box.height),
+ };
+ }
+ return constraints.ratio === null
+ ? resolveFreeDrag(drag, point, constraints)
+ : resolveRatioDrag(drag, point, constraints, constraints.ratio);
+};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/referenceImageCropGeometry.test.ts b/invokeai/frontend/webv2/src/features/generation/core/referenceImageCropGeometry.test.ts
new file mode 100644
index 0000000000..0908c70945
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/referenceImageCropGeometry.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ constrainReferenceCropBox,
+ matchReferenceCropAspectRatio,
+ REFERENCE_CROP_ASPECT_RATIOS,
+ resolveReferenceCropDrag,
+ type ReferenceCropConstraints,
+ type ReferenceCropDragMode,
+} from './referenceImage';
+
+const IMAGE = { height: 600, width: 800 };
+const constraints = (ratio: number | null, image = IMAGE): ReferenceCropConstraints => ({
+ image,
+ minDimensionPx: 64,
+ ratio,
+});
+/** The pixel ratio a percent box has on an image. */
+const pixelRatio = (box: { height: number; width: number }, image = IMAGE): number =>
+ (box.width * image.width) / (box.height * image.height);
+const drag = (
+ mode: ReferenceCropDragMode,
+ box: { height: number; width: number; x: number; y: number },
+ from: { x: number; y: number },
+ to: { x: number; y: number },
+ ratio: number | null
+) => resolveReferenceCropDrag({ box, mode, ...from }, to, constraints(ratio));
+const expectInside = (box: { height: number; width: number; x: number; y: number }) => {
+ expect(box.x).toBeGreaterThanOrEqual(0);
+ expect(box.y).toBeGreaterThanOrEqual(0);
+ expect(box.x + box.width).toBeLessThanOrEqual(100 + 1e-9);
+ expect(box.y + box.height).toBeLessThanOrEqual(100 + 1e-9);
+};
+
+describe('constrainReferenceCropBox', () => {
+ it('reshapes a box to the preset ratio around its center while keeping its area', () => {
+ const box = { height: 50, width: 25, x: 50, y: 25 };
+ const square = constrainReferenceCropBox(box, constraints(1));
+
+ expect(pixelRatio(square)).toBeCloseTo(1);
+ expect(square.width * square.height).toBeCloseTo(box.width * box.height);
+ expect(square.x + square.width / 2).toBeCloseTo(62.5);
+ expect(square.y + square.height / 2).toBeCloseTo(50);
+ });
+
+ it('shrinks and slides a box that would otherwise leave the image, and leaves a free box alone', () => {
+ const box = { height: 100, width: 100, x: 0, y: 0 };
+ const wide = constrainReferenceCropBox(box, constraints(16 / 9));
+
+ expect(pixelRatio(wide)).toBeCloseTo(16 / 9);
+ expect(wide.width).toBe(100);
+ expectInside(wide);
+ expect(constrainReferenceCropBox(box, constraints(null))).toBe(box);
+ });
+
+ it('never drops an edge below the minimum pixel size', () => {
+ const tiny = constrainReferenceCropBox({ height: 2, width: 2, x: 10, y: 10 }, constraints(16 / 9));
+
+ expect(tiny.height * IMAGE.height).toBeGreaterThanOrEqual(64 * 100 - 1e-6);
+ expect(pixelRatio(tiny)).toBeCloseTo(16 / 9);
+ });
+});
+
+describe('resolveReferenceCropDrag', () => {
+ const box = { height: 40, width: 40, x: 30, y: 30 };
+
+ it('moves within the image and resizes freely from any handle', () => {
+ expect(drag('move', box, { x: 50, y: 50 }, { x: 90, y: 20 }, null)).toEqual({ ...box, x: 60, y: 0 });
+ expect(drag('se', box, { x: 70, y: 70 }, { x: 80, y: 60 }, null)).toEqual({ height: 30, width: 50, x: 30, y: 30 });
+ expect(drag('nw', box, { x: 30, y: 30 }, { x: 0, y: 0 }, null)).toEqual({ height: 70, width: 70, x: 0, y: 0 });
+ });
+
+ it('keeps a corner drag on the preset ratio, anchored at the opposite corner', () => {
+ // Pixel-square on a 4:3 image: 50% of the width is 400px, so the height becomes 400px, two thirds of 600.
+ const grown = drag('se', box, { x: 70, y: 70 }, { x: 80, y: 75 }, 1);
+
+ expect(pixelRatio(grown)).toBeCloseTo(1);
+ expect(grown.x).toBe(30);
+ expect(grown.y).toBe(30);
+ expect(grown.width).toBeCloseTo(50);
+ expect(grown.height).toBeCloseTo(66.667, 2);
+ expectInside(grown);
+ });
+
+ it('grows the other dimension around the center line for an edge drag', () => {
+ const wider = drag('e', box, { x: 70, y: 50 }, { x: 80, y: 50 }, 1);
+
+ expect(pixelRatio(wider)).toBeCloseTo(1);
+ expect(wider.x).toBe(30);
+ expect(wider.width).toBeCloseTo(50);
+ expect(wider.y + wider.height / 2).toBeCloseTo(50);
+ });
+
+ it.each([
+ ['e', { height: 40, width: 40, x: 0, y: 0 }, { x: 40, y: 20 }, { x: 100, y: 20 }],
+ ['w', { height: 40, width: 40, x: 60, y: 60 }, { x: 60, y: 80 }, { x: 0, y: 80 }],
+ ['s', { height: 40, width: 40, x: 0, y: 0 }, { x: 20, y: 40 }, { x: 20, y: 100 }],
+ ['n', { height: 40, width: 40, x: 60, y: 60 }, { x: 80, y: 60 }, { x: 80, y: 0 }],
+ ] as const)('lets the %s side grow to the full image by sliding the other axis', (mode, box, from, to) => {
+ const grown = resolveReferenceCropDrag({ box, mode, ...from }, to, constraints(1, { width: 800, height: 800 }));
+ expect(grown).toEqual({ x: 0, y: 0, width: 100, height: 100 });
+ });
+
+ it.each(['nw', 'ne', 'sw', 'se'] as const)('shrinks the %s corner with either single-axis gesture', (mode) => {
+ const image = { width: 600, height: 800 };
+ // A 240px square on a portrait source.
+ const box = { x: 30, y: 30, width: 40, height: 30 };
+ const from = { x: mode.includes('w') ? 30 : 70, y: mode.includes('n') ? 30 : 60 };
+ for (const to of [
+ { ...from, x: from.x + (mode.includes('w') ? 10 : -10) },
+ { ...from, y: from.y + (mode.includes('n') ? 7.5 : -7.5) },
+ ]) {
+ const shrunk = resolveReferenceCropDrag({ box, mode, ...from }, to, constraints(1, image));
+ expect(shrunk.width).toBeCloseTo(30);
+ expect(shrunk.height).toBeCloseTo(22.5);
+ expect(shrunk.x + (mode.includes('w') ? shrunk.width : 0)).toBeCloseTo(mode.includes('w') ? 70 : 30);
+ expect(shrunk.y + (mode.includes('n') ? shrunk.height : 0)).toBeCloseTo(mode.includes('n') ? 60 : 30);
+ expectInside(shrunk);
+ }
+ });
+
+ it('stops a ratio-locked drag at the image edge instead of breaking the ratio', () => {
+ const pinned = drag('se', box, { x: 70, y: 70 }, { x: 100, y: 100 }, 16 / 9);
+
+ expect(pixelRatio(pinned)).toBeCloseTo(16 / 9);
+ expectInside(pinned);
+ expect(pinned.x + pinned.width).toBeCloseTo(100);
+ });
+});
+
+describe('matchReferenceCropAspectRatio', () => {
+ it('recognizes every preset from a pixel-rounded box and reads anything else as free', () => {
+ for (const { id, ratio } of REFERENCE_CROP_ASPECT_RATIOS) {
+ if (ratio === null) {
+ continue;
+ }
+ const heightPx = 300;
+ const widthPx = Math.round(heightPx * ratio);
+ const box = { height: (heightPx / 600) * 100, width: (widthPx / 800) * 100, x: 0, y: 0 };
+ expect(matchReferenceCropAspectRatio(box, IMAGE)).toBe(id);
+ }
+ expect(matchReferenceCropAspectRatio({ height: 50, width: 37, x: 0, y: 0 }, IMAGE)).toBe('free');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
index 64ed5b2381..534ee37694 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx
@@ -162,7 +162,7 @@ const createStableGroups = () => ({
CanvasRenderSize: () => null,
account: { currentUserId: null, multiuserEnabled: false },
capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },
- gallery: { findImage: noop, selectedImage: null, touchImages: noop },
+ gallery: { findImage: noop, selectedImage: null, touchImages: noop, uploadBoardId: 'none' },
models: {
ModelSelect: MainModelPicker,
catalog: CATALOG,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
index 621078e4b4..98970c383f 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx
@@ -100,6 +100,8 @@ export interface GenerationUiAdapter {
findImage(imageName: string): void;
selectedImage: GenerationSelectedImage | null;
touchImages(): void;
+ /** The Gallery's auto-add board, where uploads made from Generate land; `none` is Uncategorized. */
+ uploadBoardId: string;
};
models: {
ModelSelect: ComponentType<GenerationModelSelectProps>;
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
index 300e322eeb..215b078994 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx
@@ -1,14 +1,23 @@
import type { GenerateReferenceImageAsset } from '@features/generation/core/types';
-import type { CSSProperties, PointerEvent } from 'react';
+import type { LucideIcon } from 'lucide-react';
+import type { CSSProperties, PointerEvent, RefCallback } from 'react';
-import { Box, Portal, Stack, Text } from '@chakra-ui/react';
+import { Box, createListCollection, HStack, Portal, Spacer, Stack, Text } from '@chakra-ui/react';
import { galleryTransfers } from '@features/gallery';
import {
+ constrainReferenceCropBox,
FULL_REFERENCE_IMAGE_CROP_BOX,
generatedImageToReferenceImage,
getReferenceImageCropBoxPct,
isFullReferenceImageCropBox,
+ matchReferenceCropAspectRatio,
+ REFERENCE_CROP_ASPECT_RATIOS,
+ resolveReferenceCropDrag,
resolveReferenceImageCrop,
+ type ReferenceCropAspectRatioId,
+ type ReferenceCropDrag,
+ type ReferenceCropDragMode,
+ type ReferenceCropHandle,
type ReferenceImageCropBoxPct,
} from '@features/generation/core/referenceImage';
import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';
@@ -19,21 +28,26 @@ import {
isAccountScopeCurrent,
type AccountScope,
} from '@platform/state/accountLifecycle';
-import { Button, CloseButton } from '@platform/ui';
+import { Button, CloseButton, IconButton } from '@platform/ui';
import { Dialog } from '@platform/ui/Dialog';
+import { Select } from '@platform/ui/Select';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { MaximizeIcon, ZoomInIcon, ZoomOutIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-type HandleName = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
-
-type DragMode = 'move' | HandleName;
-
-type DragState = { box: ReferenceImageCropBoxPct; mode: DragMode; x: number; y: number };
-
/** Matches the legacy cropper's minimum crop dimension, in image pixels. */
const MIN_CROP_DIMENSION_PX = 64;
-const HANDLES: { cursor: string; left: string; name: HandleName; top: string }[] = [
+/** Zoom is relative to the fitted image; wheel deltas are normalized to CSS pixels. */
+const ZOOM_WHEEL_PIXELS_PER_STEP = 100;
+const ZOOM_WHEEL_FACTOR = 1.1;
+const PAN_VISIBLE_PX = 48;
+const ZOOM_BUTTON_FACTOR = 1.2;
+const ZOOM_MIN = 0.25;
+const ZOOM_MAX = 16;
+
+const HANDLES: { cursor: string; left: string; name: ReferenceCropHandle; top: string }[] = [
{ cursor: 'nwse-resize', left: '0%', name: 'nw', top: '0%' },
{ cursor: 'ns-resize', left: '50%', name: 'n', top: '0%' },
{ cursor: 'nesw-resize', left: '100%', name: 'ne', top: '0%' },
@@ -46,63 +60,92 @@ const HANDLES: { cursor: string; left: string; name: HandleName; top: string }[]
const THIRDS_OFFSETS = ['33.333%', '66.667%'];
-const CONTAIN_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'contain', width: '100%' };
+const ASPECT_RATIO_TRIGGER_PROPS = { minW: '7rem' } as const;
+
+const CONTAIN_IMG_STYLE: CSSProperties = { display: 'block', height: '100%', objectFit: 'contain', width: '100%' };
-const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+/** Fit: the image fills the viewport; pan is in viewport pixels. */
+interface CropView {
+ panX: number;
+ panY: number;
+ zoom: number;
+}
-const getPointerPct = (event: PointerEvent, element: HTMLElement): { x: number; y: number } => {
- const rect = element.getBoundingClientRect();
+const FIT_VIEW: CropView = { panX: 0, panY: 0, zoom: 1 };
+/** Keep a reachable part of the image visible, including when zoomed smaller than the viewport. */
+const constrainViewPan = (view: CropView, viewport: { width: number; height: number }): CropView => {
+ const width = viewport.width * view.zoom;
+ const height = viewport.height * view.zoom;
+ const visibleX = Math.min(PAN_VISIBLE_PX, width, viewport.width);
+ const visibleY = Math.min(PAN_VISIBLE_PX, height, viewport.height);
return {
- x: ((event.clientX - rect.left) / rect.width) * 100,
- y: ((event.clientY - rect.top) / rect.height) * 100,
+ ...view,
+ panX: Math.min(viewport.width - visibleX, Math.max(visibleX - width, view.panX)),
+ panY: Math.min(viewport.height - visibleY, Math.max(visibleY - height, view.panY)),
};
};
-const resolveDrag = (
- drag: DragState,
- point: { x: number; y: number },
- minWidth: number,
- minHeight: number
-): ReferenceImageCropBoxPct => {
- const dx = point.x - drag.x;
- const dy = point.y - drag.y;
- const box = drag.box;
-
- if (drag.mode === 'move') {
- return {
- ...box,
- x: clamp(box.x + dx, 0, 100 - box.width),
- y: clamp(box.y + dy, 0, 100 - box.height),
- };
- }
+type PanState = 'idle' | 'ready' | 'panning';
- let left = box.x;
- let top = box.y;
- let right = box.x + box.width;
- let bottom = box.y + box.height;
+const isDragMode = (value: unknown): value is ReferenceCropDragMode =>
+ value === 'move' || HANDLES.some((handle) => handle.name === value);
- if (drag.mode.includes('w')) {
- left = clamp(left + dx, 0, right - minWidth);
- }
+const isAspectRatioId = (value: unknown): value is ReferenceCropAspectRatioId =>
+ REFERENCE_CROP_ASPECT_RATIOS.some((preset) => preset.id === value);
- if (drag.mode.includes('e')) {
- right = clamp(right + dx, left + minWidth, 100);
- }
+/** Space pans only when nothing that activates on Space has focus; buttons and fields keep their own behaviour. */
+const consumesSpace = (target: EventTarget | null): boolean =>
+ target instanceof Element &&
+ target.closest(
+ 'button, [role="button"], input, textarea, select, [contenteditable], [role="combobox"], [role="listbox"]'
+ ) !== null;
- if (drag.mode.includes('n')) {
- top = clamp(top + dy, 0, bottom - minHeight);
- }
+/** A saved partial crop reopens on its preset; the full image opens free, so the first drag is unconstrained. */
+const initialAspectRatioId = (image: GenerateReferenceImageAsset): ReferenceCropAspectRatioId => {
+ const box = getReferenceImageCropBoxPct(image);
+ return isFullReferenceImageCropBox(box) ? 'free' : matchReferenceCropAspectRatio(box, image.original.image);
+};
- if (drag.mode.includes('s')) {
- bottom = clamp(bottom + dy, top + minHeight, 100);
- }
+/** Pointer position as a percentage of the (transformed) stage, which holds the image at its on-screen size. */
+const getPointerPct = (event: PointerEvent, stage: HTMLElement): { x: number; y: number } => {
+ const rect = stage.getBoundingClientRect();
- return { height: bottom - top, width: right - left, x: left, y: top };
+ return {
+ x: ((event.clientX - rect.left) / rect.width) * 100,
+ y: ((event.clientY - rect.top) / rect.height) * 100,
+ };
};
-const isDragMode = (value: unknown): value is DragMode =>
- value === 'move' || HANDLES.some((handle) => handle.name === value);
+const CropViewButton = ({ icon: Icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) => (
+ <Tooltip content={label}>
+ <IconButton aria-label={label} size="sm" variant="ghost" onClick={onClick}>
+ <Icon />
+ </IconButton>
+ </Tooltip>
+);
+
+/** Capture keeps a drag alive outside the viewport; without it (synthetic pointers) the viewport still sees moves. */
+const capturePointer = (element: HTMLElement, pointerId: number): void => {
+ try {
+ element.setPointerCapture(pointerId);
+ } catch {
+ // No capture available for this pointer.
+ }
+};
+
+/** Zooms by `factor` about a viewport point, so the pixel under the cursor stays put. */
+const zoomViewAt = (view: CropView, factor: number, point: { x: number; y: number }): CropView => {
+ // Actual size can sit beyond the normal range; controls may move back toward it without reversing direction.
+ const zoom = Math.min(Math.max(ZOOM_MAX, view.zoom), Math.max(Math.min(ZOOM_MIN, view.zoom), view.zoom * factor));
+ const scale = zoom / view.zoom;
+
+ return {
+ panX: point.x - (point.x - view.panX) * scale,
+ panY: point.y - (point.y - view.panY) * scale,
+ zoom,
+ };
+};
export const exportCroppedReferenceImage = async (
image: GenerateReferenceImageAsset,
@@ -182,17 +225,42 @@ export const ReferenceImageCropDialog = ({
}) => {
const { t } = useTranslation();
const { gallery, notifications } = useGenerationUi();
+ const original = image.original.image;
const [cropBox, setCropBox] = useState<ReferenceImageCropBoxPct>(() => getReferenceImageCropBoxPct(image));
+ const [aspectRatioId, setAspectRatioId] = useState<ReferenceCropAspectRatioId>(() => initialAspectRatioId(image));
+ const [view, setView] = useState<CropView>(FIT_VIEW);
+ const [panState, setPanState] = useState<PanState>('idle');
const [isApplying, setIsApplying] = useState(false);
- const containerRef = useRef<HTMLDivElement | null>(null);
- const dragRef = useRef<DragState | null>(null);
- const original = image.original.image;
+ const [isSaving, setIsSaving] = useState(false);
+ const viewportRef = useRef<HTMLDivElement | null>(null);
+ const stageRef = useRef<HTMLDivElement | null>(null);
+ const dragRef = useRef<ReferenceCropDrag | null>(null);
+ const panRef = useRef<{ x: number; y: number } | null>(null);
+ const spaceHeldRef = useRef(false);
const imageUrl = getReferenceImageUrls({ original: image.original }).imageUrl;
const ratio = original.height > 0 ? original.width / original.height : 1;
- const minWidthPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, original.width)) * 100);
- const minHeightPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, original.height)) * 100);
+ const constraints = useMemo(
+ () => ({
+ image: original,
+ minDimensionPx: MIN_CROP_DIMENSION_PX,
+ ratio: REFERENCE_CROP_ASPECT_RATIOS.find((preset) => preset.id === aspectRatioId)?.ratio ?? null,
+ }),
+ [aspectRatioId, original]
+ );
const cropWidthPx = Math.max(1, Math.round((cropBox.width / 100) * original.width));
const cropHeightPx = Math.max(1, Math.round((cropBox.height / 100) * original.height));
+ const isBusy = isApplying || isSaving;
+
+ const aspectRatioCollection = useMemo(
+ () =>
+ createListCollection({
+ items: REFERENCE_CROP_ASPECT_RATIOS.map(({ id }) => ({
+ label: id === 'free' ? t('widgets.generate.cropAspectRatioFree') : id,
+ value: id,
+ })),
+ }),
+ [t]
+ );
const cropBoxStyle = useMemo<CSSProperties>(
() => ({
@@ -203,13 +271,17 @@ export const ReferenceImageCropDialog = ({
}),
[cropBox]
);
+ const stageStyle = useMemo<CSSProperties>(
+ () => ({ transform: `translate(${view.panX}px, ${view.panY}px) scale(${view.zoom})`, transformOrigin: '0 0' }),
+ [view]
+ );
const close = useCallback(() => {
- if (!isApplying) {
+ if (!isBusy) {
setCropBox(getReferenceImageCropBoxPct(image));
onClose();
}
- }, [image, isApplying, onClose]);
+ }, [image, isBusy, onClose]);
const handleOpenChange = useCallback(
(event: Dialog.OpenChangeDetails) => {
@@ -220,46 +292,169 @@ export const ReferenceImageCropDialog = ({
[close]
);
+ // Wheel zoom must cancel the dialog's own scrolling, which React's passive wheel listener cannot; Space is read
+ // window-wide so panning works wherever focus sits, except in fields that use Space themselves.
+ const viewportCallbackRef = useCallback<RefCallback<HTMLDivElement>>((element) => {
+ viewportRef.current = element;
+ if (!element) {
+ return;
+ }
+ const onWheel = (event: WheelEvent) => {
+ if (event.deltaY === 0) {
+ return;
+ }
+ event.preventDefault();
+ const rect = element.getBoundingClientRect();
+ const deltaPx = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1);
+ const factor = ZOOM_WHEEL_FACTOR ** (-deltaPx / ZOOM_WHEEL_PIXELS_PER_STEP);
+ setView((current) =>
+ constrainViewPan(
+ zoomViewAt(current, factor, { x: event.clientX - rect.left, y: event.clientY - rect.top }),
+ rect
+ )
+ );
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.code === 'Space' && !consumesSpace(event.target)) {
+ event.preventDefault();
+ if (!event.repeat) {
+ spaceHeldRef.current = true;
+ setPanState((current) => (current === 'idle' ? 'ready' : current));
+ }
+ }
+ };
+ const releaseSpace = (event: KeyboardEvent | FocusEvent) => {
+ if (!('code' in event) || event.code === 'Space') {
+ spaceHeldRef.current = false;
+ setPanState((current) => (current === 'ready' ? 'idle' : current));
+ }
+ };
+ element.addEventListener('wheel', onWheel, { passive: false });
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('keyup', releaseSpace);
+ window.addEventListener('blur', releaseSpace);
+ return () => {
+ element.removeEventListener('wheel', onWheel);
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('keyup', releaseSpace);
+ window.removeEventListener('blur', releaseSpace);
+ };
+ }, []);
+
+ const zoomAboutCenter = useCallback((factor: number) => {
+ const viewport = viewportRef.current;
+ if (viewport) {
+ const rect = viewport.getBoundingClientRect();
+ setView((current) =>
+ constrainViewPan(zoomViewAt(current, factor, { x: rect.width / 2, y: rect.height / 2 }), rect)
+ );
+ }
+ }, []);
+ const zoomIn = useCallback(() => zoomAboutCenter(ZOOM_BUTTON_FACTOR), [zoomAboutCenter]);
+ const zoomOut = useCallback(() => zoomAboutCenter(1 / ZOOM_BUTTON_FACTOR), [zoomAboutCenter]);
+ const fitView = useCallback(() => setView(FIT_VIEW), []);
+ // Actual size: one image pixel per CSS pixel, centered.
+ const resetView = useCallback(() => {
+ const viewport = viewportRef.current;
+ if (!viewport || viewport.clientWidth === 0) {
+ return;
+ }
+ const rect = viewport.getBoundingClientRect();
+ const zoom = original.width / rect.width;
+ setView({
+ panX: (rect.width * (1 - zoom)) / 2,
+ panY: (rect.height * (1 - zoom)) / 2,
+ zoom,
+ });
+ }, [original.width]);
+
+ const handleAspectRatioChange = useCallback(
+ ({ value }: { value: string[] }) => {
+ const next = value[0];
+ if (!isAspectRatioId(next)) {
+ return;
+ }
+ setAspectRatioId(next);
+ setCropBox((current) =>
+ constrainReferenceCropBox(current, {
+ ...constraints,
+ ratio: REFERENCE_CROP_ASPECT_RATIOS.find((preset) => preset.id === next)?.ratio ?? null,
+ })
+ );
+ },
+ [constraints]
+ );
+
+ const beginPan = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ const viewport = viewportRef.current;
+ if (!viewport || dragRef.current || (event.button !== 1 && !(event.button === 0 && panState === 'ready'))) {
+ return;
+ }
+ event.preventDefault();
+ capturePointer(viewport, event.pointerId);
+ panRef.current = { x: event.clientX, y: event.clientY };
+ setPanState('panning');
+ },
+ [panState]
+ );
+
const beginDrag = useCallback(
(event: PointerEvent<HTMLElement>) => {
- const container = containerRef.current;
+ const viewport = viewportRef.current;
+ const stage = stageRef.current;
const mode = (event.currentTarget as HTMLElement).dataset.dragMode;
- if (!container || !isDragMode(mode)) {
+ // Space or the middle button pans from anywhere, the crop box included; let it reach the viewport.
+ if (!viewport || !stage || !isDragMode(mode) || panState === 'ready' || event.button !== 0) {
return;
}
event.preventDefault();
event.stopPropagation();
- container.setPointerCapture(event.pointerId);
- dragRef.current = { box: cropBox, mode, ...getPointerPct(event, container) };
+ capturePointer(viewport, event.pointerId);
+ dragRef.current = { box: cropBox, mode, ...getPointerPct(event, stage) };
},
- [cropBox]
+ [cropBox, panState]
);
- const moveDrag = useCallback(
+ const movePointer = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
- const container = containerRef.current;
- const drag = dragRef.current;
-
- if (!container || !drag) {
+ const pan = panRef.current;
+ const viewport = viewportRef.current;
+ if (pan && viewport) {
+ const dx = event.clientX - pan.x;
+ const dy = event.clientY - pan.y;
+ panRef.current = { x: event.clientX, y: event.clientY };
+ const rect = viewport.getBoundingClientRect();
+ setView((current) => constrainViewPan({ ...current, panX: current.panX + dx, panY: current.panY + dy }, rect));
return;
}
-
- setCropBox(resolveDrag(drag, getPointerPct(event, container), minWidthPct, minHeightPct));
+ const stage = stageRef.current;
+ const drag = dragRef.current;
+ if (stage && drag) {
+ setCropBox(resolveReferenceCropDrag(drag, getPointerPct(event, stage), constraints));
+ }
},
- [minHeightPct, minWidthPct]
+ [constraints]
);
- const endDrag = useCallback((event: PointerEvent<HTMLDivElement>) => {
+ const endPointer = useCallback((event: PointerEvent<HTMLDivElement>) => {
dragRef.current = null;
-
- if (containerRef.current?.hasPointerCapture(event.pointerId)) {
- containerRef.current.releasePointerCapture(event.pointerId);
+ if (panRef.current) {
+ panRef.current = null;
+ // Space still held keeps the viewport ready for the next pan.
+ setPanState(spaceHeldRef.current ? 'ready' : 'idle');
+ }
+ if (viewportRef.current?.hasPointerCapture(event.pointerId)) {
+ viewportRef.current.releasePointerCapture(event.pointerId);
}
}, []);
- const resetCrop = useCallback(() => setCropBox(FULL_REFERENCE_IMAGE_CROP_BOX), []);
+ const resetCrop = useCallback(() => {
+ setAspectRatioId('free');
+ setCropBox(FULL_REFERENCE_IMAGE_CROP_BOX);
+ }, []);
const applyCrop = useCallback(async () => {
const owner = captureAccountScope();
@@ -301,6 +496,38 @@ export const ReferenceImageCropDialog = ({
}
}, [close, cropBox, gallery, image, notifications, onApply, onClose]);
+ // A durable copy of the crop in Uploads on the Gallery's auto-add board, unrelated to applying it: the dialog
+ // stays open and the reference unchanged.
+ const saveToAssets = useCallback(async () => {
+ const owner = captureAccountScope();
+ setIsSaving(true);
+
+ try {
+ const file = await exportCroppedReferenceImage(image, cropBox, owner);
+ assertAccountScopeCurrent(owner);
+ await galleryTransfers.upload(file, gallery.uploadBoardId, { isIntermediate: false, signal: owner.signal });
+ assertAccountScopeCurrent(owner);
+ gallery.touchImages();
+ notifications.info(t('widgets.generate.cropSavedToAssets'));
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ notifications.reportError({
+ area: 'reference-images',
+ message: error instanceof Error ? error.message : String(error),
+ namespace: 'generation',
+ });
+ } finally {
+ if (isAccountScopeCurrent(owner)) {
+ setIsSaving(false);
+ }
+ }
+ }, [cropBox, gallery, image, notifications, t]);
+
+ const aspectRatioValue = useMemo(() => [aspectRatioId], [aspectRatioId]);
+
return (
<Dialog.Root
lazyMount
@@ -318,101 +545,141 @@ export const ReferenceImageCropDialog = ({
<Dialog.Title>{t('widgets.generate.cropReferenceImage')}</Dialog.Title>
</Dialog.Header>
<Dialog.CloseTrigger asChild>
- <CloseButton disabled={isApplying} />
+ <CloseButton disabled={isBusy} />
</Dialog.CloseTrigger>
<Dialog.Body>
<Stack gap="3">
- <Text color="fg.muted" fontSize="md">
- {t('widgets.generate.cropReferenceImageHelp')}
- </Text>
+ <HStack gap="2">
+ <Text color="fg.muted" fontSize="sm">
+ {t('widgets.generate.aspectRatio')}
+ </Text>
+ <Select
+ aria-label={t('widgets.generate.aspectRatio')}
+ collection={aspectRatioCollection}
+ disabled={isBusy}
+ size="sm"
+ triggerProps={ASPECT_RATIO_TRIGGER_PROPS}
+ value={aspectRatioValue}
+ w="auto"
+ onValueChange={handleAspectRatioChange}
+ />
+ <Spacer />
+ <CropViewButton icon={MaximizeIcon} label={t('widgets.generate.cropFitView')} onClick={fitView} />
+ <Tooltip content={t('widgets.generate.cropActualSize')}>
+ <Button
+ aria-label={`1:1 ${t('widgets.generate.cropActualSize')}`}
+ minW="8"
+ px="0"
+ size="sm"
+ variant="ghost"
+ onClick={resetView}
+ >
+ 1:1
+ </Button>
+ </Tooltip>
+ <CropViewButton icon={ZoomInIcon} label={t('widgets.generate.cropZoomIn')} onClick={zoomIn} />
+ <CropViewButton icon={ZoomOutIcon} label={t('widgets.generate.cropZoomOut')} onClick={zoomOut} />
+ </HStack>
<Box
- ref={containerRef}
+ ref={viewportCallbackRef}
aspectRatio={ratio}
bg="bg.muted"
- maxH="60vh"
+ cursor={panState === 'panning' ? 'grabbing' : panState === 'ready' ? 'grab' : undefined}
+ data-pan-state={panState}
+ alignSelf="center"
overflow="hidden"
position="relative"
rounded="md"
touchAction="none"
userSelect="none"
- w="full"
- onPointerCancel={endDrag}
- onPointerMove={moveDrag}
- onPointerUp={endDrag}
+ w={`min(100%, ${60 * ratio}vh)`}
+ onPointerCancel={endPointer}
+ onPointerDown={beginPan}
+ onPointerMove={movePointer}
+ onPointerUp={endPointer}
>
- <img alt={original.image_name} draggable={false} src={imageUrl} style={CONTAIN_IMG_STYLE} />
- <Box
- borderColor="accent.solid"
- borderWidth="1.5px"
- boxShadow="0 0 0 9999px rgba(0, 0, 0, 0.45)"
- cursor="move"
- data-drag-mode="move"
- position="absolute"
- touchAction="none"
- style={cropBoxStyle}
- onPointerDown={beginDrag}
- >
- {THIRDS_OFFSETS.map((offset) => (
- <Box
- key={`v-${offset}`}
- bg="whiteAlpha.500"
- bottom="0"
- left={offset}
- pointerEvents="none"
- position="absolute"
- top="0"
- w="1px"
- />
- ))}
- {THIRDS_OFFSETS.map((offset) => (
- <Box
- key={`h-${offset}`}
- bg="whiteAlpha.500"
- h="1px"
- left="0"
- pointerEvents="none"
- position="absolute"
- right="0"
- top={offset}
- />
- ))}
- {HANDLES.map((handle) => (
- <Box
- key={handle.name}
- bg="white"
- boxShadow="0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 3px rgba(0, 0, 0, 0.5)"
- cursor={handle.cursor}
- data-drag-mode={handle.name}
- h="3"
- left={handle.left}
- position="absolute"
- rounded="xs"
- top={handle.top}
- touchAction="none"
- transform="translate(-50%, -50%)"
- w="3"
- onPointerDown={beginDrag}
- />
- ))}
+ <Box ref={stageRef} data-crop-stage="" inset="0" position="absolute" style={stageStyle}>
+ <img alt={original.image_name} draggable={false} src={imageUrl} style={CONTAIN_IMG_STYLE} />
+ <Box
+ borderColor="accent.solid"
+ borderWidth="1.5px"
+ boxShadow="0 0 0 9999px rgba(0, 0, 0, 0.45)"
+ cursor={panState === 'idle' ? 'move' : undefined}
+ data-crop-box=""
+ data-drag-mode="move"
+ position="absolute"
+ touchAction="none"
+ style={cropBoxStyle}
+ onPointerDown={beginDrag}
+ >
+ {THIRDS_OFFSETS.map((offset) => (
+ <Box
+ key={`v-${offset}`}
+ bg="whiteAlpha.500"
+ bottom="0"
+ left={offset}
+ pointerEvents="none"
+ position="absolute"
+ top="0"
+ w="1px"
+ />
+ ))}
+ {THIRDS_OFFSETS.map((offset) => (
+ <Box
+ key={`h-${offset}`}
+ bg="whiteAlpha.500"
+ h="1px"
+ left="0"
+ pointerEvents="none"
+ position="absolute"
+ right="0"
+ top={offset}
+ />
+ ))}
+ {HANDLES.map((handle) => (
+ <Box
+ key={handle.name}
+ bg="white"
+ boxShadow="0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 3px rgba(0, 0, 0, 0.5)"
+ cursor={panState === 'idle' ? handle.cursor : undefined}
+ data-drag-mode={handle.name}
+ h="3"
+ left={handle.left}
+ position="absolute"
+ rounded="xs"
+ top={handle.top}
+ touchAction="none"
+ transform="translate(-50%, -50%)"
+ w="3"
+ onPointerDown={beginDrag}
+ />
+ ))}
+ </Box>
</Box>
</Box>
- <Text color="fg.muted" fontFamily="mono" fontSize="xs">
- {cropWidthPx} × {cropHeightPx} px
- </Text>
+ <HStack gap="3">
+ <Text color="fg.muted" fontSize="sm">
+ {t('widgets.generate.cropReferenceImageHelp')}
+ </Text>
+ <Spacer />
+ <Text color="fg.muted" flexShrink={0} fontFamily="mono" fontSize="xs">
+ {cropWidthPx} × {cropHeightPx} px
+ </Text>
+ </HStack>
</Stack>
</Dialog.Body>
<Dialog.Footer>
- <Button
- disabled={isApplying || isFullReferenceImageCropBox(cropBox)}
- variant="outline"
- onClick={resetCrop}
- >
+ <Button disabled={isApplying} loading={isSaving} variant="outline" onClick={saveToAssets}>
+ {t('widgets.generate.cropSaveToAssets')}
+ </Button>
+ <Spacer />
+ <Button disabled={isBusy || isFullReferenceImageCropBox(cropBox)} variant="outline" onClick={resetCrop}>
{t('common.reset')}
</Button>
- <Button disabled={isApplying} variant="ghost" onClick={close}>
+ <Button disabled={isBusy} variant="ghost" onClick={close}>
{t('common.cancel')}
</Button>
- <Button loading={isApplying} onClick={applyCrop}>
+ <Button disabled={isSaving} loading={isApplying} onClick={applyCrop}>
{t('common.apply')}
</Button>
</Dialog.Footer>
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx
index f5269113d7..156c2152b9 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx
@@ -10,10 +10,33 @@ 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 { userEvent } from 'vitest/browser';
+import { page, userEvent } from 'vitest/browser';
import { ReferenceImageCard } from './ReferenceImageCard';
+const mocks = vi.hoisted(() => {
+ // A real decodable image, so the crop export's <img> loads without a backend.
+ const createImage = (width: number, height: number) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext('2d')!;
+ context.fillStyle = '#4080c0';
+ context.fillRect(0, 0, width, height);
+ return canvas.toDataURL('image/png');
+ };
+ return {
+ createImage,
+ imageDataUrl: createImage(512, 512),
+ upload: vi.fn(),
+ };
+});
+
+vi.mock('@features/gallery', () => ({ galleryTransfers: { upload: mocks.upload } }));
+vi.mock('@features/gallery/utility', () => ({
+ galleryImageUrls: { full: () => mocks.imageDataUrl, thumbnail: () => mocks.imageDataUrl },
+}));
+
const i18n = i18next.createInstance();
await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en' });
@@ -23,8 +46,8 @@ let root: Root | null = null;
const noop = vi.fn();
const ADAPTER = {
- gallery: { touchImages: vi.fn() },
- notifications: { reportError: vi.fn() },
+ gallery: { touchImages: vi.fn(), uploadBoardId: 'board-7' },
+ notifications: { info: vi.fn(), reportError: vi.fn() },
} as unknown as GenerationUiAdapter;
const REFERENCE: GenerateReferenceImage = {
@@ -36,11 +59,26 @@ const REFERENCE: GenerateReferenceImage = {
isEnabled: true,
};
-beforeEach(async () => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- await act(() =>
+/** A reference whose saved crop is the centred 256px square of the 512px original. */
+const SQUARE_CROPPED_REFERENCE: GenerateReferenceImage = {
+ ...REFERENCE,
+ config: {
+ image: {
+ crop: {
+ box: { height: 256, width: 256, x: 128, y: 128 },
+ image: { height: 256, image_name: 'crop.png', width: 256 },
+ ratio: null,
+ },
+ original: { image: { height: 512, image_name: 'original.png', width: 512 } },
+ },
+ type: 'external_reference_image',
+ },
+};
+
+const renderCard = (referenceImage: GenerateReferenceImage) => {
+ const original = referenceImage.config.image!.original.image;
+ mocks.imageDataUrl = mocks.createImage(original.width, original.height);
+ return act(() =>
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
@@ -48,7 +86,7 @@ beforeEach(async () => {
<ReferenceImageCard
count={1}
index={0}
- referenceImage={REFERENCE}
+ referenceImage={referenceImage}
selectedModel={undefined}
onFindInGallery={noop}
onMove={noop}
@@ -61,13 +99,68 @@ beforeEach(async () => {
</I18nextProvider>
)
);
+};
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await renderCard(REFERENCE);
});
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
+ await page.viewport(1280, 720);
+ vi.clearAllMocks();
});
+const openCropDialog = async (): Promise<HTMLElement> => {
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="common.crop"]')!));
+ await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;
+ await expect
+ .poll(() => dialog.getAnimations().filter((animation) => animation.playState === 'running').length)
+ .toBe(0);
+ return dialog;
+};
+
+/** The crop box as percentages of the image, read back from its inline style. */
+const readCropBox = (dialog: HTMLElement) => {
+ const style = dialog.querySelector<HTMLElement>('[data-crop-box]')!.style;
+ return {
+ height: parseFloat(style.height),
+ width: parseFloat(style.width),
+ x: parseFloat(style.left),
+ y: parseFloat(style.top),
+ };
+};
+
+const pointer = (type: string, target: Element, clientX: number, clientY: number, button = 0) =>
+ target.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ button,
+ buttons: button === 1 ? 4 : 1,
+ clientX,
+ clientY,
+ isPrimary: true,
+ pointerId: 7,
+ })
+ );
+
+/** `translate(x px, y px) scale(z)` from the stage's inline transform. */
+const readView = (dialog: HTMLElement) => {
+ const transform = dialog.querySelector<HTMLElement>('[data-crop-stage]')!.style.transform;
+ const [, x, y, zoom] = /translate\(([-\d.e]+)px, ([-\d.e]+)px\) scale\(([-\d.e]+)\)/.exec(transform) ?? [];
+ return { x: parseFloat(x ?? ''), y: parseFloat(y ?? ''), zoom: parseFloat(zoom ?? '') };
+};
+
+const viewportOf = (dialog: HTMLElement) => dialog.querySelector<HTMLElement>('[data-crop-stage]')!.parentElement!;
+
+const spaceKey = (type: 'keydown' | 'keyup', target: EventTarget = window) =>
+ target.dispatchEvent(new KeyboardEvent(type, { bubbles: true, cancelable: true, code: 'Space', key: ' ' }));
+
describe('reference image crop dialog', () => {
it('animates out instead of unmounting on close', async () => {
await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="common.crop"]')!));
@@ -79,4 +172,310 @@ describe('reference image crop dialog', () => {
expect(frames).not.toHaveLength(0);
});
+
+ it('holds the chosen aspect ratio while the crop box is resized from a handle', async () => {
+ const dialog = await openCropDialog();
+ const full = readCropBox(dialog);
+ expect(full).toEqual({ height: 100, width: 100, x: 0, y: 0 });
+
+ await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[role="combobox"]')!));
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role="option"][data-value="9:16"]')!));
+
+ // The source is square, so the box's percentages carry its pixel ratio directly.
+ const portrait = readCropBox(dialog);
+ expect(portrait.width / portrait.height).toBeCloseTo(9 / 16, 3);
+ expect(portrait.height).toBe(100);
+ expect(portrait.x + portrait.width / 2).toBeCloseTo(50, 3);
+
+ const stage = dialog.querySelector<HTMLElement>('[data-crop-stage]')!;
+ const viewport = stage.parentElement!;
+ const handle = dialog.querySelector<HTMLElement>('[data-drag-mode="nw"]')!;
+ const rect = stage.getBoundingClientRect();
+ const start = handle.getBoundingClientRect();
+ const startX = start.left + start.width / 2;
+ const startY = start.top + start.height / 2;
+ await act(() => {
+ pointer('pointerdown', handle, startX, startY);
+ pointer('pointermove', viewport, startX + rect.width * 0.1, startY + rect.height * 0.3);
+ pointer('pointerup', viewport, startX + rect.width * 0.1, startY + rect.height * 0.3);
+ });
+
+ // The 30% vertical shrink dominates after accounting for the ratio; the opposite corner stays anchored.
+ const resized = readCropBox(dialog);
+ expect(resized.width / resized.height).toBeCloseTo(9 / 16, 3);
+ expect(resized.height).toBeCloseTo(portrait.height - 30, 1);
+ expect(resized.x + resized.width).toBeCloseTo(portrait.x + portrait.width, 1);
+ expect(resized.y + resized.height).toBeCloseTo(100, 1);
+ expect(dialog.textContent).toContain(
+ `${Math.round((resized.width / 100) * 512)} × ${Math.round((resized.height / 100) * 512)} px`
+ );
+ });
+
+ it('opens the full image free, and a saved crop on the preset it matches', async () => {
+ let dialog = await openCropDialog();
+ expect(dialog.querySelector('[role="combobox"]')?.textContent).toContain('widgets.generate.cropAspectRatioFree');
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
+
+ await renderCard(SQUARE_CROPPED_REFERENCE);
+ dialog = await openCropDialog();
+ expect(dialog.querySelector('[role="combobox"]')?.textContent).toContain('1:1');
+ expect(readCropBox(dialog)).toEqual({ height: 50, width: 50, x: 25, y: 25 });
+ });
+
+ it('zooms about the wheel cursor without scrolling the dialog, and pans with Space or the middle button', async () => {
+ const dialog = await openCropDialog();
+ const viewport = viewportOf(dialog);
+ const rect = viewport.getBoundingClientRect();
+ expect(readView(dialog)).toEqual({ x: 0, y: 0, zoom: 1 });
+
+ const wheel = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + 100,
+ clientY: rect.top + 50,
+ deltaY: -100,
+ });
+ await act(() => {
+ expect(viewport.dispatchEvent(wheel)).toBe(false);
+ });
+ // The pixel under the cursor stays put: the stage grows by 1.1 about the cursor's viewport offset (the event
+ // stores integer client coordinates, so read the offset back from it).
+ const zoomed = readView(dialog);
+ expect(zoomed.zoom).toBeCloseTo(1.1, 3);
+ expect(zoomed.x).toBeCloseTo(-0.1 * (wheel.clientX - rect.left), 3);
+ expect(zoomed.y).toBeCloseTo(-0.1 * (wheel.clientY - rect.top), 3);
+
+ // Space arms a pan from anywhere, and a drag on the crop box moves the view rather than the box.
+ await act(() => {
+ spaceKey('keydown');
+ });
+ expect(viewport.dataset.panState).toBe('ready');
+ const box = dialog.querySelector<HTMLElement>('[data-crop-box]')!;
+ const before = readCropBox(dialog);
+ await act(() => {
+ pointer('pointerdown', box, rect.left + 200, rect.top + 200);
+ pointer('pointermove', viewport, rect.left + 230, rect.top + 220);
+ pointer('pointerup', viewport, rect.left + 230, rect.top + 220);
+ });
+ const panned = readView(dialog);
+ expect(panned.zoom).toBe(zoomed.zoom);
+ expect(panned.x).toBeCloseTo(zoomed.x + 30, 0);
+ expect(panned.y).toBeCloseTo(zoomed.y + 20, 0);
+ expect(readCropBox(dialog)).toEqual(before);
+ // Still held, so the next drag pans too; releasing returns to crop editing.
+ expect(viewport.dataset.panState).toBe('ready');
+ await act(() => {
+ spaceKey('keyup');
+ });
+ expect(viewport.dataset.panState).toBe('idle');
+
+ await act(() => {
+ pointer('pointerdown', viewport, rect.left + 50, rect.top + 50, 1);
+ pointer('pointermove', viewport, rect.left + 40, rect.top + 60, 1);
+ pointer('pointerup', viewport, rect.left + 40, rect.top + 60, 1);
+ });
+ const middlePanned = readView(dialog);
+ expect(middlePanned.x).toBeCloseTo(panned.x - 10, 0);
+ expect(middlePanned.y).toBeCloseTo(panned.y + 10, 0);
+ expect(viewport.dataset.panState).toBe('idle');
+
+ await act(() =>
+ userEvent.click(
+ [...dialog.querySelectorAll('button')].find(
+ (b) => b.getAttribute('aria-label') === 'widgets.generate.cropFitView'
+ )!
+ )
+ );
+ expect(readView(dialog)).toEqual({ x: 0, y: 0, zoom: 1 });
+ });
+
+ it.each([
+ { width: 1200, height: 600, viewportHeight: 720 },
+ { width: 600, height: 1200, viewportHeight: 720 },
+ { width: 800, height: 600, viewportHeight: 400 },
+ ])('fits the stage and overlay to $width × $height at a $viewportHeight px viewport', async (size) => {
+ await page.viewport(1280, size.viewportHeight);
+ await renderCard({
+ ...REFERENCE,
+ config: {
+ type: 'external_reference_image',
+ image: { original: { image: { width: size.width, height: size.height, image_name: 'original.png' } } },
+ },
+ });
+ const dialog = await openCropDialog();
+ const stage = dialog.querySelector<HTMLElement>('[data-crop-stage]')!;
+ const overlay = dialog.querySelector<HTMLElement>('[data-crop-box]')!;
+ const img = stage.querySelector('img')!;
+ await expect.poll(() => img.naturalWidth).toBe(size.width);
+ const fitted = stage.getBoundingClientRect();
+ expect(fitted.width / fitted.height).toBeCloseTo(size.width / size.height, 2);
+ expect(fitted.height).toBeLessThanOrEqual(size.viewportHeight * 0.6 + 1);
+ expect(overlay.getBoundingClientRect().width).toBeCloseTo(fitted.width, 1);
+ expect(overlay.getBoundingClientRect().height).toBeCloseTo(fitted.height, 1);
+
+ await act(() =>
+ userEvent.click(dialog.querySelector<HTMLElement>('[aria-label="1:1 widgets.generate.cropActualSize"]')!)
+ );
+ expect(stage.getBoundingClientRect().width).toBeCloseTo(size.width, 1);
+ expect(stage.getBoundingClientRect().height).toBeCloseTo(size.height, 1);
+ await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[aria-label="widgets.generate.cropZoomIn"]')!));
+ expect(stage.getBoundingClientRect().width).toBeCloseTo(size.width * 1.2, 1);
+ await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[aria-label="widgets.generate.cropZoomOut"]')!));
+ expect(stage.getBoundingClientRect().width).toBeCloseTo(size.width, 1);
+ await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[aria-label="widgets.generate.cropFitView"]')!));
+ expect(stage.getBoundingClientRect().width).toBeCloseTo(fitted.width, 1);
+ expect(readCropBox(dialog)).toEqual({ height: 100, width: 100, x: 0, y: 0 });
+ });
+
+ it.each([
+ { width: 64, height: 64, limitedControl: 'cropZoomOut', movingControl: 'cropZoomIn', factor: 1.2 },
+ { width: 256, height: 8000, limitedControl: 'cropZoomIn', movingControl: 'cropZoomOut', factor: 1 / 1.2 },
+ ])('keeps zoom controls monotonic after Actual size for a $width × $height image', async (size) => {
+ await renderCard({
+ ...REFERENCE,
+ config: {
+ type: 'external_reference_image',
+ image: { original: { image: { width: size.width, height: size.height, image_name: 'original.png' } } },
+ },
+ });
+ const dialog = await openCropDialog();
+ const clickControl = (name: string) =>
+ act(() =>
+ userEvent.click(
+ dialog.querySelector<HTMLElement>(
+ `[aria-label="${name === 'cropActualSize' ? '1:1 ' : ''}widgets.generate.${name}"]`
+ )!
+ )
+ );
+ const stage = dialog.querySelector<HTMLElement>('[data-crop-stage]')!;
+ await clickControl('cropActualSize');
+ expect(stage.getBoundingClientRect().height).toBeCloseTo(size.height, 1);
+ await clickControl(size.limitedControl);
+ expect(stage.getBoundingClientRect().height).toBeCloseTo(size.height, 1);
+ await clickControl(size.movingControl);
+ expect(stage.getBoundingClientRect().height).toBeCloseTo(size.height * size.factor, 1);
+ });
+
+ it('ignores horizontal wheels and normalizes proportional pixel, line and page zoom', async () => {
+ const dialog = await openCropDialog();
+ const viewport = viewportOf(dialog);
+ const rect = viewport.getBoundingClientRect();
+ const wheel = (deltaY: number, deltaMode = 0) =>
+ act(() => {
+ viewport.dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ deltaX: 50,
+ deltaY,
+ deltaMode,
+ })
+ );
+ });
+ await wheel(0);
+ expect(readView(dialog)).toEqual({ x: 0, y: 0, zoom: 1 });
+ await wheel(-1);
+ expect(readView(dialog).zoom).toBeCloseTo(1.1 ** 0.01, 5);
+ await wheel(1);
+ expect(readView(dialog).zoom).toBeCloseTo(1, 6);
+ await wheel(-6.25, 1);
+ expect(readView(dialog).zoom).toBeCloseTo(1.1, 6);
+ await wheel(100 / rect.height, 2);
+ expect(readView(dialog).zoom).toBeCloseTo(1, 6);
+ });
+
+ it('keeps panning continuous across wheel zoom, bounds the view, and ignores Space plus right click', async () => {
+ const dialog = await openCropDialog();
+ const viewport = viewportOf(dialog);
+ const rect = viewport.getBoundingClientRect();
+ await act(() => {
+ spaceKey('keydown');
+ });
+ await act(() => {
+ pointer('pointerdown', viewport, rect.left + 100, rect.top + 100, 2);
+ pointer('pointermove', viewport, rect.left + 150, rect.top + 150, 2);
+ pointer('pointerup', viewport, rect.left + 150, rect.top + 150, 2);
+ });
+ expect(readView(dialog)).toEqual({ x: 0, y: 0, zoom: 1 });
+ await act(() => {
+ pointer('pointerdown', viewport, rect.left + 100, rect.top + 100);
+ pointer('pointermove', viewport, rect.left + 120, rect.top + 120);
+ });
+ await act(() => {
+ viewport.dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + 120,
+ clientY: rect.top + 120,
+ deltaY: -100,
+ })
+ );
+ });
+ const zoomed = readView(dialog);
+ await act(() => {
+ pointer('pointermove', viewport, rect.left + 121, rect.top + 121);
+ });
+ expect(readView(dialog).x).toBeCloseTo(zoomed.x + 1, 5);
+ expect(readView(dialog).y).toBeCloseTo(zoomed.y + 1, 5);
+ await act(() => {
+ pointer('pointermove', viewport, rect.left + 10000, rect.top + 10000);
+ });
+ expect(readView(dialog).x).toBeCloseTo(rect.width - 48, 2);
+ expect(readView(dialog).y).toBeCloseTo(rect.height - 48, 2);
+ await act(() => {
+ pointer('pointermove', viewport, rect.left - 10000, rect.top - 10000);
+ });
+ const stage = dialog.querySelector<HTMLElement>('[data-crop-stage]')!.getBoundingClientRect();
+ expect(stage.right - rect.left).toBeCloseTo(48, 2);
+ expect(stage.bottom - rect.top).toBeCloseTo(48, 2);
+ await act(() => {
+ pointer('pointerup', viewport, rect.left - 10000, rect.top - 10000);
+ spaceKey('keyup');
+ });
+ });
+
+ it('leaves Space to a focused button, so Apply still activates from the keyboard', async () => {
+ const dialog = await openCropDialog();
+ const apply = [...dialog.querySelectorAll('button')].find((button) => button.textContent === 'common.apply')!;
+ await act(() => apply.focus());
+
+ await act(() => {
+ expect(spaceKey('keydown', apply)).toBe(true);
+ });
+ expect(viewportOf(dialog).dataset.panState).toBe('idle');
+ await act(() => userEvent.keyboard(' '));
+
+ // The unchanged full crop applies and closes the dialog.
+ await expect.poll(() => noop.mock.calls.length).toBeGreaterThan(0);
+ await expect
+ .poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state') ?? null)
+ .not.toBe('open');
+ });
+
+ it('saves the current crop to Uploads as a durable user image without applying it', async () => {
+ mocks.upload.mockResolvedValue({ imageName: 'saved.png' });
+ const dialog = await openCropDialog();
+ await act(() => userEvent.click(dialog.querySelector<HTMLElement>('[role="combobox"]')!));
+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role="option"][data-value="1:1"]')!));
+ const save = [...dialog.querySelectorAll('button')].find(
+ (button) => button.textContent === 'widgets.generate.cropSaveToAssets'
+ )!;
+ await act(() => userEvent.click(save));
+
+ await expect.poll(() => mocks.upload.mock.calls.length).toBe(1);
+ const [file, boardId, options] = mocks.upload.mock.calls[0] as [File, string, { isIntermediate: boolean }];
+ expect(file).toBeInstanceOf(File);
+ expect(file.name).toBe('original-crop.png');
+ expect(boardId).toBe('board-7');
+ expect(options.isIntermediate).toBe(false);
+ await expect.poll(() => (ADAPTER.notifications.info as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1);
+ expect(ADAPTER.gallery.touchImages).toHaveBeenCalledOnce();
+ // Nothing was applied: the dialog stays open and the reference untouched.
+ expect(dialog.getAttribute('data-state')).toBe('open');
+ expect(noop).not.toHaveBeenCalled();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 68ec69a879..95ef03401b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -4,7 +4,7 @@ Paths are relative to `src/workbench/canvas-engine/`, except those starting with
## Ownership invariant
-Workbench reducer owns serializable canvas contract. Per-project canvas engine owns pixels, decoded images, rendering, interaction, history, transient editing state, caller-owned raster snapshots. Engine-owned objects never enter reducer actions or persisted project state.
+Workbench reducer owns serializable canvas contract. Per-project canvas engine owns pixels, decoded images, rendering, interaction, history, transient editing state, caller-owned raster snapshots. Engine-owned objects never enter reducer actions or persisted project state. Eraser options and layer quick-switch memory belong to the engine lifetime: they survive cooldown only while the registry retains that engine and reset on disposal/recreation. Quick-switch memory updates its return target only on explicit non-null selection changes outside engine edits; deselection, temporary engine selections, and removed targets do not overwrite it. The next explicit switch records the layer actually being left, including an automatic selection after an edit.
Canvas mutations are explicitly project-addressed. `CanvasProjectMutation` is the complete reducer mutation vocabulary; the only `WorkbenchAction` carrying one is:
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 77e7ad718e..258771e607 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -34,6 +34,7 @@ import type {
EraserOptions,
GradientToolOptions,
LassoToolOptions,
+ LayerQuickSwitchState,
LayerThumbnailStatus,
MarqueeToolOptions,
ShapeToolOptions,
@@ -126,6 +127,8 @@ export interface CanvasInteractionState {
historyEpoch: number;
invertBrushSizeScroll: boolean;
lassoOptions: LassoToolOptions;
+ /** Q quick-switch memory; callers write the bookmark, the engine maintains the previous selection. */
+ layerQuickSwitch: LayerQuickSwitchState;
marqueeOptions: MarqueeToolOptions;
/** Monotonic signal: some layer published new cache pixels (thumbnails, overview). */
layerPixelEpoch: number;
@@ -157,6 +160,7 @@ export type CanvasWritableInteractionKey = Extract<
| 'gradientOptions'
| 'invertBrushSizeScroll'
| 'lassoOptions'
+ | 'layerQuickSwitch'
| 'marqueeOptions'
| 'ruleOfThirds'
| 'shapeOptions'
@@ -662,6 +666,7 @@ export type {
GradientStop,
GradientToolOptions,
LassoToolOptions,
+ LayerQuickSwitchState,
LayerThumbnailStatus,
MarqueeToolOptions,
ShapeToolKind,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 71fa8d79bc..e257044e1e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -44,6 +44,7 @@ import {
} from '@workbench/canvas-operations/createCanvasEngine';
import { FILTER_AUTO_PROCESS_DEBOUNCE_MS } from '@workbench/canvas-operations/filterOperationSession';
import { getCanvasOperationImplementation as getCanvasOperations } from '@workbench/canvas-operations/operationAccess';
+import { executeCanvasHotkeyCommand } from '@workbench/widgets/canvas/canvasHotkeyCommands';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';
@@ -16660,6 +16661,23 @@ describe('text edit session', () => {
engine.lifecycle.dispose();
});
+ it('does not replace quick-switch memory when text editing selects its target', () => {
+ const document = textDoc();
+ const withRaster = {
+ ...document,
+ stacks: stacksFrom([...getDocumentLeaves(document), rasterLayer('a'), rasterLayer('b')]),
+ selectedLayerId: 'a',
+ };
+ const { engine, setDocument } = makeEngine(withRaster);
+ setDocument({ ...withRaster, selectedLayerId: 'b' });
+ engine.layers.openTextEdit('txt1');
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('txt1');
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ setDocument({ ...withRaster, selectedLayerId: 'a' });
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('txt1');
+ engine.lifecycle.dispose();
+ });
+
it('opening an edit on the selected text layer dispatches nothing', () => {
const { dispatch, engine } = makeEngine(textDoc());
engine.tools.setTool('text');
@@ -17332,7 +17350,10 @@ describe('Select Object canvas engine integration', () => {
expect(getCanvasOperations(h.engine).startSelectObject('first')).toBe('started');
expect(h.store.dispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'setCanvasSelectedLayer' }));
+ const memory = { bookmarkedLayerId: 'first', previousLayerId: 'second' };
+ h.engine.interaction.set('layerQuickSwitch', memory);
expect(getCanvasOperations(h.engine).startSelectObject('second')).toBe('started');
+ expect(h.engine.interaction.get('layerQuickSwitch')).toEqual(memory);
expect(h.store.dispatch).toHaveBeenCalledWith({ id: 'second', type: 'setCanvasSelectedLayer' });
h.engine.lifecycle.dispose();
});
@@ -18929,6 +18950,162 @@ describe('floating selection lifecycle', () => {
});
});
+describe('layer quick-switch memory', () => {
+ const pressQuickSwitch = (engine: CanvasEngine, mutationPort: CanvasProjectMutationPort): void => {
+ const document = engine.document.getDocument()!;
+ executeCanvasHotkeyCommand('canvas.quickSwitch', {
+ document,
+ engine,
+ dispatch: (mutation) => mutationPort.dispatch(mutation, 'user'),
+ selectedLayerIds: document.selectedLayerId ? [document.selectedLayerId] : [],
+ hasStagingSlots: false,
+ hasSelectedStagedCandidate: false,
+ isInteractionLocked: false,
+ copySelection: vi.fn(),
+ swapActiveColors: vi.fn(),
+ resetActiveColors: vi.fn(),
+ pasteFromClipboard: vi.fn(),
+ notifyLayerDuplicateFailed: vi.fn(),
+ reportStructuralCommit: vi.fn(),
+ reportPreparedCommit: vi.fn(),
+ reportLayerOperation: vi.fn(),
+ t: (key) => key,
+ });
+ };
+ it.each(['external repair', 'engine removal'] as const)('keeps a surviving previous layer after %s', (removal) => {
+ const document = {
+ ...makeDoc(),
+ stacks: stacksFrom([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')]),
+ selectedLayerId: 'a',
+ };
+ const { setDocument, store } = createReactiveStore(document);
+ const mutationPort = createTestMutationPort(store, 'p1');
+ const engine = createCanvasEngine({
+ mutationPort,
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ setDocument({ ...document, selectedLayerId: 'b' });
+ if (removal === 'external repair') {
+ setDocument({ ...document, stacks: stacksFrom([rasterLayer('a'), rasterLayer('c')]), selectedLayerId: 'c' });
+ } else {
+ const edit = engine.document.model()!.prepare({ type: 'remove', ids: ['b'] });
+ if (edit.status !== 'prepared') {
+ throw new Error('Expected prepared removal');
+ }
+ expect(engine.layers.commitPrepared('Delete layer', edit.edit).status).toBe('committed');
+ }
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('c');
+ const history = engine.history.getEntries();
+ pressQuickSwitch(engine, mutationPort);
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('a');
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('c');
+ pressQuickSwitch(engine, mutationPort);
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('c');
+ expect(engine.history.getEntries()).toEqual(history);
+ engine.lifecycle.dispose();
+ });
+
+ it('returns from a bookmark to the automatically selected new text layer', () => {
+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('a'), rasterLayer('b')]), selectedLayerId: 'a' };
+ const { setDocument, store } = createReactiveStore(document);
+ const mutationPort = createTestMutationPort(store, 'p1');
+ const engine = createCanvasEngine({
+ mutationPort,
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ setDocument({ ...document, selectedLayerId: 'b' });
+ engine.layers.openTextCreate({ x: 10, y: 20 });
+ engine.layers.commitTextEdit('Text');
+ const textId = engine.document.getDocument()!.selectedLayerId!;
+ expect(textId).not.toBe('a');
+ expect(textId).not.toBe('b');
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ engine.interaction.set('layerQuickSwitch', {
+ ...engine.interaction.get('layerQuickSwitch'),
+ bookmarkedLayerId: 'a',
+ });
+ const history = engine.history.getEntries();
+ pressQuickSwitch(engine, mutationPort);
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('a');
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe(textId);
+ pressQuickSwitch(engine, mutationPort);
+ expect(engine.document.getDocument()?.selectedLayerId).toBe(textId);
+ expect(engine.history.getEntries()).toEqual(history);
+ engine.lifecycle.dispose();
+ });
+
+ it('ignores the temporary paint layer and its cancellation rollback', () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const document = {
+ ...makeDoc(),
+ stacks: stacksFrom([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')]),
+ selectedLayerId: 'a',
+ };
+ const { setDocument, store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ setDocument({ ...document, selectedLayerId: 'b' });
+ const overlay = createInputCanvas();
+ engine.surface.attach(createInputCanvas().element, overlay.element);
+ engine.tools.setTool('brush');
+ overlay.fire('pointerdown', pointerAt(20, 20));
+ expect(engine.document.getDocument()?.selectedLayerId).not.toBe('b');
+ engine.tools.setTool('move');
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('b');
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ expect(engine.history.getEntries().past).toEqual([]);
+ engine.lifecycle.dispose();
+ });
+
+ it('remembers the previously selected layer across selection changes, keeping it through a deselect', () => {
+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('a'), rasterLayer('b')]), selectedLayerId: 'a' };
+ const { setDocument, store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect(engine.interaction.get('layerQuickSwitch')).toEqual({ bookmarkedLayerId: null, previousLayerId: null });
+
+ setDocument({ ...document, selectedLayerId: 'b' });
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ setDocument({ ...document, selectedLayerId: null });
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ setDocument({ ...document, selectedLayerId: 'b' });
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('a');
+ // A different explicit choice after deselect still returns to the last non-null selection.
+ setDocument({ ...document, selectedLayerId: null });
+ setDocument({ ...document, selectedLayerId: 'a' });
+ expect(engine.interaction.get('layerQuickSwitch').previousLayerId).toBe('b');
+
+ // The bookmark is caller-owned and survives selection changes.
+ engine.interaction.set('layerQuickSwitch', {
+ ...engine.interaction.get('layerQuickSwitch'),
+ bookmarkedLayerId: 'b',
+ });
+ setDocument({ ...document, selectedLayerId: 'b' });
+ expect(engine.interaction.get('layerQuickSwitch')).toEqual({ bookmarkedLayerId: 'b', previousLayerId: 'a' });
+ expect(engine.history.getEntries().past).toEqual([]);
+ engine.lifecycle.dispose();
+ });
+});
+
describe('document epoch', () => {
it('advances on each document change, once the engine model already reflects it', () => {
const { setDocument, store } = createReactiveStore(paintDoc());
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index fc80ab2176..a20b48b537 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -125,7 +125,12 @@ import {
createDocumentModel,
type CanvasDocumentModel,
} from '@workbench/canvas-engine/document-model/documentModel';
-import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
+import {
+ getDocumentIndex,
+ getDocumentLayer,
+ getDocumentLeaves,
+ getDocumentNode,
+} from '@workbench/canvas-engine/document/documentIndex';
import {
createEngineStores,
type EngineStores,
@@ -375,6 +380,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
historyEpoch: stores.historyEpoch,
invertBrushSizeScroll: stores.invertBrushSizeScroll,
lassoOptions: stores.lassoOptions,
+ layerQuickSwitch: stores.layerQuickSwitch,
marqueeOptions: stores.marqueeOptions,
layerPixelEpoch: stores.layerPixelEpoch,
documentEpoch: stores.documentEpoch,
@@ -650,8 +656,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
});
const history = historyController.history;
const unsubscribeHistoryEpoch = history.subscribe(() => stores.historyEpoch.set(stores.historyEpoch.get() + 1));
- const dispatchCanvasMutation = (action: CanvasProjectMutation, origin: 'system' | 'user' = 'user'): boolean =>
- mutationPort.dispatch(action, origin);
+ let engineMutationDepth = 0;
+ const dispatchCanvasMutation = (action: CanvasProjectMutation, origin: 'system' | 'user' = 'user'): boolean => {
+ // Engine edits can select temporary layers, replay selections, or repair them on rollback. They are not
+ // explicit layer navigation, even when the edit itself is user-originated.
+ engineMutationDepth += 1;
+ try {
+ return mutationPort.dispatch(action, origin);
+ } finally {
+ engineMutationDepth -= 1;
+ }
+ };
// Direct pixel writes do not replace the reducer canvas object. Snapshot
// freshness therefore also binds to this engine-local direct-pixel epoch.
let directPixelEpoch = 0;
@@ -1446,6 +1461,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// ---- Document mirror ----------------------------------------------------
+ /** Actual last non-null selection, retained across deselect/reselect and updated by engine selections too. */
+ let lastSelectedLayerId: string | null = null;
const mirror: DocumentMirror = createDocumentMirror(mutationPort, {
onDocumentChanged: () => stores.documentEpoch.set(stores.documentEpoch.get() + 1),
// Bbox changes need only overlay redraw unless a bbox-relative staged preview must move in the composite.
@@ -1589,6 +1606,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
*/
onSelectionChanged: (selectedLayerId) => {
const cleanup = createCleanupAccumulator();
+ if (selectedLayerId !== null && selectedLayerId !== lastSelectedLayerId) {
+ // A deletion/merge may choose a replacement after removing the current layer. Keep the surviving
+ // previous choice instead of replacing it with the removed id.
+ if (
+ engineMutationDepth === 0 &&
+ lastSelectedLayerId !== null &&
+ getDocumentNode(mirror.getDocument(), lastSelectedLayerId)
+ ) {
+ stores.layerQuickSwitch.set({ ...stores.layerQuickSwitch.get(), previousLayerId: lastSelectedLayerId });
+ }
+ // Internal selections do not change the return target, but the next explicit switch must return
+ // to the layer actually being left (including a deletion fallback or an automatically selected layer).
+ lastSelectedLayerId = selectedLayerId;
+ }
// A float belongs to exactly one layer; selecting another banks it rather
// than leaving pixels in flight over a layer the user is no longer on.
cleanup.run(() => floatingSelection.commit());
@@ -1604,6 +1635,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
},
onStagingChanged: () => scheduler.invalidate({ overlay: true }),
});
+ // The mirror seeds silently from the current state, so the memory starts from that selection too.
+ lastSelectedLayerId = mirror.getDocument()?.selectedLayerId ?? null;
let fontSourceStacks: CanvasDocumentContractV3['stacks'] | null = null;
let documentFontSources: CanvasTextSource[] = [];
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 5ce265a9a4..78890b9850 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -48,6 +48,19 @@ export interface EraserOptions {
opacity: number;
/** Edge hardness in [0, 1]: 1 is a crisp edge, lower feathers the silhouette. */
hardness: number;
+ /** Whether pen pressure modulates the eraser width; pressure never modulates erase strength. */
+ pressureAffectsWidth: boolean;
+}
+
+/**
+ * Quick-switch memory (Q): the layer a user bookmarked from its menu, and the layer selected before the current
+ * one. Transient like tool options: it lives with the engine, never in the project.
+ */
+export interface LayerQuickSwitchState {
+ /** Set from the layer menu; a stale id (the layer was removed) is ignored by readers. */
+ bookmarkedLayerId: string | null;
+ /** Engine-maintained: the layer left by the last explicit switch; internal edits and deselection preserve it. */
+ previousLayerId: string | null;
}
/** Lasso (selection) tool options: how the path is drawn, and the op it applies. */
@@ -249,6 +262,7 @@ export const DEFAULT_BRUSH_OPTIONS: Readonly<BrushOptions> = {
export const DEFAULT_ERASER_OPTIONS: Readonly<EraserOptions> = {
hardness: 1,
opacity: 1,
+ pressureAffectsWidth: true,
size: 50,
};
@@ -439,8 +453,10 @@ export interface EngineStores {
brushOptions: ScalarStore<BrushOptions>;
/** One-way foreground/background mirror for gesture-start reads; the engine never writes it. */
colorPair: ScalarStore<ActiveColorPairState>;
- /** Eraser tool options (size / opacity). */
+ /** Eraser tool options (size / opacity / pressure width). */
eraserOptions: ScalarStore<EraserOptions>;
+ /** The Q quick-switch memory: the bookmarked layer and the previously selected one. */
+ layerQuickSwitch: ScalarStore<LayerQuickSwitchState>;
/** Whether the engine-owned canvas history has an entry to undo. */
canUndo: ScalarStore<boolean>;
/** Whether the engine-owned canvas history has an entry to redo. */
@@ -523,7 +539,13 @@ const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>
a.pressureAffectsOpacity === b.pressureAffectsOpacity;
const eraserOptionsEqual = (a: EraserOptions, b: EraserOptions): boolean =>
- a.size === b.size && a.opacity === b.opacity && a.hardness === b.hardness;
+ a.size === b.size &&
+ a.opacity === b.opacity &&
+ a.hardness === b.hardness &&
+ a.pressureAffectsWidth === b.pressureAffectsWidth;
+
+const layerQuickSwitchEqual = (a: LayerQuickSwitchState, b: LayerQuickSwitchState): boolean =>
+ a.bookmarkedLayerId === b.bookmarkedLayerId && a.previousLayerId === b.previousLayerId;
const checkerColorsEqual = (a: CheckerColors, b: CheckerColors): boolean => a.a === b.a && a.b === b.b;
@@ -678,6 +700,10 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
hasFloatingSelection: createScalarStore<boolean>(false),
hasSelection: createScalarStore<boolean>(false),
invertBrushSizeScroll: createScalarStore<boolean>(false),
+ layerQuickSwitch: createScalarStore<LayerQuickSwitchState>(
+ { bookmarkedLayerId: null, previousLayerId: null },
+ layerQuickSwitchEqual
+ ),
gradientOptions: createScalarStore<GradientToolOptions>(
{ ...DEFAULT_GRADIENT_OPTIONS, stops: DEFAULT_GRADIENT_OPTIONS.stops.map((s) => ({ ...s })) },
gradientOptionsEqual
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
index ab23840356..36e779a6f2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
@@ -1,8 +1,9 @@
/**
- * Eraser binds shared paint gestures to destination-out with eraser size/opacity, no color and pressure thinning
- * zero. Gesture state is per engine.
+ * Eraser binds shared paint gestures to destination-out with eraser size/opacity and no color. Pen pressure may thin
+ * the width like the brush; it never modulates erase strength. Gesture state is per engine.
*/
+import { PRESSURE_THINNING } from '@workbench/canvas-engine/tools/paintConstants';
import { createPaintTool } from '@workbench/canvas-engine/tools/paintTool';
import type { Tool } from './tool';
@@ -17,5 +18,5 @@ export const createEraserTool = (): Tool =>
opacity: (ctx) => ctx.stores.eraserOptions.get().opacity,
pressureOpacity: () => false,
size: (ctx) => ctx.stores.eraserOptions.get().size,
- thinning: () => 0,
+ thinning: (ctx) => (ctx.stores.eraserOptions.get().pressureAffectsWidth ? PRESSURE_THINNING : 0),
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
index d341d0784e..dc71e212ab 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
@@ -305,6 +305,29 @@ describe('eraser tool', () => {
expect(lastCompositeOp(cacheSurface(h, 'paint1'))).toBe('destination-out');
});
+ /** The committed width of one horizontal eraser stroke drawn at a constant pen pressure. */
+ const erasedHeight = (pressure: number, pressureAffectsWidth: boolean): number => {
+ const h = createHarness(makeDoc([paintLayer('paint1')], 'paint1'));
+ h.ctx.stores.eraserOptions.set({ ...h.ctx.stores.eraserOptions.get(), pressureAffectsWidth, size: 20 });
+ const eraser = createEraserTool();
+ const input = (x: number) => ({ ...pointer(x, 50, { pressure }), pointerType: 'pen' as const });
+
+ down(eraser, h.ctx, input(20));
+ move(eraser, h.ctx, input(60), [input(40), input(60)]);
+ up(eraser, h.ctx, input(80));
+
+ expect(h.strokes).toHaveLength(1);
+ return h.strokes[0]!.dirtyRect.height;
+ };
+
+ it('thins the stroke with pen pressure when width dynamics are on', () => {
+ expect(erasedHeight(0.1, true)).toBeLessThan(erasedHeight(1, true));
+ });
+
+ it('keeps a constant width regardless of pressure when width dynamics are off', () => {
+ expect(erasedHeight(0.1, false)).toBe(erasedHeight(1, false));
+ });
+
it('edits a selected image layer through a materializing pixel transaction', () => {
const transaction = controlTransaction('img1');
const h = createHarness(makeDoc([imageLayer('img1')], 'img1'), transaction);
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 2b90fb2873..125126e078 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -54,6 +54,7 @@ const implemented = new Set([
'canvas.saveBboxToGallery',
'canvas.saveToGallery',
'canvas.prevEntity',
+ 'canvas.quickSwitch',
'canvas.redo',
'canvas.setFillColorsToDefault',
'canvas.toggleFillColor',
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
index 05da1c0be2..0881156012 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
@@ -229,12 +229,24 @@ describe('layer panel state store', () => {
});
describe('revealing an external primary', () => {
+ it('keeps a filter when the selected layer or a selected group descendant matches', () => {
+ const index = indexStacks(
+ stacksFrom([groupContract('g', [layerContract('a', 'raster', { name: 'Sky' })]), layerContract('b')])
+ );
+ const state = createLayerPanelState('project', 'b', { filter: ' sky ' });
+ expect(reconcileLayerPanelState(state, 'project', index, 'a').filter).toBe(' sky ');
+ expect(reconcileLayerPanelState(state, 'project', index, 'g').filter).toBe(' sky ');
+ });
+
it('expands every group above a primary that arrived from outside the panel', () => {
const index = indexStacks(
stacksFrom([groupContract('g', [groupContract('h', [layerContract('a')])]), layerContract('b')])
);
- expect(reconcileLayerPanelState(createLayerPanelState('project', 'b'), 'project', index, 'a')).toMatchObject({
+ expect(
+ reconcileLayerPanelState(createLayerPanelState('project', 'b', { filter: 'b' }), 'project', index, 'a')
+ ).toMatchObject({
expandedGroupIds: ['g', 'h'],
+ filter: '',
primaryId: 'a',
selectedIds: ['a'],
});
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
index 01e71e23b0..c58b1e48e0 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
@@ -212,8 +212,20 @@ export const reconcileLayerPanelState = (
}
// The new primary is revealed: its stack opens and every group on its path expands.
const carry = carryOf(state);
+ const filter = carry.filter.trim().toLocaleLowerCase();
+ // A group is also visible when a matching descendant keeps its ancestor path in the filtered tree.
+ const filterHidesPrimary =
+ primary &&
+ filter !== '' &&
+ !index.nodes.some(
+ (entry) =>
+ (entry.node.id === validPrimaryId || entry.path.includes(validPrimaryId!)) &&
+ entry.node.name.toLocaleLowerCase().includes(filter)
+ );
return createLayerPanelState(projectId, validPrimaryId, {
...carry,
+ // An external navigation must reveal its target even when a name filter hid it.
+ filter: filterHidesPrimary ? '' : carry.filter,
collapsedChildLayerIds: carry.collapsedChildLayerIds.filter((id) => index.byId.has(id)),
collapsedStacks: primary
? carry.collapsedStacks.filter((stack) => stack !== primary.stack)
diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx
index fc415dc6e5..c9d17e26cf 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx
@@ -214,6 +214,7 @@ describe('gallery maintenance in Data & workspace settings', () => {
onContextMenu={() => {}}
onFocusLost={() => {}}
onOpen={() => {}}
+ onOpenInNewTab={null}
onToggleStarred={() => {}}
/>
<GalleryThumbnailCell
@@ -231,6 +232,7 @@ describe('gallery maintenance in Data & workspace settings', () => {
onContextMenu={() => {}}
onFocusLost={() => {}}
onOpen={() => {}}
+ onOpenInNewTab={null}
onToggleStarred={() => {}}
/>
</DndContext>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index b98d892393..d8a0a47980 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -441,6 +441,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
// then intercepted above to cycle staging slots while any slot exists.
['canvas.prevEntity', t('widgets.canvas.commands.previousEntity'), ['alt+[']],
['canvas.nextEntity', t('widgets.canvas.commands.nextEntity'), ['alt+]']],
+ ['canvas.quickSwitch', t('widgets.canvas.commands.quickSwitch'), ['q']],
['canvas.deleteSelected', t('widgets.canvas.commands.deleteSelected'), ['delete', 'backspace']],
['canvas.resetSelected', t('widgets.canvas.commands.resetSelected'), ['shift+c']],
['canvas.undo', t('widgets.canvas.commands.undo'), ['mod+z']],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
index f1aadf756e..777d98baf1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -46,6 +46,7 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
activeTool: 'brush',
hasSelection: false,
lassoOptions: { shape: 'freehand' },
+ layerQuickSwitch: { bookmarkedLayerId: null, previousLayerId: null },
marqueeOptions: { kind: 'rect' },
...interaction,
};
@@ -155,11 +156,86 @@ describe('staging precedence', () => {
expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
});
+});
+
+describe('layer navigation without staging', () => {
+ const select = (id: string): CanvasProjectMutation => ({ id, type: 'setCanvasSelectedLayer' });
+ // Document order puts the control stack above the raster stack: b, a, c.
+ const layers = [rasterLayer('a'), createControlLayer('Control', 'b'), rasterLayer('c')];
+
+ it.each([
+ ['canvas.nextEntity', 'a', 'c'],
+ ['canvas.nextEntity', 'c', 'b'],
+ ['canvas.prevEntity', 'b', 'c'],
+ ['canvas.prevEntity', 'a', 'b'],
+ ] as const)('%s from %s selects %s, wrapping across every layer kind in layer order', (commandId, from, to) => {
+ const engine = run(commandId, { document: documentOf(layers, from), selectedLayerIds: [from] });
+ expect(dispatch).toHaveBeenCalledExactlyOnceWith(select(to));
+ expect(engine.layers.nudgeSelectedLayer).not.toHaveBeenCalled();
+ });
- it('prevEntity does nothing at all without staging slots', () => {
- const engine = run('canvas.prevEntity');
+ it('starts from either end when nothing is selected, and does nothing without layers', () => {
+ run('canvas.nextEntity', { document: documentOf(layers, null), selectedLayerIds: [] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('b'));
+ run('canvas.prevEntity', { document: documentOf(layers, null), selectedLayerIds: [] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('c'));
+ dispatch.mockClear();
+ run('canvas.nextEntity', { document: documentOf([], null), selectedLayerIds: [] });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('enters a selected group at its first leaf and leaves it upward, skipping an empty group to the ends', () => {
+ const grouped = {
+ ...documentOf([], 'g'),
+ stacks: stacksFrom([
+ rasterLayer('a'),
+ groupContract('g', [rasterLayer('b'), rasterLayer('c')]),
+ rasterLayer('d'),
+ ]),
+ };
+ run('canvas.nextEntity', { document: grouped, selectedLayerIds: ['g'] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('b'));
+ run('canvas.prevEntity', { document: grouped, selectedLayerIds: ['g'] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('a'));
+
+ const empty = {
+ ...documentOf([], 'g'),
+ stacks: stacksFrom([rasterLayer('a'), groupContract('g'), rasterLayer('d')]),
+ };
+ run('canvas.nextEntity', { document: empty, selectedLayerIds: ['g'] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('a'));
+ run('canvas.prevEntity', { document: empty, selectedLayerIds: ['g'] });
+ expect(dispatch).toHaveBeenLastCalledWith(select('d'));
+ });
+
+ it('stays put on the only layer and while interaction is locked', () => {
+ run('canvas.nextEntity', { document: documentOf([rasterLayer('a')], 'a') });
+ run('canvas.prevEntity', { document: documentOf(layers, 'a'), isInteractionLocked: true });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('quick switch prefers the bookmark, falls back to the previous selection, and skips missing layers', () => {
+ const quickSwitch = (bookmarkedLayerId: string | null, previousLayerId: string | null, selected: string) =>
+ run('canvas.quickSwitch', {
+ document: documentOf(layers, selected),
+ engine: createEngine({ layerQuickSwitch: { bookmarkedLayerId, previousLayerId } }),
+ selectedLayerIds: [selected],
+ });
+
+ quickSwitch('c', 'b', 'a');
+ expect(dispatch).toHaveBeenLastCalledWith(select('c'));
+ // On the bookmark already: back to the previous layer.
+ quickSwitch('c', 'a', 'c');
+ expect(dispatch).toHaveBeenLastCalledWith(select('a'));
+ // A bookmark whose layer was removed is skipped, not an empty selection.
+ quickSwitch('gone', 'b', 'a');
+ expect(dispatch).toHaveBeenLastCalledWith(select('b'));
+ dispatch.mockClear();
+ quickSwitch(null, null, 'a');
+ quickSwitch(null, 'a', 'a');
+ quickSwitch('gone', 'gone', 'a');
+ executeCanvasHotkeyCommand('canvas.quickSwitch', contextOf({ engine: null }));
expect(dispatch).not.toHaveBeenCalled();
- expect(engine.tools.setTool).not.toHaveBeenCalled();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index d7c8a0db9a..835f17437f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -47,6 +47,44 @@ const REORDER_KINDS: Record<string, LayerStackMoveKind> = {
'canvas.layerToFront': 'front',
};
+/**
+ * The layer `steps` away from the selection in layer order, wrapping. A selected group stands at its first
+ * descendant leaf: next enters the group there, previous leaves it upward. None selected starts from either end.
+ */
+const cycleLayerId = (document: CanvasDocumentContractV3, steps: 1 | -1): string | null => {
+ const { byId, leaves } = getDocumentIndex(document);
+ if (leaves.length === 0) {
+ return null;
+ }
+ const { selectedLayerId } = document;
+ const selected = selectedLayerId ? byId.get(selectedLayerId) : undefined;
+ if (selected && isGroupNode(selected.node)) {
+ const first = leaves.findIndex((leaf) => byId.get(leaf.id)?.path.includes(selected.node.id));
+ if (first >= 0) {
+ return leaves[steps === 1 ? first : (first - 1 + leaves.length) % leaves.length]!.id;
+ }
+ }
+ const current = leaves.findIndex((leaf) => leaf.id === selectedLayerId);
+ if (current < 0) {
+ return leaves[steps === 1 ? 0 : leaves.length - 1]!.id;
+ }
+ return leaves[(current + steps + leaves.length) % leaves.length]!.id;
+};
+
+/**
+ * Q: the bookmarked layer when one is set and not already selected, else the previously selected layer. Ids whose
+ * layer no longer exists are skipped rather than cleared, so a removed bookmark never selects nothing.
+ */
+const quickSwitchLayerId = (document: CanvasDocumentContractV3, engine: CanvasEngine): string | null => {
+ const { byId } = getDocumentIndex(document);
+ const { bookmarkedLayerId, previousLayerId } = engine.interaction.get('layerQuickSwitch');
+ const exists = (id: string | null): id is string => id !== null && byId.has(id);
+ if (exists(bookmarkedLayerId) && bookmarkedLayerId !== document.selectedLayerId) {
+ return bookmarkedLayerId;
+ }
+ return exists(previousLayerId) && previousLayerId !== document.selectedLayerId ? previousLayerId : null;
+};
+
/** Pass hotkey dependencies explicitly so dispatch can be tested without mounting React. */
export interface CanvasHotkeyContext {
readonly document: CanvasDocumentContractV3;
@@ -121,6 +159,18 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
return;
}
+ // Without staged results, alt+[ / alt+] walk the layers themselves; Q jumps to the bookmark or back.
+ if (commandId === 'canvas.prevEntity' || commandId === 'canvas.nextEntity' || commandId === 'canvas.quickSwitch') {
+ const target =
+ commandId === 'canvas.quickSwitch'
+ ? engine && quickSwitchLayerId(document, engine)
+ : cycleLayerId(document, commandId === 'canvas.nextEntity' ? 1 : -1);
+ if (target !== null && target !== selectedLayerId) {
+ dispatch({ id: target, type: 'setCanvasSelectedLayer' });
+ }
+ return;
+ }
+
// Arrow-key nudge: engine owns the bounds/lock logic (no-op with no/locked selection).
const nudge = NUDGE_DELTAS[commandId];
if (nudge) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index 087ca4421c..0629fcae78 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -8,6 +8,7 @@ import type {
EraserOptions,
GradientToolOptions,
LassoToolOptions,
+ LayerQuickSwitchState,
MarqueeToolOptions,
ShapeToolOptions,
TextEditSession,
@@ -25,6 +26,8 @@ import {
} from '@workbench/canvas-operations/api';
import { useCallback, useSyncExternalStore } from 'react';
+const EMPTY_LAYER_QUICK_SWITCH: LayerQuickSwitchState = { bookmarkedLayerId: null, previousLayerId: null };
+
/** Subscribes the calling component to a single engine scalar store. */
const useCanvasInteractionState = <K extends keyof CanvasInteractionState>(
engine: CanvasCoreStoreCapability,
@@ -179,6 +182,19 @@ export const useBrushOptions = (engine: CanvasCoreStoreCapability): BrushOptions
export const useEraserOptions = (engine: CanvasCoreStoreCapability): EraserOptions =>
useCanvasInteractionState(engine, 'eraserOptions');
+/** The Q quick-switch memory; a null engine reads as empty without subscribing. */
+export const useLayerQuickSwitch = (engine: CanvasCoreStoreCapability | null): LayerQuickSwitchState => {
+ const subscribe = useCallback(
+ (listener: () => void) => engine?.interaction.subscribe('layerQuickSwitch', listener) ?? (() => undefined),
+ [engine]
+ );
+ const getSnapshot = useCallback(
+ () => engine?.interaction.get('layerQuickSwitch') ?? EMPTY_LAYER_QUICK_SWITCH,
+ [engine]
+ );
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+};
+
/** The bbox tool's current options (aspect lock / ratio). Write through `engine.interaction.set`. */
export const useBboxOptions = (engine: CanvasCoreStoreCapability): BboxToolOptions =>
useCanvasInteractionState(engine, 'bboxOptions');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx
index 6f5eb573bb..ae5af27749 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/paintForm.tsx
@@ -103,49 +103,57 @@ const PaintColorSettings = ({ engine }: ToolFormProps) => {
);
};
-/** Width and opacity are separate pressure responses (opacity also costs a scratch refill per frame). */
+/**
+ * Width and opacity are separate pressure responses (opacity also costs a scratch refill per frame). The eraser
+ * exposes width only: pressure never modulates erase strength.
+ */
const PaintDynamicsSettings = ({ engine }: ToolFormProps) => {
const { t } = useTranslation();
+ const { isEraser, options, set } = usePaintOptions(engine);
const brush = useBrushOptions(engine);
- const set = useCallback(
- (changes: Partial<typeof brush>) => engine.interaction.set('brushOptions', { ...brush, ...changes }),
- [brush, engine]
- );
const onWidth = useCallback((pressureAffectsWidth: boolean) => set({ pressureAffectsWidth }), [set]);
- const onOpacity = useCallback((pressureAffectsOpacity: boolean) => set({ pressureAffectsOpacity }), [set]);
+ const onOpacity = useCallback(
+ (pressureAffectsOpacity: boolean) =>
+ engine.interaction.set('brushOptions', { ...engine.interaction.get('brushOptions'), pressureAffectsOpacity }),
+ [engine]
+ );
return (
<>
<PropertySwitchRow
- checked={brush.pressureAffectsWidth}
+ checked={options.pressureAffectsWidth}
label={t('widgets.canvas.toolOptions.pressureAffectsWidth')}
onCheckedChange={onWidth}
/>
- <PropertySwitchRow
- checked={brush.pressureAffectsOpacity}
- label={t('widgets.canvas.toolOptions.pressureAffectsOpacity')}
- onCheckedChange={onOpacity}
- />
+ {isEraser ? null : (
+ <PropertySwitchRow
+ checked={brush.pressureAffectsOpacity}
+ label={t('widgets.canvas.toolOptions.pressureAffectsOpacity')}
+ onCheckedChange={onOpacity}
+ />
+ )}
</>
);
};
-/** Shared literal: the same object in both forms, so id, type and DOM survive the switch. */
+/** Shared literals: the same objects in both forms, so id, type and DOM survive the switch. */
const STROKE_GROUP: ToolPropertyGroup = {
body: PaintStrokeSettings,
id: 'paint-stroke',
labelKey: 'widgets.properties.groups.stroke',
};
+const DYNAMICS_GROUP: ToolPropertyGroup = {
+ body: PaintDynamicsSettings,
+ collapsible: 'collapsed',
+ id: 'paint-dynamics',
+ labelKey: 'widgets.properties.groups.dynamics',
+};
+
export const brushForm: ToolPropertyForm = {
groups: [
STROKE_GROUP,
{ body: PaintColorSettings, id: 'paint-color', labelKey: 'widgets.properties.rows.color' },
- {
- body: PaintDynamicsSettings,
- collapsible: 'collapsed',
- id: 'paint-dynamics',
- labelKey: 'widgets.properties.groups.dynamics',
- },
+ DYNAMICS_GROUP,
],
id: 'brush',
paintsLeaf: true,
@@ -153,7 +161,7 @@ export const brushForm: ToolPropertyForm = {
};
export const eraserForm: ToolPropertyForm = {
- groups: [STROKE_GROUP],
+ groups: [STROKE_GROUP, DYNAMICS_GROUP],
id: 'eraser',
paintsLeaf: true,
preview: PaintPreview,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index b290e4f0b7..e08bd8e905 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -38,7 +38,11 @@ import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
-import { useCanvasDocumentEditingLocked, useCanvasEngineRead } from '@workbench/widgets/canvas/engineStoreHooks';
+import {
+ useCanvasDocumentEditingLocked,
+ useCanvasEngineRead,
+ useLayerQuickSwitch,
+} from '@workbench/widgets/canvas/engineStoreHooks';
import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
@@ -300,12 +304,14 @@ const LayerMenu = ({
);
const hiddenByAncestor =
(lookupDocumentNodeState(document, layer.id)?.documentHidden ?? false) && !isNodeHidden(layer);
+ const isQuickSwitchBookmark = useLayerQuickSwitch(engine).bookmarkedLayerId === layer.id;
const actionState = useMemo<LayerContextActionState>(
() => ({
canDeleteSelection,
canGroupSelection: canGroup,
canMergeSelection: canMerge,
hiddenByAncestor,
+ isQuickSwitchBookmark,
canRunWorkflow: workflowAvailability.canRunWorkflow,
document,
hasEngine: engine !== null,
@@ -319,6 +325,7 @@ const LayerMenu = ({
[
base,
hiddenByAncestor,
+ isQuickSwitchBookmark,
canDeleteSelection,
canGroup,
canMerge,
@@ -832,6 +839,16 @@ const LayerMenu = ({
);
}, [base, commitPrepared, layer, t]);
+ const handleToggleQuickSwitchBookmark = useCallback(() => {
+ if (engine) {
+ const quickSwitch = engine.interaction.get('layerQuickSwitch');
+ engine.interaction.set('layerQuickSwitch', {
+ ...quickSwitch,
+ bookmarkedLayerId: quickSwitch.bookmarkedLayerId === layer.id ? null : layer.id,
+ });
+ }
+ }, [engine, layer.id]);
+
const effects = useMemo<LayerContextActionEffects>(
() => ({
addAdjustment: handleAddAdjustment,
@@ -871,6 +888,7 @@ const LayerMenu = ({
saveToAssets: handleSaveToAssets,
setColorLabel: handleSetColorLabel,
toggleLock: handleToggleLock,
+ toggleQuickSwitchBookmark: handleToggleQuickSwitchBookmark,
toggleHidden: handleToggleHidden,
toggleVisibility: handleToggleVisibility,
transform: handleTransform,
@@ -899,6 +917,7 @@ const LayerMenu = ({
handleSaveToAssets,
handleSetColorLabel,
handleToggleLock,
+ handleToggleQuickSwitchBookmark,
handleToggleHidden,
handleToggleVisibility,
handleTransform,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
index b8b1e133f0..e6cd9ddd1a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
@@ -74,12 +74,21 @@ const nodes: CanvasNodeContract[] = [
layerContract('layer', 'raster', { name: 'Layer' }),
groupContract('group', [layerContract('child', 'raster', { name: 'Child' })], { name: 'Group' }),
];
+const quickSwitch = { bookmarkedLayerId: null as string | null, previousLayerId: 'child' as string | null };
const engine = {
document: {
model: () => createDocumentModel(mocks.project.canvas.document, { editRevision: 0, projectId: PROJECT_ID }),
},
exports: { hasExportableLayerContent: () => true },
- interaction: { get: () => false, subscribe: () => () => undefined },
+ interaction: {
+ get: (key: string) => (key === 'layerQuickSwitch' ? quickSwitch : false),
+ set: (key: string, value: typeof quickSwitch) => {
+ if (key === 'layerQuickSwitch') {
+ Object.assign(quickSwitch, value);
+ }
+ },
+ subscribe: () => () => undefined,
+ },
layers: { commitPrepared: () => ({ status: 'committed' as const }), endStructuralPreview: () => undefined },
projectId: PROJECT_ID,
} as unknown as LayerSurfaceEngine;
@@ -111,6 +120,8 @@ let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
beforeEach(async () => {
+ quickSwitch.bookmarkedLayerId = null;
+ quickSwitch.previousLayerId = 'child';
const initial = { ...createInitialWorkbenchState().projects[0]!, id: PROJECT_ID };
mocks.project = applyCanvasProjectMutation(initial, {
document: { ...createEmptyCanvasDocument(), selectedLayerId: null, stacks: stacksFrom(nodes) },
@@ -272,3 +283,13 @@ it('offers an adjustment every other raster layer and group the model accepts un
await act(() => page.getByRole('menuitem', { name: 'Group', exact: true }).click());
expect(moveChildToLayer).toHaveBeenCalledWith(child, 'group');
});
+
+it('toggles the real bookmark menu handler without changing previous-layer memory', async () => {
+ await act(() => openSurface({ anchor, id: 'layer', kind: 'menu' }));
+ await act(() => page.getByRole('menuitem', { name: /^Bookmark for quick switch/ }).click());
+ expect(quickSwitch).toEqual({ bookmarkedLayerId: 'layer', previousLayerId: 'child' });
+ await expect.poll(openMenu).toBeNull();
+ await act(() => openSurface({ anchor, id: 'layer', kind: 'menu' }));
+ await act(() => page.getByRole('menuitem', { name: /^Remove quick switch bookmark/ }).click());
+ expect(quickSwitch).toEqual({ bookmarkedLayerId: null, previousLayerId: 'child' });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
index 4936de143e..72febccb00 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
@@ -1,5 +1,5 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
-import type { CanvasNodeContract, PreparedDocumentEdit } from '@workbench/canvas-engine/api';
+import type { CanvasEngine, CanvasNodeContract, PreparedDocumentEdit } from '@workbench/canvas-engine/api';
import type { CanvasOperationState } from '@workbench/canvas-operations/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project } from '@workbench/projectContracts';
@@ -28,6 +28,7 @@ import {
toggleLayerStackCollapsed,
useLayerPanelState,
} from '@workbench/layerPanelState';
+import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from '@workbench/widgets/canvas/canvasHotkeyCommands';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { createInstance } from 'i18next';
import { act, useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react';
@@ -616,6 +617,54 @@ describe('LayersTree selection, surfaces and structure', () => {
expect(output('selected-layer')).toBe('third');
});
+ it('reveals a cycled layer through collapsed ancestors and a filter without opening properties', async () => {
+ await renderTree([
+ ...manyLayers(60),
+ groupContract('outer', [groupContract('inner', [layerContract('target', 'raster', { name: 'Target' })])]),
+ ]);
+ await act(() => dispatchExternal({ id: 'l59', type: 'setCanvasSelectedLayer' }));
+ await act(() => {
+ setLayerPanelFilter(PROJECT_ID, 'l59', 'Layer 59');
+ toggleLayerStackCollapsed(PROJECT_ID, 'l59', 'raster');
+ });
+ const ctx: CanvasHotkeyContext = {
+ document: harnessDocument,
+ engine: engine as CanvasEngine,
+ dispatch: (mutation) => {
+ dispatchExternal(mutation);
+ return true;
+ },
+ selectedLayerIds: ['l59'],
+ hasStagingSlots: false,
+ hasSelectedStagedCandidate: false,
+ isInteractionLocked: false,
+ copySelection: vi.fn(),
+ swapActiveColors: vi.fn(),
+ resetActiveColors: vi.fn(),
+ pasteFromClipboard: vi.fn(),
+ notifyLayerDuplicateFailed: vi.fn(),
+ reportStructuralCommit: vi.fn(),
+ reportPreparedCommit: vi.fn(),
+ reportLayerOperation: vi.fn(),
+ t: (key) => key,
+ };
+ await act(() => executeCanvasHotkeyCommand('canvas.nextEntity', ctx));
+ await settle();
+ expect(output('selected-layer')).toBe('target');
+ expect(readLayerPanelState(PROJECT_ID, 'target')).toMatchObject({
+ expandedGroupIds: ['outer', 'inner'],
+ collapsedStacks: [],
+ filter: '',
+ });
+ const row = treeitem('Target');
+ const scroller = host!.querySelector<HTMLElement>('[role="tree"]')!.closest<HTMLElement>('[data-part="viewport"]')!;
+ expect(scroller.scrollTop).toBeGreaterThan(0);
+ expect(row.getBoundingClientRect().top).toBeGreaterThanOrEqual(scroller.getBoundingClientRect().top);
+ expect(row.getBoundingClientRect().bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom);
+ expect(output('surface')).toBe('none');
+ expect(revealRequests).not.toHaveBeenCalled();
+ });
+
it('reveals a primary that changed outside the panel once, even inside a collapsed stack', async () => {
await renderTree([layerContract('c1', 'control', { name: 'Control' }), ...manyLayers(2000)]);
const scroller = host!.querySelector<HTMLElement>('[role="tree"]')!.closest<HTMLElement>('[data-part="viewport"]')!;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 04921871e4..cf7b31915a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -78,6 +78,7 @@ const makeState = (
document,
hasEngine: true,
hiddenByAncestor: false,
+ isQuickSwitchBookmark: false,
hasSupportedContent: true,
hasWorkflowBindings: true,
interactionLocked: false,
@@ -119,6 +120,7 @@ const makeEffects = (): LayerContextActionEffects => ({
setColorLabel: vi.fn(),
saveToAssets: vi.fn(() => Promise.resolve()),
toggleLock: vi.fn(),
+ toggleQuickSwitchBookmark: vi.fn(),
toggleVisibility: vi.fn(),
transform: vi.fn(),
convertTo: vi.fn(),
@@ -498,6 +500,7 @@ describe('getLayerContextActions', () => {
'toggle-visibility',
'toggle-hidden',
'toggle-lock',
+ 'bookmark-quick-switch',
'color-label-red',
'color-label-orange',
'color-label-yellow',
@@ -514,6 +517,31 @@ describe('getLayerContextActions', () => {
expect([...new Set(actions.filter((action) => !action.isDisabled).map((action) => action.id))]).toEqual([]);
});
+ it('offers the quick-switch bookmark on every layer type whenever an engine exists, and toggles its label', () => {
+ for (const type of ['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const) {
+ const layer = makeLayer(type);
+ expect(idsFor(layer)).toContain('bookmark-quick-switch');
+ expect(idsFor(layer, [layer], { hasEngine: false })).not.toContain('bookmark-quick-switch');
+ }
+ const lockedRaster = { ...rasterLayer, isLocked: true };
+ const plain = byId(getLayerContextActions(makeState(lockedRaster)), 'bookmark-quick-switch');
+ expect(plain).toMatchObject({
+ hint: 'q',
+ isDisabled: false,
+ labelKey: 'widgets.layers.actions.bookmarkForQuickSwitch',
+ });
+ const bookmarked = byId(
+ getLayerContextActions(makeState(lockedRaster, { isQuickSwitchBookmark: true })),
+ 'bookmark-quick-switch'
+ );
+ expect(bookmarked.labelKey).toBe('widgets.layers.actions.removeQuickSwitchBookmark');
+ expect(getEnglishTranslation(bookmarked.labelKey)).toBe('Remove quick switch bookmark');
+
+ const effects = makeEffects();
+ bookmarked.handler(makeRuntimeContext(lockedRaster, { effects }));
+ expect(effects.toggleQuickSwitchBookmark).toHaveBeenCalledOnce();
+ });
+
it('offers color labels on every layer type, locked layers included, and routes to the effect', () => {
const locked = { ...makeLayer('raster'), isLocked: true };
const actions = getLayerContextActions(makeState(locked));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 8b4fbb29d3..eb1aa1fbfe 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -24,6 +24,8 @@ import {
ArrowDownToLineIcon,
ArrowUpIcon,
ArrowUpToLineIcon,
+ BookmarkIcon,
+ BookmarkMinusIcon,
CircleIcon,
CircleOffIcon,
CopyIcon,
@@ -103,6 +105,7 @@ export type LayerContextActionId =
| 'toggle-visibility'
| 'toggle-hidden'
| 'toggle-lock'
+ | 'bookmark-quick-switch'
| 'color-label-none'
| `color-label-${CanvasColorLabel}`
| 'delete';
@@ -131,6 +134,8 @@ export interface LayerContextActionState {
canMergeSelection: boolean;
/** A group above the layer hides it on the canvas; the layer's own flag cannot override that. */
hiddenByAncestor: boolean;
+ /** Whether Q jumps to this layer: the engine's transient quick-switch bookmark names it. */
+ isQuickSwitchBookmark: boolean;
}
export interface LayerContextActionEffects {
@@ -163,6 +168,7 @@ export interface LayerContextActionEffects {
toggleVisibility(): void;
toggleHidden(): void;
toggleLock(): void;
+ toggleQuickSwitchBookmark(): void;
delete(): void;
}
@@ -907,6 +913,27 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'state',
supportedLayerTypes: ALL_LAYER_TYPES,
},
+ // The bookmark is a transient engine preference, so a locked layer still takes one.
+ {
+ defaultLabel: 'Bookmark for quick switch',
+ getDefaultLabel: (context) =>
+ context.isQuickSwitchBookmark ? 'Remove quick switch bookmark' : 'Bookmark for quick switch',
+ getIcon: (context) => (context.isQuickSwitchBookmark ? BookmarkMinusIcon : BookmarkIcon),
+ getLabelKey: (context) =>
+ context.isQuickSwitchBookmark
+ ? 'widgets.layers.actions.removeQuickSwitchBookmark'
+ : 'widgets.layers.actions.bookmarkForQuickSwitch',
+ handler: ({ effects }) => effects.toggleQuickSwitchBookmark(),
+ hint: 'q',
+ icon: BookmarkIcon,
+ id: 'bookmark-quick-switch',
+ isEnabled: isInteractionFree,
+ isVisible: (context) => context.hasEngine,
+ labelKey: 'widgets.layers.actions.bookmarkForQuickSwitch',
+ order: 12,
+ section: 'state',
+ supportedLayerTypes: ALL_LAYER_TYPES,
+ },
// Color labels are organizational, so a locked layer still takes one.
...COLOR_LABEL_ITEMS.map((item, index): LayerContextActionDefinition => ({
defaultLabel: item.defaultLabel,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index af03fcb123..4c81e94fda 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -43,6 +43,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
canRunWorkflow: true,
document: makeDocument([...layers]),
hiddenByAncestor: false,
+ isQuickSwitchBookmark: false,
hasEngine: true,
hasSupportedContent: true,
hasWorkflowBindings: true,
@@ -111,6 +112,7 @@ describe('getLayerContextMenuLayout', () => {
items: [
'toggle-visibility',
'toggle-lock',
+ 'bookmark-quick-switch',
'color-label(color-label-red,color-label-orange,color-label-yellow,color-label-green,color-label-blue,color-label-violet,color-label-gray,color-label-none)',
],
presentation: 'list',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index b435a60ba5..09e6c04c2b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -326,6 +326,16 @@ describe('Properties pane', () => {
.element(page.getByRole('checkbox', { exact: true, name: 'Pen pressure affects opacity' }))
.toBeVisible();
+ // The eraser shares the group but exposes width only: pressure never modulates erase strength.
+ await act(() => engine!.tools.setTool('eraser'));
+ await settle();
+ const eraserWidth = page.getByRole('checkbox', { exact: true, name: 'Pen pressure affects width' });
+ await expect.element(eraserWidth).toBeChecked();
+ expect(page.getByRole('checkbox', { exact: true, name: 'Pen pressure affects opacity' }).query()).toBeNull();
+ await act(() => userEvent.click(page.getByText('Pen pressure affects width', { exact: true })));
+ expect(engine!.interaction.get('eraserOptions').pressureAffectsWidth).toBe(false);
+ expect(engine!.interaction.get('brushOptions').pressureAffectsWidth).toBe(true);
+
await act(() => engine!.tools.setTool('view'));
await settle();
expect(page.getByRole('slider', { exact: true, name: 'Brush size' }).query()).toBeNull();