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(canvas): History and Overview panes

Josh Corbettf878e0014279
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c9d8f0b18f..68be324dd2 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1540,7 +1540,9 @@
"workflow": "Workflow",
"video": "Video",
"color": "Color",
- "swatches": "Swatches"
+ "swatches": "Swatches",
+ "history": "History",
+ "overview": "Overview"
},
"generate": {
"activeCount_one": "{{count}} active",
@@ -3015,6 +3017,15 @@
"resize": "Resize color pane",
"swatches": "Swatches",
"tabs": "Color panes"
+ },
+ "historyPane": {
+ "count_one": "{{count}} step",
+ "count_other": "{{count}} steps",
+ "empty": "No edits yet.",
+ "steps": "Edit history"
+ },
+ "overviewPane": {
+ "pan": "Pan the canvas view"
}
},
"gallery": {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index d531cd0fe6..4ebd57bbcc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -41,7 +41,7 @@ The document mirror diffs forests by leaf identity and ancestor-effective state:
### Properties and Transform
-Tool and operation settings live off the surface, as editor panes of the Layers panel (`widgets/layers/panes`). The Properties pane renders the running operation first (its inputs, secondary controls and status with Apply / Cancel) and then the active tool's settings as labelled rows; the Transform pane edits the selected layer's transform without a tool — each field commits one undoable `patch`, and while the Transform tool holds a session the same fields drive its preview and Apply / Cancel land or drop it. Both read the engine's option stores and document transactions through one `ToolPresentationAdapter` per tool and one `OperationPresentationAdapter` per operation (`widgets/canvas/tool-presentation`): a component per settings region, no state mirror. Staging and generation lock the tool rows in place (`inert`) while an operation keeps its own controls live and Cancel always reachable. The panes are fixed parts of the panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through the Layers widget's project state — not movable widgets.
+Tool and operation settings live off the surface, as editor panes of the Layers panel (`widgets/layers/panes`). The Properties pane renders the running operation first (its inputs, secondary controls and status with Apply / Cancel) and then the active tool's settings as labelled rows; the Transform pane edits the selected layer's transform without a tool — each field commits one undoable `patch`, and while the Transform tool holds a session the same fields drive its preview and Apply / Cancel land or drop it. Both read the engine's option stores and document transactions through one `ToolPresentationAdapter` per tool and one `OperationPresentationAdapter` per operation (`widgets/canvas/tool-presentation`): a component per settings region, no state mirror. Staging and generation lock the tool rows in place (`inert`) while an operation keeps its own controls live and Cancel always reachable. The panes are fixed parts of the panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through the Layers widget's project state — not movable widgets. The same blocks host the Color/Swatches workspace (the project foreground/background pair), the History pane (the engine's labeled undo/redo stack via `history.getEntries()`/`stepBy`), and the Overview navigator (`previews.drawDocumentOverview` plus the live viewport handle).
## Package and capability boundaries
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index b0335a04e3..ca69d04baa 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -102,6 +102,8 @@ export interface CanvasInteractionState {
gradientOptions: GradientToolOptions;
hasFloatingSelection: boolean;
hasSelection: boolean;
+ /** Monotonic signal for engine history-stack mutations (see the History pane). */
+ historyEpoch: number;
invertBrushSizeScroll: boolean;
lassoOptions: LassoToolOptions;
marqueeOptions: MarqueeToolOptions;
@@ -193,10 +195,21 @@ export interface CanvasToolCapability {
stepBrushSize(direction: 1 | -1): void;
}
+/** Labels of the retained undo/redo steps, for the History pane. */
+export interface CanvasHistoryEntries {
+ /** Applied steps, oldest first; the last is what `undo()` reverts. */
+ past: readonly string[];
+ /** Undone steps, next-redo first. */
+ future: readonly string[];
+}
+
export interface CanvasHistoryCapability {
undo(): void;
redo(): void;
clearHistory(): void;
+ getEntries(): CanvasHistoryEntries;
+ /** Replays `offset` steps — negative undoes, positive redoes — clamped to the stacks. */
+ stepBy(offset: number): void;
}
export type LayerThumbnailRequestResult =
@@ -522,6 +535,12 @@ export interface CanvasEngineExportCapability extends CanvasExportCapability {
}
export interface CanvasEnginePreviewCapability extends CanvasPreviewCapability {
+ /**
+ * Draws a fit-to-`maxSizePx` composite of the whole document into `target`
+ * (sizing its backing store), for the Overview pane. Returns the drawn
+ * document rect, or null when no document is attached.
+ */
+ drawDocumentOverview(target: HTMLCanvasElement, maxSizePx: number): Rect | null;
preloadStagedPreview(imageName: string): void;
setGuardedFilterPreview(
layerId: string,
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 0fae49d987..130277f8ac 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -18233,3 +18233,56 @@ describe('Select Object canvas engine integration', () => {
h.engine.lifecycle.dispose();
});
});
+
+describe('history entries and stepBy', () => {
+ it('enumerates the stroke entry and replays it with clamped stepBy', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+ const layer = { ...rasterLayer('a'), source: { bitmap: null, type: 'paint' as const } };
+ const document = { ...makeDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ const overlay = createInputCanvas();
+ const screen = createInputCanvas();
+ engine.surface.attach(screen.element, overlay.element);
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ expect(engine.history.getEntries()).toEqual({ future: [], past: [] });
+
+ engine.tools.setTool('brush');
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ overlay.fire('pointermove', pointerAt(12, 12));
+ overlay.fire('pointerup', pointerAt(12, 12, { buttons: 0 }));
+
+ const afterStroke = engine.history.getEntries();
+ expect(afterStroke.past).toHaveLength(1);
+ expect(afterStroke.future).toHaveLength(0);
+
+ engine.history.stepBy(-1);
+ expect(engine.history.getEntries()).toEqual({ future: afterStroke.past, past: [] });
+
+ // Clamped: asking for more redos than exist replays what is there and stops.
+ engine.history.stepBy(5);
+ expect(engine.history.getEntries()).toEqual({ future: [], past: afterStroke.past });
+
+ engine.lifecycle.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index f09de9cc2c..a80029d01b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -130,7 +130,7 @@ import {
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
import { isEmpty, union } from '@workbench/canvas-engine/math/rect';
-import { createCheckerboardTile } from '@workbench/canvas-engine/render/compositor';
+import { compositeDocument, createCheckerboardTile } from '@workbench/canvas-engine/render/compositor';
import { createFontLoader, domFontLoadApi } from '@workbench/canvas-engine/render/fontLoader';
import { hasLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';
import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill';
@@ -138,7 +138,7 @@ import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';
import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';
import { createDomRasterBackend, type RasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';
import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';
-import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';
+import { fitThumbnailSize, getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';
import { documentDeltaToLocal, liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';
import { ANTS_STEP_PX, createAntsAnimator, type AntsAnimator } from '@workbench/canvas-engine/selection/marchingAnts';
import { createBboxTool } from '@workbench/canvas-engine/tools/bboxTool';
@@ -383,6 +383,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
gradientOptions: stores.gradientOptions,
hasFloatingSelection: stores.hasFloatingSelection,
hasSelection: stores.hasSelection,
+ historyEpoch: stores.historyEpoch,
invertBrushSizeScroll: stores.invertBrushSizeScroll,
lassoOptions: stores.lassoOptions,
marqueeOptions: stores.marqueeOptions,
@@ -712,6 +713,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
isGestureActive: () => pipeline.isGestureActive(),
});
const history = historyController.history;
+ const unsubscribeHistoryEpoch = history.subscribe(() => stores.historyEpoch.set(stores.historyEpoch.get() + 1));
const dispatchCanvasMutation = (
action: CanvasProjectMutation,
origin: 'system' | 'user' = history.isApplying() ? 'system' : 'user'
@@ -2553,6 +2555,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(unsubscribeRuleOfThirds);
cleanup.run(unsubscribeProjectPreviewLifecycle);
cleanup.run(() => mutationContext.dispose());
+ cleanup.run(unsubscribeHistoryEpoch);
cleanup.run(() => historyController.dispose());
cleanup.run(() => persistenceController.dispose());
cleanup.run(() => mirror.dispose());
@@ -2693,7 +2696,26 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
});
const surface: CanvasSurfaceCapability = { attach, detach, resize };
const viewportCapability: CanvasViewportCapability = { fitToView, fitToViewOnFirstShow, getViewport, setBboxGrid };
- const historyCapability: CanvasHistoryCapability = { clearHistory, redo, undo };
+ const stepHistoryBy = (offset: number): void => {
+ const steps = Math.abs(Math.trunc(offset));
+ for (let i = 0; i < steps; i += 1) {
+ if (offset < 0 ? !history.canUndo() : !history.canRedo()) {
+ return;
+ }
+ if (offset < 0) {
+ undo();
+ } else {
+ redo();
+ }
+ }
+ };
+ const historyCapability: CanvasHistoryCapability = {
+ clearHistory,
+ getEntries: () => history.entries(),
+ redo,
+ stepBy: stepHistoryBy,
+ undo,
+ };
const lifecycle: CanvasLifecycleCapability = {
activate,
beginCooldown,
@@ -2957,8 +2979,66 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
updateTextEditStyle,
updateTransformSession,
};
+ // The Overview pane's document composite: fit the whole document into the
+ // target at thumbnail scale through the canonical compositor, so ordering,
+ // blend modes, transforms, adjustments and mask fills match the main surface.
+ let overviewRequestedDoc: CanvasDocumentContractV3 | null = null;
+ const overviewRequestedLayerIds = new Set<string>();
+ 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) {
+ return null;
+ }
+ // The frame path rasterizes only what its viewport demands and the budget
+ // may evict what it culled; the overview wants everything, so ask for the
+ // missing caches and heal on the next content-epoch repaint (a publish
+ // bumps it). One request per layer per document: a source that cannot
+ // rasterize must not be retried (and re-toast) on every repaint. It never
+ // pins: under real memory pressure the budget still wins over the navigator.
+ if (overviewRequestedDoc !== doc) {
+ overviewRequestedDoc = doc;
+ overviewRequestedLayerIds.clear();
+ }
+ const missing: string[] = [];
+ for (const leaf of getDocumentLeaves(doc)) {
+ if (!leaf.isEnabled || !renderableSourceOf(leaf) || overviewRequestedLayerIds.has(leaf.id)) {
+ continue;
+ }
+ const entry = layerCache.peek(leaf.id);
+ if (!entry || entry.stale) {
+ missing.push(leaf.id);
+ overviewRequestedLayerIds.add(leaf.id);
+ }
+ }
+ if (missing.length > 0) {
+ scheduleLayerRasterization(missing);
+ }
+ const size = fitThumbnailSize(doc.width, doc.height, maxSizePx);
+ target.width = size.width;
+ target.height = size.height;
+ const scale = size.width / doc.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 },
+ {
+ adjustedSurface: getAdjustedSurface,
+ backend,
+ checkerboardTile: null,
+ derivedSurfaces: derivedSurfaceCache,
+ imageSmoothing: true,
+ maskPatternTile: getMaskPatternTile,
+ }
+ );
+ return { height: doc.height, width: doc.width, x: 0, y: 0 };
+ };
const previewCapability: CanvasEnginePreviewCapability = {
...layerController.previews,
+ drawDocumentOverview,
preloadStagedPreview,
setGuardedFilterPreview,
setStagedPreview,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 298f66c956..c0287fe24f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -416,6 +416,8 @@ export interface EngineStores {
canUndo: ScalarStore<boolean>;
/** Whether the engine-owned canvas history has an entry to redo. */
canRedo: ScalarStore<boolean>;
+ /** Bumped on every history-stack mutation, so a history list can re-read the entries. */
+ historyEpoch: ScalarStore<number>;
/** Bbox tool options (aspect lock / ratio). */
bboxOptions: ScalarStore<BboxToolOptions>;
/** Lasso tool options (the committed boolean op mode). */
@@ -670,6 +672,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
brushOptions: createScalarStore<BrushOptions>({ ...DEFAULT_BRUSH_OPTIONS }, brushOptionsEqual),
canRedo: createScalarStore<boolean>(false),
canUndo: createScalarStore<boolean>(false),
+ historyEpoch: createScalarStore<number>(0),
checkerboard: createScalarStore<boolean>(true),
clipToBbox: createScalarStore<boolean>(false),
checkerColors: createScalarStore<CheckerColors>({ ...DEFAULT_CHECKER_COLORS }, checkerColorsEqual),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts
index 66b72dd931..5c7a960a87 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.test.ts
@@ -528,3 +528,29 @@ describe('createHistory: failure-atomic replay', () => {
expect(disposed).toEqual(['evicted', 'redo-cleared', 'amended', 'cleared']);
});
});
+
+describe('createHistory: entries enumeration', () => {
+ it('lists past oldest-first and future next-redo-first, tracking every mutation', () => {
+ const log: string[] = [];
+ const history = createHistory();
+ expect(history.entries()).toEqual({ future: [], past: [] });
+
+ history.push(makeEntry('a', log));
+ history.push(makeEntry('b', log));
+ history.push(makeEntry('c', log));
+ expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'c'] });
+
+ history.undo();
+ history.undo();
+ expect(history.entries()).toEqual({ future: ['b', 'c'], past: ['a'] });
+
+ history.redo();
+ expect(history.entries()).toEqual({ future: ['c'], past: ['a', 'b'] });
+
+ history.push(makeEntry('d', log));
+ expect(history.entries()).toEqual({ future: [], past: ['a', 'b', 'd'] });
+
+ history.clear();
+ expect(history.entries()).toEqual({ future: [], past: [] });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
index 41d3e067af..54c23533ca 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/history/history.ts
@@ -88,7 +88,12 @@ export interface History {
canRetain(bytes: number): boolean;
/** Evicts oldest entries until retained bytes are at or below `budgetBytes`. */
trimToBytes(budgetBytes: number): void;
- /** Subscribes to any change in `canUndo`/`canRedo`. Returns an unsubscribe function. */
+ /**
+ * Labels of every retained step: `past` oldest-first (its last element is
+ * what `undo()` reverts), `future` next-redo-first. Fresh arrays per call.
+ */
+ entries(): { past: readonly string[]; future: readonly string[] };
+ /** Subscribes to every stack mutation (push, amend, undo, redo, clear, eviction). Returns an unsubscribe function. */
subscribe(listener: () => void): () => void;
}
@@ -154,6 +159,11 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {
}
};
+ const entries = (): { past: readonly string[]; future: readonly string[] } => ({
+ future: redoStack.map((entry) => entry.label).reverse(),
+ past: undoStack.map((entry) => entry.label),
+ });
+
const push = (entry: HistoryEntry): void => {
// Replaying an entry must never record a new one; drop it defensively.
if (applying) {
@@ -339,6 +349,7 @@ export const createHistory = (opts: CreateHistoryOptions = {}): History => {
return {
amendLast,
byteSize: () => undoBytes + redoBytes,
+ entries,
canRetain: (bytes) => Number.isFinite(bytes) && Math.max(0, Math.ceil(bytes)) <= byteBudget,
canRedo: () => redoStack.length > 0,
canUndo: () => undoStack.length > 0,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index ea421064d1..82e18d7053 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -131,6 +131,10 @@ export const useCanvasCanUndo = (engine: CanvasCoreStoreCapability): boolean =>
export const useCanvasCanRedo = (engine: CanvasCoreStoreCapability): boolean =>
useCanvasInteractionState(engine, 'canRedo');
+/** Bumped on every history-stack mutation; a history list re-reads the entries on change. */
+export const useCanvasHistoryEpoch = (engine: CanvasCoreStoreCapability): number =>
+ useCanvasInteractionState(engine, 'historyEpoch');
+
/** Whether a SAM/filter operation currently excludes ordinary canvas document edits. */
export const useCanvasDocumentEditingLocked = (engine: CanvasCoreStoreCapability | null): boolean => {
const subscribe = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx
new file mode 100644
index 0000000000..d06b2f72e5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/HistoryPane.tsx
@@ -0,0 +1,152 @@
+import { chakra, Flex, HStack, Icon, Stack, Text } from '@chakra-ui/react';
+import { IconButton } from '@platform/ui/Button';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { useCanvasCanRedo, useCanvasCanUndo, useCanvasHistoryEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+import { Redo2Icon, Undo2Icon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const STEP_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };
+
+/**
+ * The canvas edit history as a walkable list: every retained step, oldest
+ * first, with the current position highlighted. Clicking a step replays
+ * undo/redo up to it; the steps below the current one are the redoable future.
+ * The list mirrors the engine's own bounded history — it owns nothing.
+ */
+export const HistoryPane = () => {
+ const { t } = useTranslation();
+ const engine = useCanvasEngine();
+
+ if (!engine) {
+ return (
+ <Flex align="center" color="fg.muted" fontSize="xs" h="full" justify="center" p="4">
+ {t('widgets.properties.noCanvas')}
+ </Flex>
+ );
+ }
+ return <ConnectedHistory engine={engine} />;
+};
+
+const ConnectedHistory = ({ engine }: { engine: CanvasEngineHandle }) => {
+ const { t } = useTranslation();
+ useCanvasHistoryEpoch(engine);
+ const canUndo = useCanvasCanUndo(engine);
+ const canRedo = useCanvasCanRedo(engine);
+ const { future, past } = engine.history.getEntries();
+ const undo = useCallback(() => engine.history.undo(), [engine]);
+ const redo = useCallback(() => engine.history.redo(), [engine]);
+ const jump = useCallback((offset: number) => engine.history.stepBy(offset), [engine]);
+
+ return (
+ <Flex direction="column" h="full" minH="0">
+ <HStack borderBottomWidth="1px" borderColor="border.subtle" flexShrink={0} gap="1" px="2" py="1.5">
+ <Tooltip content={t('widgets.canvas.commands.undo')}>
+ <IconButton
+ aria-label={t('widgets.canvas.commands.undo')}
+ color="fg.muted"
+ disabled={!canUndo}
+ size="2xs"
+ variant="ghost"
+ onClick={undo}
+ >
+ <Icon as={Undo2Icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content={t('widgets.canvas.commands.redo')}>
+ <IconButton
+ aria-label={t('widgets.canvas.commands.redo')}
+ color="fg.muted"
+ disabled={!canRedo}
+ size="2xs"
+ variant="ghost"
+ onClick={redo}
+ >
+ <Icon as={Redo2Icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ <Text color="fg.subtle" fontSize="2xs" fontVariantNumeric="tabular-nums">
+ {t('widgets.layers.historyPane.count', { count: past.length })}
+ </Text>
+ </HStack>
+ {past.length === 0 && future.length === 0 ? (
+ <Flex align="center" color="fg.subtle" flex="1" fontSize="xs" justify="center" p="4">
+ {t('widgets.layers.historyPane.empty')}
+ </Flex>
+ ) : (
+ <Scrollable flex="1" minH="0">
+ <Stack aria-label={t('widgets.layers.historyPane.steps')} as="ol" gap="0" listStyleType="none" m="0" p="1">
+ {past.map((label, index) => (
+ <HistoryStep
+ key={`past-${index}`}
+ isCurrent={index === past.length - 1}
+ isFuture={false}
+ label={label}
+ offset={index - (past.length - 1)}
+ onJump={jump}
+ />
+ ))}
+ {future.map((label, index) => (
+ <HistoryStep
+ key={`future-${index}`}
+ isCurrent={false}
+ isFuture
+ label={label}
+ offset={index + 1}
+ onJump={jump}
+ />
+ ))}
+ </Stack>
+ </Scrollable>
+ )}
+ </Flex>
+ );
+};
+
+const HistoryStep = ({
+ isCurrent,
+ isFuture,
+ label,
+ offset,
+ onJump,
+}: {
+ isCurrent: boolean;
+ isFuture: boolean;
+ label: string;
+ /** Steps to replay to make this the last applied entry; 0 for the current one. */
+ offset: number;
+ onJump: (offset: number) => void;
+}) => {
+ const jump = useCallback(() => {
+ if (offset !== 0) {
+ onJump(offset);
+ }
+ }, [offset, onJump]);
+
+ return (
+ <chakra.li display="flex" m="0" p="0">
+ <chakra.button
+ aria-current={isCurrent ? 'step' : undefined}
+ bg={isCurrent ? 'bg.emphasized' : 'transparent'}
+ color={isCurrent ? 'fg' : isFuture ? 'fg.subtle' : 'fg.muted'}
+ cursor="pointer"
+ flex="1"
+ fontSize="xs"
+ minH="6"
+ px="2"
+ py="1"
+ rounded="sm"
+ textAlign="left"
+ type="button"
+ _hover={isCurrent ? undefined : STEP_HOVER_PROPS}
+ onClick={jump}
+ >
+ <Text as="span" truncate>
+ {label}
+ </Text>
+ </chakra.button>
+ </chakra.li>
+ );
+};
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 5574f748e1..0c4f1bad78 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
@@ -5,7 +5,7 @@ import type { FilterOperationSessionState } from '@workbench/canvas-operations/f
import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
import type { Project } from '@workbench/projectContracts';
-import { ChakraProvider } from '@chakra-ui/react';
+import { Box, ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
import {
groupContract,
@@ -79,7 +79,9 @@ import type { LayerEditorPaneLayout } from './editorPaneLayout';
import { ColorPane } from './ColorPane';
import { LAYER_EDITOR_PANE_DEFAULTS } from './editorPaneLayout';
+import { HistoryPane } from './HistoryPane';
import { LayerEditorPanes } from './LayerEditorPanes';
+import { OverviewPane } from './OverviewPane';
import { PropertiesPane } from './PropertiesPane';
import { SwatchesPane } from './SwatchesPane';
import { TransformPane } from './TransformPane';
@@ -419,3 +421,38 @@ describe('Color pane', () => {
expect(canvasValues().colorPalette).toEqual([]);
});
});
+
+const OverviewHarness = () => (
+ <Box h="260px" w="300px">
+ <OverviewPane />
+ </Box>
+);
+
+describe('History pane', () => {
+ it('shows the empty state with undo and redo disabled', async () => {
+ await mount(HistoryPane);
+ await expect.element(page.getByText('No edits yet.', { exact: true })).toBeVisible();
+ await expect.element(page.getByRole('button', { exact: true, name: 'Undo canvas edit' })).toBeDisabled();
+ await expect.element(page.getByRole('button', { exact: true, name: 'Redo canvas edit' })).toBeDisabled();
+ });
+});
+
+describe('Overview pane', () => {
+ it('draws the document composite and pans the viewport from a click', async () => {
+ await mount(OverviewHarness, 'layer');
+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });
+ await expect.element(pan).toBeVisible();
+ const canvasWidth = await pan.element().querySelector('canvas')!.width;
+ expect(canvasWidth).toBeGreaterThan(0);
+ const viewport = (
+ harness.engine as { viewport: { getViewport: () => { getState: () => { pan: { x: number; y: number } } } } }
+ ).viewport.getViewport();
+ const before = viewport.getState().pan;
+ await act(async () => {
+ await userEvent.click(pan);
+ });
+ await settle();
+ const after = viewport.getState().pan;
+ expect(after.x === before.x && after.y === before.y).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
index 3a26f24063..97dcf3e98c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
@@ -25,6 +25,8 @@ import {
LAYER_EDITOR_PANE_MAX_SIZE_PX,
LAYER_EDITOR_PANE_MIN_SIZE_PX,
} from './editorPaneLayout';
+import { HistoryPane } from './HistoryPane';
+import { OverviewPane } from './OverviewPane';
import { PropertiesPane } from './PropertiesPane';
import { SwatchesPane } from './SwatchesPane';
import { TransformPane } from './TransformPane';
@@ -299,6 +301,7 @@ const LayerPaneBlock = ({
const EDITOR_PANES: ReadonlyArray<{ id: LayerEditorPaneId; labelKey: string }> = [
{ id: 'properties', labelKey: 'widgets.labels.properties' },
{ id: 'transform', labelKey: 'widgets.labels.transform' },
+ { id: 'history', labelKey: 'widgets.labels.history' },
];
/**
@@ -352,7 +355,7 @@ export const LayerEditorPanes = ({
onSelectPane={onSelectPane}
panes={panes}
>
- {activePane === 'transform' ? <TransformPane /> : <PropertiesPane />}
+ {activePane === 'transform' ? <TransformPane /> : activePane === 'history' ? <HistoryPane /> : <PropertiesPane />}
</LayerPaneBlock>
);
};
@@ -360,6 +363,7 @@ export const LayerEditorPanes = ({
const COLOR_PANES: ReadonlyArray<{ id: LayerColorPaneId; labelKey: string }> = [
{ id: 'color', labelKey: 'widgets.labels.color' },
{ id: 'swatches', labelKey: 'widgets.labels.swatches' },
+ { id: 'overview', labelKey: 'widgets.labels.overview' },
];
/**
@@ -414,7 +418,7 @@ export const LayerColorPane = ({
onSelectPane={onSelectPane}
panes={panes}
>
- {activePane === 'swatches' ? <SwatchesPane /> : <ColorPane />}
+ {activePane === 'swatches' ? <SwatchesPane /> : activePane === 'overview' ? <OverviewPane /> : <ColorPane />}
</LayerPaneBlock>
);
};
@@ -445,11 +449,12 @@ const PaneTab = ({
bg={isShown ? 'bg.emphasized' : 'transparent'}
color={isShown ? 'fg' : 'fg.muted'}
cursor="pointer"
- flexShrink={0}
fontSize="xs"
fontWeight="600"
h="7"
id={`${blockId}-tab-${id}`}
+ minW="10"
+ overflow="hidden"
px="2.5"
role="tab"
rounded="md"
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx
new file mode 100644
index 0000000000..d270e34d65
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx
@@ -0,0 +1,237 @@
+import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react';
+
+import { Box, chakra, Flex } from '@chakra-ui/react';
+import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const KEY_PAN_STEP_PX = 40;
+
+const FOCUS_PROPS = { outline: '2px solid {colors.accent.solid}', outlineOffset: '2px' };
+
+/**
+ * The navigator: a fit-to-pane composite of the whole document with the live
+ * viewport outlined on top. Clicking or dragging centers the view there;
+ * arrow keys pan when the preview is focused. Reads the engine's compositor
+ * and viewport directly — no state of its own beyond the measured size.
+ */
+export const OverviewPane = () => {
+ const { t } = useTranslation();
+ const engine = useCanvasEngine();
+
+ if (!engine) {
+ return (
+ <Flex align="center" color="fg.muted" fontSize="xs" h="full" justify="center" p="4">
+ {t('widgets.properties.noCanvas')}
+ </Flex>
+ );
+ }
+ return <ConnectedOverview engine={engine} />;
+};
+
+interface OverviewFrame {
+ /** Preview pixels per document unit. */
+ scale: number;
+ widthPx: number;
+ heightPx: number;
+}
+
+const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {
+ const { t } = useTranslation();
+ const hostRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const drag = useRef<AbortController | null>(null);
+ const [hostSize, setHostSize] = useState<{ width: number; height: number }>({ height: 0, width: 0 });
+ const [viewRect, setViewRect] = useState<{ x: number; y: number; width: number; height: number } | null>(null);
+
+ // Redraw triggers: any committed document change and live stroke content;
+ // the viewport rectangle tracks zoom/pan through its own subscription below.
+ const contentEpoch = useCanvasRasterContentEpoch(engine);
+ const documentState = useActiveProjectSelector((project) => project.canvas.document);
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) {
+ return;
+ }
+ const observer = new ResizeObserver((observations) => {
+ // The content box: the client box includes the host padding, which would
+ // let the composite overflow into it and clip the document's edges.
+ const content = observations[0]?.contentRect;
+ if (content) {
+ setHostSize({ height: content.height, width: content.width });
+ }
+ });
+ observer.observe(host);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => () => drag.current?.abort(), []);
+
+ // The preview geometry derives from the document and the measured pane —
+ // mirroring the engine's `fitThumbnailSize` math exactly, so the drawn
+ // bitmap and the rectangle overlay agree without a state round trip.
+ const frame = useMemo<OverviewFrame | null>(() => {
+ const maxSize = Math.floor(Math.min(hostSize.width, hostSize.height));
+ const { height: docH, width: docW } = documentState;
+ if (maxSize < 16 || docW <= 0 || docH <= 0) {
+ return null;
+ }
+ const scale = Math.min(1, maxSize / docW, maxSize / docH);
+ return {
+ heightPx: Math.max(1, Math.round(docH * scale)),
+ scale,
+ widthPx: Math.max(1, Math.round(docW * scale)),
+ };
+ }, [documentState, hostSize]);
+
+ // Repaint the composite when content or geometry changes; the effect only
+ // updates the external canvas, never React state.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) {
+ return;
+ }
+ if (!frame) {
+ canvas.width = 0;
+ canvas.height = 0;
+ return;
+ }
+ engine.previews.drawDocumentOverview(canvas, Math.max(frame.widthPx, frame.heightPx));
+ }, [contentEpoch, documentState, engine, frame]);
+
+ // Track the live viewport rectangle in preview coordinates.
+ useEffect(() => {
+ if (!frame) {
+ return;
+ }
+ const viewport = engine.viewport.getViewport();
+ const update = () => {
+ const size = viewport.getViewportSize();
+ if (size.width <= 0 || size.height <= 0) {
+ setViewRect(null);
+ return;
+ }
+ const topLeft = viewport.screenToDocument({ x: 0, y: 0 });
+ const bottomRight = viewport.screenToDocument({ x: size.width, y: size.height });
+ setViewRect({
+ height: (bottomRight.y - topLeft.y) * frame.scale,
+ width: (bottomRight.x - topLeft.x) * frame.scale,
+ x: topLeft.x * frame.scale,
+ y: topLeft.y * frame.scale,
+ });
+ };
+ update();
+ return viewport.subscribe(update);
+ }, [engine, frame]);
+
+ const centerOn = useCallback(
+ (clientX: number, clientY: number) => {
+ const canvas = canvasRef.current;
+ if (!canvas || !frame) {
+ return;
+ }
+ const bounds = canvas.getBoundingClientRect();
+ const documentPoint = {
+ x: (clientX - bounds.left) / frame.scale,
+ y: (clientY - bounds.top) / frame.scale,
+ };
+ const viewport = engine.viewport.getViewport();
+ const size = viewport.getViewportSize();
+ const screenPoint = viewport.documentToScreen(documentPoint);
+ viewport.panBy({ x: size.width / 2 - screenPoint.x, y: size.height / 2 - screenPoint.y });
+ },
+ [engine, frame]
+ );
+
+ const onPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+ event.preventDefault();
+ // preventDefault suppresses focus-on-click; take it explicitly so the
+ // arrow keys work right after a mouse interaction.
+ event.currentTarget.focus();
+ const controller = new AbortController();
+ drag.current?.abort();
+ drag.current = controller;
+ centerOn(event.clientX, event.clientY);
+ window.addEventListener('pointermove', (moveEvent) => centerOn(moveEvent.clientX, moveEvent.clientY), {
+ signal: controller.signal,
+ });
+ window.addEventListener('pointerup', () => controller.abort(), { signal: controller.signal });
+ window.addEventListener('pointercancel', () => controller.abort(), { signal: controller.signal });
+ },
+ [centerOn]
+ );
+ const onKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLButtonElement>) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ // The button's activation keys mirror double-click: fit the document.
+ event.preventDefault();
+ engine.viewport.fitToView();
+ return;
+ }
+ const step = event.shiftKey ? KEY_PAN_STEP_PX * 4 : KEY_PAN_STEP_PX;
+ const delta =
+ event.key === 'ArrowLeft'
+ ? { x: step, y: 0 }
+ : event.key === 'ArrowRight'
+ ? { x: -step, y: 0 }
+ : event.key === 'ArrowUp'
+ ? { x: 0, y: step }
+ : event.key === 'ArrowDown'
+ ? { x: 0, y: -step }
+ : null;
+ if (!delta) {
+ return;
+ }
+ event.preventDefault();
+ engine.viewport.getViewport().panBy(delta);
+ },
+ [engine]
+ );
+ const fit = useCallback(() => engine.viewport.fitToView(), [engine]);
+ const viewRectStyle = useMemo(() => {
+ if (!viewRect || !frame) {
+ return null;
+ }
+ return {
+ height: `${Math.max(4, Math.min(viewRect.height, frame.heightPx * 2))}px`,
+ left: `${Math.max(-frame.widthPx, Math.min(viewRect.x, frame.widthPx))}px`,
+ top: `${Math.max(-frame.heightPx, Math.min(viewRect.y, frame.heightPx))}px`,
+ width: `${Math.max(4, Math.min(viewRect.width, frame.widthPx * 2))}px`,
+ };
+ }, [frame, viewRect]);
+
+ return (
+ <Flex ref={hostRef} align="center" h="full" justify="center" minH="0" overflow="hidden" p="2">
+ <chakra.button
+ aria-label={t('widgets.layers.overviewPane.pan')}
+ cursor="crosshair"
+ display="block"
+ position="relative"
+ type="button"
+ _focusVisible={FOCUS_PROPS}
+ onDoubleClick={fit}
+ onKeyDown={onKeyDown}
+ onPointerDown={onPointerDown}
+ >
+ <chakra.canvas ref={canvasRef} display="block" touchAction="none" />
+ {viewRectStyle ? (
+ <Box
+ borderColor="accent.solid"
+ borderWidth="1.5px"
+ pointerEvents="none"
+ position="absolute"
+ rounded="xs"
+ style={viewRectStyle}
+ />
+ ) : null}
+ </chakra.button>
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
index b5f8fa63d6..5613750a2f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
@@ -1,6 +1,6 @@
/** Pure layout contracts for the Layers widget's pane blocks; the manifest seeds them, so no React here. */
-export type LayerEditorPaneId = 'properties' | 'transform';
+export type LayerEditorPaneId = 'properties' | 'transform' | 'history';
/** What every pane block persists: its preferred height and whether it is collapsed to its strip. */
export interface PaneBlockLayout {
@@ -24,7 +24,8 @@ export const LAYER_EDITOR_PANE_DEFAULTS: LayerEditorPaneLayout = {
export const clampLayerEditorPaneSize = (sizePx: number): number =>
Math.min(LAYER_EDITOR_PANE_MAX_SIZE_PX, Math.max(LAYER_EDITOR_PANE_MIN_SIZE_PX, Math.round(sizePx)));
-const isPaneId = (value: unknown): value is LayerEditorPaneId => value === 'properties' || value === 'transform';
+const isPaneId = (value: unknown): value is LayerEditorPaneId =>
+ value === 'properties' || value === 'transform' || value === 'history';
/** The persisted widget values are untyped; anything malformed falls back per field. */
export const readLayerEditorPaneLayout = (values: Record<string, unknown>): LayerEditorPaneLayout => {
@@ -43,7 +44,7 @@ export const readLayerEditorPaneLayout = (values: Record<string, unknown>): Laye
export const areLayerEditorPaneLayoutsEqual = (a: LayerEditorPaneLayout, b: LayerEditorPaneLayout): boolean =>
a.activePane === b.activePane && a.isCollapsed === b.isCollapsed && a.sizePx === b.sizePx;
-export type LayerColorPaneId = 'color' | 'swatches';
+export type LayerColorPaneId = 'color' | 'swatches' | 'overview';
export interface LayerColorPaneLayout extends PaneBlockLayout {
activePane: LayerColorPaneId;
@@ -64,7 +65,8 @@ const LEGACY_COLOR_PANE_DEFAULT_SIZES = new Set([300, 420]);
export const clampColorPaneSize = (sizePx: number): number =>
Math.min(COLOR_PANE_MAX_SIZE_PX, Math.max(COLOR_PANE_MIN_SIZE_PX, Math.round(sizePx)));
-const isColorPaneId = (value: unknown): value is LayerColorPaneId => value === 'color' || value === 'swatches';
+const isColorPaneId = (value: unknown): value is LayerColorPaneId =>
+ value === 'color' || value === 'swatches' || value === 'overview';
export const readColorPaneLayout = (values: Record<string, unknown>): LayerColorPaneLayout => {
const raw = values.colorPane;