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(image-map): select whole clusters and dim the rest of the map

Lincoln Stein936a4ba9bc54
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
index fc7af4281e..b4516af095 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
@@ -5,10 +5,18 @@ import { describe, expect, it } from 'vitest';
import type { ImageMapPoint } from './api';
-import { collectClusterSelection } from './clusterSelection';
+import { getClusterColor } from './clusterPalette';
+import { collectClusterSelection, formatClusterSize } from './clusterSelection';
import {
+ buildAllPointsTraces,
buildClusterAnnotations,
+ buildClusterSelectionTraces,
buildHighlightedPointsTrace,
+ dimAppearance,
+ getDominantCluster,
+ getTraceAppearance,
+ toBaseAppearanceRestyle,
+ toClusterSelectionRestyle,
declutterAnnotations,
HIGHLIGHTED_POINTS_TRACE,
toHighlightRestyle,
@@ -59,9 +67,19 @@ describe('collectClusterSelection', () => {
expect(collectClusterSelection(POINTS, 'image:clip.mp4')).toBeNull();
});
- it('caps oversized clusters, keeping the nearest members', () => {
- const capped = collectClusterSelection(POINTS, 'image:a.png', 2);
- expect(capped).toEqual(['image:a.png', 'image:c.png']);
+ it('selects every member of a cluster far larger than the old 5,000 cap', () => {
+ const members = Array.from({ length: 12_000 }, (_, index) => ({
+ cluster: 3,
+ item: { kind: 'image' as const, name: `m${index}.png` },
+ key: `image:m${index}.png` as const,
+ x: index,
+ y: 0,
+ }));
+ const selection = collectClusterSelection([...members, ...POINTS], 'image:m6000.png');
+
+ expect(selection).toHaveLength(12_000);
+ // Still walks outward from the click.
+ expect(selection?.slice(0, 3)).toEqual(['image:m6000.png', 'image:m5999.png', 'image:m6001.png']);
});
});
@@ -290,3 +308,86 @@ describe('declutterAnnotations', () => {
expect(declutterAnnotations(annotations, sane, 0, view.heightPx)).toEqual(annotations);
});
});
+
+describe('cluster selection drawing', () => {
+ const members = new Set(['image:a.png', 'image:b.png', 'image:c.png', 'video:clip.mp4'] as const);
+
+ it('redraws the members at their cluster colour, one scalar-styled trace per kind', () => {
+ const [images, videos] = buildClusterSelectionTraces(POINTS, members);
+
+ expect(images.customdata).toEqual(['image:a.png', 'image:b.png', 'image:c.png']);
+ expect(videos.customdata).toEqual(['video:clip.mp4']);
+ expect([images.marker.symbol, videos.marker.symbol]).toEqual(['circle', 'diamond']);
+ for (const trace of [images, videos]) {
+ // Scalar, never per point: that is what keeps a 100k-member cluster zooming like the base.
+ expect(trace.marker.color).toBe(getClusterColor(0));
+ expect(typeof trace.marker.opacity).toBe('number');
+ // Clicks and hovers fall through to the base point underneath.
+ expect(trace.hoverinfo).toBe('skip');
+ }
+ expect(toClusterSelectionRestyle([images, videos])).toEqual({
+ customdata: [images.customdata, videos.customdata],
+ 'marker.color': [getClusterColor(0), getClusterColor(0)],
+ x: [images.x, videos.x],
+ y: [images.y, videos.y],
+ });
+ });
+
+ it('takes the colour of the cluster most members are in now, after a refresh renumbered them', () => {
+ const renumbered = POINTS.map((entry) => (entry.cluster === 0 ? { ...entry, cluster: 7 } : entry));
+ const moved = renumbered.map((entry) => (entry.key === 'image:c.png' ? { ...entry, cluster: 1 } : entry));
+
+ expect(getDominantCluster(moved, members)).toBe(7);
+ expect(buildClusterSelectionTraces(moved, members)[0].marker.color).toBe(getClusterColor(7));
+ });
+
+ it('draws nothing for an empty selection or members no longer on the map', () => {
+ for (const keys of [new Set<never>(), new Set(['image:gone.png'] as const)]) {
+ const traces = buildClusterSelectionTraces(POINTS, keys);
+
+ expect(traces.map((trace) => trace.x.length)).toEqual([0, 0]);
+ expect(getDominantCluster(POINTS, keys)).toBeNull();
+ }
+ });
+
+ it('dims every base trace with one greyer, fainter scalar each, and restores them exactly', () => {
+ const appearances = buildAllPointsTraces(POINTS).map(getTraceAppearance);
+ const dimmed = toBaseAppearanceRestyle(appearances, true);
+ const restored = toBaseAppearanceRestyle(appearances, false);
+
+ expect(dimmed['marker.color']).toHaveLength(appearances.length);
+ appearances.forEach((appearance, index) => {
+ const color = dimmed['marker.color']![index] as string;
+ const opacity = dimmed['marker.opacity']![index] as number;
+
+ expect(color).toMatch(/^#[0-9a-f]{6}$/);
+ expect(color).not.toBe(appearance.color.toLowerCase());
+ expect(opacity).toBeLessThan(appearance.opacity);
+ });
+ expect(restored).toEqual({
+ 'marker.color': appearances.map((appearance) => appearance.color),
+ 'marker.opacity': appearances.map((appearance) => appearance.opacity),
+ });
+ });
+
+ it('mutes colour toward grey rather than only fading it', () => {
+ // Pure red keeps a trace of its hue but loses most of its saturation.
+ const { color } = dimAppearance({ color: '#FF0000', opacity: 0.85 });
+ const [r, g, b] = [1, 3, 5].map((start) => parseInt(color.slice(start, start + 2), 16));
+
+ expect(r).toBeGreaterThan(g!);
+ expect(r! - g!).toBeLessThan(60);
+ expect(Math.abs(g! - b!)).toBeLessThan(10);
+ });
+
+ it('keeps noise fainter than clustered points once dimmed', () => {
+ expect(dimAppearance({ color: '#8A8A8A', opacity: 0.25 }).opacity).toBeLessThan(
+ dimAppearance({ color: '#4E79A7', opacity: 0.85 }).opacity
+ );
+ });
+
+ it('words the size with grouping and number', () => {
+ expect(formatClusterSize(1)).toBe('1 item');
+ expect(formatClusterSize(38112)).toBe('38,112 items');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
index d15f90532f..7c185e89ea 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
@@ -11,13 +11,14 @@ import type { ImageMapPoint } from './api';
* sits in the same cluster as the images that look like it.
*/
-/** Selection size guard; DBSCAN can put most of a huge gallery in one cluster. */
-export const MAX_CLUSTER_SELECTION = 5000;
-
+/**
+ * Every member, however large: DBSCAN can put most of a huge gallery in one cluster, and a silent cap showed only the
+ * part nearest the click. The map draws the whole cluster with scalar marker properties, and the gallery hydrates the
+ * list a page at a time.
+ */
export const collectClusterSelection = (
points: ImageMapPoint[],
- clickedKey: GalleryItemKey,
- cap: number = MAX_CLUSTER_SELECTION
+ clickedKey: GalleryItemKey
): GalleryItemKey[] | null => {
const clicked = points.find((point) => point.key === clickedKey);
@@ -32,6 +33,19 @@ export const collectClusterSelection = (
key: point.key,
}))
.sort((left, right) => left.distance - right.distance)
- .slice(0, cap)
.map((entry) => entry.key);
};
+
+// The map widget is English-only, so its numbers are grouped to match its words
+// rather than by whatever locale the browser reports.
+const CLUSTER_SIZE_FORMAT = new Intl.NumberFormat('en-US');
+
+/** A cluster's size as the map words it; also the selection's name while the cluster has no label. */
+export const formatClusterSize = (count: number): string =>
+ `${CLUSTER_SIZE_FORMAT.format(count)} ${count === 1 ? 'item' : 'items'}`;
+
+/**
+ * Whether a selection's name is only its size, as it is for a cluster that had no label. The count in such a name was
+ * taken at click time and goes stale once members are deleted, so the name is recognised rather than compared.
+ */
+export const isClusterSizeLabel = (label: string): boolean => /^\d{1,3}(,\d{3})* items?$/.test(label);
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
index c10beecb32..6bb943afa1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
@@ -14,6 +14,8 @@ import { CLUSTER_PALETTE, getClusterColor } from './clusterPalette';
*/
export const ALL_POINTS_TRACE = 'All Points';
+export const CLUSTER_SELECTION_IMAGES_TRACE = 'Cluster Selection';
+export const CLUSTER_SELECTION_VIDEOS_TRACE = 'Cluster Selection Videos';
export const HIGHLIGHTED_POINTS_TRACE = 'Highlighted Points';
export const CURRENT_IMAGE_TRACE = 'Current Image';
@@ -142,10 +144,136 @@ export const buildAllPointsTraces = (points: ImageMapPoint[]): ScatterTrace[] =>
*/
const clusterOf = (point: ImageMapPoint): number => (Number.isInteger(point.cluster) ? point.cluster : -1);
+/** A base trace's own look, kept so a dimmed map can be restored exactly. */
+export interface PointAppearance {
+ color: string;
+ opacity: number;
+}
+
+export const getTraceAppearance = (trace: ScatterTrace): PointAppearance => ({
+ color: trace.marker.color as string,
+ opacity: trace.marker.opacity as number,
+});
+
+// Dimmed points keep a trace of their hue — enough to read the map's structure,
+// not enough to compete with the selected cluster. Opacity alone was not: dense
+// clusters stack translucent markers back up to near full colour.
+const DIM_TARGET = [110, 110, 116] as const;
+const DIM_DESATURATION = 0.85;
+const DIM_OPACITY = 0.18;
+
+const mixTowardDimTarget = (hex: string): string => {
+ const channels = [1, 3, 5].map((start, index) => {
+ const value = parseInt(hex.slice(start, start + 2), 16);
+
+ return Math.round(value + (DIM_TARGET[index]! - value) * DIM_DESATURATION);
+ });
+
+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;
+};
+
+/** How a base trace looks while a cluster is selected; noise stays fainter than clustered points. */
+export const dimAppearance = ({ color, opacity }: PointAppearance): PointAppearance => ({
+ color: mixTowardDimTarget(color),
+ opacity: DIM_OPACITY * (opacity / POINT_OPACITY),
+});
+
+/**
+ * Restyle for the base traces, dimmed or restored. One scalar per trace: a per-point array here would put back the
+ * zoom cost the per-appearance split removed.
+ */
+export const toBaseAppearanceRestyle = (
+ appearances: readonly PointAppearance[],
+ dimmed: boolean
+): Record<string, unknown[]> => {
+ const applied = dimmed ? appearances.map(dimAppearance) : appearances;
+
+ return {
+ 'marker.color': applied.map((appearance) => appearance.color),
+ 'marker.opacity': applied.map((appearance) => appearance.opacity),
+ };
+};
+
+/**
+ * The cluster most of these items belong to on the current map. A refresh can renumber clusters after the selection
+ * was made, so the colour is read from the points now drawn rather than remembered from the click.
+ */
+export const getDominantCluster = (points: ImageMapPoint[], keys: ReadonlySet<GalleryItemKey>): number | null => {
+ const counts = new Map<number, number>();
+
+ for (const point of points) {
+ if (keys.has(point.key)) {
+ const cluster = clusterOf(point);
+
+ counts.set(cluster, (counts.get(cluster) ?? 0) + 1);
+ }
+ }
+
+ let dominant: number | null = null;
+ let best = 0;
+
+ for (const [cluster, count] of counts) {
+ if (count > best) {
+ best = count;
+ dominant = cluster;
+ }
+ }
+
+ return dominant;
+};
+
+/**
+ * A selected cluster redrawn at full colour over the dimmed map: one trace per kind, every marker property scalar, so
+ * a 100k-member cluster zooms like the base points do. Hit-testing falls through to the base points underneath.
+ */
+export const buildClusterSelectionTraces = (
+ points: ImageMapPoint[],
+ keys: ReadonlySet<GalleryItemKey>
+): [ScatterTrace, ScatterTrace] => {
+ const dominant = keys.size > 0 ? getDominantCluster(points, keys) : null;
+ const color = getClusterColor(dominant ?? -1);
+ const images: ImageMapPoint[] = [];
+ const videos: ImageMapPoint[] = [];
+
+ if (dominant !== null) {
+ for (const point of points) {
+ if (keys.has(point.key)) {
+ (point.item.kind === 'video' ? videos : images).push(point);
+ }
+ }
+ }
+
+ const build = (members: ImageMapPoint[], name: string, symbol: string): ScatterTrace => ({
+ customdata: members.map((point) => point.key),
+ hoverinfo: 'skip',
+ marker: { color, opacity: 1, size: 5, symbol },
+ mode: 'markers',
+ name,
+ type: 'scattergl',
+ x: members.map((point) => point.x),
+ y: members.map((point) => point.y),
+ });
+
+ return [
+ build(images, CLUSTER_SELECTION_IMAGES_TRACE, IMAGE_SYMBOL),
+ build(videos, CLUSTER_SELECTION_VIDEOS_TRACE, VIDEO_SYMBOL),
+ ];
+};
+
+/** In-place update for both cluster-selection traces, in trace order. */
+export const toClusterSelectionRestyle = (traces: readonly ScatterTrace[]): Record<string, unknown[]> => ({
+ customdata: traces.map((trace) => trace.customdata),
+ 'marker.color': traces.map((trace) => trace.marker.color),
+ x: traces.map((trace) => trace.x),
+ y: traces.map((trace) => trace.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 items are
- * selected — a single selection is already marked by the gold target.
+ * The gallery's hand-made multi-selection, drawn larger with a white outline
+ * over the base points. Empty when fewer than two items are selected — a
+ * single selection is already marked by the gold target. A cluster click is
+ * drawn by the cluster-selection traces instead; this one's per-point arrays
+ * are only affordable at hand-picked sizes.
*/
export const buildHighlightedPointsTrace = (
points: ImageMapPoint[],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterSelectionChip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterSelectionChip.tsx
new file mode 100644
index 0000000000..c64bf40ab6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterSelectionChip.tsx
@@ -0,0 +1,104 @@
+import { Box, HStack, Text } from '@chakra-ui/react';
+import { getImageCluster, parseGallerySemanticReference } from '@features/gallery/contracts';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { getClusterColor } from '@workbench/image-map/clusterPalette';
+import { formatClusterSize, isClusterSizeLabel } from '@workbench/image-map/clusterSelection';
+import { imageMapStore } from '@workbench/image-map/imageMapStore';
+import { getDominantCluster } from '@workbench/image-map/imageMapTraces';
+import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';
+import { XIcon } from 'lucide-react';
+import { useCallback, useMemo, type MouseEvent } from 'react';
+
+import { useClearClusterSelection } from './useSelectMapImage';
+
+export const CLEAR_CLUSTER_SELECTION_LABEL = 'Clear cluster selection';
+
+/** The registry key of the gallery's cluster listing, or null when it shows anything else. */
+export const selectClusterSelectionId = (values: Record<string, unknown>): string | null => {
+ const reference = parseGallerySemanticReference(values.semanticImageQuery);
+
+ return reference?.kind === 'cluster' ? reference.clusterId : null;
+};
+
+/**
+ * Names the selected cluster over the dimmed map and offers the way back to full colour. It is what explains the grey:
+ * without it a dimmed map reads as a rendering fault, and the only clear lived in the Gallery's search field.
+ */
+export const ClusterSelectionChip = () => {
+ const clusterId = useWidgetValuesSelector('gallery', selectClusterSelectionId);
+ const clearClusterSelection = useClearClusterSelection();
+ const handleClear = useCallback(
+ (event: MouseEvent<HTMLButtonElement>) => {
+ // The button unmounts with the chip; hand focus to the map instead of
+ // letting it fall to the page.
+ event.currentTarget.closest<HTMLElement>('[data-image-map-surface]')?.focus();
+ clearClusterSelection();
+ },
+ [clearClusterSelection]
+ );
+ const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);
+ // The registry entry behind an id never changes, so the id is its identity.
+ const cluster = clusterId ? getImageCluster(clusterId) : null;
+ const color = useMemo(() => {
+ if (!cluster || !points) {
+ return null;
+ }
+
+ const dominant = getDominantCluster(points, new Set(cluster.itemKeys));
+
+ return dominant === null ? null : getClusterColor(dominant);
+ }, [cluster, points]);
+
+ if (!cluster) {
+ return null;
+ }
+
+ const size = formatClusterSize(cluster.itemKeys.length);
+ const label = isClusterSizeLabel(cluster.label) ? null : cluster.label;
+
+ return (
+ <HStack
+ aria-label="Selected cluster"
+ bg="bg.panel"
+ borderColor="border.subtle"
+ borderRadius="full"
+ borderWidth="1px"
+ boxShadow="sm"
+ fontSize="xs"
+ gap="1.5"
+ maxW="full"
+ minW="0"
+ pe="0.5"
+ pointerEvents="auto"
+ ps="2.5"
+ py="0.5"
+ role="group"
+ >
+ {/* No swatch when none of the members is on the map any more: there is no colour to match. */}
+ {color ? <Box aria-hidden="true" bg={color} borderRadius="full" boxSize="2.5" flexShrink={0} /> : null}
+ {label ? (
+ <Tooltip content={label}>
+ <Text color="fg" minW="0" truncate>
+ {label}
+ </Text>
+ </Tooltip>
+ ) : null}
+ <Text color={label ? 'fg.muted' : 'fg'} flexShrink={0} fontVariantNumeric="tabular-nums">
+ {label ? `· ${size}` : size}
+ </Text>
+ <Tooltip content={`${CLEAR_CLUSTER_SELECTION_LABEL} (Esc)`}>
+ <IconButton
+ aria-label={CLEAR_CLUSTER_SELECTION_LABEL}
+ borderRadius="full"
+ flexShrink={0}
+ size="2xs"
+ variant="ghost"
+ onClick={handleClear}
+ >
+ <XIcon />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
index aa2476936b..cc33b987a4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
@@ -1,6 +1,6 @@
import type { ImageIndexCounts } from '@workbench/image-map/indexProgress';
-import { Box, Button, HStack, Progress, Stack, Text } from '@chakra-ui/react';
+import { Button, HStack, Progress, Stack, Text } from '@chakra-ui/react';
import { Tooltip } from '@platform/ui';
import { describeIndexProgress } from '@workbench/image-map/indexProgress';
import { useEffect, useState } from 'react';
@@ -135,42 +135,34 @@ export const ImageIndexActivityBadge = ({ counts, updatedAt }: ImageIndexProgres
: `Indexing ${progress.counts}. The map and its cluster labels update as images finish.`;
return (
- // The wrapper spans the plot so the badge can sit in its corner, and passes
- // every pointer event through: the plot underneath is drag-panned and
- // wheel-zoomed across its whole area, and a full-width transparent layer
- // that swallowed those would cost more than the badge is worth. The badge
- // itself takes its events back so the tooltip still opens.
- <Box inset="0" pointerEvents="none" position="absolute" zIndex="1">
- <Tooltip content={label}>
- <HStack
- bg="bg.subtle"
- borderColor="border.subtle"
- borderRadius="md"
- borderWidth="1px"
- color="fg.muted"
- fontSize="2xs"
- gap="1.5"
- insetStart="2"
- maxW="calc(100% - 1rem)"
- minW="0"
- pointerEvents="auto"
- position="absolute"
- px="2"
- py="1"
- title={label}
- top="2"
- >
- <Progress.Root flexShrink="0" max={100} size="xs" value={progress.percent} w="10">
- <Progress.Track aria-label={`${PROGRESS_LABEL}: ${label}`} aria-valuenow={progress.percent}>
- <Progress.Range />
- </Progress.Track>
- </Progress.Root>
- <Text fontVariantNumeric="tabular-nums" truncate>
- indexing {progress.compact}
- </Text>
- </HStack>
- </Tooltip>
- </Box>
+ // Positioned by the map's overlay column, which passes pointer events
+ // through to the plot; the badge takes its own back so the tooltip opens.
+ <Tooltip content={label}>
+ <HStack
+ bg="bg.subtle"
+ borderColor="border.subtle"
+ borderRadius="md"
+ borderWidth="1px"
+ color="fg.muted"
+ fontSize="2xs"
+ gap="1.5"
+ maxW="full"
+ minW="0"
+ pointerEvents="auto"
+ px="2"
+ py="1"
+ title={label}
+ >
+ <Progress.Root flexShrink="0" max={100} size="xs" value={progress.percent} w="10">
+ <Progress.Track aria-label={`${PROGRESS_LABEL}: ${label}`} aria-valuenow={progress.percent}>
+ <Progress.Range />
+ </Progress.Track>
+ </Progress.Root>
+ <Text fontVariantNumeric="tabular-nums" truncate>
+ indexing {progress.compact}
+ </Text>
+ </HStack>
+ </Tooltip>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
index aaaa30f794..565fad8ff4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
@@ -1,6 +1,6 @@
import type { GalleryItemKey } from '@features/gallery/contracts';
import type { ImageMapPoint } from '@workbench/image-map/api';
-import type { ClusterAnnotation } from '@workbench/image-map/imageMapTraces';
+import type { ClusterAnnotation, PointAppearance } from '@workbench/image-map/imageMapTraces';
import type { AxisRanges } from '@workbench/image-map/imageMapViewport';
import type { HoverCluster, HoverPreview } from '@workbench/widgets/image-map/MapHoverCard';
import type { PlotlyHTMLElement } from 'plotly.js';
@@ -14,17 +14,24 @@ import {
toGalleryItemKey,
} from '@features/gallery/contracts';
import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';
-import { collectClusterSelection } from '@workbench/image-map/clusterSelection';
+import { collectClusterSelection, formatClusterSize } from '@workbench/image-map/clusterSelection';
import { imageMapStore } from '@workbench/image-map/imageMapStore';
import {
+ ALL_POINTS_TRACE,
buildAllPointsTraces,
buildClusterAnnotations,
+ buildClusterSelectionTraces,
buildCurrentImageTrace,
buildHighlightedPointsTrace,
buildMapLayout,
+ CLUSTER_SELECTION_IMAGES_TRACE,
+ CLUSTER_SELECTION_VIDEOS_TRACE,
CURRENT_IMAGE_TRACE,
declutterAnnotations,
+ getTraceAppearance,
HIGHLIGHTED_POINTS_TRACE,
+ toBaseAppearanceRestyle,
+ toClusterSelectionRestyle,
toHighlightRestyle,
} from '@workbench/image-map/imageMapTraces';
import {
@@ -146,8 +153,8 @@ const ImageMapPlot = ({
(values) => getPersistedSelectedGalleryItemKeys(values),
shallowEqual
);
- // With a cluster filter active in the gallery, the whole cluster stays
- // highlighted on the map — the gallery is showing exactly these images.
+ // With a cluster filter active in the gallery, the whole cluster stays lit
+ // on a dimmed map — the gallery is showing exactly these images.
const clusterQueryItemKeys = useWidgetValuesSelector(
'gallery',
(values) => {
@@ -157,9 +164,10 @@ const ImageMapPlot = ({
},
shallowEqual
);
- const selectedKeys = useMemo(
- () => new Set([...selectedItemKeys, ...(clusterQueryItemKeys ?? [])]),
- [clusterQueryItemKeys, selectedItemKeys]
+ const selectedKeys = useMemo(() => new Set(selectedItemKeys), [selectedItemKeys]);
+ const clusterKeys = useMemo(
+ () => (clusterQueryItemKeys ? new Set(clusterQueryItemKeys) : null),
+ [clusterQueryItemKeys]
);
const { selectCluster, selectItem: selectMapItem } = useMapSelection();
// Bumped after every scene rebuild so the overlay effects (marker,
@@ -194,6 +202,12 @@ const ImageMapPlot = ({
// is view-dependent (see applyDeclutteredAnnotations), so the source list
// lives in a ref the relayout listener can re-filter without re-rendering.
const fullAnnotationsRef = useRef<ClusterAnnotation[]>([]);
+ // The base traces' own looks for the scene on screen, so dimming can be
+ // undone exactly; replaced with every rebuild, which also resets the dim.
+ const baseAppearancesRef = useRef<PointAppearance[]>([]);
+ // Whether the base traces on screen are currently dimmed. A rebuild draws
+ // them undimmed, so it resets this too.
+ const baseDimmedRef = useRef(false);
const appliedAnnotationsKeyRef = useRef<string | null>(null);
// Zoomed far out, cluster labels pile onto the same few pixels; declutter
@@ -261,11 +275,17 @@ const ImageMapPlot = ({
// that run straight after this one already see the new indices. Overlay traces (highlight, marker) start empty; the overlay
// effects below restyle them, so a selection change never rebuilds the
// scene.
+ const baseTraces = buildAllPointsTraces(points);
const traces = [
- ...buildAllPointsTraces(points),
+ ...baseTraces,
+ // Above the base points, below the hand-selection outline and the gold
+ // target, which both mark individual items within a lit cluster.
+ ...buildClusterSelectionTraces(points, new Set()),
buildHighlightedPointsTrace(points, new Set()),
buildCurrentImageTrace(),
];
+ baseAppearancesRef.current = baseTraces.map(getTraceAppearance);
+ baseDimmedRef.current = false;
let disposed = false;
// Feed the CURRENT view back into react so data refreshes never reset the
@@ -333,7 +353,8 @@ const ImageMapPlot = ({
// still loading, or missing for this cluster). Only the primary
// phrase is used — the alternates belong to the hover card, which
// has room to show them.
- const label = clusterLabelsRef.current?.[String(clicked.cluster)]?.label ?? `${clusterKeys.length} items`;
+ const label =
+ clusterLabelsRef.current?.[String(clicked.cluster)]?.label ?? formatClusterSize(clusterKeys.length);
selectCluster(clicked.item, clusterKeys, label);
} else {
@@ -407,7 +428,41 @@ const ImageMapPlot = ({
};
}, [applyDeclutteredAnnotations, points, selectCluster, selectMapItem]);
- // Highlight overlay: the gallery's multi-selection, restyled in place.
+ // Cluster selection: the members redrawn at full colour over a dimmed map.
+ // Restyled in place like the other overlays; the base traces take one
+ // scalar per trace, so neither the click nor later zooms pay per point.
+ useEffect(() => {
+ const container = containerRef.current as PlotElement | null;
+
+ if (!container || points === null) {
+ return;
+ }
+
+ const imagesIndex = findTraceIndex(container, CLUSTER_SELECTION_IMAGES_TRACE);
+ const videosIndex = findTraceIndex(container, CLUSTER_SELECTION_VIDEOS_TRACE);
+
+ if (imagesIndex < 0 || videosIndex < 0) {
+ return;
+ }
+
+ const traces = buildClusterSelectionTraces(points, clusterKeys ?? new Set());
+ // A cluster none of whose members are on this map (all since deleted)
+ // lights nothing, so it must not grey everything out either.
+ const dimmed = traces.some((trace) => trace.x.length > 0);
+ const baseIndices = (container.data ?? []).flatMap((trace, index) =>
+ (trace as { name?: string }).name === ALL_POINTS_TRACE ? [index] : []
+ );
+
+ swallow(Plotly.restyle(container, toClusterSelectionRestyle(traces), [imagesIndex, videosIndex]));
+
+ // Restyling the base redraws every point, so only a change of state pays for it.
+ if (dimmed !== baseDimmedRef.current && baseIndices.length === baseAppearancesRef.current.length) {
+ baseDimmedRef.current = dimmed;
+ swallow(Plotly.restyle(container, toBaseAppearanceRestyle(baseAppearancesRef.current, dimmed), baseIndices));
+ }
+ }, [clusterKeys, plotRevision, points]);
+
+ // Highlight overlay: the gallery's hand-made multi-selection, restyled in place.
useEffect(() => {
const container = containerRef.current as PlotElement | null;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
index f3f7253153..095626293d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
@@ -7,8 +7,22 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+// The gallery's values drive the cluster chip and the Esc clear; the image
+// map's own settings read as off.
+const workbench = vi.hoisted(() => ({
+ galleryValues: {} as Record<string, unknown>,
+ patchValues: vi.fn(),
+}));
+
vi.mock('@workbench/WorkbenchContext', () => ({
- useWidgetValuesSelector: () => false,
+ useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) =>
+ widgetId === 'gallery' ? selector(workbench.galleryValues) : false,
+ useWorkbenchCommands: () => ({ widgets: { patchValues: workbench.patchValues } }),
+ useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: {} }) }),
+}));
+vi.mock('@workbench/widgetState', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getProjectWidgetValues: () => workbench.galleryValues,
}));
// The real one pulls the ~1.5MB plotly chunk; the badge under test is its
@@ -95,12 +109,43 @@ vi.mock('@workbench/image-map/imageMapStore', async (importOriginal) => {
};
});
+import { registerImageCluster } from '@features/gallery/contracts';
import { imageMapStore, refreshImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';
import { ImageMapWidgetView } from './ImageMapWidgetView';
let host: HTMLDivElement | null = null;
let root: Root | null = null;
+
+/** Captures what the view registers, and what it disposes, so the Esc binding can be asserted and fired. */
+const registered = {
+ commands: [] as { handler: () => unknown; id: string; runtime: string; disposed: boolean }[],
+ hotkeys: [] as { commandId: string; defaultKeys: string[]; runtime: string; disposed: boolean }[],
+};
+const makeViewProps = (runtimeName: string) =>
+ ({
+ runtime: {
+ commands: {
+ register: (command: { handler: () => unknown; id: string }) => {
+ const entry = { ...command, disposed: false, runtime: runtimeName };
+ registered.commands.push(entry);
+ return () => {
+ entry.disposed = true;
+ };
+ },
+ },
+ hotkeys: {
+ register: (hotkey: { commandId: string; defaultKeys: string[] }) => {
+ const entry = { ...hotkey, disposed: false, runtime: runtimeName };
+ registered.hotkeys.push(entry);
+ return () => {
+ entry.disposed = true;
+ };
+ },
+ },
+ },
+ }) as unknown as WidgetViewProps;
+const viewProps = makeViewProps('project-a');
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const dataFor = (
@@ -132,7 +177,7 @@ const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_mis
await act(() =>
root?.render(
<ChakraProvider value={system}>
- <ImageMapWidgetView {...({} as WidgetViewProps)} />
+ <ImageMapWidgetView {...viewProps} />
</ChakraProvider>
)
);
@@ -151,6 +196,9 @@ const setActiveInstalls = async (sources: string[]) => {
beforeEach(() => {
vi.clearAllMocks();
+ workbench.galleryValues = {};
+ registered.commands = [];
+ registered.hotkeys = [];
models.activeSources.set([]);
host = document.createElement('div');
document.body.append(host);
@@ -331,7 +379,7 @@ describe('Image Map indexing activity', () => {
await act(() =>
root?.render(
<ChakraProvider value={system}>
- <ImageMapWidgetView {...({} as WidgetViewProps)} />
+ <ImageMapWidgetView {...viewProps} />
</ChakraProvider>
)
);
@@ -383,3 +431,155 @@ describe('Image Map indexing activity', () => {
expect(host?.textContent).not.toContain('indexing');
});
});
+
+describe('Image Map cluster selection chip', () => {
+ const POINTS = [
+ { cluster: 2, item: { kind: 'image' as const, name: 'a.png' }, key: 'image:a.png' as const, x: 0, y: 0 },
+ { cluster: 2, item: { kind: 'image' as const, name: 'b.png' }, key: 'image:b.png' as const, x: 1, y: 1 },
+ { cluster: 5, item: { kind: 'image' as const, name: 'c.png' }, key: 'image:c.png' as const, x: 9, y: 9 },
+ ];
+
+ const renderMap = async (
+ counts: { total: number; embedded: number; pending: number; failed: number } | null,
+ props: WidgetViewProps = viewProps,
+ centerChromeInset?: string
+ ) => {
+ imageMapStore.setSnapshot({
+ clusterLabels: null,
+ clusterLabelsHash: null,
+ data: {
+ clusterEps: null,
+ modelName: null,
+ pointCount: POINTS.length,
+ points: POINTS,
+ stale: false,
+ state: 'ready',
+ updatedAt: '2026-09-23T01:00:00',
+ visibleHash: 'hash',
+ },
+ error: null,
+ indexCounts: counts,
+ indexUpdatedAt: counts ? Date.now() : null,
+ loadState: 'loaded',
+ renderError: null,
+ });
+
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <div
+ style={{
+ height: 400,
+ width: 500,
+ ...(centerChromeInset ? { '--wb-center-chrome-inset': centerChromeInset } : {}),
+ }}
+ >
+ <ImageMapWidgetView {...props} />
+ </div>
+ </ChakraProvider>
+ )
+ );
+ };
+
+ const selectCluster = (label: string, count = 2) => {
+ const keys = POINTS.slice(0, count).map((point) => point.key);
+ const clusterId = registerImageCluster(keys, label);
+
+ workbench.galleryValues = { semanticImageQuery: { clusterId, kind: 'cluster', label }, searchTerm: '' };
+ };
+
+ const chip = () => host?.querySelector<HTMLElement>('[role="group"][aria-label="Selected cluster"]') ?? null;
+ const CLEARED = { galleryPage: 0, searchTerm: '', semanticImageQuery: null, semanticSearchText: null };
+
+ it('names the selected cluster with its size and colour, above the indexing badge', async () => {
+ selectCluster('sunset beach');
+ await renderMap({ embedded: 10, failed: 0, pending: 5, total: 15 });
+
+ expect(chip()?.textContent).toBe('sunset beach· 2 items');
+ // Cluster 2's palette colour: both members are in it.
+ expect(getComputedStyle(chip()!.querySelector('[aria-hidden="true"]')!).backgroundColor).toBe('rgb(225, 87, 89)');
+ // Stacked in one corner rather than drawn over each other, the selection first.
+ const badge = host?.querySelector('[role="progressbar"]');
+ expect(chip()!.compareDocumentPosition(badge!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(badge!.getBoundingClientRect().top).toBeGreaterThanOrEqual(chip()!.getBoundingClientRect().bottom);
+ });
+
+ it('shows only the current size for an unlabeled cluster, even after members were deleted', async () => {
+ // Named "2 items" at click time; one member has since gone.
+ selectCluster('2 items', 1);
+ await renderMap(null);
+
+ expect(chip()?.textContent).toBe('1 item');
+ });
+
+ it('starts below the floating view selector when the map is in the center area', async () => {
+ selectCluster('sunset beach');
+ await renderMap(null, viewProps, '3rem');
+
+ const surface = host!.querySelector<HTMLElement>('[data-image-map-surface]')!;
+ // 3rem of center chrome plus the corner's own spacing.
+ expect(chip()!.getBoundingClientRect().top - surface.getBoundingClientRect().top).toBeGreaterThanOrEqual(48 + 8);
+ });
+
+ it('clears the gallery cluster listing from its button', async () => {
+ selectCluster('sunset beach');
+ await renderMap(null);
+
+ const clear = chip()!.querySelector<HTMLButtonElement>('button[aria-label="Clear cluster selection"]')!;
+ clear.focus();
+ await act(() => clear.click());
+
+ expect(workbench.patchValues).toHaveBeenCalledWith('gallery', CLEARED);
+ // The button is about to unmount with the chip; focus stays on the map, where Esc keeps working.
+ expect(document.activeElement).toBe(host!.querySelector('[data-image-map-surface]'));
+ });
+
+ it('moves the Esc binding to the new project when the runtime changes without a remount', async () => {
+ await renderMap(null);
+ await renderMap(null, makeViewProps('project-b'));
+
+ const escBindings = registered.hotkeys.filter((entry) => entry.defaultKeys.includes('esc'));
+ // Registrations carry the project they were made for; a binding left on the
+ // old project's runtime would never resolve in the new one.
+ expect(escBindings.map((entry) => [entry.runtime, entry.disposed])).toEqual([
+ ['project-a', true],
+ ['project-b', false],
+ ]);
+ expect(
+ registered.commands
+ .filter((entry) => entry.id === escBindings[0]!.commandId)
+ .map((entry) => [entry.runtime, entry.disposed])
+ ).toEqual([
+ ['project-a', true],
+ ['project-b', false],
+ ]);
+ });
+
+ it('shows nothing when the gallery is not listing a cluster', async () => {
+ workbench.galleryValues = { searchTerm: 'cats' };
+ await renderMap(null);
+
+ expect(chip()).toBeNull();
+ });
+
+ it('binds Esc to the clear, which leaves an ordinary search alone', async () => {
+ workbench.galleryValues = { searchTerm: 'cats' };
+ await renderMap(null);
+
+ const hotkey = registered.hotkeys.find((entry) => entry.defaultKeys.includes('esc'));
+ const command = registered.commands.find((entry) => entry.id === hotkey?.commandId);
+ expect(command).toBeDefined();
+
+ // Esc with no cluster selected must not wipe the user's search.
+ await act(() => {
+ command!.handler();
+ });
+ expect(workbench.patchValues).not.toHaveBeenCalled();
+
+ selectCluster('sunset beach');
+ await act(() => {
+ command!.handler();
+ });
+ expect(workbench.patchValues).toHaveBeenCalledWith('gallery', CLEARED);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 3f85e35d11..204e2ee72c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -23,7 +23,15 @@ import { isIndexing } from '@workbench/image-map/indexProgress';
import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from 'react';
+import { CLEAR_CLUSTER_SELECTION_LABEL, ClusterSelectionChip } from './ClusterSelectionChip';
import { ImageIndexActivityBadge, ImageIndexProgressPanel } from './ImageIndexProgress';
+import { useClearClusterSelection } from './useSelectMapImage';
+
+const CLEAR_CLUSTER_SELECTION_COMMAND = 'image-map.clearClusterSelection';
+// In the center area the view selector floats over the content's top-left
+// corner; the shell publishes its height so overlays can start below it.
+const OVERLAY_COLUMN_TOP = 'calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))';
+const MAP_SURFACE_FOCUS_STYLE = { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' } as const;
// Lazy so the plotly bundle (its own vite chunk, ~1.5MB) loads only when the
// widget is actually shown.
@@ -62,10 +70,38 @@ const plotLoadingFallback = (
* index, projected to 2D with UMAP and colored by cluster. Clicking a point
* selects that image in the gallery (and so in Preview).
*/
-export const ImageMapWidgetView = (_props: WidgetViewProps) => {
+export const ImageMapWidgetView = ({ runtime }: WidgetViewProps) => {
const { data, error, indexCounts, indexUpdatedAt, loadState, renderError } = imageMapStore.useSnapshot();
const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);
const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);
+ const clearClusterSelection = useClearClusterSelection();
+
+ // Esc while the map owns focus, the keyboard path to the chip's clear. Also
+ // a palette command. The runtime stamps registrations with the active
+ // project and is rebuilt on a project switch without remounting this view,
+ // so registration follows it; the clear reads the selection when it fires.
+ const { commands: runtimeCommands, hotkeys: runtimeHotkeys } = runtime;
+
+ useEffect(() => {
+ const disposers = [
+ runtimeCommands.register({
+ handler: clearClusterSelection,
+ id: CLEAR_CLUSTER_SELECTION_COMMAND,
+ title: CLEAR_CLUSTER_SELECTION_LABEL,
+ }),
+ runtimeHotkeys.register({
+ allowInEditable: false,
+ commandId: CLEAR_CLUSTER_SELECTION_COMMAND,
+ defaultKeys: ['esc'],
+ id: CLEAR_CLUSTER_SELECTION_COMMAND,
+ title: CLEAR_CLUSTER_SELECTION_LABEL,
+ }),
+ ];
+
+ return () => {
+ disposers.forEach((dispose) => dispose());
+ };
+ }, [clearClusterSelection, runtimeCommands, runtimeHotkeys]);
useEffect(() => {
ensureImageMapLoaded();
@@ -107,11 +143,38 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {
// the only sign of an index run once there are points to draw: this
// branch preempts the progress panel below, which is right — a usable
// stale map beats a progress bar — but silently, which was not.
- <Box h="full" position="relative" w="full">
+ // Focusable so a cleared selection can hand focus back to the map (the
+ // chip's button unmounts with it), which also keeps Esc and the map's
+ // other widget hotkeys in reach.
+ <Box
+ _focusVisible={MAP_SURFACE_FOCUS_STYLE}
+ data-image-map-surface=""
+ h="full"
+ outline="none"
+ position="relative"
+ tabIndex={-1}
+ w="full"
+ >
<Suspense fallback={plotLoadingFallback}>
<ImageMapPlot clickSelectsCluster={clickSelectsCluster} showClusterLabels={showClusterLabels} />
</Suspense>
- {isIndexing(indexCounts) ? <ImageIndexActivityBadge counts={indexCounts} updatedAt={indexUpdatedAt} /> : null}
+ {/* One corner, stacked: the selection first, since the user made it.
+ The column passes pointer events through, because the plot under
+ it is drag-panned and wheel-zoomed across its whole area; each
+ overlay takes its own back. */}
+ <Stack
+ align="flex-start"
+ gap="1.5"
+ insetStart="2"
+ maxW="calc(100% - 1rem)"
+ pointerEvents="none"
+ position="absolute"
+ top={OVERLAY_COLUMN_TOP}
+ zIndex="1"
+ >
+ <ClusterSelectionChip />
+ {isIndexing(indexCounts) ? <ImageIndexActivityBadge counts={indexCounts} updatedAt={indexUpdatedAt} /> : null}
+ </Stack>
</Box>
);
}
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.tsx
index 0467e86176..342cf41085 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
@@ -1,3 +1,5 @@
+import type * as GalleryContracts from '@features/gallery/contracts';
+
import { act, useEffect } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -78,7 +80,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({
}),
}));
-import { useMapSelection } from './useSelectMapImage';
+import { useClearClusterSelection, useMapSelection } from './useSelectMapImage';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -95,15 +97,18 @@ const handle: {
label: string
) => void)
| null;
-} = { click: null, clickCluster: null };
+ clear: (() => void) | null;
+} = { clear: null, click: null, clickCluster: null };
const Probe = () => {
const { selectCluster, selectItem } = useMapSelection();
+ const clearClusterSelection = useClearClusterSelection();
useEffect(() => {
+ handle.clear = clearClusterSelection;
handle.click = selectItem;
handle.clickCluster = selectCluster;
- }, [selectCluster, selectItem]);
+ }, [clearClusterSelection, selectCluster, selectItem]);
return null;
};
@@ -625,6 +630,45 @@ describe('useMapSelection', () => {
expect(mocks.selectItem.mock.calls[0]?.[0].name).toBe('fast.png');
});
+ it('retires a cluster click still hydrating when the selection is cleared', async () => {
+ // A cluster listing is showing; the user clicks another cluster and clears
+ // before that click's image resolves. The late resolution must not bring
+ // the cleared selection back.
+ // Through the real registry (the module's export is stubbed above): a
+ // reference to an unregistered cluster reads as no cluster at all.
+ const { registerImageCluster } = await vi.importActual<typeof GalleryContracts>('@features/gallery/contracts');
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png'], 'beaches');
+ mocks.galleryValues = { semanticImageQuery: { clusterId, kind: 'cluster', label: 'beaches' } };
+ const slow = deferred<{ boardId: string; category: string; kind: string; name: string }>();
+
+ mocks.resolve.mockReturnValueOnce(slow.promise);
+ await mount();
+
+ await flush(() => {
+ handle.clickCluster?.({ kind: 'image', name: 'slow.png' }, ['image:slow.png'], 'forests');
+ handle.clear?.();
+ });
+ await flush(() => {
+ slow.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'slow.png' });
+ });
+
+ expect(mocks.patchValues).toHaveBeenCalledTimes(1);
+ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', expect.objectContaining({ semanticImageQuery: null }));
+ expect(mocks.registerImageCluster).not.toHaveBeenCalled();
+ expect(mocks.selectItem).not.toHaveBeenCalled();
+ });
+
+ it('leaves the gallery alone when a clear finds no cluster listing', async () => {
+ mocks.galleryValues = { searchTerm: 'cats', semanticImageQuery: { imageName: 'a.png', kind: 'image' } };
+ await mount();
+
+ await flush(() => {
+ handle.clear?.();
+ });
+
+ expect(mocks.patchValues).not.toHaveBeenCalled();
+ });
+
it('ignores a slow click that resolves after a newer one', async () => {
const slow = deferred<{ boardId: string; category: string; kind: string; name: string }>();
const fast = deferred<{ boardId: string; category: string; kind: string; name: string }>();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
index 164170e3cd..28604b432a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
@@ -4,11 +4,13 @@ import { galleryItems, toGalleryItemKey } from '@features/gallery';
import {
claimGalleryNavigationSequence,
isGalleryNavigationCurrent,
+ parseGallerySemanticReference,
registerImageCluster,
requestGalleryItemReveal,
} from '@features/gallery/contracts';
import { useQueryClient } from '@tanstack/react-query';
import { revealGalleryItem } from '@workbench/image-actions/revealGalleryItem';
+import { getProjectWidgetValues } from '@workbench/widgetState';
import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
@@ -91,3 +93,32 @@ export const useMapSelection = (): MapSelectionActions => {
return useMemo(() => ({ selectCluster, selectItem }), [selectCluster, selectItem]);
};
+
+/**
+ * Ends a cluster selection: the gallery drops the cluster listing (as its own chip's clear does) and the map regains
+ * its colours, since both draw from the same reference. Claiming a navigation ticket retires a cluster click still
+ * hydrating, which would otherwise re-apply the selection just cleared.
+ *
+ * Checks at call time that a cluster is what the gallery shows: Esc reaches this whenever the map has focus, and
+ * the same reset applied to an ordinary search would wipe the user's search text.
+ */
+export const useClearClusterSelection = (): (() => void) => {
+ const { widgets } = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
+
+ return useCallback(() => {
+ const galleryValues = getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');
+
+ if (parseGallerySemanticReference(galleryValues.semanticImageQuery)?.kind !== 'cluster') {
+ return;
+ }
+
+ claimGalleryNavigationSequence();
+ widgets.patchValues('gallery', {
+ galleryPage: 0,
+ searchTerm: '',
+ semanticImageQuery: null,
+ semanticSearchText: null,
+ });
+ }, [queries, widgets]);
+};