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(ui): image map current-image marker, focal-point zoom, auto-recenter

Lincoln Steine5cdcc41b506
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts
new file mode 100644
index 0000000000..b669cc4a94
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts
@@ -0,0 +1,112 @@
+import type { AxisRanges } from './imageMapViewport';
+
+import { zoomFactorFromWheel, zoomRangesAroundFraction } from './imageMapViewport';
+
+/**
+ * Custom wheel + two-finger-pinch zoom for the plotly map. Plotly's built-in
+ * scrollZoom is deliberately off (long-standing Safari/trackpad issues —
+ * PhotoMapAI replaced it the same way); single-finger drag still uses
+ * plotly's native pan.
+ */
+
+interface ZoomHost {
+ /** Read the current axis ranges (null while plotly is initializing). */
+ readRanges: () => AxisRanges | null;
+ /** Apply new axis ranges (a plotly relayout). */
+ applyRanges: (ranges: AxisRanges) => void;
+ /** Stamp pinch activity so a finger-lift is not treated as a click. */
+ onPinch?: () => void;
+}
+
+const touchDistance = (touches: TouchList): number => {
+ const dx = touches[0].clientX - touches[1].clientX;
+ const dy = touches[0].clientY - touches[1].clientY;
+
+ return Math.hypot(dx, dy);
+};
+
+export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => void) => {
+ const zoomAtClientPoint = (clientX: number, clientY: number, factor: number) => {
+ const ranges = host.readRanges();
+
+ if (!ranges) {
+ return;
+ }
+
+ const rect = element.getBoundingClientRect();
+
+ if (rect.width === 0 || rect.height === 0) {
+ return;
+ }
+
+ const fractionX = (clientX - rect.left) / rect.width;
+ // Screen y grows downward; data y grows upward.
+ const fractionY = 1 - (clientY - rect.top) / rect.height;
+ host.applyRanges(zoomRangesAroundFraction(ranges, fractionX, fractionY, factor));
+ };
+
+ const handleWheel = (event: WheelEvent) => {
+ // Also stops ctrl+wheel browser page zoom over the map.
+ event.preventDefault();
+ zoomAtClientPoint(event.clientX, event.clientY, zoomFactorFromWheel(event.deltaY, event.ctrlKey));
+ };
+
+ let pinchDistance: number | null = null;
+
+ const handleTouchStart = (event: TouchEvent) => {
+ if (event.touches.length === 2) {
+ pinchDistance = touchDistance(event.touches);
+ }
+ };
+
+ const handleTouchMove = (event: TouchEvent) => {
+ if (event.touches.length !== 2 || pinchDistance === null) {
+ return;
+ }
+
+ // Coincident touches at gesture start would make the first factor 0 and
+ // collapse the viewport; use the first separated move as the baseline.
+ if (pinchDistance === 0) {
+ pinchDistance = touchDistance(event.touches);
+
+ return;
+ }
+
+ // Capture-phase + stopPropagation keeps plotly's own touch handling from
+ // fighting the pinch (it would pan with one of the two fingers).
+ event.preventDefault();
+ event.stopPropagation();
+ const distance = touchDistance(event.touches);
+
+ if (distance > 0) {
+ const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;
+ const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;
+ zoomAtClientPoint(centerX, centerY, pinchDistance / distance);
+ pinchDistance = distance;
+ host.onPinch?.();
+ }
+ };
+
+ const handleTouchEnd = (event: TouchEvent) => {
+ if (event.touches.length < 2 && pinchDistance !== null) {
+ pinchDistance = null;
+ // Stamp gesture end too: a pinch held still before lifting would
+ // otherwise let plotly's synthetic click through.
+ host.onPinch?.();
+ }
+ };
+
+ element.addEventListener('wheel', handleWheel, { passive: false });
+ element.addEventListener('touchstart', handleTouchStart, { capture: true, passive: true });
+ element.addEventListener('touchmove', handleTouchMove, { capture: true, passive: false });
+ element.addEventListener('touchend', handleTouchEnd, { capture: true, passive: true });
+ element.addEventListener('touchcancel', handleTouchEnd, { capture: true, passive: true });
+
+ return () => {
+ element.removeEventListener('wheel', handleWheel);
+ element.removeEventListener('touchstart', handleTouchStart, { capture: true });
+ element.removeEventListener('touchmove', handleTouchMove, { capture: true });
+ element.removeEventListener('touchend', handleTouchEnd, { capture: true });
+ element.removeEventListener('touchcancel', handleTouchEnd, { capture: true });
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
index 1b12ee65cf..498089522f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
@@ -1,6 +1,7 @@
import type { Layout } from 'plotly.js';
import type { ImageMapPoint } from './api';
+import type { AxisRanges } from './imageMapViewport';
import { getClusterColor } from './clusterPalette';
@@ -25,7 +26,7 @@ export interface ScatterTrace {
mode: 'markers';
type: 'scattergl';
name: string;
- hoverinfo: 'none' | 'text';
+ hoverinfo: 'none' | 'skip' | 'text';
text?: string[];
marker: {
color: string | string[];
@@ -57,7 +58,9 @@ export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({
*/
export const buildCurrentImageTrace = (): ScatterTrace => ({
customdata: [],
- hoverinfo: 'none',
+ // 'skip' (not 'none') excludes the marker from hit-testing entirely, so
+ // clicks and hovers land on the underlying data point it covers.
+ hoverinfo: 'skip',
marker: {
color: '#FFD700',
line: { color: '#000000', width: 2 },
@@ -77,7 +80,7 @@ export const buildCurrentImageTrace = (): ScatterTrace => ({
const GRID_LINE_COLOR = 'rgba(128, 128, 128, 0.16)';
const GRID_ZERO_COLOR = 'rgba(128, 128, 128, 0.32)';
-export const buildMapLayout = (): Partial<Layout> => ({
+export const buildMapLayout = (initialRanges?: AxisRanges | null): Partial<Layout> => ({
dragmode: 'pan',
margin: { b: 0, l: 0, r: 0, t: 0 },
paper_bgcolor: 'rgba(0,0,0,0)',
@@ -91,6 +94,7 @@ export const buildMapLayout = (): Partial<Layout> => ({
// the rest of the map's fixed styling.
gridcolor: GRID_LINE_COLOR,
gridwidth: 1,
+ range: initialRanges?.x,
scaleanchor: 'y',
showgrid: true,
showticklabels: false,
@@ -101,6 +105,7 @@ export const buildMapLayout = (): Partial<Layout> => ({
yaxis: {
gridcolor: GRID_LINE_COLOR,
gridwidth: 1,
+ range: initialRanges?.y,
showgrid: true,
showticklabels: false,
zeroline: true,
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts
new file mode 100644
index 0000000000..bf9d07ad8c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ImageMapPoint } from './api';
+
+import {
+ computePercentileRanges,
+ expandRangesToInclude,
+ fitRangesToAspect,
+ rangesToKeepMarkerInView,
+ zoomFactorFromWheel,
+ zoomRangesAroundFraction,
+ type AxisRanges,
+} from './imageMapViewport';
+
+const point = (x: number, y: number): ImageMapPoint => ({ cluster: 0, imageName: `${x},${y}`, x, y });
+
+describe('computePercentileRanges', () => {
+ it('returns null for no points and a non-degenerate box for one point', () => {
+ expect(computePercentileRanges([])).toBeNull();
+
+ const single = computePercentileRanges([point(3, 4)]);
+ expect(single).not.toBeNull();
+ expect(single!.x[0]).toBeLessThan(3);
+ expect(single!.x[1]).toBeGreaterThan(3);
+ expect(single!.y[0]).toBeLessThan(4);
+ expect(single!.y[1]).toBeGreaterThan(4);
+ });
+
+ it('excludes extreme outliers from the initial view', () => {
+ const cloud = Array.from({ length: 999 }, (_, i) => point(i % 10, Math.floor(i / 100)));
+ const withOutlier = [...cloud, point(10_000, 10_000)];
+
+ const ranges = computePercentileRanges(withOutlier);
+
+ expect(ranges!.x[1]).toBeLessThan(100);
+ expect(ranges!.y[1]).toBeLessThan(100);
+ });
+});
+
+describe('zoomRangesAroundFraction', () => {
+ const ranges: AxisRanges = { x: [0, 10], y: [100, 200] };
+
+ it('keeps the focal point fixed while scaling the span', () => {
+ const zoomed = zoomRangesAroundFraction(ranges, 0.25, 0.5, 0.5);
+
+ // Focal x = 2.5 sits at 25% of the new range; focal y = 150 at 50%.
+ expect(zoomed.x[0] + (zoomed.x[1] - zoomed.x[0]) * 0.25).toBeCloseTo(2.5);
+ expect(zoomed.y[0] + (zoomed.y[1] - zoomed.y[0]) * 0.5).toBeCloseTo(150);
+ expect(zoomed.x[1] - zoomed.x[0]).toBeCloseTo(5);
+ expect(zoomed.y[1] - zoomed.y[0]).toBeCloseTo(50);
+ });
+
+ it('never collapses or inverts ranges for non-positive factors', () => {
+ const collapsed = zoomRangesAroundFraction(ranges, 0.5, 0.5, 0);
+ expect(collapsed.x[1]).toBeGreaterThan(collapsed.x[0]);
+ expect(collapsed.y[1]).toBeGreaterThan(collapsed.y[0]);
+ });
+
+ it('is the inverse of itself with the reciprocal factor', () => {
+ const there = zoomRangesAroundFraction(ranges, 0.3, 0.7, 2);
+ const back = zoomRangesAroundFraction(there, 0.3, 0.7, 0.5);
+
+ expect(back.x[0]).toBeCloseTo(ranges.x[0]);
+ expect(back.x[1]).toBeCloseTo(ranges.x[1]);
+ expect(back.y[0]).toBeCloseTo(ranges.y[0]);
+ expect(back.y[1]).toBeCloseTo(ranges.y[1]);
+ });
+});
+
+describe('zoomFactorFromWheel', () => {
+ it('zooms out on positive deltas, in on negative, faster for pinch', () => {
+ expect(zoomFactorFromWheel(100, false)).toBeCloseTo(Math.exp(0.1), 10);
+ expect(zoomFactorFromWheel(-100, false)).toBeCloseTo(Math.exp(-0.1), 10);
+ expect(zoomFactorFromWheel(100, true)).toBeCloseTo(Math.exp(1), 10);
+ });
+});
+
+describe('rangesToKeepMarkerInView', () => {
+ const ranges: AxisRanges = { x: [0, 10], y: [0, 10] };
+
+ it('returns null when the marker is comfortably inside', () => {
+ expect(rangesToKeepMarkerInView(ranges, { x: 5, y: 5 })).toBeNull();
+ expect(rangesToKeepMarkerInView(ranges, { x: 1.5, y: 8.5 })).toBeNull();
+ });
+
+ it('recenters on the marker while preserving the zoom width', () => {
+ const recentered = rangesToKeepMarkerInView(ranges, { x: 25, y: 0.2 });
+
+ expect(recentered).not.toBeNull();
+ expect(recentered!.x[1] - recentered!.x[0]).toBeCloseTo(10);
+ expect(recentered!.y[1] - recentered!.y[0]).toBeCloseTo(10);
+ expect((recentered!.x[0] + recentered!.x[1]) / 2).toBeCloseTo(25);
+ expect((recentered!.y[0] + recentered!.y[1]) / 2).toBeCloseTo(0.2);
+ });
+
+ it('treats the pad band as out of view', () => {
+ // Within 10% of the edge -> recenter.
+ expect(rangesToKeepMarkerInView(ranges, { x: 0.5, y: 5 })).not.toBeNull();
+ expect(rangesToKeepMarkerInView(ranges, { x: 5, y: 9.8 })).not.toBeNull();
+ });
+});
+
+describe('fitRangesToAspect', () => {
+ const box = { x: [0, 10] as [number, number], y: [0, 20] as [number, number] };
+
+ const containsBox = (outer: { x: [number, number]; y: [number, number] }) =>
+ outer.x[0] <= box.x[0] && outer.x[1] >= box.x[1] && outer.y[0] <= box.y[0] && outer.y[1] >= box.y[1];
+
+ it('only ever expands, and matches the requested aspect ratio', () => {
+ for (const aspect of [0.25, 0.5, 1, 2, 4]) {
+ const fitted = fitRangesToAspect(box, aspect);
+
+ expect(containsBox(fitted)).toBe(true);
+ expect((fitted.x[1] - fitted.x[0]) / (fitted.y[1] - fitted.y[0])).toBeCloseTo(aspect);
+ }
+ });
+
+ it('returns the input unchanged for degenerate aspect ratios', () => {
+ expect(fitRangesToAspect(box, 0)).toEqual(box);
+ expect(fitRangesToAspect(box, Number.NaN)).toEqual(box);
+ });
+
+ it('keeps at least 90% of points in view for any container shape', () => {
+ // The user-facing contract for the first render: the fitted view must
+ // show (nearly) the whole map, however skewed the container.
+ const points = Array.from({ length: 100 }, (_, index) => ({
+ cluster: 0,
+ imageName: `p${index}.png`,
+ x: Math.sin(index * 2.399) * 13,
+ y: Math.cos(index * 1.618) * 7 + (index % 10),
+ }));
+ const percentile = computePercentileRanges(points)!;
+
+ for (const aspect of [0.3, 1, 3.5]) {
+ const fitted = fitRangesToAspect(percentile, aspect);
+ const visible = points.filter(
+ (point) => point.x >= fitted.x[0] && point.x <= fitted.x[1] && point.y >= fitted.y[0] && point.y <= fitted.y[1]
+ );
+
+ expect(visible.length).toBeGreaterThanOrEqual(90);
+ }
+ });
+});
+
+describe('expandRangesToInclude', () => {
+ const box = { x: [0, 10] as [number, number], y: [0, 10] as [number, number] };
+
+ it('leaves ranges unchanged when the point is comfortably inside', () => {
+ expect(expandRangesToInclude(box, { x: 5, y: 5 })).toEqual(box);
+ });
+
+ it('grows the box so an outside point sits inside with margin', () => {
+ const grown = expandRangesToInclude(box, { x: 14, y: -3 });
+
+ expect(grown.x[1]).toBeGreaterThan(14);
+ expect(grown.y[0]).toBeLessThan(-3);
+ // Untouched edges stay put.
+ expect(grown.x[0]).toBe(0);
+ expect(grown.y[1]).toBe(10);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts
new file mode 100644
index 0000000000..2302517c89
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts
@@ -0,0 +1,165 @@
+import type { ImageMapPoint } from './api';
+
+/**
+ * Pure viewport math for the image map: initial axis ranges, focal-point
+ * zoom, and keep-the-marker-in-view recentering. Kept free of plotly/DOM so
+ * every invariant is unit-testable.
+ */
+
+export interface AxisRanges {
+ x: [number, number];
+ y: [number, number];
+}
+
+const RANGE_PAD_FRACTION = 0.05;
+
+const quantile = (sorted: number[], q: number): number => {
+ if (sorted.length === 0) {
+ return 0;
+ }
+
+ const position = (sorted.length - 1) * q;
+ const lower = Math.floor(position);
+ const upper = Math.ceil(position);
+ const weight = position - lower;
+
+ return sorted[lower] * (1 - weight) + sorted[upper] * weight;
+};
+
+/**
+ * Initial view: the 1st..99th percentile of each axis (PhotoMapAI's choice —
+ * a handful of outlier points must not dwarf the whole map), padded slightly.
+ */
+export const computePercentileRanges = (
+ points: ImageMapPoint[],
+ lowerQ: number = 0.01,
+ upperQ: number = 0.99
+): AxisRanges | null => {
+ if (points.length === 0) {
+ return null;
+ }
+
+ const xs = points.map((point) => point.x).sort((a, b) => a - b);
+ const ys = points.map((point) => point.y).sort((a, b) => a - b);
+ const build = (values: number[]): [number, number] => {
+ const low = quantile(values, lowerQ);
+ const high = quantile(values, upperQ);
+ // Degenerate spans (single point, tiny gallery) still need a visible box.
+ const pad = Math.max((high - low) * RANGE_PAD_FRACTION, 1e-3);
+
+ return [low - pad, high + pad];
+ };
+
+ return { x: build(xs), y: build(ys) };
+};
+
+/**
+ * Grow ranges minimally so `point` sits at least `padFraction` of the span
+ * inside every edge. Used before the initial fit so the current-image marker
+ * starts comfortably in view and the auto-recenter has no reason to shift
+ * the freshly fitted map.
+ */
+export const expandRangesToInclude = (
+ ranges: AxisRanges,
+ point: { x: number; y: number },
+ padFraction: number = 0.15
+): AxisRanges => {
+ const expandAxis = (range: [number, number], value: number): [number, number] => {
+ const pad = (range[1] - range[0]) * padFraction;
+
+ return [Math.min(range[0], value - pad), Math.max(range[1], value + pad)];
+ };
+
+ return { x: expandAxis(ranges.x, point.x), y: expandAxis(ranges.y, point.y) };
+};
+
+/**
+ * Expand ranges so the whole box stays visible in a plot whose axes are
+ * constrained to equal unit scale (xaxis.scaleanchor = 'y'). Handing plotly
+ * an over-constrained range pair makes it re-solve against the container's
+ * aspect ratio, which can CROP one axis — silently zooming the first render
+ * into a sliver of the map. Pre-expanding the narrower constraint instead
+ * guarantees everything inside the box remains in view. Only ever expands.
+ */
+export const fitRangesToAspect = (ranges: AxisRanges, aspectRatio: number): AxisRanges => {
+ if (!Number.isFinite(aspectRatio) || aspectRatio <= 0) {
+ return ranges;
+ }
+
+ const spanX = ranges.x[1] - ranges.x[0];
+ const spanY = ranges.y[1] - ranges.y[0];
+
+ if (spanX <= 0 || spanY <= 0) {
+ return ranges;
+ }
+
+ const centerX = (ranges.x[0] + ranges.x[1]) / 2;
+ const centerY = (ranges.y[0] + ranges.y[1]) / 2;
+
+ if (spanX / spanY < aspectRatio) {
+ const nextSpanX = spanY * aspectRatio;
+
+ return { x: [centerX - nextSpanX / 2, centerX + nextSpanX / 2], y: ranges.y };
+ }
+
+ const nextSpanY = spanX / aspectRatio;
+
+ return { x: ranges.x, y: [centerY - nextSpanY / 2, centerY + nextSpanY / 2] };
+};
+
+/** exp() gain per wheel tick; ctrl+wheel is trackpad pinch and moves faster. */
+export const zoomFactorFromWheel = (deltaY: number, isPinch: boolean): number =>
+ Math.exp(deltaY * (isPinch ? 0.01 : 0.001));
+
+/**
+ * Scale both ranges by `factor` while keeping the point at the given
+ * fractional position (0..1 from each range's start) fixed on screen.
+ */
+export const zoomRangesAroundFraction = (
+ ranges: AxisRanges,
+ fractionX: number,
+ fractionY: number,
+ factor: number
+): AxisRanges => {
+ // A non-positive factor would collapse or invert the ranges.
+ factor = Math.max(factor, 1e-6);
+
+ const zoomAxis = (range: [number, number], fraction: number): [number, number] => {
+ const width = range[1] - range[0];
+ const focal = range[0] + width * fraction;
+ const nextWidth = width * factor;
+
+ return [focal - nextWidth * fraction, focal + nextWidth * (1 - fraction)];
+ };
+
+ return { x: zoomAxis(ranges.x, fractionX), y: zoomAxis(ranges.y, fractionY) };
+};
+
+/**
+ * If the point sits within `padFraction` of (or beyond) a viewport edge,
+ * translate the ranges to center it — preserving the zoom width. Returns
+ * null when the point is comfortably in view.
+ */
+export const rangesToKeepMarkerInView = (
+ ranges: AxisRanges,
+ point: { x: number; y: number },
+ padFraction: number = 0.1
+): AxisRanges | null => {
+ const isComfortable = (range: [number, number], value: number): boolean => {
+ const pad = (range[1] - range[0]) * padFraction;
+
+ return value >= range[0] + pad && value <= range[1] - pad;
+ };
+
+ if (isComfortable(ranges.x, point.x) && isComfortable(ranges.y, point.y)) {
+ return null;
+ }
+
+ const center = (range: [number, number], value: number): [number, number] => {
+ const half = (range[1] - range[0]) / 2;
+
+ return [value - half, value + half];
+ };
+
+ return { x: center(ranges.x, point.x), y: center(ranges.y, point.y) };
+};
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 dffbc3cdac..9e8ce15d7d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
@@ -1,13 +1,94 @@
+import type { ImageMapPoint } from '@workbench/image-map/api';
+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 { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';
import { imageMapStore } from '@workbench/image-map/imageMapStore';
-import { buildAllPointsTrace, buildCurrentImageTrace, buildMapLayout } from '@workbench/image-map/imageMapTraces';
+import {
+ buildAllPointsTrace,
+ buildCurrentImageTrace,
+ buildMapLayout,
+ CURRENT_IMAGE_TRACE,
+} from '@workbench/image-map/imageMapTraces';
+import {
+ computePercentileRanges,
+ expandRangesToInclude,
+ fitRangesToAspect,
+ rangesToKeepMarkerInView,
+} from '@workbench/image-map/imageMapViewport';
+import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';
import Plotly from 'plotly.js-gl2d-dist-min';
import { useEffect, useRef } from 'react';
import { useSelectMapImage } from './useSelectMapImage';
+/** Suppress the synthetic click plotly fires when a pinch gesture ends. */
+const PINCH_CLICK_SUPPRESS_MS = 500;
+
+/** How long a map click may suppress the recenter its own selection causes. */
+const MAP_CLICK_SUPPRESS_MS = 5000;
+
+/** These plotly calls can reject on a plot whose WebGL init failed; the map
+ * already shows the store's error state, so the rejection itself is noise. */
+const swallow = (promise: Promise<unknown>): void => {
+ promise.catch(() => {});
+};
+
+interface PlotElement extends PlotlyHTMLElement {
+ _fullLayout?: {
+ xaxis?: { range?: [number, number] };
+ yaxis?: { range?: [number, number] };
+ };
+}
+
+const readRanges = (plot: PlotElement): AxisRanges | null => {
+ const x = plot._fullLayout?.xaxis?.range;
+ const y = plot._fullLayout?.yaxis?.range;
+
+ return x && y ? { x: [x[0], x[1]], y: [y[0], y[1]] } : null;
+};
+
+/**
+ * The whole-map view for the first properly-sized render: the percentile box
+ * expanded to include the current-image marker (so the auto-recenter has no
+ * reason to immediately shift it), then aspect-corrected to the container.
+ * The axes are constrained to equal unit scale, and letting plotly resolve an
+ * over-constrained range pair itself can crop one axis — a first render in a
+ * still-unmeasured container ends up zoomed into a sliver of the map, which
+ * the view-preservation on later renders would then keep forever.
+ */
+const computeInitialFit = (
+ points: ImageMapPoint[],
+ selectedImageName: string | null,
+ width: number,
+ height: number
+): AxisRanges | null => {
+ if (points.length === 0 || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ let box = computePercentileRanges(points);
+
+ if (!box) {
+ return null;
+ }
+
+ const selected = selectedImageName
+ ? points.find((candidate) => candidate.imageName === selectedImageName)
+ : undefined;
+
+ if (selected) {
+ box = expandRangesToInclude(box, selected);
+ }
+
+ return fitRangesToAspect(box, width / height);
+};
+
+const findTraceIndex = (plot: PlotElement, name: string): number =>
+ (plot.data ?? []).findIndex((trace) => (trace as { name?: string }).name === name);
+
/**
* Imperative plotly host. All plotly calls happen in effects against a ref
* div — plotly manages its own DOM and must never render through JSX. This
@@ -17,7 +98,25 @@ import { useSelectMapImage } from './useSelectMapImage';
const ImageMapPlot = () => {
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();
+ 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
+ // first render where the container has real dimensions; these refs let the
+ // scene effect and the resize observer coordinate without re-running.
+ const initialFitDoneRef = useRef(false);
+ const pointsRef = useRef(points);
+ const selectedImageNameRef = useRef(selectedImageName);
+
+ // Declared before the effects below so the refs are fresh when they run.
+ useEffect(() => {
+ pointsRef.current = points;
+ selectedImageNameRef.current = selectedImageName;
+ }, [points, selectedImageName]);
useEffect(() => {
const container = containerRef.current;
@@ -29,10 +128,31 @@ const ImageMapPlot = () => {
const traces = [buildAllPointsTrace(points), buildCurrentImageTrace()];
let disposed = false;
- void Plotly.react(container, traces as Plotly.Data[], buildMapLayout(), {
+ // 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.
+ let initialRanges = readRanges(container as unknown as PlotElement) ?? computePercentileRanges(points);
+
+ if (!initialFitDoneRef.current) {
+ const fitted = computeInitialFit(
+ points,
+ selectedImageNameRef.current,
+ container.offsetWidth,
+ container.offsetHeight
+ );
+
+ if (fitted) {
+ initialRanges = fitted;
+ initialFitDoneRef.current = true;
+ }
+ }
+
+ void Plotly.react(container, traces as Plotly.Data[], buildMapLayout(initialRanges), {
displayModeBar: false,
- // Wheel/pinch zoom is replaced with custom handlers in a later PR;
- // plotly's own scrollZoom has long-standing Safari issues.
+ // Custom wheel/pinch zoom below; plotly's own scrollZoom has
+ // long-standing Safari issues.
scrollZoom: false,
})
.then((plot: PlotlyHTMLElement) => {
@@ -42,9 +162,18 @@ const ImageMapPlot = () => {
plot.removeAllListeners?.('plotly_click');
plot.on('plotly_click', (event) => {
+ if (Date.now() - lastPinchAtRef.current < PINCH_CLICK_SUPPRESS_MS) {
+ return;
+ }
+
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 };
selectImage(imageName);
}
});
@@ -70,22 +199,99 @@ const ImageMapPlot = () => {
};
}, [points, selectImage]);
- // Track the widget frame's size; plotly does not observe its container.
+ // Live gold target on the currently selected gallery image, with a gentle
+ // recenter (zoom width preserved) when it drifts near or beyond an edge.
useEffect(() => {
- const container = containerRef.current;
+ const container = containerRef.current as PlotElement | null;
+
+ if (!container || points === null) {
+ return;
+ }
+
+ const markerIndex = findTraceIndex(container, CURRENT_IMAGE_TRACE);
+
+ if (markerIndex < 0) {
+ return;
+ }
+
+ const point = selectedImageName ? points.find((candidate) => candidate.imageName === selectedImageName) : undefined;
+
+ if (!point) {
+ swallow(Plotly.restyle(container, { x: [[]], y: [[]] }, [markerIndex]));
+
+ return;
+ }
+
+ swallow(Plotly.restyle(container, { x: [[point.x]], y: [[point.y]] }, [markerIndex]));
+
+ const suppression = lastMapSelectionRef.current;
+ const cameFromMapClick =
+ suppression !== null &&
+ suppression.name === selectedImageName &&
+ Date.now() - suppression.at < MAP_CLICK_SUPPRESS_MS;
+
+ if (suppression !== null && suppression.name === selectedImageName) {
+ // Consume only a matching entry; an interleaved external selection
+ // keeps a pending map click's suppression intact for when it lands.
+ lastMapSelectionRef.current = null;
+ }
+
+ if (cameFromMapClick) {
+ return;
+ }
+
+ const ranges = readRanges(container);
+ const recentered = ranges ? rangesToKeepMarkerInView(ranges, point) : null;
+
+ if (recentered) {
+ swallow(Plotly.relayout(container, { 'xaxis.range': recentered.x, 'yaxis.range': recentered.y }));
+ }
+ }, [points, selectedImageName]);
+
+ // Custom zoom handlers + container size tracking, attached once for the
+ // plot's lifetime; plotly does not observe its container.
+ useEffect(() => {
+ const container = containerRef.current as PlotElement | null;
if (!container) {
return;
}
+ const detachZoom = attachWheelZoom(container, {
+ applyRanges: (ranges) => {
+ swallow(Plotly.relayout(container, { 'xaxis.range': ranges.x, 'yaxis.range': ranges.y }));
+ },
+ onPinch: () => {
+ lastPinchAtRef.current = Date.now();
+ },
+ readRanges: () => readRanges(container),
+ });
+
const observer = new ResizeObserver(() => {
if (container.offsetWidth > 0 && container.offsetHeight > 0) {
void Plotly.Plots.resize(container);
+
+ // A plot first built while the container was unmeasured never got
+ // its whole-map fit; apply it on the first real layout.
+ if (!initialFitDoneRef.current) {
+ const fitted = computeInitialFit(
+ pointsRef.current ?? [],
+ selectedImageNameRef.current,
+ container.offsetWidth,
+ container.offsetHeight
+ );
+
+ if (fitted) {
+ swallow(Plotly.relayout(container, { 'xaxis.range': fitted.x, 'yaxis.range': fitted.y }));
+ initialFitDoneRef.current = true;
+ }
+ }
}
});
observer.observe(container);
return () => {
+ detachZoom();
observer.disconnect();
Plotly.purge(container);
};