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
Merge remote-tracking branch 'origin/perf/image-map-zoom' into perf/image-map-cluster-selection
Lincoln Stein38f65bb63063
diff --cc invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.tsindex 7c185e89ea,1e678c30bf..bf73fc9aa7--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts@@@ -2,23 -2,15 +2,16 @@@ import type { GalleryItemKey } from '@fimport 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.- *- * Members are item keys: a cluster groups by what the encoder saw, so a video- * sits in the same cluster as the images that look like it.- */+ /** Cluster clicks select image/video keys ordered outward by distance, following PhotoMapAI proximity ordering. */-/** 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);diff --cc invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsindex 6bb943afa1,d784624495..a0ee0ac71e--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@@ -144,137 -140,7 +142,135 @@@ export const buildAllPointsTraces = (po*/const clusterOf = (point: ImageMapPoint): number => (Number.isInteger(point.cluster) ? point.cluster : -1);-/** White-outlined enlarged multi-selection trace; fewer than two items need only the gold current target. */+/** 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 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.++ * White-outlined enlarged trace for hand-made multi-selections; fewer than two items need only the gold current++ * target. Cluster clicks use the cluster-selection traces, since per-point arrays are affordable only at hand-picked++ * sizes.+ */export const buildHighlightedPointsTrace = (points: ImageMapPoint[],selectedKeys: ReadonlySet<GalleryItemKey>diff --cc invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 565fad8ff4,98fa32db8e..602fdf9cbb--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@@ -198,29 -171,12 +179,18 @@@ const ImageMapPlot = (clusterModeRef.current = clickSelectsCluster;clusterLabelsRef.current = clusterLabels;}, [clickSelectsCluster, clusterLabels, points, selectedKey]);- // 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.+ // Keep full annotations in a ref so relayout can refilter visibility without React renders.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- // 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.- //- // The gold target is passed in so it outranks the labels: it draws on the- // WebGL canvas *below* plotly's annotation layer, so a label overlapping it- // wins on z-order no matter how the traces are ordered. Dropping that label- // is what keeps the current position findable in a dense field.+ // Declutter against the current view and skip unchanged visibility to avoid relayout feedback. Reserve space for+ // the gold target beneath Plotly's annotation layer.const applyDeclutteredAnnotations = useCallback((container: PlotElement) => {const ranges = readRanges(container);const selectedItemKey = selectedKeyRef.current;@@@ -284,15 -236,10 +254,12 @@@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- // user's pan/zoom (uirevision alone does not preserve ranges set through- // the public relayout API). The first properly-sized render instead gets- // an aspect-corrected whole-map fit — never a preserved view, which- // could be a cropped artifact of a zero-size initial layout.+ // Preserve user ranges across refreshes, but use an aspect-corrected fit for the first measured render rather+ // than retaining zero-size artifacts.let initialRanges = readRanges(container as unknown as PlotElement) ?? computePercentileRanges(points);if (!initialFitDoneRef.current) {@@@ -348,13 -291,9 +311,10 @@@const clusterKeys = clusterModeRef.current ? collectClusterSelection(points, clicked.key) : null;if (clusterKeys) {- // The backend's cluster label names the filter chip when one has- // arrived; the member count is the fallback (labels can be off,- // 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.+ // Use the primary cluster phrase for filter chips, falling back to member count; alternates belong in+ // hover cards.- 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 {diff --cc invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsxindex 095626293d,e001df6c96..b737040f1c--- 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,31 -7,13 +7,27 @@@ 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- // sibling, not its child, so a stand-in is enough.+ // Stub the heavy Plotly sibling; this test owns the progress badge.vi.mock('./ImageMapPlot', () => ({ default: () => <div data-testid="plot" /> }));- // The install link resolves the configured encoder against the starter- // catalog and queues it; both come from the models feature, so the catalog is- // pinned here and the queueing spied on.const models = vi.hoisted(() => {// A real subscribable store, like the one behind `useActiveInstallSources`:// putting the encoder into (and out of) an in-flight install has to re-renderdiff --cc invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex 204e2ee72c,eb3a0b8edd..04b8420f1a--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@@ -23,18 -23,9 +23,17 @@@ import { isIndexing } from '@workbench/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.+ // Load Plotly only when the map widget is shown.const ImageMapPlot = lazy(() => import('./ImageMapPlot'));const handleRefresh = () => {@@@ -65,12 -49,8 +57,8 @@@ const plotLoadingFallback =</Center>);- /**- * Semantic map of the gallery: every image embedded by the backend's image- * index, projected to 2D with UMAP and colored by cluster. Clicking a point- * selects that image in the gallery (and so in Preview).- */+ /** Show backend embeddings projected by UMAP and colored by cluster; point selection drives Gallery and 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);@@@ -130,31 -80,11 +116,21 @@@// A working map beats a full-screen error: when a refresh fails but prior// points exist, keep showing them (the next successful refresh recovers).if (data && data.points.length > 0) {- // Its own boundary, rather than leaning on WidgetRenderer's. That one wraps- // the whole widget, so suspending on the plotly chunk replaced the entire- // panel — header and actions menu included — with a skeleton frame, and- // then held the resolved content for React's fallback throttle on top. It- // also sits above `loadWidgets`, which preloads only the implementation- // chunk and cannot reach this nested import, so a preset switch onto an- // already-loaded map suspended anyway. Confining it here keeps the frame- // mounted and the spinner where the plot will appear.+ // Keep a nested Suspense boundary around Plotly so its separate lazy load preserves widget chrome and places+ // loading feedback in the plot area.return (- // Positioned so the indexing badge can overlay the plot. That badge is- // 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.- // 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.- // Overlay indexing status on usable stale points because this branch bypasses the progress panel.- <Box h="full" position="relative" w="full">++ // Overlay indexing status on usable stale points because this branch bypasses the progress panel. Focusable so a++ // cleared selection can hand focus back to the map (the chip's button unmounts with it), keeping 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>