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
fix(ui): declutter image map cluster labels when zoomed out
Lincoln Steine2b3a2c67a4a
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.tsindex 3b1ee97f7a..86399583b4 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts@@ -3,7 +3,12 @@ import { describe, expect, it } from 'vitest';import type { ImageMapPoint } from './api';import { collectClusterSelection } from './clusterSelection';-import { buildClusterAnnotations, buildHighlightedPointsTrace, HIGHLIGHTED_POINTS_TRACE } from './imageMapTraces';+import {+ buildClusterAnnotations,+ buildHighlightedPointsTrace,+ declutterAnnotations,+ HIGHLIGHTED_POINTS_TRACE,+} from './imageMapTraces';const point = (imageName: string, x: number, y: number, cluster: number): ImageMapPoint => ({cluster,@@ -71,4 +76,65 @@ describe('buildClusterAnnotations', () => {const onlyOne = buildClusterAnnotations(POINTS, { '1': 'portraits' });expect(onlyOne.map((annotation) => annotation.text)).toEqual(['portraits']);});++ it('orders annotations by cluster size so declutter keeps the biggest labels', () => {+ // The smaller cluster's point comes FIRST in the points array: without the+ // explicit sort, Map insertion order would put 'portraits' first.+ const smallFirst = [point('solo.png', 10, 0, 1), point('a.png', 0, 0, 0), point('b.png', 1, 0, 0)];+ const annotations = buildClusterAnnotations(smallFirst, { '0': 'landscapes', '1': 'portraits' });+ expect(annotations.map((annotation) => annotation.text)).toEqual(['landscapes', 'portraits']);+ });++ it('breaks size ties by cluster id, ascending', () => {+ const tied = [point('b.png', 10, 0, 1), point('a.png', 0, 0, 0)];+ const annotations = buildClusterAnnotations(tied, { '0': 'landscapes', '1': 'portraits' });+ expect(annotations.map((annotation) => annotation.text)).toEqual(['landscapes', 'portraits']);+ });+});++describe('declutterAnnotations', () => {+ // Cluster 0: three points near the origin; cluster 1: one point at (10, 0).+ // The small cluster's point deliberately comes first, so these tests fail+ // if the size-priority ordering in buildClusterAnnotations regresses.+ const clusters = [+ point('far.png', 10, 0, 1),+ point('a.png', 0, 0, 0),+ point('b.png', 1, 0, 0),+ point('c.png', 2, 0, 0),+ ];+ const annotations = buildClusterAnnotations(clusters, { '0': 'landscapes', '1': 'portraits' });+ const view = { widthPx: 800, heightPx: 600 };++ it('keeps every label when the view gives them room', () => {+ // Zoomed in: 11 data units across 800px puts the anchors ~650px apart.+ const ranges = { x: [-0.5, 10.5] as [number, number], y: [-4, 4] as [number, number] };+ const kept = declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx);+ expect(kept.map((annotation) => annotation.text)).toEqual(['landscapes', 'portraits']);+ });++ it('drops the smaller cluster label when zooming out collapses the gap', () => {+ // Zoomed way out: 1000 data units across 800px squeezes the anchors to+ // ~7px apart — well inside either label's pixel footprint.+ const ranges = { x: [-500, 500] as [number, number], y: [-375, 375] as [number, number] };+ const kept = declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx);+ expect(kept.map((annotation) => annotation.text)).toEqual(['landscapes']);+ });++ it('keeps labels that overlap horizontally but are far apart vertically', () => {+ // Both clusters share x≈0 but sit 2 data units apart in y; at 75px per+ // unit that is 150px of vertical separation — no collision, both kept.+ // Collapsing the y term in the collision math would fail this.+ const stacked = [point('top.png', 0, 2, 1), point('a.png', 0, 0, 0), point('b.png', 1, 0, 0)];+ const stackedAnnotations = buildClusterAnnotations(stacked, { '0': 'landscapes', '1': 'portraits' });+ const ranges = { x: [-4, 4] as [number, number], y: [-3, 5] as [number, number] };+ const kept = declutterAnnotations(stackedAnnotations, ranges, 800, 600);+ expect(kept.map((annotation) => annotation.text)).toEqual(['landscapes', 'portraits']);+ });++ it('returns the full set unfiltered when the viewport is degenerate', () => {+ const ranges = { x: [0, 0] as [number, number], y: [-375, 375] as [number, number] };+ expect(declutterAnnotations(annotations, ranges, view.widthPx, view.heightPx)).toEqual(annotations);+ const sane = { x: [-500, 500] as [number, number], y: [-375, 375] as [number, number] };+ expect(declutterAnnotations(annotations, sane, 0, view.heightPx)).toEqual(annotations);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsindex a6f27fd244..d1bbc3fcd7 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@ -169,6 +169,10 @@ export interface ClusterAnnotation {* zoom never lands the label on the points it names). White-on-dark pill* styling is theme-independent — it reads on every map background.* Pure so placement math is testable; plotly consumes the array via layout.+ *+ * Ordered by cluster size (largest first, cluster id as the tiebreak): array+ * order is the keep-priority for declutterAnnotations, so when two labels+ * collide the one naming more images survives.*/export const buildClusterAnnotations = (points: ImageMapPoint[],@@ -192,17 +196,86 @@ export const buildClusterAnnotations = (sums.set(point.cluster, entry);}- return [...sums.entries()].map(([cluster, { count, x, maxY }]) => ({- bgcolor: 'rgba(0,0,0,0.65)',- borderpad: 2,- font: { color: '#FFFFFF', size: 10 },- opacity: 1,- showarrow: false,- text: labelsByCluster[String(cluster)],- x: x / count,- xanchor: 'center',- y: maxY,- yanchor: 'bottom',- yshift: 8,- }));+ return [...sums.entries()]+ .sort(([clusterA, a], [clusterB, b]) => b.count - a.count || clusterA - clusterB)+ .map(([cluster, { count, x, maxY }]) => ({+ bgcolor: 'rgba(0,0,0,0.65)',+ borderpad: 2,+ font: { color: '#FFFFFF', size: 10 },+ opacity: 1,+ showarrow: false,+ text: labelsByCluster[String(cluster)],+ x: x / count,+ xanchor: 'center',+ y: maxY,+ yanchor: 'bottom',+ yshift: 8,+ }));+};++// Label extent estimates for collision testing. Annotations render in an SVG+// layer we cannot measure before drawing, so the pill's footprint is+// approximated from its text length at the fixed 10px font.+const LABEL_CHAR_WIDTH_PX = 6;+const LABEL_HEIGHT_PX = 18;+/** Two labels closer than this (edge to edge) count as colliding. */+const LABEL_GAP_PX = 4;++interface LabelRect {+ left: number;+ right: number;+ top: number;+ bottom: number;+}++const rectsCollide = (a: LabelRect, b: LabelRect): boolean =>+ a.left < b.right + LABEL_GAP_PX &&+ a.right > b.left - LABEL_GAP_PX &&+ a.top < b.bottom + LABEL_GAP_PX &&+ a.bottom > b.top - LABEL_GAP_PX;++/**+ * Zoomed far out, every cluster label converges on the same few pixels and+ * the map disappears under a pile of pills. Greedily keep labels in array+ * order (buildClusterAnnotations puts larger clusters first), dropping any+ * whose estimated pixel footprint collides with one already kept — fully+ * deterministic for a given annotation set and view. Zooming back in spreads+ * the anchors apart and the dropped labels reappear.+ */+export const declutterAnnotations = (+ annotations: ClusterAnnotation[],+ ranges: AxisRanges,+ widthPx: number,+ heightPx: number+): ClusterAnnotation[] => {+ const spanX = ranges.x[1] - ranges.x[0];+ const spanY = ranges.y[1] - ranges.y[0];++ if (spanX <= 0 || spanY <= 0 || widthPx <= 0 || heightPx <= 0) {+ return annotations;+ }++ const kept: ClusterAnnotation[] = [];+ const keptRects: LabelRect[] = [];++ for (const annotation of annotations) {+ const centerX = ((annotation.x - ranges.x[0]) / spanX) * widthPx;+ // Screen y grows downward; yanchor 'bottom' + positive yshift puts the+ // pill's bottom edge yshift pixels above the anchor point.+ const bottom = ((ranges.y[1] - annotation.y) / spanY) * heightPx - annotation.yshift;+ const halfWidth = (annotation.text.length * LABEL_CHAR_WIDTH_PX) / 2 + annotation.borderpad;+ const rect: LabelRect = {+ bottom,+ left: centerX - halfWidth,+ right: centerX + halfWidth,+ top: bottom - LABEL_HEIGHT_PX,+ };++ if (!keptRects.some((other) => rectsCollide(rect, other))) {+ kept.push(annotation);+ keptRects.push(rect);+ }+ }++ return kept;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex d0d2244d7e..7890929bf3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -1,4 +1,5 @@import type { ImageMapPoint } from '@workbench/image-map/api';+import type { ClusterAnnotation } from '@workbench/image-map/imageMapTraces';import type { AxisRanges } from '@workbench/image-map/imageMapViewport';import type { PlotlyHTMLElement } from 'plotly.js';@@ -18,6 +19,7 @@ import {buildHighlightedPointsTrace,buildMapLayout,CURRENT_IMAGE_TRACE,+ declutterAnnotations,HIGHLIGHTED_POINTS_TRACE,} from '@workbench/image-map/imageMapTraces';import {@@ -29,7 +31,7 @@ import {import { getThumbnailUrl } from '@workbench/image-map/thumbnailCache';import { shallowEqual, useWidgetValuesSelector } from '@workbench/WorkbenchContext';import Plotly from 'plotly.js-gl2d-dist-min';-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useMapSelection } from './useSelectMapImage';@@ -164,6 +166,33 @@ const ImageMapPlot = ({selectedImageNameRef.current = selectedImageName;clusterModeRef.current = clickSelectsCluster;}, [clickSelectsCluster, points, selectedImageName]);+ // The full annotation set for the current data; which of them actually show+ // 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[]>([]);+ const appliedAnnotationsKeyRef = useRef<string | null>(null);++ // Zoomed far out, cluster labels pile onto the same few pixels; declutter+ // against the CURRENT view so only labels with room to breathe render, and+ // zooming back in restores the rest. The applied-key check makes the common+ // case (a pan/zoom that changes no label's visibility) a no-op — it also+ // keeps this from feeding back into itself through the plotly_relayout+ // event its own relayout fires.+ const applyDeclutteredAnnotations = useCallback((container: PlotElement) => {+ const ranges = readRanges(container);+ const annotations =+ ranges && container.offsetWidth > 0 && container.offsetHeight > 0+ ? declutterAnnotations(fullAnnotationsRef.current, ranges, container.offsetWidth, container.offsetHeight)+ : fullAnnotationsRef.current;+ const key = annotations.map((annotation) => `${annotation.text}@${annotation.x},${annotation.y}`).join('\n');++ if (key === appliedAnnotationsKeyRef.current) {+ return;+ }++ appliedAnnotationsKeyRef.current = key;+ swallow(Plotly.relayout(container, { annotations }));+ }, []);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@@ -219,6 +248,9 @@ const ImageMapPlot = ({// Annotations are deliberately absent here: they are a layout concern, and// rebuilding the scene for them is what made labels arriving a second after// the points re-materialize every trace. See the relayout effect below.+ // Since the rebuilt layout carries no annotations, the applied-key must be+ // forgotten or the label effect would skip re-adding an identical set.+ appliedAnnotationsKeyRef.current = null;const layout = buildMapLayout(initialRanges);void Plotly.react(container, traces as Plotly.Data[], layout, {@@ -288,6 +320,19 @@ const ImageMapPlot = ({plot.on('plotly_unhover', () => {clearHover();});+ plot.removeAllListeners?.('plotly_relayout');+ plot.on('plotly_relayout', (event) => {+ // Every zoom, pan, and resize changes which labels have room; the+ // annotation-only relayouts this triggers carry no axis keys, so+ // they fall through without recursing.+ const viewChanged = Object.keys(event ?? {}).some(+ (key) => key.startsWith('xaxis.') || key.startsWith('yaxis.') || key === 'autosize'+ );++ if (viewChanged) {+ applyDeclutteredAnnotations(container as unknown as PlotElement);+ }+ });setPlotRevision((revision) => revision + 1);}).catch(() => {@@ -309,7 +354,7 @@ const ImageMapPlot = ({return () => {disposed = true;};- }, [points, selectCluster, selectImage]);+ }, [applyDeclutteredAnnotations, points, selectCluster, selectImage]);// Highlight overlay: the gallery's multi-selection, restyled in place.useEffect(() => {@@ -411,12 +456,9 @@ const ImageMapPlot = ({return;}- swallow(- Plotly.relayout(container, {- annotations: buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null),- })- );- }, [clusterLabels, plotRevision, points, showClusterLabels]);+ fullAnnotationsRef.current = buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null);+ applyDeclutteredAnnotations(container);+ }, [applyDeclutteredAnnotations, clusterLabels, plotRevision, points, showClusterLabels]);// Custom zoom handlers + container size tracking, attached once for the// plot's lifetime; plotly does not observe its container.