Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(ui): image map cluster selection mode
Lincoln Stein6748adfca88a
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.tsnew file mode 100644index 0000000000..1e3489b4ae--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import type { ImageMapPoint } from './api';++import { collectClusterSelection } from './clusterSelection';+import { buildHighlightedPointsTrace, HIGHLIGHTED_POINTS_TRACE } from './imageMapTraces';++const point = (imageName: string, x: number, y: number, cluster: number): ImageMapPoint => ({+ cluster,+ imageName,+ x,+ y,+});++const POINTS = [+ point('a.png', 0, 0, 0),+ point('b.png', 3, 0, 0),+ point('c.png', 1, 0, 0),+ point('other.png', 50, 50, 1),+ point('noise.png', -50, 50, -1),+];++describe('collectClusterSelection', () => {+ it('returns the clicked cluster ordered by distance from the click', () => {+ expect(collectClusterSelection(POINTS, 'b.png')).toEqual(['b.png', 'c.png', 'a.png']);+ });++ it('returns null for noise points and unknown names', () => {+ expect(collectClusterSelection(POINTS, 'noise.png')).toBeNull();+ expect(collectClusterSelection(POINTS, 'missing.png')).toBeNull();+ });++ it('caps oversized clusters, keeping the nearest members', () => {+ const capped = collectClusterSelection(POINTS, 'a.png', 2);+ expect(capped).toEqual(['a.png', 'c.png']);+ });+});++describe('buildHighlightedPointsTrace', () => {+ it('draws only multi-selections, larger and outlined', () => {+ const single = buildHighlightedPointsTrace(POINTS, new Set(['a.png']));+ expect(single.x).toEqual([]);++ const multi = buildHighlightedPointsTrace(POINTS, new Set(['a.png', 'c.png']));+ expect(multi.name).toBe(HIGHLIGHTED_POINTS_TRACE);+ expect(multi.customdata).toEqual(['a.png', 'c.png']);+ expect(multi.marker.size).toBe(8);+ expect(multi.marker.line).toEqual({ color: '#FFFFFF', width: 1 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.tsnew file mode 100644index 0000000000..cbd1fdcd0a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts@@ -0,0 +1,32 @@+import type { ImageMapPoint } from './api';++/**+ * Cluster-click selection: everything in the clicked point's cluster,+ * ordered by distance from the clicked point (PhotoMapAI's proximity+ * ordering) so gallery multi-selection walks outward from the click.+ */++/** Selection size guard; DBSCAN can put most of a huge gallery in one cluster. */+export const MAX_CLUSTER_SELECTION = 5000;++export const collectClusterSelection = (+ points: ImageMapPoint[],+ clickedImageName: string,+ cap: number = MAX_CLUSTER_SELECTION+): string[] | null => {+ const clicked = points.find((point) => point.imageName === clickedImageName);++ if (!clicked || clicked.cluster < 0) {+ return null;+ }++ return points+ .filter((point) => point.cluster === clicked.cluster)+ .map((point) => ({+ distance: (point.x - clicked.x) ** 2 + (point.y - clicked.y) ** 2,+ name: point.imageName,+ }))+ .sort((left, right) => left.distance - right.distance)+ .slice(0, cap)+ .map((entry) => entry.name);+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsindex 498089522f..48f767c95b 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@ -13,6 +13,7 @@ import { getClusterColor } from './clusterPalette';*/export const ALL_POINTS_TRACE = 'All Points';+export const HIGHLIGHTED_POINTS_TRACE = 'Highlighted Points';export const CURRENT_IMAGE_TRACE = 'Current Image';/** Opacity for DBSCAN noise points (cluster -1); clustered points are solid. */@@ -52,6 +53,36 @@ export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({y: points.map((point) => point.y),});+/**+ * The gallery's multi-selection (e.g. a cluster click), drawn larger with a+ * white outline over the base points. Empty when fewer than two images are+ * selected — a single selection is already marked by the gold target.+ */+export const buildHighlightedPointsTrace = (+ points: ImageMapPoint[],+ selectedNames: ReadonlySet<string>+): ScatterTrace => {+ const selected = selectedNames.size >= 2 ? points.filter((point) => selectedNames.has(point.imageName)) : [];++ return {+ customdata: selected.map((point) => point.imageName),+ // 'skip': highlighted points sit over their base points, which carry the+ // same customdata — hit-testing should fall through to them.+ hoverinfo: 'skip',+ marker: {+ color: selected.map((point) => getClusterColor(point.cluster)),+ line: { color: '#FFFFFF', width: 1 },+ opacity: 1,+ size: 8,+ },+ mode: 'markers',+ name: HIGHLIGHTED_POINTS_TRACE,+ type: 'scattergl',+ x: selected.map((point) => point.x),+ y: selected.map((point) => point.y),+ };+};+/*** The gold target marking the current gallery image. Built empty here; a later* PR restyles it live as the selection changes.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsxnew file mode 100644index 0000000000..35654c45dd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx@@ -0,0 +1,36 @@+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { Icon } from '@chakra-ui/react';+import { IconButton, Tooltip } from '@platform/ui';+import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { GroupIcon } from 'lucide-react';+import { useCallback } from 'react';++/**+ * Header toggle for cluster-selection mode: when on, clicking a map point+ * selects its whole cluster in the gallery instead of just the one image.+ * Persisted in the widget's values, like the gallery's own view settings.+ */+export const ImageMapHeaderActions = (_props: WidgetViewProps) => {+ const { widgets } = useWorkbenchCommands();+ const clickSelectsCluster = useWidgetValuesSelector('image-map', (values) => Boolean(values.clickSelectsCluster));+ const handleToggle = useCallback(+ () => widgets.patchValues('image-map', { clickSelectsCluster: !clickSelectsCluster }),+ [clickSelectsCluster, widgets]+ );++ return (+ <Tooltip content={clickSelectsCluster ? 'Click selects the whole cluster' : 'Click selects one image'}>+ <IconButton+ aria-label="Toggle cluster selection mode"+ aria-pressed={clickSelectsCluster}+ color={clickSelectsCluster ? 'accent.fg' : 'fg.muted'}+ size="2xs"+ variant={clickSelectsCluster ? 'subtle' : 'ghost'}+ onClick={handleToggle}+ >+ <Icon as={GroupIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 734a059dbd..9caa4d2dc5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -3,14 +3,21 @@ import type { AxisRanges } from '@workbench/image-map/imageMapViewport';import type { PlotlyHTMLElement } from 'plotly.js';import { Box } from '@chakra-ui/react';-import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';+import {+ getPersistedSelectedGalleryItemKeys,+ getSelectedGalleryImageFromValues,+ parseGalleryItemKey,+} from '@features/gallery/contracts';import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';+import { collectClusterSelection } from '@workbench/image-map/clusterSelection';import { imageMapStore } from '@workbench/image-map/imageMapStore';import {buildAllPointsTrace,buildCurrentImageTrace,+ buildHighlightedPointsTrace,buildMapLayout,CURRENT_IMAGE_TRACE,+ HIGHLIGHTED_POINTS_TRACE,} from '@workbench/image-map/imageMapTraces';import {computePercentileRanges,@@ -19,11 +26,11 @@ import {rangesToKeepMarkerInView,} from '@workbench/image-map/imageMapViewport';import { getThumbnailUrl } from '@workbench/image-map/thumbnailCache';-import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';+import { shallowEqual, useWidgetValuesSelector } from '@workbench/WorkbenchContext';import Plotly from 'plotly.js-gl2d-dist-min';-import { useEffect, useRef, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';-import { useSelectMapImage } from './useSelectMapImage';+import { useMapSelection } from './useSelectMapImage';/** Suppress the synthetic click plotly fires when a pinch gesture ends. */const PINCH_CLICK_SUPPRESS_MS = 500;@@ -110,14 +117,29 @@ const findTraceIndex = (plot: PlotElement, name: string): number =>* module is lazy-loaded so the plotly bundle stays out of the app's critical* path.*/-const ImageMapPlot = () => {+const ImageMapPlot = ({ clickSelectsCluster = false }: { clickSelectsCluster?: boolean }) => {const containerRef = useRef<HTMLDivElement | null>(null);const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);const selectedImageName = useWidgetValuesSelector('gallery',(values) => getSelectedGalleryImageFromValues(values)?.imageName ?? null);- const selectImage = useSelectMapImage();+ // The persisted selection stores kind-tagged item keys; map points carry+ // bare image names, so parse the keys back down (videos never plot).+ const selectedImageNames = useWidgetValuesSelector(+ 'gallery',+ (values) =>+ getPersistedSelectedGalleryItemKeys(values)+ .map(parseGalleryItemKey)+ .filter((ref) => ref.kind === 'image')+ .map((ref) => ref.name),+ shallowEqual+ );+ const selectedNames = useMemo(() => new Set(selectedImageNames), [selectedImageNames]);+ const { selectCluster, selectImage } = useMapSelection();+ // Bumped after every scene rebuild so the overlay effects (marker,+ // highlight) re-apply onto the fresh, empty overlay traces.+ const [plotRevision, setPlotRevision] = useState(0);const lastPinchAtRef = useRef(0);const lastMapSelectionRef = useRef<{ name: string; at: number } | null>(null);// The initial whole-map fit must happen exactly once per mount, at the@@ -126,12 +148,14 @@ const ImageMapPlot = () => {const initialFitDoneRef = useRef(false);const pointsRef = useRef(points);const selectedImageNameRef = useRef(selectedImageName);+ const clusterModeRef = useRef(clickSelectsCluster);// Declared before the effects below so the refs are fresh when they run.useEffect(() => {pointsRef.current = points;selectedImageNameRef.current = selectedImageName;- }, [points, selectedImageName]);+ clusterModeRef.current = clickSelectsCluster;+ }, [clickSelectsCluster, points, selectedImageName]);const [pendingHoverPreview, setHoverPreview] = useState<HoverPreview | null>(null);const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// Monotonic hover session: a resolution from a previous hover (even of the@@ -154,7 +178,13 @@ const ImageMapPlot = () => {return;}- const traces = [buildAllPointsTrace(points), buildCurrentImageTrace()];+ // Overlay traces (highlight, marker) start empty; the overlay effects+ // below restyle them, so a selection change never rebuilds the scene.+ const traces = [+ buildAllPointsTrace(points),+ buildHighlightedPointsTrace(points, new Set()),+ buildCurrentImageTrace(),+ ];let disposed = false;// Feed the CURRENT view back into react so data refreshes never reset the@@ -197,12 +227,22 @@ const ImageMapPlot = () => {const imageName = event.points?.[0]?.customdata;- if (typeof imageName === 'string') {- // A selection made by clicking the map must not recenter the map- // under the user's cursor; the marker effect checks this. The- // stamp expires so a stale entry (failed hydrate, re-click of the- // current point) cannot suppress a legitimate future recenter.- lastMapSelectionRef.current = { at: Date.now(), name: imageName };+ if (typeof imageName !== 'string') {+ return;+ }++ // A selection made by clicking the map must not recenter the map+ // under the user's cursor; the marker effect checks this. The+ // stamp expires so a stale entry (failed hydrate, re-click of the+ // current point) cannot suppress a legitimate future recenter.+ lastMapSelectionRef.current = { at: Date.now(), name: imageName };++ const clusterNames = clusterModeRef.current ? collectClusterSelection(points, imageName) : null;++ if (clusterNames) {+ selectCluster(imageName, clusterNames);+ } else {+ // Also the cluster-mode fallback for noise points (cluster -1).selectImage(imageName);}});@@ -235,6 +275,7 @@ const ImageMapPlot = () => {plot.on('plotly_unhover', () => {clearHover();});+ setPlotRevision((revision) => revision + 1);}).catch(() => {if (disposed) {@@ -255,7 +296,36 @@ const ImageMapPlot = () => {return () => {disposed = true;};- }, [points, selectImage]);+ }, [points, selectCluster, selectImage]);++ // Highlight overlay: the gallery's multi-selection, restyled in place.+ useEffect(() => {+ const container = containerRef.current as PlotElement | null;++ if (!container || points === null) {+ return;+ }++ const highlightIndex = findTraceIndex(container, HIGHLIGHTED_POINTS_TRACE);++ if (highlightIndex < 0) {+ return;+ }++ const trace = buildHighlightedPointsTrace(points, selectedNames);+ swallow(+ Plotly.restyle(+ container,+ {+ customdata: [trace.customdata],+ 'marker.color': [trace.marker.color as string[]],+ x: [trace.x],+ y: [trace.y],+ },+ [highlightIndex]+ )+ );+ }, [plotRevision, points, selectedNames]);// The timer must not outlive the component; the scene effect used to do// this, but it reruns on every `points` change.@@ -314,7 +384,7 @@ const ImageMapPlot = () => {if (recentered) {swallow(Plotly.relayout(container, { 'xaxis.range': recentered.x, 'yaxis.range': recentered.y }));}- }, [points, selectedImageName]);+ }, [plotRevision, points, selectedImageName]);// Custom zoom handlers + container size tracking, attached once for the// plot's lifetime; plotly does not observe its container.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex 029b9420be..516610ceb4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -2,6 +2,7 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import { Button, Center, Spinner, Stack, Text } from '@chakra-ui/react';import { ensureImageMapLoaded, imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';import { lazy, Suspense, useEffect } from 'react';// Lazy so the plotly bundle (its own vite chunk, ~1.5MB) loads only when the@@ -28,6 +29,7 @@ const plotLoadingFallback = (*/export const ImageMapWidgetView = (_props: WidgetViewProps) => {const { data, error, loadState, renderError } = imageMapStore.useSnapshot();+ const clickSelectsCluster = useWidgetValuesSelector('image-map', (values) => Boolean(values.clickSelectsCluster));useEffect(() => {ensureImageMapLoaded();@@ -60,7 +62,7 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {// mounted and the spinner where the plot will appear.return (<Suspense fallback={plotLoadingFallback}>- <ImageMapPlot />+ <ImageMapPlot clickSelectsCluster={clickSelectsCluster} /></Suspense>);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.tsindex 2491c0d27b..629bfded5f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.ts@@ -1,11 +1,13 @@import type { WidgetImplementation } from '@workbench/widgetContracts';import { ImageMapDataRuntime } from './ImageMapDataRuntime';+import { ImageMapHeaderActions } from './ImageMapHeaderActions';import { ImageMapWidgetFooter } from './ImageMapWidgetFooter';import { ImageMapWidgetView } from './ImageMapWidgetView';export const widgetImplementation = {footer: ImageMapWidgetFooter,+ headerActions: ImageMapHeaderActions,host: ImageMapDataRuntime,view: ImageMapWidgetView,} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsxindex a438fb54b3..38b2b39a21 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({vi.mock('@features/gallery', () => ({galleryImages: { resolveMany: mocks.resolveMany },legacyGeneratedImageToGalleryItem: (image: { image_name: string }) => image,+ toGalleryItemKey: (key: { kind: string; name: string }) => key,}));vi.mock('@workbench/WorkbenchContext', () => ({@@ -19,7 +20,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({}),}));-import { useSelectMapImage } from './useSelectMapImage';+import { useMapSelection } from './useSelectMapImage';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -30,11 +31,11 @@ let root: Root | null = null;const handle: { click: ((imageName: string) => void) | null } = { click: null };const Probe = () => {- const select = useSelectMapImage();+ const { selectImage } = useMapSelection();useEffect(() => {- handle.click = select;- }, [select]);+ handle.click = selectImage;+ }, [selectImage]);return null;};@@ -81,7 +82,7 @@ afterEach(async () => {mocks.selectItem.mockReset();});-describe('useSelectMapImage', () => {+describe('useMapSelection', () => {it('dispatches the selection for a click', async () => {mocks.resolveMany.mockResolvedValue([{ image_name: 'a.png' }]);await mount();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsindex 688a36c29f..7d4d5a5c23 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -1,6 +1,13 @@-import { galleryImages, legacyGeneratedImageToGalleryItem } from '@features/gallery';+import { galleryImages, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery';import { useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { useCallback } from 'react';+import { useCallback, useMemo } from 'react';++export interface MapSelectionActions {+ /** Select one image (hydrates the item, then gallery.selectItem). */+ selectImage: (imageName: string) => void;+ /** Multi-select a cluster with the clicked image as primary. */+ selectCluster: (primaryImageName: string, imageNames: string[]) => void;+}/*** Module-scoped, deliberately: the thing being guarded — the gallery selection —@@ -12,18 +19,18 @@ import { useCallback } from 'react';let selectionSequence = 0;/**- * Turns a map point's image name into the current gallery selection. The map- * only knows names; the selection contract wants a full gallery item, so names- * are hydrated through the bulk by-names resolver — always fresh, since a- * cached DTO's star/board state can drift. A monotonic sequence guards rapid- * clicks: only the most recent click may dispatch, so a slow fetch can never- * overwrite a newer selection. Preview follows the gallery selection on its- * own.+ * Turns map clicks into gallery selections. The map only knows names; the+ * selection contract wants a full gallery item, so names are hydrated through+ * the bulk by-names resolver — always fresh, since a cached DTO's star/board+ * state can drift. ONE monotonic sequence spans both selection kinds, so+ * rapid clicks always resolve to the latest click regardless of which mode+ * each went through; a slow fetch can never overwrite a newer selection.+ * Preview follows the gallery selection on its own.*/-export const useSelectMapImage = (): ((imageName: string) => void) => {+export const useMapSelection = (): MapSelectionActions => {const commands = useWorkbenchCommands();- return useCallback(+ const selectImage = useCallback((imageName: string) => {const sequence = ++selectionSequence;@@ -61,4 +68,30 @@ export const useSelectMapImage = (): ((imageName: string) => void) => {},[commands]);++ const selectCluster = useCallback(+ (primaryImageName: string, imageNames: string[]) => {+ const sequence = ++selectionSequence;++ galleryImages+ .resolveMany([primaryImageName])+ .then((images) => {+ const image = images.at(0);++ if (!image || sequence !== selectionSequence) {+ return;+ }++ // Map points are always images, so every key is kind-tagged 'image'.+ const itemKeys = imageNames.map((name) => toGalleryItemKey({ kind: 'image', name }));+ commands.gallery.setItemMultiSelection(itemKeys, legacyGeneratedImageToGalleryItem(image));+ })+ .catch(() => {+ // Selection is simply left unchanged on hydrate failure.+ });+ },+ [commands]+ );++ return useMemo(() => ({ selectCluster, selectImage }), [selectCluster, selectImage]);};