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): hide masks under previews again; tidy Layers panel visibility and nesting (#10111)

Josh Corbett57a715a81fdc
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
index b591827f8a..bc5d589750 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
@@ -39,7 +39,7 @@ The Layers panel groups layers by type, in the stacks **Inpaint Masks**, **Regio
<Image src={addLayerMenu} alt="The Add layer menu with Inpaint mask, Regional guidance, Regional reference image, Control layer, Raster layer and New group." width={500} />
-Each layer row has a dot on the left that switches the layer on or off for generation. Masks, regional guidance and control layers also have an eye button, which only hides them from view: a hidden mask still affects generation. **Shift+H** hides all of them at once so you can see the image underneath.
+Each layer row has an eye button on the right. A hidden layer is off the canvas and takes no part in generation. To only get a mask, regional guidance or control layer out of view while it still affects generation, choose **Hide on canvas only** in its right-click menu. **Shift+H** does that for all of them at once so you can see the image underneath.
### Settings live in the Properties pane
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index e02de078d7..21d6da68ba 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -169,7 +169,7 @@ Right-click a result's thumbnail to recall its settings into the Generate panel.
The canvas stays editable while results are staged or a canvas generation runs: every tool, layer action and shortcut works as usual. Each result keeps its place. It lands where the generation frame was when you pressed **Invoke**, and the canvas outlines that spot with a dashed amber frame for each pending result (thicker for the selected one). Moving or resizing the generation frame afterwards only affects the next **Invoke**; the results, and the live progress image, stay where they were. **Accept to layer** adds the result above all raster layers as they are at that moment, whatever you painted, added or deleted meanwhile, and first places any pixels you are still moving and applies a transform you have not applied yet.
-While a progress image or a staged result is shown, inpaint masks, regional guidance and regenerate regions are hidden from view so they do not cover the result. They still take part in generation. They reappear when you hide the preview or accept or discard the results, and while an inpaint mask or regional guidance layer is selected, so you can see what you paint: they then show over the result.
+While a progress image or a staged result is shown, inpaint masks, regional guidance and regenerate regions are hidden from view so they do not cover the result. They still take part in generation. They reappear when you hide the preview or accept or discard the results. While you paint, erase, drag out a shape on or move an inpaint mask or regional guidance layer, they show over the result so you can see what you change, and hide again when you let go. Panning, zooming and picking colors keep them hidden.
## The canvas menu
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index ef7199efc2..007ec92087 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -1,7 +1,7 @@
---
title: Layers panel guide
description: A detailed guide to the Canvas Layers panel — the color picker, managing layers, history, the layer menu, and every layer type's settings in the Properties pane.
-lastUpdated: 2026-10-29
+lastUpdated: 2026-11-02
---
import { Image } from 'astro:assets';
@@ -17,7 +17,7 @@ The **Layers** panel sits to the right of the Canvas in the **Edit** layout. It
Drag the dividers between the parts to resize them, and use the chevron at the right of the Color and Properties tabs to collapse them. The sizes are saved with the project.
-<Image src={layersPanel} alt="The Layers panel: the color wheel at the top, the layer list grouped into Inpaint Masks, Regional Guidance, Control Layers and Raster Layers, and the Properties pane showing a control layer's settings." width={420} />
+<Image src={layersPanel} alt="The Layers panel: the color wheel at the top; the layer list with Inpaint Masks, Regional Guidance, Control Layers and Raster Layers, each row ending in an eye and a lock in one column; an Exposure adjustment as a child row under the City raster layer, joined to it by a connector line, its eye in the same column; and the Properties pane showing the selected depth control layer's settings." width={420} />
For an introduction to the layer types, see [Crafting images with the Canvas](/users-guide/canvas/introduction/#canvas-concepts).
@@ -40,17 +40,19 @@ The **Swatches** tab has built-in **Swatches**, your **Recent colors**, and the
### The layer list
-Layers are grouped into four stacks: **Inpaint Masks**, **Regional Guidance**, **Control Layers** and **Raster Layers**. Within a stack, higher layers are drawn over lower ones. Click a stack's header to collapse it. Its buttons add a **New layer** of that type, and **Hide all** or **Show all**: for raster layers this hides them (and leaves them out of generation); for masks, regional guidance and control layers it is **Hide all on canvas**, which only gets them out of view. The Raster Layers header also has **Merge visible** and **Export to PSD**. Collapsed stacks and groups stay as you left them when you switch to another open project and back.
+Layers are grouped into four stacks: **Inpaint Masks**, **Regional Guidance**, **Control Layers** and **Raster Layers**. Within a stack, higher layers are drawn over lower ones. Click a stack's header to collapse it. The buttons at the right of a header end with **New layer**, which adds a layer of that type. The Inpaint Masks, Regional Guidance and Control Layers headers have **Hide all on canvas** (or **Show all on canvas**) just before it, which only gets the stack's layers out of view: they still affect generation. The Raster Layers header has **Merge visible** and **Export to PSD** instead. Collapsed stacks and groups stay as you left them when you switch to another open project and back.
Each row shows, from left to right:
* A colored stripe, if you gave the layer a color label.
-* An eye button (**Show or hide layer**). A hidden layer is off the canvas and takes no part in generation.
* A thumbnail, the layer type and the name.
* On masks, regional guidance and control layers hidden with **Hide on canvas only** (in the layer menu), a closed-eye button: the layer is off the canvas but still affects generation. Click it to show the layer again.
+* An eye button (**Show or hide layer**). A hidden layer is off the canvas and takes no part in generation.
* A lock button (**Toggle lock**), which prevents editing. Painting, moving or transforming a locked layer is refused with a notice that says so.
-Rows can have child rows, shown with a chevron: adjustments and regenerate regions on raster layers, noise and denoise limits on inpaint masks, and reference images on regional guidance layers. Select a child row to edit it in Properties.
+Rows can have child rows, shown with a chevron: adjustments and regenerate regions on raster layers, noise and denoise limits on inpaint masks, and reference images on regional guidance layers. A child row shows its icon (or the reference image), its name, its value where it has one, and its own eye button (**Enable/disable**), which turns it off without removing it. While its layer is hidden, a child row's eye is dimmed and the child has no effect. Select a child row to edit it in Properties. Thin lines run from each expanded layer or group down to its child rows and the layers inside it, so you can see what belongs where.
+
+The eye buttons of layers and child rows line up in one column at the right edge of the list, with the lock buttons in a column beside them, however deeply a layer is nested in groups.
Drag an adjustment to reorder it, or drop it on another raster layer or group, or among that layer's adjustments, to move it there as one undoable step. Reference images move between regional guidance layers the same way. A child row's right-click menu also has a **Move to layer** submenu listing the layers that can take it.
@@ -100,7 +102,7 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw
* **Use as control layer** — copies the layer's pixels to a new control layer, whose Properties then ask for its **Type**.
* **Boolean operations** — combine the layer with the one below: intersect, cut out, cut away or exclude.
* **Convert to** — make it a control layer, inpaint mask or regional guidance layer. Text, shape and gradient layers can also be rasterized into plain pixels. Control layers have no adjustments, so converting a layer with adjustments to a control layer, or using it as one, bakes them, with the layer's scaling and rotation, into its pixels; undo restores the raster layer with its adjustments.
-* **Control layers:** **Transform**, **Select object**, **Run workflow**, **Enable transparent preview**, and **Convert to raster layer**. A control layer's map comes from its **Detection** row in Properties, so it has no **Filter**.
+* **Control layers:** **Transform**, **Select object**, **Run workflow**, **Enable transparent preview**, **Convert to raster layer**, and **Hide on canvas only**. A control layer's map comes from its **Detection** row in Properties, so it has no **Filter**.
* **Inpaint masks:** **Add noise**, **Add denoise limit**, **Extract masked area** (copy the masked part of the image to a new layer), and **Hide on canvas only**.
* **Regional guidance:** **Enable auto-negative**, **Add reference image**, and **Hide on canvas only**.
diff --git a/docs/src/content/docs/Users Guide/assets/layers-panel.webp b/docs/src/content/docs/Users Guide/assets/layers-panel.webp
index 2033ffb7c0..f0107b86a3 100644
Binary files a/docs/src/content/docs/Users Guide/assets/layers-panel.webp and b/docs/src/content/docs/Users Guide/assets/layers-panel.webp differ
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 5d0aba8674..021d645e18 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -3146,7 +3146,6 @@
"source:src/workbench/widgets/layers/ControlSourceRow.tsx",
"source:src/workbench/widgets/layers/ControlTypeRow.tsx",
"source:src/workbench/widgets/layers/InpaintMaskSettings.tsx",
- "source:src/workbench/widgets/layers/LayerActiveDot.tsx",
"source:src/workbench/widgets/layers/LayerBlendRow.tsx",
"source:src/workbench/widgets/layers/LayerChildMenu.tsx",
"source:src/workbench/widgets/layers/LayerChildRow.tsx",
@@ -3162,6 +3161,7 @@
"source:src/workbench/widgets/layers/LayerStackMenu.tsx",
"source:src/workbench/widgets/layers/LayerSurfaceHost.tsx",
"source:src/workbench/widgets/layers/LayerThumbnail.tsx",
+ "source:src/workbench/widgets/layers/LayerTreeGuides.tsx",
"source:src/workbench/widgets/layers/LayersHeaderActions.tsx",
"source:src/workbench/widgets/layers/LayersPanelFooter.tsx",
"source:src/workbench/widgets/layers/LayersTree.tsx",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 2f46743708..b601d501ff 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -5517,7 +5517,7 @@
"modifiers": {
"disable": "Disable",
"enable": "Enable",
- "parentDisabled": "Layer is disabled",
+ "parentDisabled": "The layer is hidden, so this has no effect.",
"toggleActive": "Enable/disable",
"denoise": "Denoise limit",
"denoiseHelp": "Caps how strongly generation may repaint the masked area.",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index a1d2c25487..eeabfa27e6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -111,7 +111,7 @@ Nothing in the document freezes while a generation runs or its results wait for
## 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 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 staged or progress preview is shown it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted, unless the selection is a mask or region (or a group in those stacks; `isEditingStagingHiddenStack`), which shows them again so the user never paints a mask blind. The staged preview always lands above the raster and control stacks and below masks and regions, so a shown mask draws over it. A candidate whose preview is toggled off hides nothing. Control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame (`hidesOverlayStacksForStaging`) and joins the description's reuse key; publishing or clearing the preview repaints in full, and so does any document change that moves the selection into or out of a mask or region while a preview is shown: a selection change, or an in-place conversion of the selected layer, which keeps its id. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.
+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 staged or progress preview is shown it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted, whatever is selected. They show again, drawn above the preview, only while a pointer gesture edits the selected mask or region (or a group in those stacks; `isStagingHiddenStackSelected`), so the user never paints a mask blind. Whether a gesture edits is the active tool's `Tool.editsSelectedLayer` contract, asked once as the pointer pipeline reports the gesture starting (`onGestureChange`): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag aimed at the selection whose leaf accepts its pixels. A tool that knows only later calls `ToolContext.beginSelectedLayerEdit`, which runs the same reveal decision mid-gesture: a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses or that moves a float. A locked or hidden mask reveals nothing, and a selected group reveals only for a move, since the brush, eraser and shapes paint a new layer instead. Navigation, sampling, bbox, selection, transform, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture carries, such as undoing a mask stroke or closing a polygon, change nothing visible while the preview hides the stacks. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions and floating selections never open on masks or regions, so the transform tool has nothing to reveal. The staged preview always lands above the raster and control stacks and below masks and regions, so a shown mask draws over it. A candidate whose preview is toggled off hides nothing. Control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and joins the description's reuse key; publishing or clearing the preview repaints in full, and while a preview is shown so do the reveal's start (the press, or a move's threshold crossing) and the gesture's end (release, cancel or reset); its other pointer moves repaint only their own damage. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.
`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/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index f97dadec4d..b4fcd90544 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -15914,12 +15914,41 @@ describe('overview: composites the fit-to-view extent', () => {
// ---- transform session: param commit (image) + pixel bake (paint) ----------
describe('masks while a result is staged', () => {
- it('hides masks and region tints only under a shown preview, and shows them while a mask is being edited', async () => {
+ const candidate: CanvasStagingCandidateContract = {
+ height: 20,
+ imageName: 'staged.png',
+ imageUrl: '/staged.png',
+ placement: { height: 20, opacity: 1, width: 20, x: 0, y: 0 },
+ queuedAt: '2026-07-16T00:00:00.000Z',
+ sourceQueueItemId: 'queue',
+ thumbnailUrl: '/staged-thumb.png',
+ width: 20,
+ };
+ const MASKED = { drawn: ['a', 'm'], regionOverlays: true };
+ const UNMASKED = { drawn: ['a'], regionOverlays: false };
+
+ /** An attached engine over `stacks` (a mask `m` above a raster `a` by default), hovered, with frames on demand. */
+ const setup = (stacks = stacksFrom([maskLayer('m'), rasterLayer('a')])) => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+ // The window key listeners attach adds, so a test can hold Space as the browser would deliver it.
+ const windowListeners = new Map<string, (event: unknown) => void>();
+ vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>
+ windowListeners.set(type, listener)
+ );
+ vi.stubGlobal('removeEventListener', () => {});
const composite = vi.spyOn(compositor, 'compositeDocument');
- let canvas = makeCanvas({ ...makeDoc(), stacks: stacksFrom([maskLayer('m'), rasterLayer('a')]) });
+ let canvas = makeCanvas({ ...makeDoc(), stacks });
const listeners = new Set<() => void>();
const store: EngineStore = {
dispatch: vi.fn(),
@@ -15929,75 +15958,253 @@ describe('masks while a result is staged', () => {
return () => listeners.delete(listener);
},
};
- const update = (next: typeof canvas): void => {
- canvas = next;
+ const update = (next: Partial<typeof canvas>): void => {
+ canvas = { ...canvas, ...next };
for (const listener of listeners) {
listener();
}
};
+ const select = (selectedLayerId: string): void => update({ document: { ...canvas.document, selectedLayerId } });
const engine = createCanvasEngine({
backend: {
...createTestStubRasterBackend(),
createImageBitmap: () => Promise.resolve({ close: vi.fn(), height: 20, width: 20 } as unknown as ImageBitmap),
},
+ bitmapStore: createSpyBitmapStore(),
imageResolver: () => Promise.resolve(new Blob()),
projectId: 'p1',
store,
});
- engine.surface.attach(createInputCanvas().element, createInputCanvas().element);
+ const overlay = createInputCanvas();
+ engine.surface.attach(createInputCanvas().element, overlay.element);
+ overlay.fire('pointerenter', pointerAt(5, 5));
+ /** The frame's composites: how many repainted in full, and what the last one drew. */
const frame = () => {
composite.mockClear();
raf.flush();
const options = composite.mock.calls.at(-1)?.[4];
return {
- damage: options?.damage?.kind,
drawn: options?.preparation?.leaves.map((leaf) => leaf.id),
+ full: composite.mock.calls.filter((call) => call[4]?.damage?.kind === 'full').length,
regionOverlays: options?.regionOverlays,
};
};
- expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });
+ const showPreview = async (): Promise<void> => {
+ update({ stagingArea: { ...canvas.stagingArea, isVisible: true, pendingImages: [candidate] } });
+ engine.previews.setStagedPreview({ imageName: candidate.imageName, placement: candidate.placement });
+ await flushMicrotasks();
+ };
+ const useTool = (tool: ToolId): void => {
+ engine.tools.setTool(tool);
+ raf.flush();
+ };
+ const key = (type: 'keydown' | 'keyup', code: string): void =>
+ windowListeners.get(type)?.({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null });
+ /** A press that must leave the masks hidden, whatever else its frames repaint. */
+ const expectPressHidden = (): void => {
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ const pressed = frame();
+ expect(pressed.drawn ?? []).not.toContain('m');
+ expect(pressed.regionOverlays).not.toBe(true);
+ overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));
+ expect(frame().drawn ?? []).not.toContain('m');
+ };
+ const dispose = (): void => {
+ composite.mockRestore();
+ engine.lifecycle.dispose();
+ };
+ return { dispose, engine, expectPressHidden, frame, key, overlay, select, showPreview, update, useTool };
+ };
+
+ it('hides masks and region tints under a shown preview, showing them only while a gesture edits a mask', async () => {
+ const h = setup();
+ const { frame, overlay } = h;
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
// A staged candidate whose preview is off hides nothing, so staging it repaints nothing either.
- const candidate: CanvasStagingCandidateContract = {
- height: 20,
- imageName: 'staged.png',
- imageUrl: '/staged.png',
- placement: { height: 20, opacity: 1, width: 20, x: 0, y: 0 },
- queuedAt: '2026-07-16T00:00:00.000Z',
- sourceQueueItemId: 'queue',
- thumbnailUrl: '/staged-thumb.png',
- width: 20,
- };
- update({ ...canvas, stagingArea: { ...canvas.stagingArea, isVisible: false, pendingImages: [candidate] } });
+ h.update({ stagingArea: { ...makeCanvas(makeDoc()).stagingArea, isVisible: false, pendingImages: [candidate] } });
expect(frame().drawn).toBeUndefined();
// Showing it hides masks and the region tint, so the result reads as it would be accepted.
- engine.previews.setStagedPreview({ imageName: candidate.imageName, placement: candidate.placement });
+ await h.showPreview();
+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });
+
+ // Selecting the mask alone (as after painting it, before Invoke) keeps the result unmasked.
+ h.select('m');
+ expect(frame()).toMatchObject({ full: 0 });
+
+ // A brush stroke on it shows the masks over the preview for the stroke: one full repaint as it starts, then the
+ // stroke's own damage, and one full repaint hiding them as it lands.
+ h.useTool('brush');
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
+ overlay.fire('pointermove', pointerAt(15, 15));
+ expect(frame()).toEqual({ ...MASKED, full: 0 });
+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });
+
+ // A cancelled stroke hides them again too.
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
+ overlay.fire('pointercancel', pointerAt(5, 5));
+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });
+
+ // A move click edits nothing, so it shows nothing, even with a wobble under the drag threshold.
+ h.useTool('move');
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toMatchObject({ full: 0 });
+ overlay.fire('pointermove', pointerAt(6, 6));
+ overlay.fire('pointerup', pointerAt(6, 6, { buttons: 0 }));
+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);
+
+ // A move drag shows them from the move that crosses the threshold until it lands or is cancelled.
+ for (const end of ['pointerup', 'pointercancel'] as const) {
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toMatchObject({ full: 0 });
+ overlay.fire('pointermove', pointerAt(15, 15));
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
+ overlay.fire('pointermove', pointerAt(16, 16));
+ expect(frame()).toMatchObject(MASKED);
+ overlay.fire(end, pointerAt(16, 16, { buttons: 0 }));
+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });
+ }
+
+ // Panning and sampling colors edit nothing, so the masks stay hidden from the press on.
+ for (const tool of ['view', 'colorPicker'] as const) {
+ h.useTool(tool);
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toMatchObject({ full: 0 });
+ overlay.fire('pointermove', pointerAt(15, 15));
+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ const after = frame();
+ expect(after.drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);
+ // Only the pan itself repaints the view.
+ expect(after.full).toBe(tool === 'view' ? 1 : 0);
+ }
+
+ // Without a shown preview the masks always draw, and a stroke on one adds no full repaints.
+ h.engine.previews.setStagedPreview(null);
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
+ h.useTool('brush');
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ overlay.fire('pointermove', pointerAt(15, 15));
+ expect(frame()).toEqual({ ...MASKED, full: 0 });
+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ expect(frame()).toMatchObject(MASKED);
+ h.dispose();
+ });
+
+ it('keeps the selected mask loaded while hidden, so a stroke on it starts at once', async () => {
+ const h = setup(stacksFrom([rasterLayer('a')]));
+ await h.showPreview();
+ h.frame();
+ // A mask with durable pixels arrives while the preview hides its stack, and is selected; nothing else (no
+ // Layers-panel thumbnail) asks for its pixels.
+ const mask: CanvasInpaintMaskLayerContract = {
+ ...maskLayer('m'),
+ mask: { ...maskLayer('m').mask, bitmap: { height: 20, imageName: 'mask.png', width: 20 } },
+ };
+ h.update({ document: { ...makeDoc(), selectedLayerId: 'm', stacks: stacksFrom([mask, rasterLayer('a')]) } });
+ expect(h.frame().drawn).toEqual(UNMASKED.drawn);
await flushMicrotasks();
- expect(frame()).toEqual({ damage: 'full', drawn: ['a'], regionOverlays: false });
+ h.frame();
- // Selecting the mask to paint it shows the masks again, over the preview, in one full repaint.
- update({ ...canvas, document: { ...canvas.document, selectedLayerId: 'm' } });
- expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });
- update({ ...canvas, document: { ...canvas.document, selectedLayerId: 'a' } });
- expect(frame()).toEqual({ damage: 'full', drawn: ['a'], regionOverlays: false });
+ const refusals: CanvasEditRefusal[] = [];
+ h.engine.tools.onEditRefused((refusal) => refusals.push(refusal));
+ const strokes: StrokeCommittedEvent[] = [];
+ h.engine.tools.onStrokeCommitted((event) => strokes.push(event));
+ h.useTool('brush');
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(h.frame()).toEqual({ ...MASKED, full: 1 });
+ h.overlay.fire('pointermove', pointerAt(15, 15));
+ h.overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ expect(refusals).toEqual([]);
+ expect(strokes.map((stroke) => stroke.layerId)).toEqual(['m']);
+ h.dispose();
+ });
+
+ it('keeps them hidden through a Space pan held over the brush', async () => {
+ const h = setup();
+ await h.showPreview();
+ h.select('m');
+ h.useTool('brush');
+ h.frame();
+ h.key('keydown', 'Space');
+ expect(h.engine.stores.activeTool.get()).toBe('view');
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(h.frame()).toMatchObject({ full: 0 });
+ h.overlay.fire('pointermove', pointerAt(15, 15));
+ h.overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ expect(h.frame()).toEqual({ ...UNMASKED, full: 1 });
+ h.key('keyup', 'Space');
+ expect(h.engine.stores.activeTool.get()).toBe('brush');
+ h.dispose();
+ });
- // Converting the selected raster to a mask in place (same id) turns it into mask editing: one full repaint too.
- update({
- ...canvas,
- document: { ...canvas.document, stacks: stacksFrom([maskLayer('m'), maskLayer('a')]) },
- });
- expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });
- update({
- ...canvas,
- document: { ...canvas.document, stacks: stacksFrom([maskLayer('m'), rasterLayer('a')]) },
- });
- expect(frame()).toEqual({ damage: 'full', drawn: ['a'], regionOverlays: false });
+ it('shows them for a shape dragged into the mask, not for a new shape layer or polygon vertices', async () => {
+ const h = setup();
+ const { frame, overlay } = h;
+ await h.showPreview();
+ h.select('m');
+ h.useTool('shape');
+ frame();
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ expect(frame()).toEqual({ ...MASKED, full: 1 });
+ overlay.fire('pointermove', pointerAt(15, 15));
+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });
- engine.previews.setStagedPreview(null);
- expect(frame()).toEqual({ damage: 'full', drawn: ['a', 'm'], regionOverlays: true });
- composite.mockRestore();
- engine.lifecycle.dispose();
+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), target: 'new' });
+ h.expectPressHidden();
+
+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), kind: 'polygon', target: 'selected' });
+ h.expectPressHidden();
+ h.dispose();
+ });
+
+ it.each([
+ ['a locked mask, which refuses every edit', [{ ...maskLayer('m'), isLocked: true }, rasterLayer('a')], 'm', false],
+ [
+ 'a disabled mask, which refuses every edit',
+ [{ ...maskLayer('m'), isEnabled: false }, rasterLayer('a')],
+ 'm',
+ false,
+ ],
+ [
+ 'a group in the mask stack, which paints a new layer but moves its masks',
+ [groupContract('g', [maskLayer('m')]), rasterLayer('a')],
+ 'g',
+ true,
+ ],
+ ])('keeps them hidden for a press that edits no mask on %s', async (_, layers, selected, moveReveals) => {
+ const h = setup(stacksFrom(layers));
+ await h.showPreview();
+ h.select(selected);
+ // Move first: the layers a paint or shape press adds never land in this store, yet the panel would select them.
+ for (const tool of ['move', 'brush', 'eraser', 'shape'] as const) {
+ h.useTool(tool);
+ h.frame();
+ h.expectPressHidden();
+ if (tool !== 'move') {
+ continue;
+ }
+ // A move drag is refused on a locked or disabled mask, but moves a group's masks, showing them from the
+ // threshold on.
+ h.overlay.fire('pointerdown', pointerAt(5, 5));
+ h.overlay.fire('pointermove', pointerAt(15, 15));
+ const dragged = h.frame();
+ h.overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));
+ if (moveReveals) {
+ expect(dragged).toMatchObject({ full: 1, regionOverlays: true });
+ expect(h.frame()).toMatchObject({ full: 1, regionOverlays: false });
+ } else {
+ // The refused drag repaints nothing, so neither the drag nor its release shows or hides a stack.
+ expect(dragged).toMatchObject({ full: 0 });
+ expect(dragged.regionOverlays).not.toBe(true);
+ expect(h.frame()).toMatchObject({ full: 0 });
+ }
+ }
+ h.dispose();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 10a91e3f47..3564be3c85 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -213,7 +213,7 @@ import { createLayerExportGuards, isSupportedExportSource, layerUnreadable } fro
import { createLayerRasterizer } from './layerRasterizer';
import { createPreviewPublisher } from './previewPublisher';
import { createRasterSnapshotCapture } from './rasterSnapshotCapture';
-import { createCompositeFrame, isEditingStagingHiddenStack } from './render/compositeFrame';
+import { createCompositeFrame, isStagingHiddenStackSelected } from './render/compositeFrame';
import { floatingSelectionFrame } from './render/floatingSelectionFrame';
import { createOverlayFrame } from './render/overlayFrame';
import { createSelectObjectBridge } from './selectObjectBridge';
@@ -1141,6 +1141,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
createPath2D: createPath2DImpl,
dispatch: (action) => dispatchCanvasMutation(action),
beginStrokeEdit: (initialBytes) => strokeEdits.begin(initialBytes),
+ beginSelectedLayerEdit: () => beginSelectedLayerEdit(),
reportEditRefusal,
getDocument: () => mirror.getDocument(),
getSelectedLayerIds: () => {
@@ -1523,6 +1524,36 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
});
const scheduler: RenderScheduler = renderController.scheduler;
+ /** Whether the pointer gesture in progress edits a mask or a region, which a shown staged preview otherwise hides. */
+ let gestureEditsStagingHiddenStack = false;
+ /**
+ * Set once per gesture, so its pointer moves read a flag. While a preview is shown, setting and clearing it each
+ * repaint in full: the stacks show above the preview, then hide again.
+ */
+ const setGestureEditsStagingHiddenStack = (edits: boolean): void => {
+ if (edits === gestureEditsStagingHiddenStack) {
+ return;
+ }
+ gestureEditsStagingHiddenStack = edits;
+ if (renderController.previews.getStaged()) {
+ scheduler.invalidate({ all: true });
+ }
+ };
+ /** The pointer gesture in progress edits the selected layer in place: at its press, or later (a move's drag). */
+ const beginSelectedLayerEdit = (): void => {
+ const document = mirror.getDocument();
+ if (pipeline.isGestureActive() && document && isStagingHiddenStackSelected(document)) {
+ setGestureEditsStagingHiddenStack(true);
+ }
+ };
+ const onGestureChange = (active: boolean): void => {
+ if (!active) {
+ setGestureEditsStagingHiddenStack(false);
+ } else if (activeTool()?.editsSelectedLayer?.(toolContext)) {
+ beginSelectedLayerEdit();
+ }
+ };
+
const compositeFrame = createCompositeFrame({
backend,
derivedSurfaceCache,
@@ -1534,6 +1565,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
getCheckerboardTile,
getMaskPatternTile,
getControlView: () => controlView.get(),
+ isEditingStagingHiddenStack: () => gestureEditsStagingHiddenStack,
layerCache,
previews: renderController.previews,
raster: rasterController,
@@ -1610,23 +1642,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
/** Actual last non-null selection, retained across deselect/reselect and updated by engine selections too. */
let lastSelectedLayerId: string | null = null;
- /** Whether the selection is a mask or region, which a shown staged preview otherwise hides on the screen. */
- let selectionEditsHiddenStack = false;
let toolsReady = false;
const mirror: DocumentMirror = createDocumentMirror(mutationPort, {
onDocumentChanged: () => {
editingController.transform.onDocumentChanged();
stores.documentEpoch.set(stores.documentEpoch.get() + 1);
- // Selecting into or out of a mask or region, or converting the selected layer between them and raster or
- // control work (same id), shows or hides those stacks across the screen while a preview is shown.
- const document = mirror.getDocument();
- const editsHiddenStack = !!document && isEditingStagingHiddenStack(document);
- if (editsHiddenStack !== selectionEditsHiddenStack) {
- selectionEditsHiddenStack = editsHiddenStack;
- if (renderController.previews.getStaged()) {
- scheduler.invalidate({ all: true });
- }
- }
// A tool's cursor reads the selected layer (not-allowed over a locked or hidden one), which this may change.
// Skipped until the interaction controller exists, which the cursor reads.
if (toolsReady) {
@@ -1808,8 +1828,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
});
// The mirror seeds silently from the current state, so the memory starts from that selection too.
lastSelectedLayerId = mirror.getDocument()?.selectedLayerId ?? null;
- const seededDocument = mirror.getDocument();
- selectionEditsHiddenStack = !!seededDocument && isEditingStagingHiddenStack(seededDocument);
let fontSourceStacks: CanvasDocumentContractV3['stacks'] | null = null;
let documentFontSources: CanvasTextSource[] = [];
@@ -2012,6 +2030,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// A primary-button pointerdown while a text-edit session is open commits it
// (engine reads the live portal content). The pipeline swallows that press.
maybeCommitModalSession: () => commitOpenTextSession(),
+ onGestureChange,
setTool: (id, opts) => setTool(id, opts),
updateCursor,
viewport,
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 974e49fa08..379dca6462 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
@@ -120,6 +120,7 @@ const createHarness = (
activeToolId = id;
});
const ctx = {} as ToolContext;
+ const gestureChanges: boolean[] = [];
const deps: PointerPipelineDeps = {
getActiveTool: () => tool,
@@ -132,12 +133,13 @@ const createHarness = (
hasTool: (id) => registered.has(id),
isReplaying: () => opts.replaying?.() ?? false,
maybeCommitModalSession: opts.maybeCommitModalSession,
+ onGestureChange: (active) => gestureChanges.push(active),
setTool,
updateCursor: vi.fn(),
viewport: createViewport(),
};
- return { captures, deps, pipeline: createPointerPipeline(deps), releases, setTool, tool };
+ return { captures, deps, gestureChanges, pipeline: createPointerPipeline(deps), releases, setTool, tool };
};
// ---- Tests -----------------------------------------------------------------
@@ -342,36 +344,44 @@ describe('pointer pipeline: multi-pointer isolation during an active gesture', (
});
describe('pointer pipeline: gesture-active state', () => {
- it('reports the primary-button gesture from down to up', () => {
+ it('reports the primary-button gesture from down to up, announcing it before the tool sees the press', () => {
const h = createHarness();
+ const announcedAtToolDown: boolean[][] = [];
+ h.tool.onPointerDown = () => announcedAtToolDown.push([...h.gestureChanges]);
expect(h.pipeline.isGestureActive()).toBe(false);
h.pipeline.onPointerDown(makePointerEvent({ pointerId: 1 }));
expect(h.pipeline.isGestureActive()).toBe(true);
+ expect(announcedAtToolDown).toEqual([[true]]);
h.pipeline.onPointerMove(makePointerEvent({ pointerId: 1, clientX: 10 }));
expect(h.pipeline.isGestureActive()).toBe(true);
h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, pointerId: 1 }));
expect(h.pipeline.isGestureActive()).toBe(false);
+ expect(h.gestureChanges).toEqual([true, false]);
});
- it('clears on pointercancel, Escape, and reset', () => {
+ it.each([
+ ['pointercancel', (h: ReturnType<typeof createHarness>) => h.pipeline.onPointerCancel(makePointerEvent())],
+ ['Escape', (h: ReturnType<typeof createHarness>) => h.pipeline.onKeyDown(makeKeyEvent({ key: 'Escape' }))],
+ ['reset', (h: ReturnType<typeof createHarness>) => h.pipeline.reset()],
+ ['cancelActiveGesture', (h: ReturnType<typeof createHarness>) => h.pipeline.cancelActiveGesture()],
+ ['a tool switch', (h: ReturnType<typeof createHarness>) => h.pipeline.endForToolSwitch()],
+ ])('clears once on %s; repeats and the later release announce nothing more', (_, end) => {
const h = createHarness();
- h.pipeline.onPointerDown(makePointerEvent({ pointerId: 1 }));
- h.pipeline.onPointerCancel(makePointerEvent({ pointerId: 1 }));
- expect(h.pipeline.isGestureActive()).toBe(false);
-
- h.pipeline.onPointerDown(makePointerEvent({ pointerId: 2 }));
- h.pipeline.onKeyDown(makeKeyEvent({ key: 'Escape' }));
- expect(h.pipeline.isGestureActive()).toBe(false);
-
- h.pipeline.onPointerDown(makePointerEvent({ pointerId: 3 }));
- h.pipeline.reset();
+ h.pipeline.onPointerDown(makePointerEvent());
+ end(h);
+ end(h);
expect(h.pipeline.isGestureActive()).toBe(false);
+ h.pipeline.onPointerUp(makePointerEvent({ buttons: 0 }));
+ expect(h.gestureChanges).toEqual([true, false]);
});
it('does not report a middle-mouse pan as a gesture', () => {
const h = createHarness();
h.pipeline.onPointerDown(makePointerEvent({ button: 1, buttons: 4 }));
expect(h.pipeline.isGestureActive()).toBe(false);
+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 4, clientX: 10 }));
+ h.pipeline.onPointerUp(makePointerEvent({ button: 1, buttons: 0 }));
+ expect(h.gestureChanges).toEqual([]);
});
});
@@ -816,6 +826,7 @@ describe('pointer pipeline: history replay', () => {
replaying = false;
h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, pointerId: 2 }));
+ expect(h.gestureChanges).toEqual([]);
h.pipeline.onPointerDown(makePointerEvent({ pointerId: 3 }));
expect(h.tool.downs).toHaveLength(1);
});
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 d6042453e6..4fca445379 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -60,6 +60,11 @@ export interface PointerPipelineDeps {
maybeCommitModalSession?(): boolean;
/** True while an undo/redo replays; primary presses start no gesture then (panning stays available). */
isReplaying(): boolean;
+ /**
+ * A primary gesture began (before the tool sees its press) or ended (released, cancelled or reset). Middle-button
+ * pans are not gestures.
+ */
+ onGestureChange?(active: boolean): void;
}
/** The pipeline handle: DOM handlers plus lifecycle reset. */
@@ -282,6 +287,13 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return owner !== null && (hovered || owner === 'surface') ? owner : null;
};
+ const setGestureActive = (active: boolean): void => {
+ if (gestureActive !== active) {
+ gestureActive = active;
+ deps.onGestureChange?.(active);
+ }
+ };
+
const releaseCapture = (pointerId: number): void => {
deps.getInputElement()?.releasePointerCapture?.(pointerId);
};
@@ -290,7 +302,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
if (!gestureActive) {
return;
}
- gestureActive = false;
+ setGestureActive(false);
if (activePointerId !== null) {
releaseCapture(activePointerId);
cancelledPointerId = activePointerId;
@@ -540,7 +552,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
markBboxHold();
el?.setPointerCapture?.(event.pointerId);
activePointerId = event.pointerId;
- gestureActive = true;
+ setGestureActive(true);
event.preventDefault();
deps.getActiveTool()?.onPointerDown?.(deps.getToolContext(), buildPointerInput(event));
deps.updateCursor();
@@ -606,7 +618,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
if (!gestureActive) {
return;
}
- gestureActive = false;
+ setGestureActive(false);
activePointerId = null;
deps.getActiveTool()?.onPointerUp?.(deps.getToolContext(), buildPointerInput(event));
deps.updateCursor();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts
index e21b5f9bbe..3a485dc183 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts
@@ -56,6 +56,7 @@ const scene = (budgetBytes = SURFACE_BYTES * 2) => {
getControlView: () => null,
getGroupSurface: (scope, members, matrices, content) => raster.groups.get(scope, members, matrices, content),
getMaskPatternTile: () => null,
+ isEditingStagingHiddenStack: () => false,
layerCache: raster.layers,
previews: new PreviewStateController(),
raster,
@@ -126,6 +127,7 @@ describe('frame description over 2,000 nodes', () => {
getControlView: () => null,
getGroupSurface: () => null,
getMaskPatternTile: () => null,
+ isEditingStagingHiddenStack: () => false,
layerCache: raster.layers,
previews: new PreviewStateController(),
raster,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
index ec672f4525..768ed80c3e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
@@ -1,11 +1,15 @@
-import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasDocumentContractV3,
+ CanvasLayerContract,
+ CanvasNodeContract,
+} from '@workbench/canvas-engine/contracts';
import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';
import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d } from '@workbench/canvas-engine/types';
import { PreviewStateController } from '@workbench/canvas-engine/controllers/previewStateController';
-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import * as compositor from '@workbench/canvas-engine/render/compositor';
@@ -13,7 +17,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { FloatingSelectionFrame } from './floatingSelectionFrame';
-import { createCompositeFrame, type CreateCompositeFrameDeps } from './compositeFrame';
+import { createCompositeFrame, type CreateCompositeFrameDeps, isStagingHiddenStackSelected } from './compositeFrame';
const VIEW = [1, 0, 0, 1, 0, 0] as unknown as Mat2d;
@@ -36,7 +40,7 @@ const layer = (id: string, overrides: Record<string, unknown> = {}): CanvasLayer
...overrides,
}) as unknown as CanvasLayerContract;
-const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 =>
+const documentOf = (layers: CanvasNodeContract[]): CanvasDocumentContractV3 =>
({
bbox: { height: 32, width: 32, x: 4, y: 6 },
height: 64,
@@ -54,6 +58,8 @@ interface Harness {
rasterizeLayer: ReturnType<typeof vi.fn>;
beginFrame: ReturnType<typeof vi.fn>;
enforce: ReturnType<typeof vi.fn>;
+ /** What the engine reports for a gesture editing a mask or region. */
+ editingHiddenStack: boolean;
}
let harness: Harness;
@@ -83,6 +89,7 @@ const makeHarness = (): Harness => {
getCheckerboardTile: () => surface(8, 8),
getControlView: () => harness.controlView,
getMaskPatternTile: () => null,
+ isEditingStagingHiddenStack: () => harness.editingHiddenStack,
layerCache: {
byteSize: () => 0,
get: (id: string) => entries.get(id),
@@ -101,6 +108,7 @@ const makeHarness = (): Harness => {
screenToDocument: ({ x, y }: { x: number; y: number }) => ({ x, y }),
} as unknown as CreateCompositeFrameDeps['viewport'],
},
+ editingHiddenStack: false,
enforce,
entries,
overrides,
@@ -331,11 +339,12 @@ describe('the surface budget', () => {
});
describe('masks while a result is staged', () => {
- const mask = (id: string) =>
+ const mask = (id: string, overrides: Record<string, unknown> = {}) =>
layer(id, {
mask: { bitmap: { height: 8, imageName: `${id}.png`, width: 8 }, fill: { color: '#e07575', style: 'solid' } },
source: undefined,
type: 'inpaint_mask',
+ ...overrides,
});
const region = (id: string) => ({ ...mask(id), type: 'regional_guidance' }) as unknown as CanvasLayerContract;
const control = (id: string) => layer(id, { type: 'control' });
@@ -382,15 +391,75 @@ describe('masks while a result is staged', () => {
expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);
});
- it.each(['m', 'r'])('shows them over the preview while %s, a mask or region, is selected for editing', (id) => {
+ it('shows them over the preview only while a gesture edits a mask or region, whatever is selected', () => {
+ const frame = createCompositeFrame(harness.deps);
publishPreview();
- draw({ ...doc, selectedLayerId: id });
+ // Selecting a mask alone keeps the result unmasked.
+ frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);
+ expect(drawnIds()).toEqual(['a', 'c']);
+
+ harness.editingHiddenStack = true;
+ frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);
expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);
+ expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);
expect(lastCompositeOptions().regionOverlays).toBe(true);
expect(lastCompositeOptions().stagedPreview).not.toBeNull();
- // Selecting raster or control work hides them again.
- draw({ ...doc, selectedLayerId: 'c' });
+ harness.editingHiddenStack = false;
+ frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);
+ expect(drawnIds()).toEqual(['a', 'c']);
+ expect(lastCompositeOptions().regionOverlays).toBe(false);
+ });
+
+ it('keeps the selected mask or region loaded and demanded while hidden, and nothing else', () => {
+ const frame = createCompositeFrame(harness.deps);
+ publishPreview();
+ const drawSelected = (selectedLayerId: string, document = doc) => {
+ harness.rasterizeLayer.mockClear();
+ frame.draw(surface(), { ...document, selectedLayerId }, VIEW, null, null);
+ return harness.rasterizeLayer.mock.calls.map(([layer]) => (layer as CanvasLayerContract).id);
+ };
+
+ // A stale cache starts loading, and the frame protects the leaf from eviction though it draws none.
+ harness.entries.set('m', entryFor(undefined, true));
+ harness.entries.set('r', entryFor(undefined, true));
+ expect(drawSelected('m')).toEqual(['m']);
expect(drawnIds()).toEqual(['a', 'c']);
+ expect(demandedIds()).toEqual(['a', 'c', 'm']);
+ expect(drawSelected('r')).toEqual(['r']);
+ expect(demandedIds()).toEqual(['a', 'c', 'r']);
+
+ // A disabled mask draws nowhere, and a selected group's brush or shape paints a new layer instead.
+ const disabled = documentOf([layer('a'), control('c'), { ...mask('m'), isEnabled: false }, region('r')]);
+ expect(drawSelected('m', disabled)).toEqual([]);
+ expect(demandedIds()).toEqual(['a', 'c']);
+ const grouped = documentOf([layer('a'), control('c'), groupContract('g', [mask('m')]), region('r')]);
+ expect(drawSelected('g', grouped)).toEqual([]);
+ expect(demandedIds()).toEqual(['a', 'c']);
+
+ // Off screen it is left on demand, as a drawn leaf would be.
+ const offscreen = documentOf([
+ layer('a'),
+ control('c'),
+ mask('m', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 500, y: 0 } }),
+ region('r'),
+ ]);
+ expect(drawSelected('m', offscreen)).toEqual([]);
+ expect(demandedIds()).toEqual(['a', 'c']);
+
+ // Without a shown preview the stacks draw, so their leaves are demanded as usual.
+ harness.previews.clearStaged();
+ frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);
+ expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);
+ });
+
+ it.each([
+ ['m', true],
+ ['r', true],
+ ['c', false],
+ ['a', false],
+ [null, false],
+ ])('counts selecting %s as selecting a stack the staged view hides: %s', (id, hidden) => {
+ expect(isStagingHiddenStackSelected({ ...doc, selectedLayerId: id })).toBe(hidden);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
index d82d965971..390be72b1c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
@@ -1,8 +1,11 @@
-import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasDocumentContractV3,
+ CanvasLayerContract,
+ CanvasLayerStackKind,
+} from '@workbench/canvas-engine/contracts';
import type {
PreviewStateController,
SamPreviewState,
- StagedPreviewState,
} from '@workbench/canvas-engine/controllers/previewStateController';
import type { RasterController } from '@workbench/canvas-engine/controllers/rasterController';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
@@ -14,10 +17,13 @@ import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/rend
import type { FrameDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
+import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import { isLeafDrawableForScreen } from '@workbench/canvas-engine/document-model/screenComposition';
import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
import { isOverlayStack } from '@workbench/canvas-engine/document/layerStacks';
import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
+import { intersect } from '@workbench/canvas-engine/math/rect';
import {
compositeDocument,
reusePreparation,
@@ -49,6 +55,11 @@ export interface CreateCompositeFrameDeps {
readonly getControlView: () => CompositeOptions['controlView'];
/** Starts (or joins) the rasterization of a layer whose cache is stale. */
readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV3) => void;
+ /**
+ * Whether a pointer gesture in progress edits a mask or a region. Its stacks and the regenerate tint then draw
+ * above a shown preview, so the user never paints a mask blind; the frame after the gesture hides them again.
+ */
+ readonly isEditingStagingHiddenStack: () => boolean;
}
/**
@@ -57,20 +68,28 @@ export interface CreateCompositeFrameDeps {
*/
const STAGING_OVERLAY_STACKS = { control: true, inpaint_mask: false, regional_guidance: false } as const;
-/** Whether the selection sits in a stack the staging view hides: the user is editing a mask or a region. */
-export const isEditingStagingHiddenStack = (doc: CanvasDocumentContractV3): boolean => {
+const isStagingHiddenStack = (stack: CanvasLayerStackKind): boolean =>
+ isOverlayStack(stack) && !STAGING_OVERLAY_STACKS[stack];
+
+/**
+ * Whether the selection sits in a stack the staging view hides: a mask or a region, or a group in those stacks. A
+ * gesture that edits it shows those stacks again ({@link CreateCompositeFrameDeps.isEditingStagingHiddenStack}).
+ */
+export const isStagingHiddenStackSelected = (doc: CanvasDocumentContractV3): boolean => {
const stack = doc.selectedLayerId ? getDocumentIndex(doc).byId.get(doc.selectedLayerId)?.stack : undefined;
- return stack !== undefined && isOverlayStack(stack) && !STAGING_OVERLAY_STACKS[stack];
+ return stack !== undefined && isStagingHiddenStack(stack);
};
/**
- * Whether the screen hides masks, regions and the regenerate tint for a shown preview. Selecting a mask or a region
- * shows them again, drawn above the preview, so what the user edits is never painted blind.
+ * The selected mask or region a shown preview hides, when the screen would draw it with the stack shown. A gesture
+ * on it reveals the stack (and a brush refuses a mask whose pixels are not loaded yet), so the frame keeps it
+ * resident while hidden and on screen. A selected group needs nothing up front: brush and shapes paint a new layer,
+ * move drags whatever caches exist.
*/
-export const hidesOverlayStacksForStaging = (
- doc: CanvasDocumentContractV3,
- stagedPreview: StagedPreviewState | null
-): boolean => stagedPreview !== null && !isEditingStagingHiddenStack(doc);
+const stagingHiddenSelectedLeaf = (doc: CanvasDocumentContractV3): SemanticLeaf | null => {
+ const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ return leaf && isStagingHiddenStack(leaf.stack) && isLeafDrawableForScreen(leaf, false) ? leaf : null;
+};
export interface CompositeFrame {
/** Composites the document onto the screen surface and enforces the surface budget. */
@@ -116,19 +135,22 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
activeFrameLayerIds: ReadonlySet<string>
): void => {
for (const { layer } of frame.leaves) {
- if (!activeFrameLayerIds.has(layer.id) || !isLayerContributing(layer) || !renderableSourceOf(layer)) {
- continue;
- }
- if (!isRenderableLayer(layer)) {
- continue;
- }
- const entry = layerCache.getOrCreateRect(layer.id, getSourceContentRect(layer, doc));
- if (entry.stale) {
- deps.rasterizeLayer(layer, doc);
+ if (activeFrameLayerIds.has(layer.id)) {
+ ensureLayerCache(doc, layer);
}
}
};
+ const ensureLayerCache = (doc: CanvasDocumentContractV3, layer: CanvasLayerContract): void => {
+ if (!isLayerContributing(layer) || !renderableSourceOf(layer) || !isRenderableLayer(layer)) {
+ return;
+ }
+ const entry = layerCache.getOrCreateRect(layer.id, getSourceContentRect(layer, doc));
+ if (entry.stale) {
+ deps.rasterizeLayer(layer, doc);
+ }
+ };
+
/** The document-space rect currently on screen, which bounds what the frame demands. */
const visibleDocumentRect = (screen: RasterSurface): Rect => {
const viewportSize = viewport.getViewportSize();
@@ -212,21 +234,38 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
const stagedPreview = previews.getStaged();
const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;
const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;
- const staging = hidesOverlayStacksForStaging(doc, stagedPreview);
+ // A shown preview hides masks, regions and the regenerate tint, unless a gesture is editing one of them.
+ const staging = stagedPreview !== null && !deps.isEditingStagingHiddenStack();
const showOverlayStacks = staging ? STAGING_OVERLAY_STACKS : undefined;
const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides, showOverlayStacks);
// Snapshot filter previews only when active, avoiding an empty map allocation every frame.
const layerPreviews = !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null;
+ const visibleRect = visibleDocumentRect(screen);
const activeFrameLayerIds = calculateActiveFrameLayerIds({
document: doc,
preparation: frame,
- viewport: visibleDocumentRect(screen),
+ viewport: visibleRect,
});
// A previewed layer draws through its cache entry even when only the preview is on screen.
for (const layerId of layerPreviews?.keys() ?? []) {
activeFrameLayerIds.add(layerId);
}
ensureLayerCaches(doc, frame, activeFrameLayerIds);
+ // The selected mask or region stays loaded and unevicted while hidden, ready for a gesture to reveal and edit,
+ // under the same on-screen rule as the leaves the frame draws. No transform override moves a hidden leaf.
+ const hiddenSelected = staging && !isolatedGuard ? stagingHiddenSelectedLeaf(doc) : null;
+ const hiddenBounds = hiddenSelected
+ ? committedLeafBounds(
+ hiddenSelected,
+ hiddenSelected.worldTransform,
+ doc,
+ layerCache.peek(hiddenSelected.id)?.rect
+ )
+ : null;
+ if (hiddenSelected && hiddenBounds && intersect(hiddenBounds, visibleRect)) {
+ activeFrameLayerIds.add(hiddenSelected.id);
+ ensureLayerCache(doc, hiddenSelected.layer);
+ }
const frameDamage = isolatedGuard ? FULL_DAMAGE : (damage ?? FULL_DAMAGE);
const usage = raster.beginFrame();
if (frameDamage.kind === 'full' || !fullFrameUsage) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-selected.json b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-edited.json
similarity index 100%
rename from invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-selected.json
rename to invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-edited.json
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-selected.png b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-edited.png
similarity index 100%
rename from invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-selected.png
rename to invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/staged-candidate-mask-edited.png
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
index 0b1dd76ea3..b560996b37 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
@@ -198,14 +198,14 @@ describe('compositor goldens', () => {
const candidate = backend.createSurface(60, 50);
solid('#4f8ff2')(candidate.ctx, { height: 50, width: 60, x: 0, y: 0 });
const target = backend.createSurface(WIDTH, HEIGHT);
- // With the mask selected the staging view keeps every overlay stack shown (no `showOverlayStacks`).
+ // While a gesture edits the mask the staging view keeps every overlay stack shown (no `showOverlayStacks`).
compositeDocument(target, doc(layers), caches, identity(), {
backend,
checkerboardTile: createCheckerboardTile(backend),
maskPatternTile: (fillStyle, color) => createMaskPatternTile(backend, fillStyle as 'solid', color),
stagedPreview: { rect: { height: 50, width: 60, x: 70, y: 45 }, surface: candidate },
});
- await expectGolden('staged-candidate-mask-selected', target);
+ await expectGolden('staged-candidate-mask-edited', target);
});
it('skips a hidden control layer normally but draws it while isolated', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
index 86d9bc71b5..3c9118ae14 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
@@ -94,6 +94,8 @@ interface Harness {
commitFloat: ReturnType<typeof vi.fn>;
transforms: LayerTransform[];
refusals: CanvasEditRefusal[];
+ /** Calls to `beginSelectedLayerEdit`: the gesture started moving the selected layer in place. */
+ selectedLayerEdits: ReturnType<typeof vi.fn>;
}
interface HarnessOptions {
@@ -128,6 +130,7 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =
};
const commitFloat = vi.fn();
const refusals: CanvasEditRefusal[] = [];
+ const selectedLayerEdits = vi.fn();
const stores = createEngineStores();
stores.snapToGrid.set(options.snapToGrid ?? false);
if (options.bboxGrid !== undefined) {
@@ -145,6 +148,7 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =
createLayerId: () => 'x',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
+ beginSelectedLayerEdit: selectedLayerEdits,
beginStrokeEdit: () => null,
getDocument: () => doc,
getSelectedLayerIds: () => options.selectedLayerIds ?? (doc.selectedLayerId ? [doc.selectedLayerId] : []),
@@ -174,7 +178,7 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =
updateCursor: vi.fn(),
viewport: null as never,
};
- return { commitFloat, commits, ctx, dispatched, float, lifts, overrides, refusals, transforms };
+ return { commitFloat, commits, ctx, dispatched, float, lifts, overrides, refusals, selectedLayerEdits, transforms };
};
const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);
@@ -430,6 +434,42 @@ describe('move tool: drag', () => {
});
});
+describe('move tool: editing the selected layer in place', () => {
+ /** Presses at x 10 and moves through `path`, returning how many times each move reported the edit. */
+ const press = (h: Harness, tool: Tool, path: readonly number[]): number[] => {
+ h.selectedLayerEdits.mockClear();
+ down(tool, h.ctx, pointer(10, 10));
+ const reported = path.map((x) => {
+ const before = h.selectedLayerEdits.mock.calls.length;
+ move(tool, h.ctx, pointer(x, 10));
+ return h.selectedLayerEdits.mock.calls.length - before;
+ });
+ up(tool, h.ctx, pointer(path.at(-1)!, 10));
+ return reported;
+ };
+
+ it('reports a layer drag once, as it crosses the threshold, and never a click', () => {
+ const h = createHarness(makeDoc([imageLayer('a')], 'a'));
+ const tool = createMoveTool();
+ expect(press(h, tool, [11, 12])).toEqual([0, 0]);
+ expect(press(h, tool, [11, 30, 35])).toEqual([0, 1, 0]);
+ });
+
+ it('reports the layer drag a lift falls back to', () => {
+ const h = createHarness(makeDoc([imageLayer('a')], 'a'), { lift: 'unavailable', selectionContainsPoint: true });
+ expect(press(h, createMoveTool(), [30, 35])).toEqual([1, 0]);
+ });
+
+ it.each([
+ ['a refused drag on a locked layer', makeDoc([imageLayer('a', { isLocked: true })], 'a'), {}],
+ ['a float already in flight', makeDoc([imageLayer('a')], 'a'), { existingFloat: true }],
+ ['a lifted float', makeDoc([imageLayer('a')], 'a'), { selectionContainsPoint: true }],
+ ['a refused lift', makeDoc([imageLayer('a')], 'a'), { lift: 'refused' as const, selectionContainsPoint: true }],
+ ])('reports nothing for %s, which moves no layer', (_, doc, options) => {
+ expect(press(createHarness(doc, options), createMoveTool(), [30, 35])).toEqual([0, 0]);
+ });
+});
+
describe('move tool: grid snapping', () => {
const snapDoc = () => makeDoc([imageLayer('a', { x: 0, y: 0, width: 50, height: 50 })], 'a');
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
index 1eef61dbc0..3b27097f30 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
@@ -8,7 +8,9 @@
* bake. Cancel restores the drag start; clicks/zero movement do nothing.
*/
+import type { CanvasLayerEditRefusal } from '@workbench/canvas-engine/capabilities';
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
@@ -27,6 +29,45 @@ const PRIMARY_BUTTON = 1;
/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */
export const MOVE_DRAG_THRESHOLD_PX = 3;
+/**
+ * What a press drags from the panel selection: every selected leaf, and every leaf beneath a selected group, with
+ * the primary one under the document selection; refused, naming the first leaf in the way, when any is locked or
+ * hidden. Pure, so a press can ask before it reports.
+ */
+type SelectedLayerDrag =
+ | { kind: 'drag'; layers: readonly CanvasLayerContract[]; primary: CanvasLayerContract }
+ | { kind: 'refused'; leaf: SemanticLeaf; status: CanvasLayerEditRefusal['status'] }
+ | { kind: 'none' };
+
+/** Target comes solely from document selection, regardless of press location. */
+const planSelectedLayerDrag = (ctx: ToolContext): SelectedLayerDrag => {
+ const doc = ctx.getDocument();
+ const selectedId = doc?.selectedLayerId;
+ if (!doc || !selectedId) {
+ return { kind: 'none' };
+ }
+ const requested = new Set(ctx.getSelectedLayerIds?.() ?? [selectedId]);
+ requested.add(selectedId);
+ const index = getDocumentIndex(doc);
+ if ([...requested].some((id) => !index.byId.has(id))) {
+ return { kind: 'none' };
+ }
+ // A selected group drags every leaf beneath it; a locked node anywhere in the set refuses the drag.
+ const leaves = compileDocumentLeaves(doc).filter(
+ (leaf) => requested.has(leaf.id) || leaf.parentIds.some((ancestor) => requested.has(ancestor))
+ );
+ for (const leaf of leaves) {
+ const status = leafEditRefusal(leaf);
+ if (status) {
+ return { kind: 'refused', leaf, status };
+ }
+ }
+ const primary = leaves.find((leaf) => leaf.id === selectedId || leaf.parentIds.includes(selectedId));
+ return primary
+ ? { kind: 'drag', layers: leaves.map((leaf) => leaf.layer), primary: primary.layer }
+ : { kind: 'none' };
+};
+
/** Applies the shift-to-dominant-axis constraint to a document-space delta. */
export const constrainDelta = (dx: number, dy: number, shift: boolean): Vec2 => {
if (!shift) {
@@ -70,40 +111,6 @@ export const createMoveTool = (): Tool => {
state = null;
};
- /** Target comes solely from document selection, regardless of press location. */
- const selectedDraggableLayers = (
- ctx: ToolContext
- ): { layers: readonly CanvasLayerContract[]; primaryId: string | null } => {
- const doc = ctx.getDocument();
- const selectedId = doc?.selectedLayerId;
- if (!doc || !selectedId) {
- return { layers: [], primaryId: null };
- }
- const requested = new Set(ctx.getSelectedLayerIds?.() ?? [selectedId]);
- requested.add(selectedId);
- const index = getDocumentIndex(doc);
- if ([...requested].some((id) => !index.byId.has(id))) {
- return { layers: [], primaryId: null };
- }
- // A selected group drags every leaf beneath it; a locked node anywhere in the set refuses the drag.
- const leaves = compileDocumentLeaves(doc).filter(
- (leaf) => requested.has(leaf.id) || leaf.parentIds.some((ancestor) => requested.has(ancestor))
- );
- for (const leaf of leaves) {
- const status = leafEditRefusal(leaf);
- if (status) {
- // Said once per press, naming the first layer in the way; nothing moves.
- ctx.reportEditRefusal?.({ layerId: leaf.id, layerName: leaf.layer.name, status });
- return { layers: [], primaryId: null };
- }
- }
- if (leaves.length === 0) {
- return { layers: [], primaryId: null };
- }
- const primary = leaves.find((leaf) => leaf.id === selectedId || leaf.parentIds.includes(selectedId));
- return { layers: leaves.map((leaf) => leaf.layer), primaryId: primary?.id ?? null };
- };
-
/**
* Resolves what a press at `point` drags. Pixels win over the layer when a
* float is already in flight, or when a live selection contains the press.
@@ -113,11 +120,15 @@ export const createMoveTool = (): Tool => {
if (existing) {
return { kind: 'float', layerId: existing.layerId, origin: { ...existing.transform } };
}
- const { layers, primaryId } = selectedDraggableLayers(ctx);
- const primary = layers.find((layer) => layer.id === primaryId);
- if (!primary) {
+ const plan = planSelectedLayerDrag(ctx);
+ if (plan.kind === 'refused') {
+ // Said once per press, naming the first layer in the way; nothing moves.
+ ctx.reportEditRefusal?.({ layerId: plan.leaf.id, layerName: plan.leaf.layer.name, status: plan.status });
+ }
+ if (plan.kind !== 'drag') {
return { kind: 'none' };
}
+ const { layers, primary } = plan;
const layerDrag: LayerDrag = {
kind: 'layer',
targets: layers.map((layer) => ({
@@ -242,6 +253,10 @@ export const createMoveTool = (): Tool => {
if (state.mode.kind === 'lift') {
state.mode = liftOnDrag(ctx, state.mode);
}
+ // Only now does the gesture edit the selected layer in place; a click, a float or a refused drag never does.
+ if (state.mode.kind === 'layer') {
+ ctx.beginSelectedLayerEdit?.();
+ }
}
applyDelta(ctx, state, input);
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 8452dc5984..54266cad05 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -114,6 +114,12 @@ const awaitsPixels = (ctx: ToolContext, layerId: string, hasDurablePixels: boole
return true;
};
+/** Whether a press paints `layer` itself; any other selection (a group, text, a gradient) gets a new paint layer. */
+const paintsInPlace = (layer: CanvasLayerContract): boolean =>
+ layer.type === 'raster'
+ ? layer.source.type === 'paint' || layer.source.type === 'image'
+ : layer.type === 'control' || isMaskLayer(layer);
+
/**
* Why a press of `tool` on the selected leaf would be refused before it starts, without side effects: drives the
* not-allowed cursor. Loading pixels are not predicted; the press itself reports them.
@@ -123,14 +129,7 @@ const predictRefusal = (
tool: PaintToolSpec['id']
): CanvasLayerEditRefusal['status'] | null => {
const selected = leaf?.layer;
- if (!leaf || !selected) {
- return null;
- }
- const paintsInPlace =
- selected.type === 'raster'
- ? selected.source.type === 'paint' || selected.source.type === 'image'
- : selected.type === 'control' || isMaskLayer(selected);
- if (!paintsInPlace) {
+ if (!leaf || !selected || !paintsInPlace(selected)) {
return null;
}
const refusal = leafEditRefusal(leaf);
@@ -303,6 +302,12 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
return !session && predictRefusal(leaf, spec.id) ? 'not-allowed' : 'crosshair';
},
+ // A press paints the selected leaf in place unless it is refused up front; any other selection gets a new layer.
+ editsSelectedLayer: (ctx) => {
+ const doc = ctx.getDocument();
+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ return !!leaf && paintsInPlace(leaf.layer) && predictRefusal(leaf, spec.id) === null;
+ },
id: spec.id,
onDeactivate: (ctx, opts) => {
try {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
index 0cce2efbf8..e209e9c936 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
@@ -5,7 +5,11 @@
* dispatch, and nonzero shapes produce one structural or stroke commit.
*/
-import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasLayerContract,
+ CanvasLayerSourceContract,
+ CanvasRasterLayerContractV2,
+} from '@workbench/canvas-engine/contracts';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
@@ -102,6 +106,10 @@ export const polygonShapeFrom = (
/** Where a finished shape went: pixels, nothing to draw, refused by the paint layer or mask, or neither at all. */
type PixelPlacement = 'placed' | 'nothing' | 'refused' | 'unsupported';
+/** The pixels a shape aimed at `layer` draws into: a paint layer's, or a mask's alpha; null for any other layer. */
+const pixelTargetOf = (layer: CanvasLayerContract): Extract<CanvasLayerSourceContract, { type: 'paint' }> | null =>
+ layer.type === 'raster' && layer.source.type === 'paint' ? layer.source : maskAsPaintSource(layer);
+
/** With fill off and no stroke to draw, a shape changes no pixel, so it records no step and uploads nothing. */
const drawsNothing = (source: ShapeSource): boolean =>
source.fill === null && (source.stroke === null || source.strokeWidth <= 0);
@@ -153,7 +161,7 @@ export const createShapeTool = (): Tool => {
*/
const commitPixels = (ctx: ToolContext, leaf: SemanticLeaf, placed: PlacedShape): PixelPlacement => {
const layer = leaf.layer;
- const paint = layer.type === 'raster' && layer.source.type === 'paint' ? layer.source : maskAsPaintSource(layer);
+ const paint = pixelTargetOf(layer);
if (!paint) {
return 'unsupported';
}
@@ -317,6 +325,18 @@ export const createShapeTool = (): Tool => {
return {
cursor: () => (session?.kind === 'polyline' && session.session.closeArmed ? 'pointer' : 'crosshair'),
+ // Box and freehand drags draw into a selected paint layer or mask that accepts pixels, when aimed at the
+ // selection; anything else gets a new layer. A polygon's vertex presses are separate gestures that write nothing
+ // until it closes, so they leave a staged view alone instead of blinking.
+ editsSelectedLayer: (ctx) => {
+ const options = ctx.stores.shapeOptions.get();
+ if (options.target !== 'selected' || options.kind === 'polygon') {
+ return false;
+ }
+ const doc = ctx.getDocument();
+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
+ return !!leaf && pixelTargetOf(leaf.layer) !== null && isLeafPaintable(leaf);
+ },
id: 'shape',
onDeactivate: (ctx, opts) => {
// A modifier-hold switch (space → view to pan mid-polygon) keeps the session.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index 34234729db..7e22f9712a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -198,6 +198,12 @@ export interface ToolContext {
documentDeltaToLayerLocal?(layerId: string, delta: Vec2): Vec2;
/** True if `point` (document space) falls inside the live selection. */
isPointInSelection?(point: Vec2): boolean;
+ /**
+ * The gesture in progress has started editing the selected layer in place after its press, e.g. a move crossing
+ * its drag threshold. Answers what {@link Tool.editsSelectedLayer} would have at the press, for a tool that only
+ * knows later; outside a pointer gesture it does nothing.
+ */
+ beginSelectedLayerEdit?(): void;
}
/** Temporary modifier switches/restores preserve sessions; real switches or disposal tear them down. */
@@ -237,4 +243,12 @@ export interface Tool {
* pointer pipeline must not turn an alt-hold into the temporary color picker.
*/
readonly usesAltKey?: boolean;
+ /**
+ * Whether a primary gesture starting now edits the selected layer in place, writing its pixels or its placement:
+ * false when the press would be refused up front or would add a new layer instead. Asked once as each gesture
+ * starts; absent means never at the press (a tool that decides later calls
+ * {@link ToolContext.beginSelectedLayerEdit}). While such a gesture targets a mask or a region, the screen shows
+ * their stacks above a staged preview that otherwise hides them.
+ */
+ editsSelectedLayer?(ctx: ToolContext): boolean;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx
index 3d29f09421..9517bb6dfa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx
@@ -412,7 +412,7 @@ describe('StagingBar thumbnail strip', () => {
}
);
- // The bar's floor is a 360px canvas (see the compact breakpoints); the pending pill adds nothing to it.
+ // The bar's floor is a 360px canvas (see the compact breakpoints); the pending status adds nothing to it.
it.each([false, true])(
'keeps Accept inside the narrowest canvas (generating: %s), the pending count read but not shown',
async (isGenerating) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx
index 3bce5bd676..f3335a6dd2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx
@@ -74,9 +74,6 @@ const NARROW_HIDDEN_CSS = { [NARROW]: { display: 'none' } } as const;
const NARROW_ONLY_CSS = { display: 'none', [NARROW]: { display: 'inline-flex' } } as const;
/** Buttons whose text goes while narrow keep a square icon footprint. */
const NARROW_ICON_BUTTON_CSS = { [NARROW]: { minW: '8', px: '0' } } as const;
-/** The status pill tightens once narrow. */
-const STATUS_PILL_CSS = { px: '2', [NARROW]: { px: '1' } } as const;
-const STATUS_PILL_IDLE_CSS = { px: '2', [COMPACT]: SR_ONLY } as const;
/** Marks a thumbnail with its slot index, for roving focus and focus restore. */
const THUMBNAIL_ATTR = 'data-staging-thumbnail';
/** Marks the previous/next buttons, a focus target once no thumbnail shows. */
@@ -344,19 +341,17 @@ export const StagingBar = ({
{/* Results keep coming in and waiting here while the canvas stays editable; the status says how many. */}
<Tooltip content={statusLabel}>
<HStack
- bg="bg.muted"
color="fg.muted"
- // Once compact a running batch keeps its spinner; otherwise the pill goes, since the counter shows the
- // count, and its status still reads the sentence.
- css={isGenerating ? STATUS_PILL_CSS : STATUS_PILL_IDLE_CSS}
+ // Once compact a running batch keeps its spinner; otherwise the status goes, since the counter shows the
+ // count, and it still reads the sentence.
+ css={isGenerating ? undefined : COMPACT_SR_ONLY_CSS}
flexShrink="0"
gap="1.5"
- h="6"
position="relative"
- rounded="full"
+ px="1"
>
{isGenerating ? <Spinner /> : null}
- <Text css={COMPACT_SR_ONLY_CSS} fontSize="md" fontWeight="600" role="status" whiteSpace="nowrap">
+ <Text css={COMPACT_SR_ONLY_CSS} fontSize="md" role="status" whiteSpace="nowrap">
{statusLabel}
</Text>
</HStack>
@@ -370,6 +365,9 @@ export const StagingBar = ({
</IconButton>
</Tooltip>
+ {/* The status and its thumbnail toggle read as one group: the toggle shows or hides the pending results. */}
+ <CanvasFloatingBarDivider css={NARROW_HIDDEN_CSS} />
+
<HStack gap="0.5">
<Tooltip content={t('widgets.canvas.previousStagedCandidate')}>
<IconButton
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx
deleted file mode 100644
index e738d395d6..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { MouseEvent } from 'react';
-
-import { Box } from '@chakra-ui/react';
-import { ToggleDot } from '@platform/ui';
-
-export const ROW_SELECTION_FOCUS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' };
-
-/**
- * Tree rows keep a gap below their surface (`pb="0.5"`); the ring frames the surface, not the gap, so the row's
- * content stays centred inside it.
- */
-export const TREE_ROW_FOCUS = {
- _after: {
- borderRadius: 'sm',
- bottom: '0.5',
- boxShadow: 'inset 0 0 0 2px {colors.accent.solid}',
- content: '""',
- insetInline: '0',
- pointerEvents: 'none',
- position: 'absolute',
- top: '0',
- },
- outline: 'none',
-};
-
-const DOT_BASE = {
- borderRadius: 'full',
- borderWidth: '1px',
- content: '""',
- h: '3',
- inset: '50% auto auto calc(50% + 1.5px)',
- position: 'absolute',
- transform: 'translate(-50%, -50%)',
- transition: 'background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)',
- w: '3',
-};
-const DOT_CHECKED = { ...DOT_BASE, bg: 'accent.solid', borderColor: 'accent.solid' };
-/** Enabled on its own, but an ancestor keeps it out of the composite. */
-const DOT_GATED = { ...DOT_BASE, bg: 'transparent', borderColor: 'accent.solid' };
-const DOT_UNCHECKED = { ...DOT_BASE, bg: 'transparent', borderColor: 'border.emphasized' };
-const DOT_CHECKED_HOVER = { _before: { bg: 'accent.emphasized', borderColor: 'accent.emphasized' } };
-const DOT_UNCHECKED_HOVER = { _before: { borderColor: 'fg.muted' } };
-
-const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();
-
-/** Show contributing, ancestor-gated, and off states distinctly; keep toggle clicks/focus off the tree item. */
-export const LayerActiveDot = ({
- checked,
- disabled,
- gated,
- label,
- onCheckedChange,
- onKeepRowFocus,
- tooltip,
-}: {
- checked: boolean;
- disabled: boolean;
- /** Checked, but an ancestor keeps the node out of the composite. */
- gated: boolean;
- label: string;
- onCheckedChange: (checked: boolean) => void;
- onKeepRowFocus: (event: MouseEvent<HTMLElement>) => void;
- tooltip?: string;
-}) => (
- <Box
- display="flex"
- flexShrink="0"
- onClick={stopPropagation}
- onMouseDown={onKeepRowFocus}
- onPointerDown={stopPropagation}
- >
- <ToggleDot
- _before={checked ? (gated ? DOT_GATED : DOT_CHECKED) : DOT_UNCHECKED}
- _focusVisible={ROW_SELECTION_FOCUS}
- _hover={checked ? DOT_CHECKED_HOVER : DOT_UNCHECKED_HOVER}
- bg="transparent"
- borderWidth="0"
- checked={checked}
- cursor={disabled ? 'not-allowed' : undefined}
- disabled={disabled}
- h="6"
- label={label}
- position="relative"
- tabIndex={-1}
- tooltip={tooltip}
- transition="none"
- w="6"
- onCheckedChange={onCheckedChange}
- />
- </Box>
-);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
index 9e8a9f5f89..95a672d179 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
@@ -2,11 +2,15 @@ import type { CSSProperties, FocusEvent, KeyboardEvent, MouseEvent } from 'react
import { Box, HStack, Icon, Input, Text } from '@chakra-ui/react';
import { useDraggable, useDroppable } from '@dnd-kit/core';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
import {
ApertureIcon,
WandSparklesIcon,
ContrastIcon,
DropletIcon,
+ EyeIcon,
+ EyeOffIcon,
FilmIcon,
FingerprintPatternIcon,
FocusIcon,
@@ -25,12 +29,10 @@ import { useTranslation } from 'react-i18next';
import type { LayerRowCommands } from './layerRowCommands';
-import { LayerActiveDot, TREE_ROW_FOCUS } from './LayerActiveDot';
import { childRowNameKey, isOrderedChildKind, type LayerChildRowKind, type ProjectedChildRow } from './layerChildRows';
import { recordLayerRowCommit } from './layerPanelDiagnostics';
-import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
import { anchorFromPoint } from './layerRowCommands';
-import { LayerRowSurface } from './LayerRowSurface';
+import { LAYER_PANEL_CONTROL_GAP, LayerRowSurface, TREE_ROW_FOCUS } from './LayerRowSurface';
const THUMBNAIL_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'cover', width: '100%' };
@@ -135,14 +137,19 @@ const LayerChildRowComponent = ({
? [child.detail, t(child.detailLabelKey)].filter((part) => part !== null).join(' · ')
: child.detail;
- const indentStyle = useMemo(() => ({ paddingLeft: `${child.depth * LAYER_TREE_INDENT_PX}px` }), [child.depth]);
const handleSelect = useCallback(() => commands.selectChild(child), [child, commands]);
const handleFocus = useCallback(() => commands.focus(child.key), [child.key, commands]);
const keepRowFocus = useCallback((event: MouseEvent<HTMLElement>) => {
event.preventDefault();
rowElement.current?.focus();
}, []);
- const handleToggle = useCallback((checked: boolean) => commands.setChildEnabled(child, checked), [child, commands]);
+ const handleToggle = useCallback(
+ (event: { stopPropagation: () => void }) => {
+ event.stopPropagation();
+ commands.setChildEnabled(child, !child.isEnabled);
+ },
+ [child, commands]
+ );
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLElement>) => {
if (event.target !== event.currentTarget) {
@@ -260,16 +267,7 @@ const LayerChildRowComponent = ({
onFocus={handleFocus}
onKeyDown={handleKeyDown}
>
- <LayerRowSurface active={selected ? 'emphasized' : undefined} indentStyle={indentStyle}>
- <LayerActiveDot
- checked={child.isEnabled}
- disabled={editingLocked}
- gated={!child.parentContributing}
- label={t('widgets.layers.modifiers.toggleActive')}
- tooltip={child.parentContributing ? undefined : t('widgets.layers.modifiers.parentDisabled')}
- onCheckedChange={handleToggle}
- onKeepRowFocus={keepRowFocus}
- />
+ <LayerRowSurface active={selected ? 'emphasized' : undefined} depth={child.depth}>
<Box
alignItems="center"
bg="bg.muted"
@@ -312,6 +310,32 @@ const LayerChildRowComponent = ({
{detail}
</Text>
) : null}
+ {/* The layer rows' trailing cluster: the eye shares their eye column, and the blank slot holds the lock column
+ a child row has no use for. */}
+ <HStack flexShrink="0" gap={LAYER_PANEL_CONTROL_GAP} onClick={stopPropagation} onMouseDown={keepRowFocus}>
+ <Tooltip
+ content={
+ child.parentContributing
+ ? t('widgets.layers.modifiers.toggleActive')
+ : t('widgets.layers.modifiers.parentDisabled')
+ }
+ >
+ <IconButton
+ aria-label={t('widgets.layers.modifiers.toggleActive')}
+ aria-pressed={child.isEnabled}
+ color={muted ? 'fg.subtle' : 'fg.muted'}
+ disabled={editingLocked}
+ size="sm"
+ tabIndex={-1}
+ variant="ghost"
+ onClick={handleToggle}
+ onPointerDown={stopPropagation}
+ >
+ {child.isEnabled ? <EyeIcon /> : <EyeOffIcon />}
+ </IconButton>
+ </Tooltip>
+ <Box boxSize="6" flexShrink={0} />
+ </HStack>
</LayerRowSurface>
</Box>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
index c7fdb60a79..ac71e7c359 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
@@ -26,20 +26,17 @@ import type { LayerTreeRow } from './layerTreeRows';
import { AdjustmentStatusIcon, useAdjustmentStatus } from './AdjustmentStatusIcon';
import { colorLabelHex } from './colorLabels';
import { ControlLayerStatusIcon } from './ControlLayerStatusIcon';
-import { TREE_ROW_FOCUS } from './LayerActiveDot';
import { recordLayerRowCommit } from './layerPanelDiagnostics';
-import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
import { anchorFromPoint } from './layerRowCommands';
import { layerRowSummary } from './layerRowSummary';
-import { LayerRowSurface } from './LayerRowSurface';
+import { LAYER_LEADING_BOX_PX, LAYER_PANEL_CONTROL_GAP, LayerRowSurface, TREE_ROW_FOCUS } from './LayerRowSurface';
import { LayerThumbnail, type LayerThumbnailEngine } from './LayerThumbnail';
import { layerTypeIcon } from './layerTypeIcon';
const CHEVRON_HOVER = { bg: 'bg.muted', color: 'fg' };
-const THUMBNAIL_SIZE = '8';
+const THUMBNAIL_SIZE = `${LAYER_LEADING_BOX_PX}px`;
const GROUP_PILE_OFFSET_PX = 4;
-const GROUP_PILE_CARD_PX = 24;
/** How a row takes part in the current drag. */
export type LayerRowDragState = 'source' | 'travelling' | null;
@@ -129,8 +126,6 @@ const LayerRowComponent = ({
recordLayerRowCommit(row.id);
});
- const indentStyle = useMemo(() => ({ paddingLeft: `${vm.depth * LAYER_TREE_INDENT_PX}px` }), [vm.depth]);
-
const handleSelect = useCallback(
(event: MouseEvent<HTMLElement>) =>
commands.select(row.id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey }),
@@ -333,33 +328,7 @@ const LayerRowComponent = ({
w="2px"
/>
) : null}
- <LayerRowSurface active={tone} cursor={drag === 'source' ? 'grabbing' : 'default'} indentStyle={indentStyle}>
- {/* One visibility control: a hidden layer is off the canvas and out of generation alike. */}
- <Box display="flex" flexShrink={0} onClick={stopPropagation} onMouseDown={keepRowFocus}>
- <Tooltip
- content={
- disabledByAncestor
- ? t('widgets.layers.actions.groupDisabled')
- : node.isEnabled
- ? t('widgets.layers.actions.hideLayerTooltip')
- : t('widgets.layers.actions.showLayerTooltip')
- }
- >
- <IconButton
- aria-label={t('widgets.layers.actions.toggleActive')}
- aria-pressed={node.isEnabled}
- color={vm.contributionEnabled ? 'fg.muted' : 'fg.subtle'}
- disabled={editingLocked}
- size="sm"
- tabIndex={-1}
- variant="ghost"
- onClick={handleToggleVisible}
- onPointerDown={stopPropagation}
- >
- {node.isEnabled ? <EyeIcon /> : <EyeOffIcon />}
- </IconButton>
- </Tooltip>
- </Box>
+ <LayerRowSurface active={tone} cursor={drag === 'source' ? 'grabbing' : 'default'} depth={vm.depth}>
{group ? (
<GroupPreview engine={engine} expanded={row.expanded} node={node} thumbnails={thumbnails} />
) : !thumbnails ? (
@@ -466,11 +435,12 @@ const LayerRowComponent = ({
{layer?.type === 'control' ? (
<ControlLayerStatusIcon contributing={vm.contributionEnabled} engine={engine} layer={layer} />
) : null}
- {/* One control cluster on the same rhythm as the stack header; slots a row cannot use are held open. */}
- <HStack flexShrink="0" gap="0.5" onClick={stopPropagation} onMouseDown={keepRowFocus}>
+ {/* Trailing cluster on the stack header's rhythm: the eye sits left of the lock as an overlay header's eye sits
+ left of its New button, so eyes and locks each form one column at every depth. */}
+ <HStack flexShrink="0" gap={LAYER_PANEL_CONTROL_GAP} onClick={stopPropagation} onMouseDown={keepRowFocus}>
{hideable && vm.documentHidden && vm.contributionEnabled ? (
// Hidden on the canvas only (an overlay put out of the way): it still shapes generation. The row menu
- // sets it; this says so and brings it back.
+ // sets it; this says so and brings it back. Rendered only when it applies, left of the eye column.
<Tooltip
content={
hiddenByAncestor
@@ -491,9 +461,31 @@ const LayerRowComponent = ({
<EyeClosedIcon />
</IconButton>
</Tooltip>
- ) : (
- <Box boxSize="6" />
- )}
+ ) : null}
+ {/* One visibility control: a hidden layer is off the canvas and out of generation alike. */}
+ <Tooltip
+ content={
+ disabledByAncestor
+ ? t('widgets.layers.actions.groupDisabled')
+ : node.isEnabled
+ ? t('widgets.layers.actions.hideLayerTooltip')
+ : t('widgets.layers.actions.showLayerTooltip')
+ }
+ >
+ <IconButton
+ aria-label={t('widgets.layers.actions.toggleActive')}
+ aria-pressed={node.isEnabled}
+ color={vm.contributionEnabled ? 'fg.muted' : 'fg.subtle'}
+ disabled={editingLocked}
+ size="sm"
+ tabIndex={-1}
+ variant="ghost"
+ onClick={handleToggleVisible}
+ onPointerDown={stopPropagation}
+ >
+ {node.isEnabled ? <EyeIcon /> : <EyeOffIcon />}
+ </IconButton>
+ </Tooltip>
<Tooltip
content={
lockedByAncestor ? t('widgets.layers.actions.groupLocked') : t('widgets.layers.actions.toggleLock')
@@ -555,14 +547,14 @@ const GroupPreview = ({
thumbnails: boolean;
}) => {
const leaves = useMemo(() => (thumbnails ? groupLeafPreviews(node) : []), [node, thumbnails]);
- const cardStyles = useMemo(
- () =>
- leaves.map((_, index): CSSProperties => {
- const offset = index * GROUP_PILE_OFFSET_PX;
- return { height: GROUP_PILE_CARD_PX, left: offset, top: offset, width: GROUP_PILE_CARD_PX };
- }),
- [leaves]
- );
+ // Cards shrink by one offset per extra card so the pile always spans the whole leading box; one card fills it.
+ const cardStyles = useMemo(() => {
+ const card = LAYER_LEADING_BOX_PX - (leaves.length - 1) * GROUP_PILE_OFFSET_PX;
+ return leaves.map((_, index): CSSProperties => {
+ const offset = index * GROUP_PILE_OFFSET_PX;
+ return { height: card, left: offset, top: offset, width: card };
+ });
+ }, [leaves]);
if (leaves.length === 0) {
return (
<Box
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx
index ae50ee40f5..1e3b8115ec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx
@@ -1,32 +1,59 @@
import type { RowProps } from '@platform/ui';
-import type { CSSProperties, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { Row } from '@platform/ui';
+import { useMemo } from 'react';
+
+import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';
+/**
+ * Rows and stack headers end with this inset and space their trailing buttons by this gap, so the header eye and New
+ * buttons share columns with the rows' eyes and locks. Nesting indents the start edge only.
+ */
+export const LAYER_PANEL_END_INSET = '1.5';
+export const LAYER_PANEL_CONTROL_GAP = '0.5';
+/**
+ * Tree rows keep a gap below their surface (`pb="0.5"`) and indent it past the tree guides; the ring frames the
+ * surface, not the gap or the guides, so it matches the selection fill and the row's content stays centred inside it.
+ */
+export const TREE_ROW_FOCUS = {
+ '& > [data-layer-row-surface]': { boxShadow: 'inset 0 0 0 2px {colors.accent.solid}' },
+ outline: 'none',
+};
+// The leading inset mirrors the end inset.
+export const LAYER_ROW_INSET_PX = 6;
+/** Layer and group rows lead with a box this wide: thumbnail, group pile or degraded placeholder. */
+export const LAYER_LEADING_BOX_PX = 32;
export const LayerRowSurface = ({
active,
children,
cursor = 'default',
- indentStyle,
+ depth,
}: {
active: RowProps['active'];
children: ReactNode;
cursor?: 'default' | 'grabbing';
- indentStyle?: CSSProperties;
-}) => (
- <Row
- active={active}
- alignItems="center"
- cursor={cursor}
- display="flex"
- gap="1.5"
- h="full"
- px="1.5"
- style={indentStyle}
- transition={LAYER_ROW_BACKGROUND_TRANSITION}
- >
- {children}
- </Row>
-);
+ depth: number;
+}) => {
+ // Nesting is a margin, not padding: the selection fill starts right of the tree guides.
+ const indentStyle = useMemo(() => ({ marginLeft: `${depth * LAYER_TREE_INDENT_PX}px`, width: 'auto' }), [depth]);
+ return (
+ <Row
+ active={active}
+ alignItems="center"
+ cursor={cursor}
+ data-layer-row-surface=""
+ display="flex"
+ gap="1.5"
+ h="full"
+ pe={LAYER_PANEL_END_INSET}
+ ps={`${LAYER_ROW_INSET_PX}px`}
+ style={indentStyle}
+ transition={LAYER_ROW_BACKGROUND_TRANSITION}
+ >
+ {children}
+ </Row>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
index efbb286ac0..6e565f4dc6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import type { LayerRowCommands } from './layerRowCommands';
import { anchorFromPoint } from './layerRowCommands';
+import { LAYER_PANEL_CONTROL_GAP, LAYER_PANEL_END_INSET } from './LayerRowSurface';
import { useLayerStackActions, type LayerStackActionsEngine } from './useLayerStackActions';
const HEADER_FOCUS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' };
@@ -120,7 +121,7 @@ const LayerStackHeaderComponent = ({
onKeyDown={pinned ? undefined : handleKeyDown}
>
{pinned ? null : <VisuallyHidden id={descriptionId}>{t(`hints.${hintId}.paragraphs.0`)}</VisuallyHidden>}
- <HStack gap="1" h="full" pe="1.5" ps="0">
+ <HStack gap="1" h="full" pe={LAYER_PANEL_END_INSET} ps="0">
<IconButton
aria-label={t(collapsed ? 'widgets.layers.groupActions.expand' : 'widgets.layers.groupActions.collapse')}
color="fg.muted"
@@ -150,7 +151,7 @@ const LayerStackHeaderComponent = ({
{t(`widgets.layers.groups.${stack}`)} ({leafCount})
</Text>
<FeatureHintExclusion>
- <HStack gap="0.5" onClick={stopPropagation} onMouseDown={keepFocus}>
+ <HStack gap={LAYER_PANEL_CONTROL_GAP} onClick={stopPropagation} onMouseDown={keepFocus}>
{actions.map((action) => (
<Tooltip key={action.id} content={action.label}>
<IconButton
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerTreeGuides.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerTreeGuides.tsx
new file mode 100644
index 0000000000..23a5407a43
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerTreeGuides.tsx
@@ -0,0 +1,87 @@
+import type { CSSProperties } from 'react';
+
+import { Box } from '@chakra-ui/react';
+import { memo } from 'react';
+
+import { LAYER_TREE_INDENT_PX, TREE_GUIDE } from './layerPanelRows';
+import { LAYER_LEADING_BOX_PX, LAYER_ROW_INSET_PX } from './LayerRowSurface';
+
+const GUIDE_COLOR = 'border.subtle';
+const ELBOW_RADIUS = '4px';
+/** Column `c`'s 1px line sits under the centre of the leading box of rows at depth `c`. */
+const columnLeft = (column: number): number =>
+ column * LAYER_TREE_INDENT_PX + LAYER_ROW_INSET_PX + LAYER_LEADING_BOX_PX / 2 - 1;
+/** A branch ends where the next level's surface (and its selection fill) begins. */
+const BRANCH_WIDTH_PX = LAYER_TREE_INDENT_PX - columnLeft(0);
+/**
+ * Rows keep a 2px gap below their surface, so the leading box is centred at `50% - 1px`. The branch's 1px stroke
+ * fills the pixel just below that centre, and a stem starts 2px under the parent's leading box.
+ */
+const BRANCH_HEIGHT = '50%';
+const STEM_TOP = `calc(50% - 1px + ${LAYER_LEADING_BOX_PX / 2 + 2}px)`;
+
+const lineStyle = (column: number): CSSProperties => ({ left: columnLeft(column) });
+const elbowStyle = (column: number): CSSProperties => ({ left: columnLeft(column), width: BRANCH_WIDTH_PX });
+
+/** A full-height line through the row, or a stem from beneath the row's own leading box to its end. */
+const Line = ({ column, stem = false }: { column: number; stem?: boolean }) => (
+ <Box
+ bg={GUIDE_COLOR}
+ bottom="0"
+ data-tree-guide={stem ? 'stem' : 'line'}
+ position="absolute"
+ style={lineStyle(column)}
+ top={stem ? STEM_TOP : '0'}
+ w="1px"
+ />
+);
+
+const Elbow = ({ column }: { column: number }) => (
+ <Box
+ borderBottomLeftRadius={ELBOW_RADIUS}
+ borderBottomWidth="1px"
+ borderColor={GUIDE_COLOR}
+ borderLeftWidth="1px"
+ data-tree-guide="branch"
+ h={BRANCH_HEIGHT}
+ position="absolute"
+ style={elbowStyle(column)}
+ top="0"
+ />
+);
+
+const Guide = ({ column, glyph }: { column: number; glyph: string }) => {
+ switch (glyph) {
+ case TREE_GUIDE.pass:
+ return <Line column={column} />;
+ case TREE_GUIDE.tee:
+ return (
+ <>
+ <Line column={column} />
+ <Elbow column={column} />
+ </>
+ );
+ case TREE_GUIDE.elbow:
+ return <Elbow column={column} />;
+ case TREE_GUIDE.stem:
+ return <Line column={column} stem />;
+ default:
+ return null;
+ }
+};
+
+/**
+ * One row's connector lines, drawn behind it in its virtual slot. Each row draws only its own full-height segments,
+ * so consecutive rows join without knowing about each other. Decorative: hidden from assistive technology and
+ * transparent to the pointer, so hit-testing, drag and drop and focus see only the row.
+ */
+const LayerTreeGuidesComponent = ({ guides }: { guides: string }) => (
+ <Box aria-hidden data-tree-guides="" inset="0" pointerEvents="none" position="absolute">
+ {[...guides].map((glyph, column) => (
+ // Columns are positional: a column's glyph changes in place, never moves.
+ <Guide key={column} column={column} glyph={glyph} />
+ ))}
+ </Box>
+);
+
+export const LayerTreeGuides = memo(LayerTreeGuidesComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
index 299d3785d1..a5ee7e375a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
@@ -39,47 +39,69 @@ import { userEvent } from 'vitest/browser';
import type { ProjectedChildRow } from './layerChildRows';
import type { LayerRowCommands } from './layerRowCommands';
+import type * as LayerStackHeaderModule from './LayerStackHeader';
import { ADJUSTMENT_SPINNER_DELAY_MS } from './AdjustmentStatusIcon';
import { createFakeAdjustmentStatus } from './AdjustmentStatusIcon.testing';
import { clearLayerChildSelection, getLayerChildSelection } from './layerChildSelection';
import { getLayerRowCommits, resetLayerRowCommits } from './layerPanelDiagnostics';
-import { LAYER_PANEL_DEGRADE_THRESHOLD, LAYER_ROW_HEIGHT_PX } from './layerPanelRows';
+import { LAYER_PANEL_DEGRADE_THRESHOLD, LAYER_ROW_HEIGHT_PX, LAYER_TREE_INDENT_PX } from './layerPanelRows';
import { clearLayerPropertiesRequest, requestLayerProperties } from './layerPropertiesRequestStore';
import { LayersTree, type LayersTreeEngine } from './LayersTree';
import { buildLayerStackRows } from './layerTreeRows';
vi.mock('./ControlLayerStatusIcon', () => ({ ControlLayerStatusIcon: () => null }));
vi.mock('./LayerThumbnail', () => ({ LayerThumbnail: () => <span data-testid="thumbnail" /> }));
-vi.mock('./LayerStackHeader', () => ({
- LayerStackHeader: ({
- commands,
- focused,
- pinned,
- rowKey,
- stack,
- }: {
- commands: { focus(key: string): void; keyDown(key: string, event: React.KeyboardEvent<HTMLElement>): void };
- focused: boolean;
- pinned?: boolean;
- rowKey: string;
- stack: string;
- }) => (
- <div
- aria-label={stack}
- aria-level={1}
- data-layer-row-id={pinned ? undefined : rowKey}
- aria-hidden={pinned || undefined}
- data-testid="stack-header"
- role="treeitem"
- tabIndex={pinned ? undefined : focused ? 0 : -1}
- onFocus={() => commands.focus(rowKey)}
- onKeyDown={(event) => commands.keyDown(rowKey, event)}
- >
- {stack}
- </div>
- ),
-}));
+/** Most cases use a stand-in header; geometry cases render the real one with the real action order. */
+const realStackHeader = vi.hoisted(() => ({ on: false }));
+vi.mock('./useLayerStackActions', async () => {
+ const { getStackActions } = await import('./layerStackActions');
+ const { PlusIcon } = await import('lucide-react');
+ const labels = {
+ exportPsd: 'Export to PSD',
+ mergeVisible: 'Merge visible',
+ new: 'New layer',
+ toggleVisibility: 'Hide all on canvas',
+ };
+ return {
+ useLayerStackActions: (stack: Parameters<typeof getStackActions>[0]) =>
+ getStackActions(stack).map((id) => ({ disabled: false, icon: PlusIcon, id, label: labels[id], run: () => {} })),
+ };
+});
+const StubStackHeader = ({
+ commands,
+ focused,
+ pinned,
+ rowKey,
+ stack,
+}: {
+ commands: { focus(key: string): void; keyDown(key: string, event: React.KeyboardEvent<HTMLElement>): void };
+ focused: boolean;
+ pinned?: boolean;
+ rowKey: string;
+ stack: string;
+}) => (
+ <div
+ aria-label={stack}
+ aria-level={1}
+ data-layer-row-id={pinned ? undefined : rowKey}
+ aria-hidden={pinned || undefined}
+ data-testid="stack-header"
+ role="treeitem"
+ tabIndex={pinned ? undefined : focused ? 0 : -1}
+ onFocus={() => commands.focus(rowKey)}
+ onKeyDown={(event) => commands.keyDown(rowKey, event)}
+ >
+ {stack}
+ </div>
+);
+vi.mock('./LayerStackHeader', async (importOriginal) => {
+ const actual = await importOriginal<typeof LayerStackHeaderModule>();
+ return {
+ LayerStackHeader: (props: Parameters<typeof actual.LayerStackHeader>[0]) =>
+ realStackHeader.on ? <actual.LayerStackHeader {...props} /> : <StubStackHeader {...props} />,
+ };
+});
/** The command handle the tree last gave its surface host, which menus drive. */
const surfaceCommands = vi.hoisted(() => ({ current: null as LayerRowCommands | null }));
vi.mock('./LayerSurfaceHost', () => ({
@@ -392,6 +414,7 @@ beforeEach(() => {
afterEach(async () => {
await act(() => root?.unmount());
+ realStackHeader.on = false;
host?.remove();
host = null;
root = null;
@@ -565,19 +588,24 @@ describe('LayersTree keyboard and accessibility', () => {
expect(output('surface')).toBe('menu:top');
});
- it('frames the keyboard-focused row surface with its ring, not the gap below it', async () => {
+ it('frames the keyboard-focused row surface with its ring, not the gap below it or the guides beside it', async () => {
await renderTree(nested());
- treeitem('Top').focus();
+ await act(() => userEvent.click(treeitem('Group').querySelector('button[aria-label="Expand group"]')!));
+ treeitem('Group').focus();
await act(() => userEvent.keyboard('{ArrowDown}'));
- const row = treeitem('Group');
+ const row = treeitem('Inner');
expect(document.activeElement).toBe(row);
- const ring = getComputedStyle(row, '::after');
+ // The ring is the surface's own inset shadow, so it shares the selection fill's box: clear of the gap below the
+ // row and of the indent where the tree guides run.
+ const surface = row.querySelector<HTMLElement>('[data-layer-row-surface]')!;
+ expect(getComputedStyle(surface).boxShadow).toContain('inset');
+ expect(getComputedStyle(row).outlineStyle).toBe('none');
const rowRect = row.getBoundingClientRect();
- const surface = [...row.children].find((child) => child.textContent?.includes('Group'))!.getBoundingClientRect();
- // The ring and the surface share their box, so the row's content sits centred inside the ring.
- expect(rowRect.top + Number.parseFloat(ring.top)).toBeCloseTo(surface.top, 0);
- expect(rowRect.bottom - Number.parseFloat(ring.bottom)).toBeCloseTo(surface.bottom, 0);
+ const surfaceRect = surface.getBoundingClientRect();
+ expect(surfaceRect.bottom).toBeLessThan(rowRect.bottom);
+ expect(surfaceRect.left - rowRect.left).toBe(LAYER_TREE_INDENT_PX);
+ expect(getComputedStyle(treeitem('Top').querySelector('[data-layer-row-surface]')!).boxShadow).toBe('none');
});
it('keeps the focused row mounted and focused while scrolled far away', async () => {
@@ -652,6 +680,227 @@ describe('LayersTree selection, surfaces and structure', () => {
expect(output('selected-layer')).toBe('none');
});
+ it('ends every row with the eye then the lock, each in one column at any depth', async () => {
+ await renderTree([
+ paint('top', 'Top'),
+ groupContract('g', [paint('inner', 'Inner'), groupContract('h', [paint('deep', 'Deep')], { name: 'H' })], {
+ name: 'G',
+ }),
+ layerContract('masked', 'inpaint_mask', { isHidden: true, name: 'Masked' }),
+ ]);
+ await act(() => userEvent.click(treeitem('G').querySelector('button[aria-label="Expand group"]')!));
+ await act(() => userEvent.click(treeitem('H').querySelector('button[aria-label="Expand group"]')!));
+ const ids = ['top', 'g', 'inner', 'h', 'deep', 'masked'];
+ const rowButtons = (id: string) =>
+ [...host!.querySelectorAll<HTMLButtonElement>(`[data-layer-row-id="${id}"] button`)].map((button) => ({
+ label: button.getAttribute('aria-label'),
+ rect: button.getBoundingClientRect(),
+ }));
+
+ for (const id of ids) {
+ const labels = rowButtons(id).map((button) => button.label);
+ expect(labels.slice(-2)).toEqual(['Toggle layer active', 'Toggle lock']);
+ }
+ // The canvas-only marker appears only where it applies, ahead of the eye column rather than in it.
+ expect(
+ rowButtons('masked')
+ .map((button) => button.label)
+ .slice(-3)
+ ).toEqual(['Show on canvas', 'Toggle layer active', 'Toggle lock']);
+
+ const columnLefts = (label: string) =>
+ new Set(ids.map((id) => rowButtons(id).find((button) => button.label === label)!.rect.left));
+ expect(columnLefts('Toggle layer active').size).toBe(1);
+ expect(columnLefts('Toggle lock').size).toBe(1);
+ // Nesting indents the leading edge only.
+ const thumbnailLeft = (id: string) =>
+ host!.querySelector(`[data-layer-row-id="${id}"] [data-testid="thumbnail"]`)!.getBoundingClientRect().left;
+ expect(thumbnailLeft('deep') - thumbnailLeft('inner')).toBe(LAYER_TREE_INDENT_PX);
+ expect(thumbnailLeft('inner') - thumbnailLeft('top')).toBe(LAYER_TREE_INDENT_PX);
+ });
+
+ it('fills a group’s leading box with its preview pile, whatever the number of cards', async () => {
+ await renderTree([
+ paint('plain', 'Plain'),
+ groupContract('solo', [paint('only', 'Only')], { name: 'Solo' }),
+ groupContract('wrapper', [groupContract('inside', [paint('lone', 'Lone')], { name: 'Inside' })], {
+ name: 'Wrapper',
+ }),
+ groupContract('pair', [paint('p1', 'P1'), paint('p2', 'P2')], { name: 'Pair' }),
+ groupContract('crowd', [paint('c1', 'C1'), paint('c2', 'C2'), paint('c3', 'C3'), paint('c4', 'C4')], {
+ name: 'Crowd',
+ }),
+ ]);
+ const leadingBox = (name: string) =>
+ treeitem(name).querySelector('[data-layer-row-surface]')!.firstElementChild!.getBoundingClientRect();
+ const cards = (name: string) =>
+ [...treeitem(name).querySelectorAll('[data-testid="thumbnail"]')].map((thumbnail) =>
+ thumbnail.parentElement!.getBoundingClientRect()
+ );
+ const edges = (rect: DOMRect) => [rect.left, rect.top, rect.right, rect.bottom];
+
+ // Groups keep a plain layer's leading box, so nothing beside it shifts.
+ const plain = leadingBox('Plain');
+ for (const name of ['Solo', 'Wrapper', 'Pair', 'Crowd']) {
+ expect([leadingBox(name).width, leadingBox(name).height]).toEqual([plain.width, plain.height]);
+ }
+ // One card, directly or through a nested group, covers the whole box like a plain thumbnail.
+ for (const name of ['Solo', 'Wrapper']) {
+ const [card, ...rest] = cards(name);
+ expect(rest).toEqual([]);
+ expect(edges(card!)).toEqual(edges(leadingBox(name)));
+ }
+ // A pile steps from the box's top-left corner to its bottom-right one; it shows at most three cards.
+ expect(cards('Crowd')).toHaveLength(3);
+ for (const name of ['Pair', 'Crowd']) {
+ const box = leadingBox(name);
+ const pile = cards(name);
+ const front = pile.at(-1)!;
+ const back = pile[0]!;
+ expect([front.left, front.top]).toEqual([box.left, box.top]);
+ expect([back.right, back.bottom]).toEqual([box.right, box.bottom]);
+ expect(front.width).toBeLessThan(box.width);
+ }
+ });
+
+ it('joins tree guides from beneath each parent’s leading box into its children, beside their selection fill', async () => {
+ await renderTree([
+ groupContract(
+ 'g',
+ [
+ layerContract('inner', 'raster', {
+ adjustments: [
+ { id: 'a1', isEnabled: true, saturation: 0.1, type: 'hsl' },
+ { id: 'a2', isEnabled: true, saturation: 0.2, type: 'hsl' },
+ ],
+ name: 'Inner',
+ }),
+ groupContract('h', [paint('deep', 'Deep')], { name: 'H' }),
+ ],
+ { name: 'G' }
+ ),
+ paint('bottom', 'Bottom'),
+ ]);
+ await act(() => userEvent.click(treeitem('G').querySelector('button[aria-label="Expand group"]')!));
+ await act(() => userEvent.click(treeitem('H').querySelector('button[aria-label="Expand group"]')!));
+ await act(() => userEvent.click(treeitem('Saturation')));
+ await settle();
+
+ const slot = (name: string) => treeitem(name).parentElement!.getBoundingClientRect();
+ const leading = (name: string) =>
+ treeitem(name).querySelector('[data-layer-row-surface]')!.firstElementChild!.getBoundingClientRect();
+ const surface = (name: string) => treeitem(name).querySelector('[data-layer-row-surface]')!.getBoundingClientRect();
+ const guides = (name: string, kind: 'line' | 'branch' | 'stem') =>
+ [...treeitem(name).parentElement!.querySelectorAll(`[data-tree-guide="${kind}"]`)].map((element) =>
+ element.getBoundingClientRect()
+ );
+ const centreX = (rect: DOMRect) => rect.left + rect.width / 2;
+ const centreY = (rect: DOMRect) => rect.top + rect.height / 2;
+
+ // The parent's stem drops from beneath its leading box, on its centre, to the row's end.
+ const [stem] = guides('G', 'stem');
+ expect(stem!.top).toBeGreaterThan(leading('G').bottom);
+ expect(stem!.bottom).toBe(slot('G').bottom);
+ expect(Math.abs(stem!.left - centreX(leading('G')))).toBeLessThanOrEqual(1);
+
+ // A middle child: the parent's line spans its whole row and joins the stem above, and the branch turns at the
+ // parent's centre into the child's own centre line, ending where the child's surface begins.
+ const [line] = guides('Inner', 'line');
+ expect(line!.top).toBe(stem!.bottom);
+ expect(line!.bottom).toBe(slot('Inner').bottom);
+ expect(line!.left).toBe(stem!.left);
+ const [branch] = guides('Inner', 'branch');
+ expect(branch!.left).toBe(line!.left);
+ expect(branch!.top).toBe(slot('Inner').top);
+ expect(Math.abs(branch!.bottom - centreY(leading('Inner')))).toBeLessThanOrEqual(1);
+ expect(branch!.right).toBe(surface('Inner').left);
+ expect(branch!.right).toBeLessThan(leading('Inner').left);
+
+ // Inner's adjustment rows (shorter rows) branch from Inner's own column while G's line passes beside them; the
+ // middle one continues Inner's line and the last one ends it, so nothing runs on into H.
+ const adjustments = [...host!.querySelectorAll<HTMLElement>('[role="treeitem"][aria-label="Saturation"]')];
+ expect(adjustments).toHaveLength(2);
+ const rowGuides = (row: HTMLElement, kind: 'line' | 'branch') =>
+ [...row.parentElement!.querySelectorAll(`[data-tree-guide="${kind}"]`)].map((element) =>
+ element.getBoundingClientRect()
+ );
+ const [middleLines, lastLines] = adjustments.map((row) => rowGuides(row, 'line'));
+ expect(middleLines!.map((rect) => rect.left)).toEqual([line!.left, line!.left + LAYER_TREE_INDENT_PX]);
+ expect(lastLines!.map((rect) => rect.left)).toEqual([line!.left]);
+ for (const [index, row] of adjustments.entries()) {
+ const rowSlot = row.parentElement!.getBoundingClientRect();
+ expect(rowSlot.height).toBeLessThan(slot('Inner').height);
+ for (const rect of rowGuides(row, 'line')) {
+ expect([rect.top, rect.bottom]).toEqual([rowSlot.top, rowSlot.bottom]);
+ }
+ const [rowBranch] = rowGuides(row, 'branch');
+ expect(Math.abs(rowBranch!.left - centreX(leading('Inner')))).toBeLessThanOrEqual(1);
+ expect(
+ Math.abs(
+ rowBranch!.bottom -
+ centreY(row.querySelector('[data-layer-row-surface]')!.firstElementChild!.getBoundingClientRect())
+ )
+ ).toBeLessThanOrEqual(1);
+ // The selected (first) row's fill starts right of its branch, which stays drawn beside it.
+ expect(row).toHaveAttribute('aria-selected', String(index === 0));
+ expect(rowBranch!.right).toBe(row.querySelector('[data-layer-row-surface]')!.getBoundingClientRect().left);
+ }
+
+ // The last child ends its parent's line in an elbow; an ended ancestor leaves its column empty.
+ expect(guides('H', 'line')).toHaveLength(0);
+ expect(guides('H', 'branch')[0]!.left).toBe(line!.left);
+ expect(guides('Deep', 'line')).toHaveLength(0);
+ expect(Math.abs(guides('Deep', 'branch')[0]!.left - centreX(leading('H')))).toBeLessThanOrEqual(1);
+ // Stack headers are headings: top-level rows draw nothing, and a parent's stem needs visible children.
+ expect(treeitem('Bottom').parentElement!.querySelector('[data-tree-guides]')).toBeNull();
+
+ // Purely decorative: hidden from assistive technology and transparent to the pointer.
+ const container = treeitem('Inner').parentElement!.querySelector<HTMLElement>('[data-tree-guides]')!;
+ expect(container).toHaveAttribute('aria-hidden', 'true');
+ expect(document.elementFromPoint(line!.left, centreY(line!))!.closest('[role="treeitem"]')).toBe(treeitem('Inner'));
+ });
+
+ it('puts the stack headers’ and child rows’ eyes in the layer rows’ eye column', async () => {
+ realStackHeader.on = true;
+ await renderTree([
+ layerContract('top', 'raster', {
+ adjustments: [{ id: 'a1', isEnabled: true, saturation: 0.1, type: 'hsl' }],
+ name: 'Top',
+ }),
+ layerContract('mask', 'inpaint_mask', { name: 'Mask' }),
+ groupContract(
+ 'mg',
+ [layerContract('nested', 'inpaint_mask', { name: 'Nested', noise: { isEnabled: true, level: 0.25 } })],
+ { name: 'Mask group' }
+ ),
+ ]);
+ await act(() => userEvent.click(treeitem('Mask group').querySelector('button[aria-label="Expand group"]')!));
+ const lefts = (selector: string) =>
+ [...host!.querySelectorAll<HTMLElement>(`[role="tree"] ${selector}`)].map(
+ (element) => element.getBoundingClientRect().left
+ );
+ const rowLefts = (label: string) =>
+ ['top', 'mask', 'mg', 'nested'].flatMap((id) =>
+ lefts(`[data-layer-row-id="${id}"] button[aria-label="${label}"]`)
+ );
+
+ const eyes = rowLefts('Toggle layer active');
+ const locks = rowLefts('Toggle lock');
+ expect(eyes).toHaveLength(4);
+ expect(locks).toHaveLength(4);
+ // The inpaint header's eye, and both headers' New buttons (raster has no eye).
+ expect(lefts('button[aria-label="Hide all on canvas"]')).toEqual([eyes[0]]);
+ expect(lefts('button[aria-label="New layer"]')).toEqual([locks[0], locks[0]]);
+ expect(new Set(eyes).size).toBe(1);
+ expect(new Set(locks).size).toBe(1);
+ // Modifier rows at depth 1 and 2: the same eye, with the lock column held open.
+ for (const name of ['Saturation', 'Noise']) {
+ const eye = treeitem(name).querySelector('button[aria-label="Toggle active"]')!;
+ expect(eye.getBoundingClientRect().left).toBe(eyes[0]);
+ expect(eye.querySelector('svg.lucide-eye')).not.toBeNull();
+ }
+ });
+
it('marks an overlay hidden on the canvas only, and brings it back from the row', async () => {
await renderTree([
layerContract('shown', 'inpaint_mask', { name: 'Shown' }),
@@ -921,10 +1170,10 @@ describe('LayersTree projected child rows', () => {
expect(treeitem('Reference image 2')).not.toBeNull();
});
- it('toggles the item from the dot and removes it with Delete, leaving siblings alone', async () => {
+ it('toggles the item from its eye and removes it with Delete, leaving siblings alone', async () => {
await renderTree(regionWithRefs());
- const dot = treeitem('Reference image 1').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
- await act(() => userEvent.click(dot));
+ const eye = treeitem('Reference image 1').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
+ await act(() => userEvent.click(eye));
expect(output('regional-refs')).toBe('rg[ref1:off,ref2:on]');
expect(output('selected-layer')).toBe('none');
treeitem('Reference image 2').focus();
@@ -943,7 +1192,7 @@ describe('LayersTree projected child rows', () => {
expect(getLayerChildSelection()).toBeNull();
});
- it('projects mask noise and denoise rows whose dots and Delete edit the modifiers', async () => {
+ it('projects mask noise and denoise rows whose eyes and Delete edit the modifiers', async () => {
await renderTree([
layerContract('mask', 'inpaint_mask', {
denoise: { isEnabled: true, limit: 0.8 },
@@ -953,8 +1202,8 @@ describe('LayersTree projected child rows', () => {
]);
expect(treeitem('Noise')).toHaveAttribute('aria-level', '3');
expect(treeitem('Denoise limit')).toHaveAttribute('aria-posinset', '2');
- const dot = treeitem('Noise').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
- await act(() => userEvent.click(dot));
+ const eye = treeitem('Noise').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
+ await act(() => userEvent.click(eye));
expect(output('mask-modifiers')).toBe('noise:off:0.25,denoise:on:0.8');
treeitem('Denoise limit').focus();
await act(() => userEvent.keyboard('{Delete}'));
@@ -973,13 +1222,13 @@ describe('LayersTree projected child rows', () => {
layerContract('mask', 'inpaint_mask', { name: 'Mask', noise: { isEnabled: true, level: 0.5 } }),
]),
};
- const dot = treeitem('Noise').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
- await act(() => userEvent.click(dot));
+ const eye = treeitem('Noise').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
+ await act(() => userEvent.click(eye));
expect(committedEdits.at(-1)!.forward).toMatchObject({ config: { noise: { isEnabled: false, level: 0.5 } } });
});
- it('projects adjustment rows in stack order; the dot toggles one entry', async () => {
+ it('projects adjustment rows in stack order; the eye toggles one entry', async () => {
await renderTree([
layerContract('r1', 'raster', {
adjustments: [
@@ -994,9 +1243,11 @@ describe('LayersTree projected child rows', () => {
expect(treeitem('Saturation')).toHaveAttribute('aria-posinset', '2');
expect(treeitem('Curves')).toHaveAttribute('aria-setsize', '3');
expect(treeitem('Saturation').textContent).toContain('-40%');
- const dot = treeitem('Saturation').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
- await act(() => userEvent.click(dot));
+ const eye = treeitem('Saturation').querySelector<HTMLButtonElement>('button[aria-label="Toggle active"]')!;
+ await act(() => userEvent.click(eye));
expect(output('raster-adjustments')).toBe('a1:on,a2:off,a3:on');
+ expect(eye).toHaveAttribute('aria-pressed', 'false');
+ expect(eye.querySelector('svg.lucide-eye-off')).not.toBeNull();
});
it('renames an adjustment entry inline with F2 and restores the kind name on an empty draft', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 485895f4ad..1ae3fdea24 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -67,6 +67,7 @@ import { LayerStackHeader } from './LayerStackHeader';
import { LayerSurfaceHost, type LayerSurfaceEngine, type LayerSurfaceRequest } from './LayerSurfaceHost';
import { createLayerTreeAutoScroller, type LayerTreeAutoScroller } from './layerTreeAutoScroll';
import { outermostRowIds, projectLayerDrop, type LayerDropTarget } from './layerTreeDrop';
+import { LayerTreeGuides } from './LayerTreeGuides';
export type LayersTreeEngine = LayerStackActionsEngine & LayerSurfaceEngine & Pick<CanvasEngineHandle, 'previews'>;
@@ -1212,6 +1213,7 @@ export const LayersTree = ({
}
return (
<VirtualSlot key={item.key} size={item.size} start={item.start}>
+ {panelRow.kind !== 'header' && panelRow.guides ? <LayerTreeGuides guides={panelRow.guides} /> : null}
{panelRow.kind === 'node' ? (
<LayerRow
ancestorOfPrimary={primaryAncestorIds.has(panelRow.row.id)}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts
index 00cae2dfd4..2ff70de593 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts
@@ -152,3 +152,107 @@ describe('group-owned adjustment rows', () => {
expect(navigateTree(expandedRows, 'g1', 'ArrowLeft')).toEqual({ expand: 'g1', expanded: false });
});
});
+
+describe('tree guides', () => {
+ const invert = (id: string): CanvasAdjustmentEntry => ({ id, isEnabled: true, type: 'invert' });
+ /** top[a1] · g1[ga1]{ m1[x1, x2], m3, g2{ deep } } · bottom */
+ const treeStacks = (expandedGroups: ReadonlySet<string>, filter?: string) =>
+ buildLayerStackRows(
+ documentFrom([
+ layerContract('top', 'raster', { adjustments: [invert('a1')] }),
+ groupContract(
+ 'g1',
+ [
+ layerContract('m1', 'raster', { adjustments: [invert('x1'), invert('x2')] }),
+ layerContract('m3'),
+ groupContract('g2', [layerContract('deep')]),
+ ],
+ { adjustments: [invert('ga1')] }
+ ),
+ layerContract('bottom'),
+ ]).stacks,
+ expandedGroups,
+ filter
+ );
+ const guidesOf = (rows: readonly PanelRow[]) =>
+ Object.fromEntries(rows.flatMap((row) => (row.kind === 'header' ? [] : [[row.key, row.guides]])));
+
+ it('branches each visible child from its parent, ending the line at the last one', () => {
+ const rows = flattenPanelRows(treeStacks(new Set(['g1', 'g2'])), [], open, {
+ collapsedLayerIds: new Set(),
+ rowsFor: (row) => projectLayerChildRows(row.vm),
+ });
+ expect(guidesOf(rows)).toEqual({
+ bottom: '',
+ 'child:g1:ga1': '├',
+ 'child:m1:x1': '│├',
+ 'child:m1:x2': '│└',
+ 'child:top:a1': '└',
+ deep: ' └',
+ g1: '╷',
+ g2: '└╷',
+ m1: '├╷',
+ m3: '├',
+ top: '╷',
+ });
+ // Rows follow tree order, so every line runs unbroken from its stem to its last branch.
+ expect(keys(rows)).toEqual([
+ 'header:raster',
+ 'top',
+ 'child:top:a1',
+ 'g1',
+ 'child:g1:ga1',
+ 'm1',
+ 'child:m1:x1',
+ 'child:m1:x2',
+ 'm3',
+ 'g2',
+ 'deep',
+ 'bottom',
+ ]);
+ });
+
+ it('draws nothing for children a collapsed group or layer hides', () => {
+ const rows = flattenPanelRows(treeStacks(new Set(['g1'])), [], open, {
+ collapsedLayerIds: new Set(['m1', 'top']),
+ rowsFor: (row) => projectLayerChildRows(row.vm),
+ });
+ expect(guidesOf(rows)).toEqual({
+ bottom: '',
+ 'child:g1:ga1': '├',
+ g1: '╷',
+ g2: '└',
+ m1: '├',
+ m3: '├',
+ top: '',
+ });
+ });
+
+ it('follows the rows a filter keeps: matches under their opened ancestors', () => {
+ expect(guidesOf(flattenPanelRows(treeStacks(new Set(), 'deep'), [], open))).toEqual({
+ deep: ' └',
+ g1: '╷',
+ g2: '└╷',
+ });
+ expect(guidesOf(flattenPanelRows(treeStacks(new Set(), 'm'), [], open))).toEqual({
+ bottom: '',
+ g1: '╷',
+ m1: '├',
+ m3: '└',
+ });
+ });
+
+ it('starts every stack afresh: top-level rows never branch from their stack header', () => {
+ const rows = flattenPanelRows(stacks(), [], open, {
+ collapsedLayerIds: new Set(),
+ rowsFor: (row) => projectLayerChildRows(row.vm),
+ });
+ expect(guidesOf(rows)).toEqual({
+ 'child:rg1:ref1': '├',
+ 'child:rg1:ref2': '└',
+ r1: '',
+ rg1: '╷',
+ rg2: '',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
index 4ada130ea8..335a24bc2a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
@@ -9,8 +9,12 @@ import type { LayerStackRows, LayerStackRowsByKind, LayerTreeRow } from './layer
export const LAYER_ROW_HEIGHT_PX = 40;
export const LAYER_CHILD_ROW_HEIGHT_PX = 32;
export const LAYER_HEADER_HEIGHT_PX = 28;
-/** Horizontal offset per nesting level, in CSS pixels; the drag projection uses the same step. */
-export const LAYER_TREE_INDENT_PX = 16;
+/**
+ * Horizontal offset per nesting level, in CSS pixels; the drag projection uses the same step. A level's guide line
+ * runs under the centre of its rows' 32px leading box, 22px past their edge, so this step leaves the branch into the
+ * next level a short straight run after its rounded corner.
+ */
+export const LAYER_TREE_INDENT_PX = 28;
/** Above this many nodes the panel drops thumbnails and drag reordering to stay deterministic. */
export const LAYER_PANEL_DEGRADE_THRESHOLD = 2_000;
@@ -35,6 +39,8 @@ export type PanelRow =
/** Position among the parent group's COMBINED children (modifier rows first, then nodes). */
readonly ariaPosInSet: number;
readonly ariaSetSize: number;
+ /** The connector lines this row draws, as `TREE_GUIDE` glyphs. */
+ readonly guides: string;
}
| {
readonly kind: 'child';
@@ -43,8 +49,48 @@ export type PanelRow =
readonly child: ProjectedChildRow;
/** The owner's combined child count (rows + node children) for a group owner. */
readonly ariaSetSize: number;
+ /** The connector lines this row draws, as `TREE_GUIDE` glyphs. */
+ readonly guides: string;
};
+/**
+ * Tree guide glyphs, one per nesting column from the outermost in. A row at depth `d` fills columns `0..d-1`:
+ * `TREE_GUIDE.pass` where an ancestor's line runs on past it, a space where that ancestor's visible children
+ * already ended, then `tee` or `elbow` for the branch from its parent (more visible siblings follow, or none do).
+ * Column `d` holds `stem` when the row's own visible children follow it. Stack headers are headings, not
+ * parents: top-level rows get no branch.
+ */
+export const TREE_GUIDE = { elbow: '└', pass: '│', stem: '╷', tee: '├' } as const;
+
+/** Guides for one stack's visible rows in order, from their depths, in two linear passes. */
+const treeGuides = (depths: readonly number[]): string[] => {
+ const last: boolean[] = [];
+ // Whether a row at each depth sits below the current one under the same parent, scanning upward.
+ const siblingBelow: boolean[] = [];
+ for (let index = depths.length - 1; index >= 0; index -= 1) {
+ const depth = depths[index]!;
+ last[index] = !siblingBelow[depth];
+ siblingBelow.length = depth + 1;
+ siblingBelow[depth] = true;
+ }
+ // Whether each column's line continues below the most recent row branching from it, scanning downward.
+ const continues: boolean[] = [];
+ return depths.map((depth, index) => {
+ let guides = '';
+ for (let column = 0; column < depth - 1; column += 1) {
+ guides += continues[column] ? TREE_GUIDE.pass : ' ';
+ }
+ if (depth > 0) {
+ guides += last[index] ? TREE_GUIDE.elbow : TREE_GUIDE.tee;
+ continues[depth - 1] = !last[index];
+ }
+ if ((depths[index + 1] ?? -1) > depth) {
+ guides += TREE_GUIDE.stem;
+ }
+ return guides;
+ });
+};
+
/** How a flattening projects child rows beneath the layers that own them. */
export interface PanelChildRowsSource {
rowsFor(row: LayerTreeRow): readonly ProjectedChildRow[];
@@ -82,6 +128,8 @@ export const flattenPanelRows = (
stack,
});
if (!collapsed) {
+ const stackRows: Exclude<PanelRow, { kind: 'header' }>[] = [];
+ const depths: number[] = [];
const rowOffsetByParent = new Map<string, number>();
for (const row of stack.rows) {
const isGroup = row.vm.kind === 'group';
@@ -92,23 +140,30 @@ export const flattenPanelRows = (
if (isGroup && childrenExpanded) {
rowOffsetByParent.set(row.id, children.length);
}
- rows.push({
+ stackRows.push({
ariaPosInSet: row.posInSet + offset,
ariaSetSize: row.setSize + offset,
childCount: children.length,
childrenExpanded,
+ guides: '',
key: row.id,
kind: 'node',
row,
stack: kind,
});
+ depths.push(row.vm.depth);
if (childrenExpanded) {
const combined = isGroup ? children.length + row.vm.childCount : children.length;
for (const child of children) {
- rows.push({ ariaSetSize: combined, child, key: child.key, kind: 'child', stack: kind });
+ stackRows.push({ ariaSetSize: combined, child, guides: '', key: child.key, kind: 'child', stack: kind });
+ depths.push(child.depth);
}
}
}
+ const guides = treeGuides(depths);
+ stackRows.forEach((row, index) => {
+ rows.push(guides[index] ? { ...row, guides: guides[index] } : row);
+ });
}
}
return rows;