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.

fix(canvas): show the whole canvas in the overview pane

Josh Corbette6470e8a4e92
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 38e1cafbfa..47f9bdc102 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -100,7 +100,7 @@ Canvas invocation first crosses paint-flush barrier, then captures post-flush do
## Frame demand before allocation
-Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The screen description also carries which overlay stacks it shows: while a generation is staged (the staging area holds a candidate, shown or not, or a staged or progress preview is published) it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted; control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame, joins the description's reuse key, and its flip repaints in full once.
+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a generation is staged (the staging area holds a candidate, shown or not, or a staged or progress preview is published) it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted; control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame, joins the description's reuse key, and its flip repaints in full once.
`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: intersects each drawable leaf's bounds with document-space viewport. Explicitly isolated operation target is the one exception to normal document visibility: stays demanded and drawable when disabled or display-hidden, because user acts on that named layer directly.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index a660c8cba0..b5c730cd3f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -673,8 +673,10 @@ export interface CanvasEngineExportCapability extends CanvasExportCapability {
export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {
/**
- * Sizes `target` and draws the whole document fitted to `maxSizePx`. Returns its drawn rect, or null without a
- * document.
+ * Sizes `target` to fit `maxSizePx` (never above 1:1) and draws the committed document's extent into it: the frame
+ * joined with every enabled renderable layer's bounds, the same extent `fitToView` fits. Returns that
+ * document-space rect, which the caller maps between target pixels and document space with (target pixel =
+ * (document point - rect origin) * target.width / rect.width); null without a document or 2D context.
*/
drawDocumentOverview(target: HTMLCanvasElement, maxSizePx: number): Rect | null;
preloadStagedPreview(imageName: string): void;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 8a996a237d..9121ad53f1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -15416,6 +15416,47 @@ describe('fitToView: content ∪ bbox', () => {
});
});
+describe('overview: composites the fit-to-view extent', () => {
+ const paintAt = (id: string, x: number, y: number, isEnabled = true): CanvasLayerContract => ({
+ ...(rasterLayer(id) as CanvasRasterLayerContractV2),
+ isEnabled,
+ source: { bitmap: { height: 100, imageName: `${id}-pixels`, width: 100 }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y },
+ });
+ const overviewTarget = (): HTMLCanvasElement =>
+ ({
+ getContext: () => createTestStubRasterBackend().createSurface(1, 1).ctx,
+ height: 0,
+ width: 0,
+ }) as unknown as HTMLCanvasElement;
+
+ it('sizes, translates and reports the frame ∪ enabled content, leaving disabled layers out', () => {
+ const composite = vi.spyOn(compositor, 'compositeDocument');
+ // Frame (0,0)..(100,100) ∪ enabled paint (-200,-50)..(-100,50) = (-200,-50) 300×150; the disabled layer at
+ // (500,500) would stretch it to 800×650.
+ const { store } = createReactiveStore(
+ noLayerDoc({ stacks: stacksFrom([paintAt('outside', -200, -50), paintAt('hidden', 500, 500, false)]) })
+ );
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ const target = overviewTarget();
+
+ const shown = engine.previews.drawDocumentOverview(target, 150);
+
+ expect(shown).toEqual({ height: 150, width: 300, x: -200, y: -50 });
+ expect({ height: target.height, width: target.width }).toEqual({ height: 75, width: 150 });
+ // Half scale, shifted so document (-200,-50) lands on target pixel (0,0).
+ expect(composite.mock.calls.at(-1)?.[3]).toEqual({ a: 0.5, b: 0, c: 0, d: 0.5, e: 100, f: 25 });
+ composite.mockRestore();
+ engine.lifecycle.dispose();
+ });
+});
+
// ---- transform session: param commit (image) + pixel bake (paint) ----------
describe('masks while a result is staged', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 53b4a3e49e..54f672afc6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -2089,19 +2089,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
let hasEverFitToView = false;
+ /**
+ * The document's navigable extent: the bbox (the empty-canvas anchor) joined with every enabled renderable
+ * layer's source bounds. Fit-to-view and the overview share it so both show the same canvas.
+ */
+ const getDocumentExtent = (doc: CanvasDocumentContractV3): Rect => {
+ let extent: Rect = { ...doc.bbox };
+ for (const leaf of compileDocumentLeaves(doc)) {
+ if (leaf.contributionEnabled && isRenderableLayer(leaf.layer)) {
+ extent = union(extent, getSourceBounds(leaf.layer, doc));
+ }
+ }
+ return extent;
+ };
+
const fitToView = (): void => {
const doc = mirror.getDocument();
if (!doc) {
return;
}
- // Fit content union bbox, using the bbox as the empty-canvas anchor and including content beyond it.
- let bounds: Rect = { ...doc.bbox };
- for (const leaf of compileDocumentLeaves(doc)) {
- if (leaf.contributionEnabled && isRenderableLayer(leaf.layer)) {
- bounds = union(bounds, getSourceBounds(leaf.layer, doc));
- }
- }
- viewport.fitToView(bounds, viewport.getViewportSize());
+ viewport.fitToView(getDocumentExtent(doc), viewport.getViewportSize());
hasEverFitToView = true;
};
@@ -2930,7 +2937,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const drawDocumentOverview = (target: HTMLCanvasElement, maxSizePx: number): Rect | null => {
const doc = mirror.getDocument();
const ctx = target.getContext('2d');
- if (!doc || !ctx || doc.width <= 0 || doc.height <= 0) {
+ if (!doc || !ctx) {
+ return null;
+ }
+ const extent = getDocumentExtent(doc);
+ if (isEmpty(extent)) {
return null;
}
// Overview requests missing offscreen caches and repaints after publication. Attempt each layer once per
@@ -2953,17 +2964,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
if (missing.length > 0) {
scheduleLayerRasterization(missing);
}
- const size = fitThumbnailSize(doc.width, doc.height, maxSizePx);
+ const size = fitThumbnailSize(extent.width, extent.height, maxSizePx);
target.width = size.width;
target.height = size.height;
- const scale = size.width / doc.width;
+ const scale = size.width / extent.width;
// Only `ctx`/`width`/`height` are read by the compositor; the element is not resized through the surface seam.
const surfaceLike = { canvas: target, ctx, height: size.height, width: size.width } as unknown as RasterSurface;
compositeDocument(
surfaceLike,
doc,
layerCache,
- { a: scale, b: 0, c: 0, d: scale, e: 0, f: 0 },
+ // Translate so the extent's origin lands on the target's top-left pixel.
+ { a: scale, b: 0, c: 0, d: scale, e: -extent.x * scale, f: -extent.y * scale },
{
adjustedSurface: getAdjustedSurface,
backend,
@@ -2975,7 +2987,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
regionOverlays: true,
}
);
- return { height: doc.height, width: doc.width, x: 0, y: 0 };
+ return extent;
};
const previewCapability: CanvasEnginePreviewCapability = {
...layerController.previews,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index a8709facf8..5c4184625e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -164,16 +164,6 @@ export const useCanvasDocumentEditingLocked = (engine: CanvasCoreStoreCapability
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
};
-/** Re-renders when any live layer cache gains, loses, or changes pixels. */
-export const useCanvasLayerPixelEpoch = (engine: CanvasCoreStoreCapability | null): number => {
- const subscribe = useCallback(
- (listener: () => void) => engine?.interaction.subscribe('layerPixelEpoch', listener) ?? (() => undefined),
- [engine]
- );
- const getSnapshot = useCallback(() => engine?.interaction.get('layerPixelEpoch') ?? 0, [engine]);
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
-};
-
/** Read/write brush options directly through engine.interaction; no reducer mirror exists. */
export const useBrushOptions = (engine: CanvasCoreStoreCapability): BrushOptions =>
useCanvasInteractionState(engine, 'brushOptions');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index 09e6c04c2b..7c0d9456bc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -123,7 +123,11 @@ const createEngineDeps = (): EngineDeps => {
commitEdit: () => undefined,
dispatch: () => false,
getCanvasState: () => harness.project?.canvas ?? createEmptyCanvasState(64, 64),
- subscribe: () => () => undefined,
+ // Harness project changes reach the engine's document mirror, as reducer dispatches do in the app.
+ subscribe: (listener) => {
+ harness.listeners.add(listener);
+ return () => harness.listeners.delete(listener);
+ },
};
return {
getMainModelBase: () => null,
@@ -232,7 +236,11 @@ const GRADIENT_SOURCE = {
width: 10,
} satisfies Extract<CanvasLayerSourceContract, { type: 'gradient' }>;
-const mount = async (View: typeof PropertiesPane, selection: Selection = 'none') => {
+const mount = async (
+ View: typeof PropertiesPane,
+ selection: Selection = 'none',
+ extraNodes: Parameters<typeof stacksFrom>[0] = []
+) => {
const base = { ...createInitialWorkbenchState().projects[0]!, id: 'p' };
const nodes =
selection === 'none'
@@ -257,7 +265,7 @@ const mount = async (View: typeof PropertiesPane, selection: Selection = 'none')
document: {
...createEmptyCanvasDocument(),
selectedLayerId: selection === 'none' ? null : selection === 'mask' ? 'm0' : selection === 'group' ? 'g0' : 'l0',
- stacks: stacksFrom(nodes),
+ stacks: stacksFrom([...nodes, ...extraNodes]),
},
type: 'replaceCanvasDocument',
});
@@ -1055,4 +1063,104 @@ describe('Overview pane', () => {
const after = viewport.getState().pan;
expect(after.x === before.x && after.y === before.y).toBe(false);
});
+
+ it('shows content beyond the frame and centres the view on the clicked point there', async () => {
+ // Outpainted pixels left of the default 1024² frame at the origin.
+ const outpaint = layerContract('outpaint', 'raster', {
+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },
+ transform: { ...IDENTITY, x: -1024 },
+ });
+ await mount(OverviewHarness, 'none', [outpaint]);
+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });
+ await expect.element(pan).toBeVisible();
+ const canvas = pan.element().querySelector('canvas')!;
+ // Frame (0,0) 1024×1024 ∪ content (-1024,0) 1024×512 = (-1024,0) 2048×1024.
+ expect(canvas.width).toBeGreaterThan(0);
+ expect(canvas.width / canvas.height).toBeCloseTo(2, 1);
+ const unitsPerPx = 2048 / canvas.width;
+ const viewport = engine!.viewport.getViewport();
+ engine!.surface.resize(400, 300, 1);
+
+ const offset = { x: 3, y: 3 };
+ await act(async () => {
+ await userEvent.click(canvas, { position: offset });
+ });
+ await settle();
+
+ const centre = viewport.screenToDocument({ x: 200, y: 150 });
+ const expected = { x: -1024 + offset.x * unitsPerPx, y: offset.y * unitsPerPx };
+ expect(expected.x).toBeLessThan(0);
+ expect(Math.abs(centre.x - expected.x)).toBeLessThan(unitsPerPx);
+ expect(Math.abs(centre.y - expected.y)).toBeLessThan(unitsPerPx);
+ // The outline is centred where the click landed on the bitmap.
+ const outline = pan.element().querySelector('div')!;
+ await expect
+ .poll(() => parseFloat(outline.style.left) + parseFloat(outline.style.width) / 2)
+ .toBeCloseTo(offset.x, 0);
+ await expect
+ .poll(() => parseFloat(outline.style.top) + parseFloat(outline.style.height) / 2)
+ .toBeCloseTo(offset.y, 0);
+ });
+
+ it('zooms the view around the document point under the wheel', async () => {
+ const outpaint = layerContract('outpaint', 'raster', {
+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },
+ transform: { ...IDENTITY, x: -1024 },
+ });
+ await mount(OverviewHarness, 'none', [outpaint]);
+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });
+ await expect.element(pan).toBeVisible();
+ const canvas = pan.element().querySelector('canvas')!;
+ const unitsPerPx = 2048 / canvas.width;
+ const viewport = engine!.viewport.getViewport();
+ engine!.surface.resize(400, 300, 1);
+ const offset = { x: 10, y: 20 };
+ // Frame (0,0) 1024×1024 ∪ content (-1024,0) 1024×512 puts document (-1024,0) at the overview's top-left.
+ const documentPoint = { x: -1024 + offset.x * unitsPerPx, y: offset.y * unitsPerPx };
+ const anchor = viewport.documentToScreen(documentPoint);
+ const zoomBefore = viewport.getZoom();
+
+ const bounds = canvas.getBoundingClientRect();
+ act(() => {
+ pan.element().dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: bounds.left + offset.x,
+ clientY: bounds.top + offset.y,
+ deltaY: -100,
+ })
+ );
+ });
+
+ expect(viewport.getZoom()).toBeGreaterThan(zoomBefore);
+ const anchored = viewport.documentToScreen(documentPoint);
+ expect(Math.abs(anchored.x - anchor.x)).toBeLessThan(0.5);
+ expect(Math.abs(anchored.y - anchor.y)).toBeLessThan(0.5);
+ });
+
+ it('redraws to the new extent when a document edit moves content after mount', async () => {
+ await mount(OverviewHarness);
+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });
+ await expect.element(pan).toBeVisible();
+ const canvas = pan.element().querySelector('canvas')!;
+ // The empty document shows only its 1024² frame.
+ expect(canvas.width / canvas.height).toBeCloseTo(1, 1);
+
+ // Content 1024×512 placed above the frame: (0,-512)..(1024,1024) = 1024×1536.
+ const outpaint = layerContract('outpaint', 'raster', {
+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },
+ transform: { ...IDENTITY, y: -512 },
+ });
+ act(() => {
+ const project = harness.project!;
+ harness.project = applyCanvasProjectMutation(project, {
+ document: { ...project.canvas.document, stacks: stacksFrom([outpaint]) },
+ type: 'replaceCanvasDocument',
+ });
+ harness.listeners.forEach((listener) => listener());
+ });
+
+ await expect.poll(() => canvas.width / canvas.height, { timeout: 2000 }).toBeCloseTo(1024 / 1536, 1);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx
index b7bffd7b70..5007e5ca47 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx
@@ -2,9 +2,7 @@ import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerE
import { Box, chakra, Flex } from '@chakra-ui/react';
import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import { useCanvasLayerPixelEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
const KEY_PAN_STEP_PX = 40;
@@ -40,175 +38,181 @@ export const OverviewPane = () => {
return <ConnectedOverview engine={engine} />;
};
-interface OverviewFrame {
- /** Preview pixels per document unit. */
+/** How the drawn bitmap maps to document space: target pixel = (document point − origin) × scale. */
+interface OverviewMapping {
+ /** Document-space point drawn at the target's top-left pixel. */
+ x: number;
+ y: number;
+ /** Target pixels per document unit. */
scale: number;
- widthPx: number;
- heightPx: number;
}
+const clientToDocument = (
+ mapping: OverviewMapping,
+ canvasBounds: DOMRect,
+ clientX: number,
+ clientY: number
+): { x: number; y: number } => ({
+ x: mapping.x + (clientX - canvasBounds.left) / mapping.scale,
+ y: mapping.y + (clientY - canvasBounds.top) / mapping.scale,
+});
+
const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {
const { t } = useTranslation();
- const hostRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const viewRectRef = useRef<HTMLDivElement>(null);
const drag = useRef<AbortController | null>(null);
- const [hostSize, setHostSize] = useState<{ width: number; height: number }>({ height: 0, width: 0 });
-
- const pixelEpoch = useCanvasLayerPixelEpoch(engine);
- const stacks = useActiveProjectSelector((project) => project.canvas.document.stacks);
- const docWidth = useActiveProjectSelector((project) => project.canvas.document.width);
- const docHeight = useActiveProjectSelector((project) => project.canvas.document.height);
+ // Written after each draw from the rect the engine reports, so pointer mapping and the outline match the bitmap.
+ const mapping = useRef<OverviewMapping | null>(null);
- useEffect(() => {
- const host = hostRef.current;
- if (!host) {
- return;
- }
- const observer = new ResizeObserver((observations) => {
- const content = observations[0]?.contentRect;
- if (content) {
- setHostSize({ height: content.height, width: content.width });
+ // Engine-keyed host binding: the host's size, the engine's document and pixel signals, and the viewport drive the
+ // bitmap and outline imperatively, without re-rendering the pane.
+ const bindHost = useCallback(
+ (host: HTMLDivElement | null) => {
+ const canvas = canvasRef.current;
+ const button = buttonRef.current;
+ const outline = viewRectRef.current;
+ if (!host || !canvas || !button || !outline) {
+ return;
}
- });
- observer.observe(host);
- return () => observer.disconnect();
- }, []);
+ const viewport = engine.viewport.getViewport();
+ let maxSizePx = 0;
- useEffect(() => () => drag.current?.abort(), []);
+ const applyOutline = () => {
+ const current = mapping.current;
+ const size = viewport.getViewportSize();
+ if (!current || size.width <= 0 || size.height <= 0) {
+ outline.style.visibility = 'hidden';
+ return;
+ }
+ const widthPx = canvas.width;
+ const heightPx = canvas.height;
+ const topLeft = viewport.screenToDocument({ x: 0, y: 0 });
+ const bottomRight = viewport.screenToDocument({ x: size.width, y: size.height });
+ const left = (topLeft.x - current.x) * current.scale;
+ const top = (topLeft.y - current.y) * current.scale;
+ const width = (bottomRight.x - topLeft.x) * current.scale;
+ const height = (bottomRight.y - topLeft.y) * current.scale;
+ outline.style.visibility = 'visible';
+ outline.style.left = `${Math.max(-widthPx, Math.min(left, widthPx))}px`;
+ outline.style.top = `${Math.max(-heightPx, Math.min(top, heightPx))}px`;
+ outline.style.width = `${Math.max(4, Math.min(width, widthPx * 2))}px`;
+ outline.style.height = `${Math.max(4, Math.min(height, heightPx * 2))}px`;
+ };
+ // Throttle DOM outline updates and let CSS interpolate between them.
+ const outlineThrottle = { last: 0, timer: null as ReturnType<typeof setTimeout> | null };
+ const updateOutline = () => {
+ if (outlineThrottle.timer !== null) {
+ return;
+ }
+ const elapsed = Date.now() - outlineThrottle.last;
+ if (elapsed >= VIEW_RECT_INTERVAL_MS) {
+ outlineThrottle.last = Date.now();
+ applyOutline();
+ return;
+ }
+ outlineThrottle.timer = setTimeout(() => {
+ outlineThrottle.timer = null;
+ outlineThrottle.last = Date.now();
+ applyOutline();
+ }, VIEW_RECT_INTERVAL_MS - elapsed);
+ };
- // Mirrors the engine's `fitThumbnailSize` math, so the drawn bitmap and the
- // outline overlay agree without a state round trip.
- const frame = useMemo<OverviewFrame | null>(() => {
- const maxSize = Math.floor(Math.min(hostSize.width, hostSize.height));
- if (maxSize < 16 || docWidth <= 0 || docHeight <= 0) {
- return null;
- }
- const scale = Math.min(1, maxSize / docWidth, maxSize / docHeight);
- return {
- heightPx: Math.max(1, Math.round(docHeight * scale)),
- scale,
- widthPx: Math.max(1, Math.round(docWidth * scale)),
- };
- }, [docHeight, docWidth, hostSize]);
- const frameRef = useRef(frame);
- useLayoutEffect(() => {
- frameRef.current = frame;
- }, [frame]);
+ // Only a real composite consumes throttle budget, so the pre-measure clearing draw never defers the first
+ // paint. The outline follows every draw at once, so it never disagrees with the bitmap.
+ const drawComposite = (): boolean => {
+ const rect = maxSizePx < 16 ? null : engine.previews.drawDocumentOverview(canvas, maxSizePx);
+ if (!rect) {
+ canvas.width = 0;
+ canvas.height = 0;
+ }
+ mapping.current = rect && canvas.width > 0 ? { scale: canvas.width / rect.width, x: rect.x, y: rect.y } : null;
+ applyOutline();
+ return rect !== null;
+ };
+ const redraw = { last: 0, timer: null as ReturnType<typeof setTimeout> | null };
+ const scheduleRedraw = () => {
+ if (redraw.timer !== null) {
+ return;
+ }
+ const elapsed = Date.now() - redraw.last;
+ if (elapsed >= REDRAW_INTERVAL_MS) {
+ if (drawComposite()) {
+ redraw.last = Date.now();
+ }
+ return;
+ }
+ redraw.timer = setTimeout(() => {
+ redraw.timer = null;
+ if (drawComposite()) {
+ redraw.last = Date.now();
+ }
+ }, REDRAW_INTERVAL_MS - elapsed);
+ };
- const redraw = useRef({ last: 0, timer: null as ReturnType<typeof setTimeout> | null });
- // Only a real composite consumes throttle budget, so the pre-measure clearing
- // draw never defers the first paint.
- const drawComposite = useCallback((): boolean => {
- const canvas = canvasRef.current;
- const current = frameRef.current;
- if (!canvas) {
- return false;
- }
- if (!current) {
- canvas.width = 0;
- canvas.height = 0;
- return false;
- }
- engine.previews.drawDocumentOverview(canvas, Math.max(current.widthPx, current.heightPx));
- return true;
- }, [engine]);
- const scheduleRedraw = useCallback(() => {
- const state = redraw.current;
- if (state.timer !== null) {
- return;
- }
- const elapsed = Date.now() - state.last;
- if (elapsed >= REDRAW_INTERVAL_MS) {
- if (drawComposite()) {
- state.last = Date.now();
- }
- return;
- }
- state.timer = setTimeout(() => {
- state.timer = null;
- if (drawComposite()) {
- state.last = Date.now();
- }
- }, REDRAW_INTERVAL_MS - elapsed);
- }, [drawComposite]);
- useEffect(() => {
- const state = redraw.current;
- return () => {
- if (state.timer !== null) {
- clearTimeout(state.timer);
- }
- };
- }, []);
- useEffect(() => {
- scheduleRedraw();
- }, [pixelEpoch, stacks, frame, scheduleRedraw]);
+ const observer = new ResizeObserver((observations) => {
+ const content = observations[0]?.contentRect;
+ if (content) {
+ maxSizePx = Math.floor(Math.min(content.width, content.height));
+ scheduleRedraw();
+ }
+ });
+ observer.observe(host);
- // Throttle DOM outline updates and let CSS interpolate between them.
- useEffect(() => {
- const viewport = engine.viewport.getViewport();
- let timer: ReturnType<typeof setTimeout> | null = null;
- let last = 0;
- const apply = () => {
- const element = viewRectRef.current;
- const current = frameRef.current;
- if (!element) {
- return;
- }
- const size = viewport.getViewportSize();
- if (!current || size.width <= 0 || size.height <= 0) {
- element.style.visibility = 'hidden';
- return;
- }
- const topLeft = viewport.screenToDocument({ x: 0, y: 0 });
- const bottomRight = viewport.screenToDocument({ x: size.width, y: size.height });
- const width = (bottomRight.x - topLeft.x) * current.scale;
- const height = (bottomRight.y - topLeft.y) * current.scale;
- element.style.visibility = 'visible';
- element.style.left = `${Math.max(-current.widthPx, Math.min(topLeft.x * current.scale, current.widthPx))}px`;
- element.style.top = `${Math.max(-current.heightPx, Math.min(topLeft.y * current.scale, current.heightPx))}px`;
- element.style.width = `${Math.max(4, Math.min(width, current.widthPx * 2))}px`;
- element.style.height = `${Math.max(4, Math.min(height, current.heightPx * 2))}px`;
- };
- const update = () => {
- if (timer !== null) {
- return;
- }
- const elapsed = Date.now() - last;
- if (elapsed >= VIEW_RECT_INTERVAL_MS) {
- last = Date.now();
- apply();
- return;
- }
- timer = setTimeout(() => {
- timer = null;
- last = Date.now();
- apply();
- }, VIEW_RECT_INTERVAL_MS - elapsed);
- };
- apply();
- const unsubscribe = viewport.subscribe(update);
- return () => {
- unsubscribe();
- if (timer !== null) {
- clearTimeout(timer);
- }
- };
- }, [engine, frame]);
+ // Layer and frame edits change the drawn extent; selection-only document changes do not repaint.
+ let drawnDocument = engine.document.getDocument();
+ const onDocumentChange = () => {
+ const doc = engine.document.getDocument();
+ if (doc?.stacks !== drawnDocument?.stacks || doc?.bbox !== drawnDocument?.bbox) {
+ drawnDocument = doc;
+ scheduleRedraw();
+ }
+ };
+ const unsubscribeDocument = engine.interaction.subscribe('documentEpoch', onDocumentChange);
+ const unsubscribePixels = engine.interaction.subscribe('layerPixelEpoch', scheduleRedraw);
+ const unsubscribeViewport = viewport.subscribe(updateOutline);
+
+ // React registers wheel listeners passively; zooming must preventDefault, so the listener is attached natively.
+ const handleWheel = (event: WheelEvent) => {
+ event.preventDefault();
+ const current = mapping.current;
+ if (!current) {
+ return;
+ }
+ const documentPoint = clientToDocument(current, canvas.getBoundingClientRect(), event.clientX, event.clientY);
+ viewport.wheelZoom(event.deltaY, viewport.documentToScreen(documentPoint));
+ };
+ button.addEventListener('wheel', handleWheel, { passive: false });
+
+ drawComposite();
+ return () => {
+ observer.disconnect();
+ unsubscribeDocument();
+ unsubscribePixels();
+ unsubscribeViewport();
+ button.removeEventListener('wheel', handleWheel);
+ for (const timer of [redraw.timer, outlineThrottle.timer]) {
+ if (timer !== null) {
+ clearTimeout(timer);
+ }
+ }
+ mapping.current = null;
+ // A drag maps through this engine's viewport, so it ends with the binding.
+ drag.current?.abort();
+ };
+ },
+ [engine]
+ );
const centerOn = useCallback(
(clientX: number, clientY: number) => {
const canvas = canvasRef.current;
- const current = frameRef.current;
+ const current = mapping.current;
if (!canvas || !current) {
return;
}
- const bounds = canvas.getBoundingClientRect();
- const documentPoint = {
- x: (clientX - bounds.left) / current.scale,
- y: (clientY - bounds.top) / current.scale,
- };
+ const documentPoint = clientToDocument(current, canvas.getBoundingClientRect(), clientX, clientY);
const viewport = engine.viewport.getViewport();
const size = viewport.getViewportSize();
const screenPoint = viewport.documentToScreen(documentPoint);
@@ -217,32 +221,6 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {
[engine]
);
- // React registers wheel listeners passively; zooming must preventDefault, so
- // the listener is attached natively.
- useEffect(() => {
- const button = buttonRef.current;
- if (!button) {
- return;
- }
- const handleWheel = (event: WheelEvent) => {
- event.preventDefault();
- const canvas = canvasRef.current;
- const current = frameRef.current;
- if (!canvas || !current) {
- return;
- }
- const bounds = canvas.getBoundingClientRect();
- const documentPoint = {
- x: (event.clientX - bounds.left) / current.scale,
- y: (event.clientY - bounds.top) / current.scale,
- };
- const viewport = engine.viewport.getViewport();
- viewport.wheelZoom(event.deltaY, viewport.documentToScreen(documentPoint));
- };
- button.addEventListener('wheel', handleWheel, { passive: false });
- return () => button.removeEventListener('wheel', handleWheel);
- }, [engine]);
-
const onPointerDown = useCallback(
(event: ReactPointerEvent<HTMLButtonElement>) => {
if (event.button !== 0) {
@@ -291,7 +269,7 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {
const fit = useCallback(() => engine.viewport.fitToView(), [engine]);
return (
- <Flex ref={hostRef} align="center" h="full" justify="center" minH="0" overflow="hidden" p="2">
+ <Flex ref={bindHost} align="center" h="full" justify="center" minH="0" overflow="hidden" p="2">
<chakra.button
ref={buttonRef}
aria-label={t('widgets.layers.overviewPane.pan')}