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): keep hold keys after clicking a control and end holds before tool switches

Josh Corbett7df0066a4c0d
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 42b4da5f76..49806bdc16 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -172,6 +172,12 @@ The controller retains the 30,000-pixel side cap and also derives a pixel-area l
The capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-budget`, `stale`, or `aborted`. The layers widget awaits the promise and maps every non-success result to a user-visible notice.
+## Input ownership and frame scheduling
+
+The pointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and the temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit: the widget passes its focusable keyboard root to `surface.attach`, and Enter applies a session only while focus is on that root or nowhere, never on a control or an editable field. Hold keys and the Escape ladder also act after a pointer click left focus on a control such as a tool button or a layer row, since the pipeline records on `focusin` whether focus arrived by pointer (Chromium marks the focused element `:focus-visible` at any keydown, so arrival is the only reliable signal); they never act over an editable field, a control reached by keyboard, or an open dialog, menu or listbox. An owned Space keydown is prevented, so the clicked control does not activate; key releases are always observed and never consumed. A genuine tool switch first cancels the gesture through the outgoing tool and ends any hold, restoring the held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.
+
+`RenderScheduler.beforeNextFrame(task)` runs tasks once before the next frame takes its flags, so their invalidations join that frame. Tools reach it through the required `ToolContext.scheduleFrame`; a detached engine runs the task immediately because it produces no frames. Brush strokes append samples and decimate them incrementally per event, render the accumulated stroke at most once per presented frame, and render synchronously on commit.
+
## Lifecycle
Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations, and starts a dirty-pixel flush. Successful, still-current flushes release every derived and group surface and each base cache that no read lease pins and no session holds, then trim history. Failed flushes retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned reservations and pins survive these generation transitions until their owning operation settles.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index b4918efb04..7a5b11bae2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -160,7 +160,8 @@ export interface CanvasCoreStoreCapability {
}
export interface CanvasSurfaceCapability {
- attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement): void;
+ /** `keyboardRoot` is the focusable element whose focus gives the canvas its session keys; defaults to the overlay. */
+ attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement, keyboardRoot?: HTMLElement): void;
detach(): void;
resize(cssWidth: number, cssHeight: number, dpr: number): void;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
index a54112319e..8b674e2ef5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
@@ -48,6 +48,10 @@ export class InteractionController {
}
if (!switchOptions?.temporary) {
this.options.cancelGesture?.();
+ // Ending a held temporary tool may already have restored the requested tool.
+ if (toolId === this.activeToolId) {
+ return;
+ }
}
const previous = this.activeToolId;
this.options.beforeSwitch?.(previous, toolId, switchOptions);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
index 031a5a164a..d0badf8e08 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.test.ts
@@ -16,6 +16,7 @@ describe('RenderController', () => {
({
onKeyDown: vi.fn(),
onKeyUp: vi.fn(),
+ onFocusIn: vi.fn(),
onPointerCancel: vi.fn(),
onPointerDown: vi.fn(),
onPointerEnter: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
index a220750f9e..ac3038f96b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts
@@ -48,6 +48,7 @@ export interface RenderControllerOptions extends RenderSchedulerDeps {
onPointerLeave: (event: PointerEvent) => void;
onKeyDown: (event: KeyboardEvent) => void;
onKeyUp: (event: KeyboardEvent) => void;
+ onFocusIn: (event: FocusEvent) => void;
onWheel: (event: WheelEvent) => void;
reset(): void;
};
@@ -68,6 +69,7 @@ export class RenderController {
private screen: RasterSurface | null = null;
private overlay: RasterSurface | null = null;
private input: HTMLCanvasElement | null = null;
+ private keyboardRoot: HTMLElement | null = null;
private disposed = false;
constructor(private readonly options: RenderControllerOptions) {
@@ -86,7 +88,11 @@ export class RenderController {
return this.input;
}
- attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement): void {
+ getKeyboardRoot(): HTMLElement | null {
+ return this.keyboardRoot;
+ }
+
+ attach(screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement, keyboardRoot?: HTMLElement): void {
if (this.disposed || this.options.isEngineDisposed()) {
return;
}
@@ -96,6 +102,7 @@ export class RenderController {
this.screen = wrapCanvasSurface(screenCanvas);
this.overlay = wrapCanvasSurface(overlayCanvas);
this.input = overlayCanvas;
+ this.keyboardRoot = keyboardRoot ?? overlayCanvas;
const handlers = this.options.getInputHandlers();
this.input.addEventListener('pointerdown', handlers.onPointerDown);
this.input.addEventListener('pointermove', handlers.onPointerMove);
@@ -107,6 +114,7 @@ export class RenderController {
if (typeof globalThis.addEventListener === 'function') {
globalThis.addEventListener('keydown', handlers.onKeyDown);
globalThis.addEventListener('keyup', handlers.onKeyUp);
+ globalThis.addEventListener('focusin', handlers.onFocusIn);
globalThis.addEventListener('pagehide', this.options.onPageHide);
globalThis.addEventListener('blur', this.options.onWindowBlur);
}
@@ -135,6 +143,7 @@ export class RenderController {
if (typeof globalThis.removeEventListener === 'function') {
globalThis.removeEventListener('keydown', handlers.onKeyDown);
globalThis.removeEventListener('keyup', handlers.onKeyUp);
+ globalThis.removeEventListener('focusin', handlers.onFocusIn);
globalThis.removeEventListener('pagehide', this.options.onPageHide);
globalThis.removeEventListener('blur', this.options.onWindowBlur);
}
@@ -148,6 +157,7 @@ export class RenderController {
this.screen = null;
this.overlay = null;
this.input = null;
+ this.keyboardRoot = null;
this.options.updateAnimation();
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 918786edb3..9021f62134 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1710,7 +1710,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
listener({ from, temporary: switchOptions?.temporary === true, to });
}
},
- cancelGesture: () => pipeline.cancelGestureForToolSwitch(),
+ cancelGesture: () => pipeline.endForToolSwitch(),
getTool: (toolId) => tools.get(toolId),
getToolContext: () => toolContext,
invalidateOverlay: () => scheduler.invalidate({ overlay: true }),
@@ -1792,6 +1792,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
getActiveTool: activeTool,
getActiveToolId: () => interactionController.getActiveToolId(),
getInputElement: () => renderController.getInputElement(),
+ getKeyboardRoot: () => renderController.getKeyboardRoot(),
getToolContext: () => toolContext,
handleEscape: handleEscapePriority,
hasTool: (id) => tools.has(id),
@@ -1861,8 +1862,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
};
- const attach = (screenCanvas: HTMLCanvasElement, overlayCanvas: HTMLCanvasElement): void =>
- renderController.attach(screenCanvas, overlayCanvas);
+ const attach = (
+ screenCanvas: HTMLCanvasElement,
+ overlayCanvas: HTMLCanvasElement,
+ keyboardRoot?: HTMLElement
+ ): void => renderController.attach(screenCanvas, overlayCanvas, keyboardRoot);
const detach = (): void => renderController.detach();
const activate = (): void => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts
index e228d20566..bea636da37 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts
@@ -34,7 +34,7 @@ const createInputHarness = () => {
const events: string[] = [];
const tools = Object.fromEntries(
- (['brush', 'view', 'transform'] as const).map((id): [ToolId, Tool] => [
+ (['brush', 'view', 'transform', 'bbox', 'eraser'] as const).map((id): [ToolId, Tool] => [
id,
{
id,
@@ -48,7 +48,7 @@ const createInputHarness = () => {
) as Record<string, Tool>;
const ctx = {} as ToolContext;
const interaction = new InteractionController({
- cancelGesture: () => pipeline.cancelGestureForToolSwitch(),
+ cancelGesture: () => pipeline.endForToolSwitch(),
getTool: (id) => tools[id],
getToolContext: () => ctx,
initialToolId: 'brush',
@@ -62,7 +62,9 @@ const createInputHarness = () => {
getActiveTool: () => interaction.getActiveTool(),
getActiveToolId: () => interaction.getActiveToolId(),
getInputElement: () => canvas,
+ getKeyboardRoot: () => surface,
getToolContext: () => ctx,
+ handleEscape: () => events.push('escape'),
hasTool: (id) => id in tools,
setTool: (id, options) => interaction.setTool(id, options),
updateCursor: () => undefined,
@@ -75,11 +77,13 @@ const createInputHarness = () => {
};
globalThis.addEventListener('keydown', pipeline.onKeyDown);
globalThis.addEventListener('keyup', pipeline.onKeyUp);
+ globalThis.addEventListener('focusin', pipeline.onFocusIn);
globalThis.addEventListener('keydown', observe);
globalThis.addEventListener('keyup', observe);
cleanups.push(() => {
globalThis.removeEventListener('keydown', pipeline.onKeyDown);
globalThis.removeEventListener('keyup', pipeline.onKeyUp);
+ globalThis.removeEventListener('focusin', pipeline.onFocusIn);
globalThis.removeEventListener('keydown', observe);
globalThis.removeEventListener('keyup', observe);
pipeline.reset();
@@ -92,21 +96,65 @@ const createInputHarness = () => {
};
describe('pointer pipeline in Chromium: keyboard ownership', () => {
- it('leaves Enter and Space to a focused toolbar control', async () => {
+ it('leaves Enter, Space, C and Escape to a control reached by keyboard', async () => {
const h = createInputHarness();
h.interaction.setTool('transform');
h.pipeline.onPointerEnter();
- h.button.focus();
+ h.surface.focus();
+ await userEvent.tab();
+ expect(document.activeElement).toBe(h.button);
await userEvent.keyboard('{Enter}');
await userEvent.keyboard('{Control>}{Enter}{/Control}');
await userEvent.keyboard(' ');
+ await userEvent.keyboard('c');
+ await userEvent.keyboard('{Escape}');
expect(h.clicks()).toBe(2);
expect(h.events).toEqual([]);
expect(h.interaction.getActiveToolId()).toBe('transform');
expect(h.observed.filter((event) => event.defaultPrevented)).toEqual([]);
});
+ it('pans with Space over the canvas after a control was clicked, without activating that control', async () => {
+ const h = createInputHarness();
+ await userEvent.click(h.button);
+ expect(h.clicks()).toBe(1);
+ h.pipeline.onPointerEnter();
+
+ await userEvent.keyboard('{Space>}');
+ expect(h.interaction.getActiveToolId()).toBe('view');
+ await userEvent.keyboard('{/Space}');
+ expect(h.interaction.getActiveToolId()).toBe('brush');
+ expect(h.clicks()).toBe(1);
+
+ // Enter still belongs to the clicked control.
+ h.interaction.setTool('transform');
+ await userEvent.keyboard('{Enter}');
+ expect(h.clicks()).toBe(2);
+ expect(h.events).not.toContain('transform:apply');
+ });
+
+ it('leaves hold keys and Escape to an open menu', async () => {
+ const h = createInputHarness();
+ const menu = document.createElement('div');
+ menu.setAttribute('role', 'menu');
+ const item = document.createElement('div');
+ item.setAttribute('role', 'menuitem');
+ item.tabIndex = -1;
+ item.textContent = 'Menu item';
+ menu.append(item);
+ document.body.append(menu);
+ cleanups.push(() => menu.remove());
+ await userEvent.click(item);
+ h.pipeline.onPointerEnter();
+
+ await userEvent.keyboard(' ');
+ await userEvent.keyboard('c');
+ await userEvent.keyboard('{Escape}');
+ expect(h.interaction.getActiveToolId()).toBe('brush');
+ expect(h.events).toEqual([]);
+ });
+
it('applies on Enter only when the focused surface owns an unmodified, unprevented key', async () => {
const h = createInputHarness();
h.interaction.setTool('transform');
@@ -140,27 +188,17 @@ describe('pointer pipeline in Chromium: keyboard ownership', () => {
});
});
-describe('pointer pipeline in Chromium: gesture ownership across tool switches', () => {
- it('cancels a drag through the outgoing tool on a genuine switch and never routes its tail to the new tool', () => {
- const h = createInputHarness();
- h.pipeline.onPointerDown(h.pointer('pointerdown', 1));
- h.interaction.setTool('transform');
-
- expect(h.pipeline.isGestureActive()).toBe(false);
- h.pipeline.onPointerMove(h.pointer('pointermove', 1));
- h.pipeline.onPointerUp(h.pointer('pointerup', 0));
- expect(h.events).toEqual(['brush:down', 'brush:cancel']);
- });
-
- it('reset cancels the temporary tool that owns the gesture, then restores the held tool', () => {
+describe('pointer pipeline in Chromium: tool switches during a hold', () => {
+ it('keeps a tool chosen while Space is still held when Space is released', async () => {
const h = createInputHarness();
+ h.interaction.setTool('eraser');
h.pipeline.onPointerEnter();
h.surface.focus();
- h.surface.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code: 'Space', key: ' ' }));
- h.pipeline.onPointerDown(h.pointer('pointerdown', 1));
- h.pipeline.reset();
- expect(h.events).toEqual(['view:down', 'view:cancel']);
+ await userEvent.keyboard('{Space>}');
+ expect(h.interaction.getActiveToolId()).toBe('view');
+ h.interaction.setTool('brush');
+ await userEvent.keyboard('{/Space}');
expect(h.interaction.getActiveToolId()).toBe('brush');
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
index d19401e087..6518ab61f0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
@@ -65,7 +65,7 @@ const makeKeyEvent = (init: {
target: init.target ?? null,
}) as unknown as KeyboardEvent;
-/** A key target inside the canvas surface; the harness surface claims it through `contains`. */
+/** A key target inside the canvas surface; the harness keyboard root claims it through `contains`. */
const SURFACE_TARGET = { tagName: 'DIV' };
/** A focused toolbar button outside the surface; its `closest` resolves the interactive selector. */
const BUTTON_TARGET = { closest: () => ({}), tagName: 'BUTTON' };
@@ -107,7 +107,6 @@ const createHarness = (
const releases: number[] = [];
const element = {
getBoundingClientRect: () => ({ left: 0, top: 0 }) as DOMRect,
- parentElement: { contains: (node: unknown) => node === SURFACE_TARGET },
releasePointerCapture: (id: number) => releases.push(id),
setPointerCapture: (id: number) => captures.push(id),
} as unknown as HTMLElement;
@@ -122,6 +121,7 @@ const createHarness = (
getActiveTool: () => tool,
getActiveToolId: () => activeToolId,
getInputElement: () => element,
+ getKeyboardRoot: () => ({ contains: (node) => node === (SURFACE_TARGET as unknown) }),
getToolContext: () => ctx,
handleEscape: opts.handleEscape,
hasTool: (id) => registered.has(id),
@@ -568,51 +568,46 @@ describe('pointer pipeline: canvas keyboard ownership', () => {
expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });
expect(owned.preventDefault).toHaveBeenCalledOnce();
});
-
- it('restores a held tool on a release observed after focus moved, without consuming the key', () => {
- const h = createHarness();
- h.pipeline.onPointerEnter();
- h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
- h.pipeline.onPointerLeave();
-
- const release = makeKeyEvent({ code: 'Space', key: ' ', target: BUTTON_TARGET });
- h.pipeline.onKeyUp(release);
- expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });
- expect(release.preventDefault).not.toHaveBeenCalled();
- });
});
describe('pointer pipeline: cancellation ownership', () => {
- it('a tool-switch cancel drops the rest of the pressed drag until the pointer is released', () => {
+ it('a tool-switch cancel turns the rest of the pressed drag into hover until the pointer is released', () => {
const h = createHarness();
h.pipeline.onPointerDown(makePointerEvent({ pointerId: 4 }));
- h.pipeline.cancelGestureForToolSwitch();
+ h.pipeline.endForToolSwitch();
expect(h.tool.cancels).toBe(1);
expect(h.releases).toEqual([4]);
h.pipeline.onPointerMove(makePointerEvent({ clientX: 5, pointerId: 4 }));
h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, pointerId: 4 }));
- expect(h.tool.moves).toHaveLength(0);
+ expect(h.tool.moves.map(({ batch, input }) => [input.buttons, ...batch.map((sample) => sample.buttons)])).toEqual([
+ [0, 0],
+ ]);
expect(h.tool.ups).toHaveLength(0);
// The released pointer hovers normally again.
h.pipeline.onPointerMove(makePointerEvent({ buttons: 0, clientX: 6, pointerId: 4 }));
- expect(h.tool.moves).toHaveLength(1);
+ expect(h.tool.moves).toHaveLength(2);
});
- it('a tool-switch cancel drops, rather than restores, a hold released mid-gesture', () => {
+ it.each([
+ ['released mid-gesture', true],
+ ['still held', false],
+ ])('a tool switch first restores the held tool when its key is %s', (_, released) => {
const h = createHarness();
h.pipeline.onPointerEnter();
h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
h.pipeline.onPointerDown(makePointerEvent({ pointerId: 2 }));
- h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+ if (released) {
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+ }
h.setTool.mockClear();
- h.pipeline.cancelGestureForToolSwitch();
+ h.pipeline.endForToolSwitch();
expect(h.tool.cancels).toBe(1);
- expect(h.setTool).not.toHaveBeenCalled();
+ expect(h.setTool.mock.calls).toEqual([['brush', { temporary: true }]]);
h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
- expect(h.setTool).not.toHaveBeenCalled();
+ expect(h.setTool).toHaveBeenCalledOnce();
});
it('reset cancels through the held temporary tool before restoring the prior tool', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
index 2288db3414..cb498d17c7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -2,8 +2,10 @@
* Normalizes DOM events into tool input with capture, coalesced samples and default mouse pressure 0.5. Middle
* mouse pans independently. Space, Alt and held C temporarily select view, picker and bbox; release restores the
* tool, while quick C selects bbox persistently. Temporary switches preserve sessions and are blocked mid-gesture.
- * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. Enter and Space act only while the canvas
- * surface owns the keyboard; key releases are always observed and never consumed. DOM access is injected.
+ * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. Enter acts only while the keyboard root owns
+ * focus. Hold keys and the Escape ladder also act after a control was merely clicked, but never over an editable
+ * field, a keyboard-navigated control or an open overlay. Key releases are always observed and never consumed. DOM
+ * access is injected.
*/
import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
@@ -24,6 +26,8 @@ export interface PointerPipelineDeps {
viewport: Viewport;
/** The element that owns pointer capture and defines the coordinate rect. */
getInputElement(): (HTMLElement & Partial<Pick<HTMLElement, 'setPointerCapture' | 'releasePointerCapture'>>) | null;
+ /** The focusable element whose focus gives the canvas its session keys. */
+ getKeyboardRoot(): Pick<HTMLElement, 'contains'> | null;
getActiveTool(): Tool | undefined;
getActiveToolId(): ToolId;
getToolContext(): ToolContext;
@@ -56,6 +60,8 @@ export interface PointerPipeline {
onPointerLeave(): void;
onKeyDown(event: KeyboardEvent): void;
onKeyUp(event: KeyboardEvent): void;
+ /** Window focus moves; records whether focus arrived by pointer, which decides hold-key ownership. */
+ onFocusIn(event: FocusEvent): void;
/** Primary gesture state blocks undo/redo from injecting pixels during live strokes. */
isGestureActive(): boolean;
/**
@@ -64,10 +70,10 @@ export interface PointerPipeline {
*/
cancelActiveGesture(): void;
/**
- * Cancels through the outgoing tool before a genuine tool switch. A hold whose key was released mid-gesture is
- * dropped instead of restored, so the requested tool wins.
+ * Before a genuine tool switch, cancels through the outgoing tool and ends any held temporary tool, so the switch
+ * leaves the tool the user was really on and a later key release restores nothing.
*/
- cancelGestureForToolSwitch(): void;
+ endForToolSwitch(): void;
/** Replaces a matching tool id that a currently-held temporary tool would restore on release. */
replaceTemporaryRestoreTool(current: ToolId, replacement: ToolId): void;
/** Clears hover/gesture/temp-tool state, cancelling any in-flight gesture (called on detach/blur). */
@@ -123,7 +129,20 @@ const INTERACTIVE_SELECTOR = [
].map((role) => `[role="${role}"]`),
].join(', ');
-type KeyTarget = { tagName?: unknown; closest?: (selector: string) => unknown } | null;
+/** Open layers whose focused content keeps its own keys. */
+const OVERLAY_SELECTOR = '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]';
+
+type KeyTarget = {
+ tagName?: unknown;
+ closest?: (selector: string) => unknown;
+ matches?: (selector: string) => boolean;
+} | null;
+
+// Chromium turns `:focus-visible` on for the focused element at any keydown, so how focus arrived is read on arrival.
+const arrivedByPointer = (target: EventTarget | null): boolean => {
+ const el = target as KeyTarget;
+ return typeof el?.matches === 'function' && !el.matches(':focus-visible');
+};
const isInteractiveTarget = (target: EventTarget | null): boolean => {
const el = target as KeyTarget;
@@ -152,8 +171,10 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
let restoreTempAfterGesture = false;
let bboxQuickTap = false;
let bboxTapTimer: ReturnType<typeof setTimeout> | null = null;
- // A cancelled gesture's pointer keeps reporting pressed moves; none may reach a tool until it is released.
+ // A cancelled gesture's pointer keeps reporting pressed moves; they reach a tool only as hover until release.
let cancelledPointerId: number | null = null;
+ // The control focus last landed on by pointer; keyboard navigation (`:focus-visible` on arrival) clears it.
+ let pointerFocused: EventTarget | null = null;
/**
* Reads the input element's viewport offset. Hoisted out of
@@ -186,22 +207,37 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return [buildPointerInput(event, origin)];
};
- /** Session keys belong to the canvas only when focus is on its surface (or nowhere) and no control claims them. */
+ /** Enter belongs to the canvas only when focus is on its keyboard root (or nowhere) and no control claims it. */
const ownsKeyboard = (event: KeyboardEvent): boolean => {
if (event.defaultPrevented || isInteractiveTarget(event.target)) {
return false;
}
- const input = deps.getInputElement();
- const surface = (input?.parentElement ?? input) as { contains?: (node: unknown) => boolean } | null;
- return isDocumentRootTarget(event.target) || surface?.contains?.(event.target) === true;
+ return isDocumentRootTarget(event.target) || deps.getKeyboardRoot()?.contains(event.target as Node) === true;
+ };
+
+ /**
+ * Hold keys and Escape also reach the canvas after a pointer click left focus on a control (a tool button, a layer
+ * row), but not over an editable field, a control reached by keyboard or an open overlay.
+ */
+ const ownsCanvasKey = (event: KeyboardEvent): boolean => {
+ if (event.defaultPrevented || isEditableTarget(event.target)) {
+ return false;
+ }
+ if (ownsKeyboard(event)) {
+ return true;
+ }
+ return (
+ event.target !== null &&
+ event.target === pointerFocused &&
+ !(event.target as KeyTarget)?.closest?.(OVERLAY_SELECTOR)
+ );
};
const releaseCapture = (pointerId: number): void => {
deps.getInputElement()?.releasePointerCapture?.(pointerId);
};
- /** `restoreTemporary: false` lets a genuine tool switch win over a hold whose key was released mid-gesture. */
- const cancelGesture = (restoreTemporary = true): void => {
+ const cancelGesture = (): void => {
if (!gestureActive) {
return;
}
@@ -214,11 +250,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
deps.getActiveTool()?.onPointerCancel?.(deps.getToolContext());
deps.updateCursor();
if (restoreTempAfterGesture && tempHold) {
- if (restoreTemporary) {
- endTempTool();
- } else {
- clearTempHold();
- }
+ endTempTool();
}
};
@@ -311,14 +343,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
if (bboxQuickTap) {
- if (tempSwitched) {
- deps.setTool(priorToolId, { temporary: true });
- }
+ endTempTool();
deps.setTool(BBOX_TEMP_TOOL);
- tempHold = null;
- tempSwitched = false;
- restoreTempAfterGesture = false;
- bboxQuickTap = false;
return;
}
endTempTool();
@@ -328,8 +354,11 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
cancelActiveGesture: () => {
cancelGesture();
},
- cancelGestureForToolSwitch: () => {
- cancelGesture(false);
+ endForToolSwitch: () => {
+ cancelGesture();
+ if (tempHold) {
+ endTempTool();
+ }
},
onKeyDown: (event) => {
if (event.key === 'Escape') {
@@ -337,7 +366,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
// Escape may cancel a session but must preserve committed selection.
const gestureWasActive = gestureActive;
cancelGesture();
- if (!isEditableTarget(event.target)) {
+ if (ownsCanvasKey(event)) {
deps.handleEscape?.({ gestureWasActive });
}
return;
@@ -354,7 +383,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
if (event.code === 'Space' && !event.repeat) {
- if (event.ctrlKey || event.metaKey || event.altKey || !ownsKeyboard(event)) {
+ if (event.ctrlKey || event.metaKey || event.altKey || !ownsCanvasKey(event)) {
return;
}
beginTempTool('space', SPACE_TEMP_TOOL);
@@ -364,16 +393,19 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
if (isAltKey(event) && !event.repeat) {
- if (!deps.getActiveTool()?.usesAltKey) {
+ if (!deps.getActiveTool()?.usesAltKey && ownsCanvasKey(event)) {
beginTempTool('alt', ALT_TEMP_TOOL);
}
return;
}
- if (isBboxKey(event) && !event.repeat) {
+ if (isBboxKey(event) && !event.repeat && ownsCanvasKey(event)) {
beginBboxTempTool();
}
},
isGestureActive: () => gestureActive,
+ onFocusIn: (event) => {
+ pointerFocused = arrivedByPointer(event.target) ? event.target : null;
+ },
onKeyUp: (event) => {
if (event.code === 'Space' && tempHold === 'space') {
releaseTempTool();
@@ -447,13 +479,13 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
middleLast = screenPoint;
return;
}
- if (cancelledPointerId === event.pointerId) {
- if (event.buttons !== 0) {
- return;
- }
+ // A cancelled gesture's pointer stays pressed until release; its moves reach the tool only as hover, so the
+ // cursor keeps tracking but nothing resumes the gesture.
+ const cancelledPress = cancelledPointerId === event.pointerId && event.buttons !== 0;
+ if (cancelledPointerId === event.pointerId && !cancelledPress) {
cancelledPointerId = null;
}
- const batch = buildBatch(event);
+ const batch = cancelledPress ? buildBatch(event).map((input) => ({ ...input, buttons: 0 })) : buildBatch(event);
const last = batch[batch.length - 1];
if (!last) {
return;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
index c77f1c26b6..d9c68681c2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
@@ -11,6 +11,7 @@ import { createEmptyCanvasState } from '@workbench/canvasMigration';
import { act, StrictMode, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
import { CanvasSurface } from './CanvasSurface';
@@ -297,3 +298,44 @@ describe('CanvasSurface during a resize drag', () => {
);
});
});
+
+describe('CanvasSurface keyboard ownership', () => {
+ it('owns hold keys once the canvas is clicked, and leaves them to a tree row reached by keyboard', async () => {
+ const registry = createTrackedRegistry(20);
+ const { engine } = acquireTrackedEngine(registry, 'project-a', createEngineDeps(createEmptyCanvasState(64, 64)));
+ const host = document.createElement('div');
+ document.body.append(host);
+ const { root } = createTrackedRoot(host);
+ await act(async () => {
+ root.render(
+ <>
+ <StrictCanvasHarness engine={engine} />
+ <div role="tree">
+ <div aria-selected="false" role="treeitem" tabIndex={0}>
+ Layer
+ </div>
+ </div>
+ </>
+ );
+ await nextFrame();
+ });
+ const overlay = host.querySelectorAll('canvas')[1]!;
+ const row = host.querySelector<HTMLElement>('[role="treeitem"]')!;
+ const tool = () => engine.interaction.get('activeTool');
+ const initial = tool();
+
+ await userEvent.click(overlay);
+ expect(document.activeElement).toBe(overlay.parentElement);
+ await userEvent.keyboard('{Space>}');
+ expect(tool()).toBe('view');
+ await userEvent.keyboard('{/Space}');
+ expect(tool()).toBe(initial);
+
+ await userEvent.tab();
+ expect(document.activeElement).toBe(row);
+ await userEvent.hover(overlay);
+ await userEvent.keyboard('{Space>}');
+ expect(tool()).toBe(initial);
+ await userEvent.keyboard('{/Space}');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
index 7f3a4b681a..6e0ed72ff5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
@@ -38,7 +38,7 @@ export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {
return;
}
- engine.surface.attach(screen, overlay);
+ engine.surface.attach(screen, overlay, container);
// A handle drag defers the resize and full recomposition to its release; pixel CSS sizes make the interim
// canvas crop or reveal rather than stretch.