Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(webv2): hold the canvas bitmap while a divider is dragged
Josh Corbettf9254aeb5f60
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.tsxindex 0691402ab4..c77f1c26b6 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@@ -4,10 +4,11 @@ import type { EngineDeps, EngineRegistry } from '@workbench/canvas-operations/enimport type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import { ChakraProvider } from '@chakra-ui/react';+import { ResizeHandle } from '@platform/ui/ResizeHandle';import { system } from '@theme/system';import { createEngineRegistry } from '@workbench/canvas-operations/engineRegistry';import { createEmptyCanvasState } from '@workbench/canvasMigration';-import { act, StrictMode } from 'react';+import { act, StrictMode, useRef } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -210,3 +211,89 @@ describe('CanvasSurface browser lifecycle', () => {expect(registry.getEngine('project-b')).toBeUndefined();});});++const ignoreCommit = (): void => undefined;++const ResizeDragHarness = ({ engine, showCanvas = true }: { engine: CanvasEngine; showCanvas?: boolean }) => {+ const paneRef = useRef<HTMLDivElement>(null);++ return (+ <ChakraProvider value={system}>+ <div style={{ display: 'flex' }}>+ <div ref={paneRef} style={{ width: 100 }} />+ <ResizeHandle+ label="Resize pane"+ max={300}+ min={50}+ orientation="vertical"+ pane="before"+ paneRef={paneRef}+ value={100}+ onCommit={ignoreCommit}+ />+ <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>+ {showCanvas ? <CanvasSurface engine={engine} /> : null}+ </div>+ </div>+ </ChakraProvider>+ );+};++describe('CanvasSurface during a resize drag', () => {+ it('keeps its bitmap until the drag ends, cropping instead of stretching', 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(<ResizeDragHarness engine={engine} />);+ await nextFrame();+ });+ const resize = vi.spyOn(engine.surface, 'resize');+ const separator = host.querySelector<HTMLElement>('[role="separator"]')!;+ const bounds = host.querySelector<HTMLElement>('[data-testid="surface-bounds"]')!;+ const screen = host.querySelector('canvas')!;+ const pointer = (type: string, buttons: number) =>+ new PointerEvent(type, { bubbles: true, buttons, clientX: 0, pointerId: 1 });++ await act(() => separator.dispatchEvent(pointer('pointerdown', 1)));+ bounds.style.width = '200px';+ await act(async () => {+ await nextFrame();+ await nextFrame();+ });++ expect(resize).not.toHaveBeenCalled();+ expect(screen.style.width).toBe('160px');++ await act(() => window.dispatchEvent(pointer('pointerup', 0)));++ expect(resize).toHaveBeenCalledExactlyOnceWith(200, 120, globalThis.devicePixelRatio || 1);+ expect(screen.style.width).toBe('200px');+ });++ it('sizes a canvas that first appears during a drag without waiting for it', async () => {+ const registry = createTrackedRegistry(20);+ const { engine } = acquireTrackedEngine(registry, 'project-a', createEngineDeps(createEmptyCanvasState(64, 64)));+ const resize = vi.spyOn(engine.surface, 'resize');+ const host = document.createElement('div');+ document.body.append(host);+ const { root } = createTrackedRoot(host);++ await act(() => root.render(<ResizeDragHarness engine={engine} showCanvas={false} />));+ const separator = host.querySelector<HTMLElement>('[role="separator"]')!;+ await act(() =>+ separator.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, buttons: 1, clientX: 0, pointerId: 1 }))+ );+ await act(() => root.render(<ResizeDragHarness engine={engine} />));++ expect(resize).toHaveBeenCalledExactlyOnceWith(160, 120, globalThis.devicePixelRatio || 1);+ expect(host.querySelector('canvas')!.style.width).toBe('160px');++ await act(() =>+ window.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, buttons: 0, clientX: 0, pointerId: 1 }))+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsxindex 9f80a2dcc1..7f3a4b681a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx@@ -3,6 +3,7 @@ import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngiimport type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react';import { Box } from '@chakra-ui/react';+import { isResizeDragActive, subscribeResizeDrag } from '@platform/ui/ResizeHandle';import { shouldFocusCanvasSurface } from '@workbench/widgets/canvas/surfaceFocus';import { TextEditPortal } from '@workbench/widgets/canvas/TextEditPortal';import { useRef } from 'react';@@ -39,22 +40,49 @@ export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {engine.surface.attach(screen, overlay);- const syncSize = () => {+ // 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.+ let isSizeStale = false;+ let syncedSize = '';+ const syncSize = (canDefer: boolean) => {+ if (canDefer && isResizeDragActive()) {+ isSizeStale = true;+ return;+ }+ isSizeStale = false;+ const width = container.clientWidth;+ const height = container.clientHeight;const dpr = globalThis.devicePixelRatio || 1;- engine.surface.resize(container.clientWidth, container.clientHeight, dpr);+ // Resizing reallocates and recomposes everything, so an unchanged size is skipped.+ if (canDefer && syncedSize === `${width}x${height}@${dpr}`) {+ return;+ }+ syncedSize = `${width}x${height}@${dpr}`;+ for (const canvas of [screen, overlay]) {+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;+ }+ engine.surface.resize(width, height, dpr);};- syncSize();+ // The first sync never waits: the fit below needs a sized viewport.+ syncSize(false);// Fit the document into view the first time this canvas is shown, once the// viewport is sized. The shell keeps widgets mounted across layout switches,// so this callback re-runs on every re-show and an unconditional fit would// reset the user's zoom and pan each time they came back.engine.viewport.fitToViewOnFirstShow();- const observer = new ResizeObserver(syncSize);+ const observer = new ResizeObserver(() => syncSize(true));observer.observe(container);+ const unsubscribeResizeDrag = subscribeResizeDrag(() => {+ if (isSizeStale) {+ syncSize(true);+ }+ });return () => {+ unsubscribeResizeDrag();observer.disconnect();engine.surface.detach();};@@ -80,11 +108,10 @@ export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {};const CANVAS_STYLE: CSSProperties = {- height: '100%',- inset: 0,+ left: 0,position: 'absolute',+ top: 0,touchAction: 'none',- width: '100%',};const OVERLAY_STYLE: CSSProperties = { ...CANVAS_STYLE, zIndex: 1 };