Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): keep Layers panel selection and collapsed stacks per project

Josh Corbett92b381e9e1b1
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index a064128b14..331f96884d 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -110,6 +110,7 @@
"invocation.ts": "workbench",
"invocationContracts.ts": "workbench",
"invocationSubmit.ts": "workbench",
+ "layerPanelState.ts": "workbench",
"layoutContracts.ts": "workbench",
"layoutPresetActivation.ts": "workbench",
"layoutPresetCollection.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
index 4b78f6d06c..af5bcc3126 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx
@@ -13,6 +13,7 @@ import type { ProjectPushOutcome } from './projects/projectFlush';
import { WorkbenchSplashScreen } from './components/WorkbenchSplashScreen';
import { createExtensionRegistry, type ExtensionRegistry } from './extensions/extensionRegistry';
+import { clearLayerPanelStates } from './layerPanelState';
import { createWorkbenchPersistenceRuntime } from './persistenceRuntime';
import { createOpenProjectBroker } from './projects/openProjectBroker';
import { describeRefusedProjects } from './projects/projectLoadRefusal';
@@ -22,12 +23,7 @@ import {
type WorkbenchLoadOptions,
} from './projects/syncedPersistence';
import { getProjectWidgetValues } from './widgetState';
-import {
- createWorkbenchStore,
- resetLayerPanelSelection,
- type WorkbenchSnapshot,
- type WorkbenchInternalStore,
-} from './workbenchStore';
+import { createWorkbenchStore, type WorkbenchSnapshot, type WorkbenchInternalStore } from './workbenchStore';
interface WorkbenchContextValue {
activeProject: Project;
@@ -68,8 +64,6 @@ export const WorkbenchProvider = ({
// The runtime is created inside the effect: disposal is terminal, so each
// mount (including a StrictMode remount) must get its own instance.
useMountEffect(() => {
- const activeProject = store.getSnapshot().activeProject;
- resetLayerPanelSelection(activeProject.id, activeProject.canvas.document.selectedLayerId);
const persistenceRuntime = createWorkbenchPersistenceRuntime({
aggregate: {
...store.internal.persistence,
@@ -134,7 +128,7 @@ export const WorkbenchProvider = ({
persistenceRuntime.start();
return () => {
- resetLayerPanelSelection('', null);
+ clearLayerPanelStates();
openProjectBroker.dispose();
persistenceRuntime.dispose();
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
index adad06f671..47e9fbc882 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts
@@ -3,10 +3,10 @@ import type { CanvasEngine, ImageResolver } from '@workbench/canvas-engine/api';
import { galleryImageUrls } from '@features/gallery/utility';
import { getModelsSnapshot } from '@features/models';
import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';
import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';
import { useActiveProjectId, useWorkbenchCommands, useWorkbenchInternalStore } from '@workbench/WorkbenchContext';
-import { publishLayerPanelSelection, readLayerPanelSelection } from '@workbench/workbenchStore';
import { useMemo, useSyncExternalStore } from 'react';
import type { EngineDeps } from './engineRegistry';
@@ -72,7 +72,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {
},
getSelectedLayerIds: () => {
const project = store.getState().projects.find((candidate) => candidate.id === projectId);
- return project ? readLayerPanelSelection(projectId, project.canvas.document.selectedLayerId).selectedIds : [];
+ return project ? readLayerPanelState(projectId, project.canvas.document.selectedLayerId).selectedIds : [];
},
setSelectedLayerIds: (primaryId, selectedIds) =>
publishLayerPanelSelection({ primaryId, projectId, selectedIds }),
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
new file mode 100644
index 0000000000..6975719540
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
@@ -0,0 +1,195 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
+
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ clearLayerPanelStates,
+ createLayerPanelState,
+ publishLayerPanelSelection,
+ readLayerPanelState,
+ reconcileLayerPanelState,
+ isSameLayerPanelState,
+ reconcileLayerPanelStates,
+ selectLayerInPanel,
+ toggleLayerStackCollapsed,
+ type LayerPanelProjectView,
+} from './layerPanelState';
+
+const ids = ['a', 'b', 'c', 'd'];
+const plain = { additive: false, range: false };
+const toggle = { additive: true, range: false };
+const range = { additive: false, range: true };
+
+describe('layer panel selection', () => {
+ it('replaces selection on a plain click', () => {
+ const initial = createLayerPanelState('project', 'a');
+ expect(selectLayerInPanel(initial, 'c', ids, plain)).toMatchObject({
+ anchorId: 'c',
+ primaryId: 'c',
+ selectedIds: ['c'],
+ });
+ });
+
+ it('toggles layers with Ctrl/Cmd while keeping a valid primary', () => {
+ const initial = createLayerPanelState('project', 'b');
+ const added = selectLayerInPanel(initial, 'd', ids, toggle);
+ expect(added).toMatchObject({ primaryId: 'd', selectedIds: ['b', 'd'] });
+ expect(selectLayerInPanel(added, 'b', ids, toggle)).toMatchObject({
+ primaryId: 'd',
+ selectedIds: ['d'],
+ });
+ expect(selectLayerInPanel(added, 'd', ids, toggle)).toMatchObject({
+ primaryId: 'b',
+ selectedIds: ['b'],
+ });
+ });
+
+ it('selects a contiguous Shift range from the stable anchor', () => {
+ const initial = createLayerPanelState('project', 'b');
+ expect(selectLayerInPanel(initial, 'd', ids, range)).toMatchObject({
+ anchorId: 'b',
+ primaryId: 'd',
+ selectedIds: ['b', 'c', 'd'],
+ });
+ });
+
+ it('adds a Shift range when Ctrl/Cmd is held too', () => {
+ const initial = selectLayerInPanel(createLayerPanelState('project', 'a'), 'd', ids, toggle);
+ const next = selectLayerInPanel(initial, 'b', ids, { additive: true, range: true });
+ expect(next.selectedIds).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('uses only rendered rows when a Shift range crosses collapsed groups', () => {
+ const initial = createLayerPanelState('project', 'a');
+ expect(selectLayerInPanel(initial, 'd', ['a', 'd'], range).selectedIds).toEqual(['a', 'd']);
+ });
+
+ it('keeps selected rows hidden inside a collapsed group through an additive range', () => {
+ const initial = { ...createLayerPanelState('project', 'a'), anchorId: 'c', selectedIds: ['a', 'c'] };
+ expect(selectLayerInPanel(initial, 'd', ['c', 'd'], { additive: true, range: true }).selectedIds).toEqual([
+ 'c',
+ 'd',
+ 'a',
+ ]);
+ expect(selectLayerInPanel(initial, 'd', ['c', 'd'], range).selectedIds).toEqual(['c', 'd']);
+ });
+
+ it('falls back to the top-most selected row when the primary is toggled off', () => {
+ let state = createLayerPanelState('project', 'c');
+ state = selectLayerInPanel(state, 'a', ids, toggle);
+ state = selectLayerInPanel(state, 'b', ids, toggle);
+ expect(state).toMatchObject({ primaryId: 'b', selectedIds: ['a', 'b', 'c'] });
+ expect(selectLayerInPanel(state, 'b', ids, toggle)).toMatchObject({ primaryId: 'a', selectedIds: ['a', 'c'] });
+ });
+
+ it('drops duplicate ids while reconciling', () => {
+ const state = { ...createLayerPanelState('project', 'a'), selectedIds: ['a', 'a', 'b'] };
+ expect(reconcileLayerPanelState(state, 'project', ids, 'a').selectedIds).toEqual(['a', 'b']);
+ });
+
+ it('prunes removed secondaries without collapsing an unchanged primary', () => {
+ const multi = { ...createLayerPanelState('project', 'a'), anchorId: 'c', selectedIds: ['a', 'b', 'c'] };
+ expect(reconcileLayerPanelState(multi, 'project', ['a', 'b', 'd'], 'a')).toEqual({
+ ...multi,
+ anchorId: 'a',
+ selectedIds: ['a', 'b'],
+ });
+ expect(reconcileLayerPanelState(multi, 'project', ids, 'a')).toBe(multi);
+ });
+
+ it('carries collapsed stacks through a same-project primary change only', () => {
+ const collapsed = { ...createLayerPanelState('project', 'a'), collapsedStacks: ['control' as const] };
+ expect(reconcileLayerPanelState(collapsed, 'project', ids, 'b')).toMatchObject({
+ collapsedStacks: ['control'],
+ primaryId: 'b',
+ });
+ expect(reconcileLayerPanelState(collapsed, 'other', ids, 'b').collapsedStacks).toEqual([]);
+ });
+
+ it('collapses to a new primary selected outside the panel and resets between projects', () => {
+ const multi = selectLayerInPanel(createLayerPanelState('project', 'a'), 'c', ids, toggle);
+ expect(reconcileLayerPanelState(multi, 'project', ids, 'd').selectedIds).toEqual(['d']);
+ expect(reconcileLayerPanelState(multi, 'other-project', ids, 'a').selectedIds).toEqual(['a']);
+ });
+
+ it('does not resurrect secondaries after an A to B to A project round trip', () => {
+ let selection = selectLayerInPanel(createLayerPanelState('project-a', 'a'), 'c', ids, toggle);
+ selection = reconcileLayerPanelState(selection, 'project-b', ids, 'b');
+ selection = reconcileLayerPanelState(selection, 'project-a', ids, 'a');
+ expect(selection.selectedIds).toEqual(['a']);
+ });
+});
+
+describe('layer panel state store', () => {
+ beforeEach(() => clearLayerPanelStates());
+
+ const project = (id: string, layerIds: readonly string[], selectedLayerId: string | null): LayerPanelProjectView => ({
+ canvas: {
+ document: {
+ layers: layerIds.map((layerId) => ({ id: layerId }) as CanvasLayerContract),
+ selectedLayerId,
+ },
+ },
+ id,
+ });
+
+ it('keeps selection and collapsed stacks per project', () => {
+ publishLayerPanelSelection({ primaryId: 'a', projectId: 'p1', selectedIds: ['a', 'c'] });
+ toggleLayerStackCollapsed('p1', 'a', 'control');
+ publishLayerPanelSelection({ primaryId: 'x', projectId: 'p2', selectedIds: ['x', 'y'] });
+
+ expect(readLayerPanelState('p1', 'a')).toMatchObject({ collapsedStacks: ['control'], selectedIds: ['a', 'c'] });
+ expect(readLayerPanelState('p2', 'x')).toMatchObject({ collapsedStacks: [], selectedIds: ['x', 'y'] });
+ });
+
+ it('keeps collapsed stacks but drops secondaries when the primary changed outside the panel', () => {
+ publishLayerPanelSelection({ primaryId: 'a', projectId: 'p1', selectedIds: ['a', 'c'] });
+ toggleLayerStackCollapsed('p1', 'a', 'raster');
+
+ expect(readLayerPanelState('p1', 'b')).toMatchObject({
+ collapsedStacks: ['raster'],
+ primaryId: 'b',
+ selectedIds: ['b'],
+ });
+ expect(readLayerPanelState('p3', null)).toMatchObject({ collapsedStacks: [], selectedIds: [] });
+ });
+
+ it('toggles a collapsed stack on and off', () => {
+ toggleLayerStackCollapsed('p1', null, 'inpaint_mask');
+ expect(readLayerPanelState('p1', null).collapsedStacks).toEqual(['inpaint_mask']);
+ toggleLayerStackCollapsed('p1', null, 'inpaint_mask');
+ expect(readLayerPanelState('p1', null).collapsedStacks).toEqual([]);
+ });
+
+ it('reconciles every project against its document and forgets closed projects', () => {
+ publishLayerPanelSelection({ primaryId: 'a', projectId: 'p1', selectedIds: ['a', 'c'] });
+ publishLayerPanelSelection({ primaryId: 'x', projectId: 'p2', selectedIds: ['x', 'y'] });
+
+ reconcileLayerPanelStates([project('p1', ['a', 'b'], 'a')]);
+
+ expect(readLayerPanelState('p1', 'a').selectedIds).toEqual(['a']);
+ expect(readLayerPanelState('p2', 'x').selectedIds).toEqual(['x']);
+ });
+
+ it('returns the same state for a selection that already matches its document', () => {
+ publishLayerPanelSelection({ anchorId: 'c', primaryId: 'a', projectId: 'p1', selectedIds: ['a', 'c'] });
+ toggleLayerStackCollapsed('p1', 'a', 'control');
+ publishLayerPanelSelection({ primaryId: 'x', projectId: 'p2', selectedIds: ['x', 'y'] });
+ const p1 = project('p1', ['a', 'b', 'c'], 'a');
+ const before = readLayerPanelState('p1', 'a');
+
+ reconcileLayerPanelStates([p1, project('p2', ['x', 'y'], 'x')]);
+ expect(readLayerPanelState('p1', 'a')).toBe(before);
+ expect(before).toMatchObject({ anchorId: 'c', collapsedStacks: ['control'], selectedIds: ['a', 'c'] });
+
+ reconcileLayerPanelStates([p1, project('p2', ['x'], 'x')]);
+ expect(readLayerPanelState('p1', 'a')).toBe(before);
+ expect(readLayerPanelState('p2', 'x').selectedIds).toEqual(['x']);
+ });
+
+ it('compares states by content so a rebuilt read stays stable for subscribers', () => {
+ toggleLayerStackCollapsed('p1', 'a', 'control');
+ expect(isSameLayerPanelState(readLayerPanelState('p1', 'b'), readLayerPanelState('p1', 'b'))).toBe(true);
+ expect(isSameLayerPanelState(readLayerPanelState('p1', 'a'), readLayerPanelState('p1', 'b'))).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
new file mode 100644
index 0000000000..5bd24805a3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
@@ -0,0 +1,219 @@
+import type { CanvasDocumentContractV2, LayerStackKind } from '@workbench/canvas-engine/api';
+
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
+/**
+ * Transient Layers-panel state, kept per project and outside the document, its snapshots and
+ * history. The primary selection stays `document.selectedLayerId`; `primaryId` mirrors the value
+ * this state was built against so an external primary change collapses stale secondaries.
+ */
+export interface LayerPanelState {
+ readonly projectId: string;
+ readonly primaryId: string | null;
+ readonly anchorId: string | null;
+ readonly selectedIds: readonly string[];
+ readonly collapsedStacks: readonly LayerStackKind[];
+}
+
+export interface LayerSelectionModifiers {
+ additive: boolean;
+ range: boolean;
+}
+
+export interface LayerPanelSelectionUpdate {
+ projectId: string;
+ primaryId: string | null;
+ selectedIds: readonly string[];
+ anchorId?: string | null;
+}
+
+interface LayerPanelStore {
+ readonly byProject: Readonly<Record<string, LayerPanelState>>;
+}
+
+const store = createExternalStore<LayerPanelStore>({ byProject: {} });
+
+export const createLayerPanelState = (
+ projectId: string,
+ primaryId: string | null,
+ collapsedStacks: readonly LayerStackKind[] = []
+): LayerPanelState => ({
+ anchorId: primaryId,
+ collapsedStacks,
+ primaryId,
+ projectId,
+ selectedIds: primaryId ? [primaryId] : [],
+});
+
+const sameIds = (left: readonly string[], right: readonly string[]): boolean =>
+ left.length === right.length && left.every((id, index) => id === right[index]);
+
+export const isSameLayerPanelState = (left: LayerPanelState, right: LayerPanelState): boolean =>
+ left.projectId === right.projectId &&
+ left.primaryId === right.primaryId &&
+ left.anchorId === right.anchorId &&
+ sameIds(left.selectedIds, right.selectedIds) &&
+ sameIds(left.collapsedStacks, right.collapsedStacks);
+
+const stateFor = (snapshot: LayerPanelStore, projectId: string, primaryId: string | null): LayerPanelState => {
+ const stored = snapshot.byProject[projectId];
+ if (!stored) {
+ return createLayerPanelState(projectId, primaryId);
+ }
+ return stored.primaryId === primaryId ? stored : createLayerPanelState(projectId, primaryId, stored.collapsedStacks);
+};
+
+export const readLayerPanelState = (projectId: string, primaryId: string | null): LayerPanelState =>
+ stateFor(store.getSnapshot(), projectId, primaryId);
+
+export const useLayerPanelState = (projectId: string, primaryId: string | null): LayerPanelState =>
+ store.useSelector((snapshot) => stateFor(snapshot, projectId, primaryId), isSameLayerPanelState);
+
+const write = (state: LayerPanelState): void => {
+ const { byProject } = store.getSnapshot();
+ const current = byProject[state.projectId];
+ if (current && isSameLayerPanelState(current, state)) {
+ return;
+ }
+ store.setSnapshot({ byProject: { ...byProject, [state.projectId]: state } });
+};
+
+/** Records a panel-originated selection; publish before dispatching a new primary so reconciliation keeps it. */
+export const publishLayerPanelSelection = (selection: LayerPanelSelectionUpdate): void => {
+ write({
+ anchorId: selection.anchorId ?? selection.primaryId,
+ collapsedStacks: store.getSnapshot().byProject[selection.projectId]?.collapsedStacks ?? [],
+ primaryId: selection.primaryId,
+ projectId: selection.projectId,
+ selectedIds: [...selection.selectedIds],
+ });
+};
+
+export const toggleLayerStackCollapsed = (projectId: string, primaryId: string | null, stack: LayerStackKind): void => {
+ const current = readLayerPanelState(projectId, primaryId);
+ const collapsedStacks = current.collapsedStacks.includes(stack)
+ ? current.collapsedStacks.filter((candidate) => candidate !== stack)
+ : [...current.collapsedStacks, stack];
+ write({ ...current, collapsedStacks });
+};
+
+/** Keeps a state valid after an external primary change, a project switch, or a layer removal. */
+export const reconcileLayerPanelState = (
+ state: LayerPanelState,
+ projectId: string,
+ orderedIds: readonly string[],
+ primaryId: string | null
+): LayerPanelState => {
+ const existing = new Set(orderedIds);
+ const validPrimaryId = primaryId && existing.has(primaryId) ? primaryId : null;
+ if (state.projectId !== projectId || state.primaryId !== validPrimaryId) {
+ return createLayerPanelState(projectId, validPrimaryId, state.projectId === projectId ? state.collapsedStacks : []);
+ }
+ const selectedIds = [...new Set(state.selectedIds)].filter((id) => existing.has(id));
+ if (validPrimaryId && !selectedIds.includes(validPrimaryId)) {
+ selectedIds.push(validPrimaryId);
+ }
+ const anchorId = state.anchorId && existing.has(state.anchorId) ? state.anchorId : validPrimaryId;
+ if (anchorId === state.anchorId && sameIds(selectedIds, state.selectedIds)) {
+ return state;
+ }
+ return { ...state, anchorId, selectedIds };
+};
+
+/**
+ * Applies plain, Ctrl/Cmd-toggle, and Shift-range row selection semantics over the rows the panel
+ * renders; an additive range keeps selected rows hidden inside collapsed stacks.
+ */
+export const selectLayerInPanel = (
+ state: LayerPanelState,
+ layerId: string,
+ orderedIds: readonly string[],
+ modifiers: LayerSelectionModifiers
+): LayerPanelState => {
+ if (!orderedIds.includes(layerId)) {
+ return state;
+ }
+ if (modifiers.range) {
+ const anchorId = state.anchorId && orderedIds.includes(state.anchorId) ? state.anchorId : layerId;
+ const start = orderedIds.indexOf(anchorId);
+ const end = orderedIds.indexOf(layerId);
+ const rangeIds = orderedIds.slice(Math.min(start, end), Math.max(start, end) + 1);
+ const selected = new Set(modifiers.additive ? [...state.selectedIds, ...rangeIds] : rangeIds);
+ const hidden = modifiers.additive ? state.selectedIds.filter((id) => !orderedIds.includes(id)) : [];
+ return {
+ ...state,
+ anchorId,
+ primaryId: layerId,
+ selectedIds: [...orderedIds.filter((id) => selected.has(id)), ...hidden],
+ };
+ }
+ if (modifiers.additive) {
+ const selected = new Set(state.selectedIds);
+ const wasSelected = selected.has(layerId);
+ if (wasSelected) {
+ selected.delete(layerId);
+ } else {
+ selected.add(layerId);
+ }
+ const selectedIds = orderedIds.filter((id) => selected.has(id));
+ const primaryId = wasSelected
+ ? state.primaryId === layerId || !state.primaryId || !selected.has(state.primaryId)
+ ? (selectedIds[0] ?? null)
+ : state.primaryId
+ : layerId;
+ return { ...state, anchorId: layerId, primaryId, selectedIds };
+ }
+ return { ...state, anchorId: layerId, primaryId: layerId, selectedIds: [layerId] };
+};
+
+export interface LayerPanelProjectView {
+ readonly id: string;
+ readonly canvas: { readonly document: Pick<CanvasDocumentContractV2, 'layers' | 'selectedLayerId'> };
+}
+
+const reconciledDocuments = new Map<string, LayerPanelProjectView['canvas']['document']>();
+
+/** Reconciles every stored state with its project after a store transition and forgets closed projects. */
+export const reconcileLayerPanelStates = (projects: readonly LayerPanelProjectView[]): void => {
+ const { byProject } = store.getSnapshot();
+ const next: Record<string, LayerPanelState> = {};
+ let changed = false;
+ for (const project of projects) {
+ const stored = byProject[project.id];
+ if (!stored) {
+ continue;
+ }
+ const { document } = project.canvas;
+ if (reconciledDocuments.get(project.id) === document) {
+ next[project.id] = stored;
+ continue;
+ }
+ reconciledDocuments.set(project.id, document);
+ const reconciled = reconcileLayerPanelState(
+ stored,
+ project.id,
+ document.layers.map((layer) => layer.id),
+ document.selectedLayerId
+ );
+ next[project.id] = reconciled;
+ changed ||= reconciled !== stored;
+ }
+ for (const id of reconciledDocuments.keys()) {
+ if (!(id in next)) {
+ reconciledDocuments.delete(id);
+ }
+ }
+ if (changed || Object.keys(next).length !== Object.keys(byProject).length) {
+ store.setSnapshot({ byProject: next });
+ }
+};
+
+export const clearLayerPanelStates = (): void => {
+ reconciledDocuments.clear();
+ if (Object.keys(store.getSnapshot().byProject).length > 0) {
+ store.setSnapshot({ byProject: {} });
+ }
+};
+
+registerAccountOwnedResource({ clear: clearLayerPanelStates, name: 'layer-panel-state' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 5423b9e9f4..f6aa487847 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -9,6 +9,7 @@ import { preloadCanvasInvocation } from '@workbench/activeInvocationSubmission';
import { getCanvasImportNotice } from '@workbench/canvas-operations/api';
import { getCanvasStagingSlots } from '@workbench/canvasStagingView';
import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';
+import { readLayerPanelState } from '@workbench/layerPanelState';
import { useWorkbenchSettingsSelector } from '@workbench/settings/store';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { useNotify } from '@workbench/useNotify';
@@ -20,7 +21,6 @@ import {
useWorkbenchCommands,
useWorkbenchQueries,
} from '@workbench/WorkbenchContext';
-import { readLayerPanelSelection } from '@workbench/workbenchStore';
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -369,7 +369,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
}, [engine]);
const executeCanvasHotkey = useEffectEvent((commandId: string) => {
- const selectedLayerIds = readLayerPanelSelection(projectId, document.selectedLayerId).selectedIds;
+ const selectedLayerIds = readLayerPanelState(projectId, document.selectedLayerId).selectedIds;
executeCanvasHotkeyCommand(commandId, {
copySelection,
dispatch: canvasDispatch,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 9bf158d90e..a12412d945 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -8,8 +8,8 @@ import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectM
import { isHideableLayer, isLayerHidden, moveLayersWithinStacks } from '@workbench/canvas-engine/api';
import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { publishLayerPanelSelection } from '@workbench/layerPanelState';
import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
-import { publishLayerPanelSelection } from '@workbench/workbenchStore';
/** Command id → document-space nudge delta (shift variants are ×10). */
const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 6929a0cfd0..74d667eafc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -18,12 +18,12 @@ import { IconButton, MenuContent, RenameDialog, Tooltip } from '@platform/ui';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
import { deleteLayerActions, duplicateLayerActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { publishLayerPanelSelection, readLayerPanelSelection } from '@workbench/workbenchStore';
import {
ArrowRightLeftIcon,
ArrowUpDownIcon,
@@ -306,7 +306,7 @@ const LayerMenu = ({
const getActionLabel = useCallback(
(id: LayerContextActionId) => {
if (id === 'duplicate') {
- const panelSelection = readLayerPanelSelection(projectId, document.selectedLayerId);
+ const panelSelection = readLayerPanelState(projectId, document.selectedLayerId);
if (panelSelection.selectedIds.includes(layer.id) && panelSelection.selectedIds.length > 1) {
return t('widgets.layers.actions.duplicateSelected');
}
@@ -324,7 +324,7 @@ const LayerMenu = ({
const handleDuplicate = useCallback(async () => {
if (engine) {
- const panelSelection = readLayerPanelSelection(projectId, document.selectedLayerId);
+ const panelSelection = readLayerPanelState(projectId, document.selectedLayerId);
const sourceIds = panelSelection.selectedIds.includes(layer.id) ? panelSelection.selectedIds : [layer.id];
try {
const result = await engine.layers.duplicateLayers(sourceIds);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
index dd70d462f2..d42cc6a43b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
@@ -1,6 +1,7 @@
import type { DragEndEvent } from '@dnd-kit/core';
import type { CanvasLayerContract, LayerStackKind } from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { LayerSelectionModifiers } from '@workbench/layerPanelState';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
import type { LucideIcon } from 'lucide-react';
import type { Dispatch } from 'react';
@@ -19,8 +20,6 @@ import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIco
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerSelectionModifiers } from './layerGroups';
-
import { groupAddItemId } from './addLayerMenu';
import { LAYER_KEYBOARD_SENSOR_OPTIONS } from './layerDndConfig';
import {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
index b54553d7b9..318be4ea0c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
@@ -13,6 +13,7 @@ import {
} from '@dnd-kit/core';
import { arrayMove, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { system } from '@theme/system';
+import { createLayerPanelState, selectLayerInPanel } from '@workbench/layerPanelState';
import { createInstance } from 'i18next';
import { act, useCallback, useMemo, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
@@ -21,7 +22,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
import { LAYER_KEYBOARD_SENSOR_OPTIONS } from './layerDndConfig';
-import { createLayerPanelSelection, selectLayerInPanel } from './layerGroups';
import { LayerListItem, type LayerListItemEngine } from './LayerListItem';
import { createEmptyPaintLayer } from './layerOps';
@@ -79,7 +79,7 @@ const requestLayerThumbnail = vi.fn();
const Harness = () => {
const [layers, setLayers] = useState(INITIAL_LAYERS);
- const [selection, setSelection] = useState(() => createLayerPanelSelection('test-project', null));
+ const [selection, setSelection] = useState(() => createLayerPanelState('test-project', null));
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, LAYER_KEYBOARD_SENSOR_OPTIONS)
@@ -88,7 +88,7 @@ const Harness = () => {
const selectedLayerId = selection.primaryId;
const dispatch = useCallback((mutation: CanvasProjectMutation) => {
if (mutation.type === 'setCanvasSelectedLayer') {
- setSelection(createLayerPanelSelection('test-project', mutation.id));
+ setSelection(createLayerPanelState('test-project', mutation.id));
} else if (mutation.type === 'updateCanvasLayer' && mutation.patch.isEnabled !== undefined) {
setLayers((current) =>
current.map((layer) =>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
index d68693e70f..4156e977a5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
@@ -1,5 +1,6 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { LayerSelectionModifiers } from '@workbench/layerPanelState';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
import type { Dispatch, KeyboardEvent, MouseEvent } from 'react';
@@ -14,8 +15,6 @@ import { EyeIcon, EyeOffIcon, LockIcon, LockOpenIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerSelectionModifiers } from './layerGroups';
-
import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';
import {
CanvasLayerContextMenu,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
index ff4e52f0c4..6e847f7da6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
@@ -11,10 +11,10 @@ import {
type LayerStackMoveKind,
} from '@workbench/canvas-engine/api';
import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { publishLayerPanelSelection } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { publishLayerPanelSelection } from '@workbench/workbenchStore';
import {
ArrowDownIcon,
ArrowUpIcon,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 7fa817fb96..03345f588b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -1,18 +1,24 @@
import type { LayerStackKind } from '@workbench/canvas-engine/api';
import { Flex, Icon, Stack, Text } from '@chakra-ui/react';
+import {
+ publishLayerPanelSelection,
+ selectLayerInPanel,
+ toggleLayerStackCollapsed,
+ useLayerPanelState,
+ type LayerSelectionModifiers,
+} from '@workbench/layerPanelState';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';
import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
-import { publishLayerPanelSelection, readLayerPanelSelection } from '@workbench/workbenchStore';
import { LayersIcon } from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerSelectionModifiers } from './layerGroups';
+import type { LayerGroup } from './layerGroups';
-import { groupLayers, reconcileLayerPanelSelection, selectLayerInPanel } from './layerGroups';
+import { groupLayers } from './layerGroups';
import { LayerGroupSection } from './LayerGroupSection';
import { LayerMultiSelectionActions } from './LayerMultiSelectionActions';
import { isLayerPropertiesGroupRequested, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';
@@ -41,47 +47,28 @@ export const LayersWidgetView = () => {
);
const groups = useMemo(() => groupLayers(layers), [layers]);
- // Collapse is transient panel UI state (not part of the canvas document / undo
- // history): a set of collapsed group keys, defaulting to expanded.
- const [collapsedGroups, setCollapsedGroups] = useState<Partial<Record<LayerStackKind, boolean>>>({});
+ const panelState = useLayerPanelState(projectId, selectedLayerId);
+ const isCollapsed = (group: LayerGroup): boolean =>
+ panelState.collapsedStacks.includes(group.key) && !isLayerPropertiesGroupRequested(propertiesRequest, group.layers);
const allLayerIds = useMemo(() => groups.flatMap((group) => group.layers.map((layer) => layer.id)), [groups]);
- const visibleLayerIds = groups.flatMap((group) =>
- collapsedGroups[group.key] === true && !isLayerPropertiesGroupRequested(propertiesRequest, group.layers)
- ? []
- : group.layers.map((layer) => layer.id)
- );
- const [storedPanelSelection, setPanelSelection] = useState(() => {
- const shared = readLayerPanelSelection(projectId, selectedLayerId);
- return { ...shared, anchorId: shared.primaryId };
- });
- const selection = useMemo(() => {
- const shared = readLayerPanelSelection(projectId, selectedLayerId);
- const source =
- storedPanelSelection.projectId === projectId && storedPanelSelection.primaryId === selectedLayerId
- ? storedPanelSelection
- : { ...shared, anchorId: shared.primaryId };
- return reconcileLayerPanelSelection(source, projectId, allLayerIds, selectedLayerId);
- }, [allLayerIds, projectId, selectedLayerId, storedPanelSelection]);
- if (selection !== storedPanelSelection) {
- setPanelSelection(selection);
- }
- const selectedIds = selection.selectedIds;
+ const visibleLayerIds = groups.flatMap((group) => (isCollapsed(group) ? [] : group.layers.map((layer) => layer.id)));
+ const selectedIds = panelState.selectedIds;
const handleSelectLayer = useCallback(
(layerId: string, modifiers: LayerSelectionModifiers) => {
- const next = selectLayerInPanel(selection, layerId, modifiers.range ? visibleLayerIds : allLayerIds, modifiers);
- setPanelSelection(next);
+ const next = selectLayerInPanel(panelState, layerId, modifiers.range ? visibleLayerIds : allLayerIds, modifiers);
publishLayerPanelSelection(next);
if (next.primaryId !== selectedLayerId) {
dispatch({ id: next.primaryId, type: 'setCanvasSelectedLayer' });
}
},
- [allLayerIds, dispatch, selectedLayerId, selection, visibleLayerIds]
+ [allLayerIds, dispatch, panelState, selectedLayerId, visibleLayerIds]
);
- const handleToggleCollapse = useCallback((groupKey: LayerStackKind) => {
- setCollapsedGroups((prev) => ({ ...prev, [groupKey]: !prev[groupKey] }));
- }, []);
+ const handleToggleCollapse = useCallback(
+ (stack: LayerStackKind) => toggleLayerStackCollapsed(projectId, selectedLayerId, stack),
+ [projectId, selectedLayerId]
+ );
return (
<Stack h="full">
@@ -124,9 +111,7 @@ export const LayersWidgetView = () => {
engine={engine}
groupKey={group.key}
groupLayers={group.layers}
- isCollapsed={
- collapsedGroups[group.key] === true && !isLayerPropertiesGroupRequested(propertiesRequest, group.layers)
- }
+ isCollapsed={isCollapsed(group)}
layers={layers}
onSelectLayer={handleSelectLayer}
onToggleCollapse={handleToggleCollapse}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
index dfd077b32c..85ca966586 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
@@ -14,92 +14,6 @@ import {
import { moveItem } from './layersDnd';
-/** Transient Layers-panel selection; only `primaryId` is persisted in the canvas document. */
-export interface LayerPanelSelection {
- anchorId: string | null;
- primaryId: string | null;
- projectId: string;
- selectedIds: readonly string[];
-}
-
-export interface LayerSelectionModifiers {
- additive: boolean;
- range: boolean;
-}
-
-export const createLayerPanelSelection = (projectId: string, primaryId: string | null): LayerPanelSelection => ({
- anchorId: primaryId,
- primaryId,
- projectId,
- selectedIds: primaryId ? [primaryId] : [],
-});
-
-/** Reconciles transient selection after an external primary change, project switch, or layer removal. */
-export const reconcileLayerPanelSelection = (
- selection: LayerPanelSelection,
- projectId: string,
- orderedIds: readonly string[],
- primaryId: string | null
-): LayerPanelSelection => {
- const existing = new Set(orderedIds);
- const validPrimaryId = primaryId && existing.has(primaryId) ? primaryId : null;
- if (selection.projectId !== projectId || selection.primaryId !== validPrimaryId) {
- return createLayerPanelSelection(projectId, validPrimaryId);
- }
- const selected = new Set(selection.selectedIds.filter((id) => existing.has(id)));
- if (validPrimaryId) {
- selected.add(validPrimaryId);
- }
- const selectedIds = orderedIds.filter((id) => selected.has(id));
- const anchorId = selection.anchorId && existing.has(selection.anchorId) ? selection.anchorId : validPrimaryId;
- if (
- anchorId === selection.anchorId &&
- selectedIds.length === selection.selectedIds.length &&
- selectedIds.every((id, index) => id === selection.selectedIds[index])
- ) {
- return selection;
- }
- return { ...selection, anchorId, selectedIds };
-};
-
-/** Applies plain, Ctrl/Cmd-toggle, and Shift-range row selection semantics. */
-export const selectLayerInPanel = (
- selection: LayerPanelSelection,
- layerId: string,
- orderedIds: readonly string[],
- modifiers: LayerSelectionModifiers
-): LayerPanelSelection => {
- if (!orderedIds.includes(layerId)) {
- return selection;
- }
- if (modifiers.range) {
- const anchorId = selection.anchorId && orderedIds.includes(selection.anchorId) ? selection.anchorId : layerId;
- const start = orderedIds.indexOf(anchorId);
- const end = orderedIds.indexOf(layerId);
- const rangeIds = orderedIds.slice(Math.min(start, end), Math.max(start, end) + 1);
- const selected = modifiers.additive ? new Set(selection.selectedIds) : new Set<string>();
- rangeIds.forEach((id) => selected.add(id));
- return { ...selection, anchorId, primaryId: layerId, selectedIds: orderedIds.filter((id) => selected.has(id)) };
- }
- if (modifiers.additive) {
- const selected = new Set(selection.selectedIds);
- const wasSelected = selected.has(layerId);
- if (wasSelected) {
- selected.delete(layerId);
- } else {
- selected.add(layerId);
- }
- const selectedIds = orderedIds.filter((id) => selected.has(id));
- const primaryId = wasSelected
- ? selection.primaryId === layerId || !selection.primaryId || !selected.has(selection.primaryId)
- ? (selectedIds[0] ?? null)
- : selection.primaryId
- : layerId;
- return { ...selection, anchorId: layerId, primaryId, selectedIds };
- }
- return { ...selection, anchorId: layerId, primaryId: layerId, selectedIds: [layerId] };
-};
-
/** A non-empty Layers panel section: one stack plus its members in flat order. */
export interface LayerGroup {
key: LayerStackKind;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerSelection.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerSelection.test.ts
deleted file mode 100644
index 37c48a4e77..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerSelection.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { createLayerPanelSelection, reconcileLayerPanelSelection, selectLayerInPanel } from './layerGroups';
-
-const ids = ['a', 'b', 'c', 'd'];
-const plain = { additive: false, range: false };
-const toggle = { additive: true, range: false };
-const range = { additive: false, range: true };
-
-describe('layer panel selection', () => {
- it('replaces selection on a plain click', () => {
- const initial = createLayerPanelSelection('project', 'a');
- expect(selectLayerInPanel(initial, 'c', ids, plain)).toMatchObject({
- anchorId: 'c',
- primaryId: 'c',
- selectedIds: ['c'],
- });
- });
-
- it('toggles layers with Ctrl/Cmd while keeping a valid primary', () => {
- const initial = createLayerPanelSelection('project', 'b');
- const added = selectLayerInPanel(initial, 'd', ids, toggle);
- expect(added).toMatchObject({ primaryId: 'd', selectedIds: ['b', 'd'] });
- expect(selectLayerInPanel(added, 'b', ids, toggle)).toMatchObject({
- primaryId: 'd',
- selectedIds: ['d'],
- });
- expect(selectLayerInPanel(added, 'd', ids, toggle)).toMatchObject({
- primaryId: 'b',
- selectedIds: ['b'],
- });
- });
-
- it('selects a contiguous Shift range from the stable anchor', () => {
- const initial = createLayerPanelSelection('project', 'b');
- expect(selectLayerInPanel(initial, 'd', ids, range)).toMatchObject({
- anchorId: 'b',
- primaryId: 'd',
- selectedIds: ['b', 'c', 'd'],
- });
- });
-
- it('adds a Shift range when Ctrl/Cmd is held too', () => {
- const initial = selectLayerInPanel(createLayerPanelSelection('project', 'a'), 'd', ids, toggle);
- const next = selectLayerInPanel(initial, 'b', ids, { additive: true, range: true });
- expect(next.selectedIds).toEqual(['a', 'b', 'c', 'd']);
- });
-
- it('uses only rendered rows when a Shift range crosses collapsed groups', () => {
- const initial = createLayerPanelSelection('project', 'a');
- expect(selectLayerInPanel(initial, 'd', ['a', 'd'], range).selectedIds).toEqual(['a', 'd']);
- });
-
- it('prunes removed secondaries without collapsing an unchanged primary', () => {
- const multi = selectLayerInPanel(createLayerPanelSelection('project', 'a'), 'c', ids, toggle);
- expect(reconcileLayerPanelSelection(multi, 'project', ['a', 'b', 'd'], 'a')).toMatchObject({
- primaryId: 'a',
- selectedIds: ['a'],
- });
- });
-
- it('collapses to a new primary selected outside the panel and resets between projects', () => {
- const multi = selectLayerInPanel(createLayerPanelSelection('project', 'a'), 'c', ids, toggle);
- expect(reconcileLayerPanelSelection(multi, 'project', ids, 'd').selectedIds).toEqual(['d']);
- expect(reconcileLayerPanelSelection(multi, 'other-project', ids, 'a').selectedIds).toEqual(['a']);
- });
-
- it('does not resurrect secondaries after an A to B to A project round trip', () => {
- let selection = selectLayerInPanel(createLayerPanelSelection('project-a', 'a'), 'c', ids, toggle);
- selection = reconcileLayerPanelSelection(selection, 'project-b', ids, 'b');
- selection = reconcileLayerPanelSelection(selection, 'project-a', ids, 'a');
- expect(selection.selectedIds).toEqual(['a']);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index a6ba0a304e..415e1f92af 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -6,10 +6,11 @@ import type { LayoutPreset, LayoutPresetRoute } from './layoutContracts';
import type { WorkbenchInternalStore, WorkbenchSnapshot } from './workbenchStore';
import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from './diagnostics/logger';
+import { publishLayerPanelSelection, readLayerPanelState, toggleLayerStackCollapsed } from './layerPanelState';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from './widgetPlacementMeta';
import { getProjectWidgetValues } from './widgetState';
import { createInitialWorkbenchState } from './workbenchState';
-import { createWorkbenchStore, publishLayerPanelSelection, readLayerPanelSelection } from './workbenchStore';
+import { createWorkbenchStore } from './workbenchStore';
const paintLayer = (id: string): CanvasLayerContract => ({
blendMode: 'normal',
@@ -71,7 +72,7 @@ describe('createWorkbenchStore', () => {
expect(snapshot.projects).toHaveLength(1);
});
- it('resets transient layer multi-selection across project switches even without a Layers panel', () => {
+ it("keeps each project's transient layer multi-selection across project switches", () => {
const store = createWorkbenchStore();
const firstProjectId = store.getSnapshot().activeProject.id;
store.commands.canvas.apply(firstProjectId, {
@@ -89,8 +90,30 @@ describe('createWorkbenchStore', () => {
const secondProject = store.commands.projects.create();
store.commands.projects.switchTo(firstProjectId);
- expect(readLayerPanelSelection(firstProjectId, 'b').selectedIds).toEqual(['b']);
- expect(readLayerPanelSelection(secondProject.id, null).selectedIds).toEqual([]);
+ expect(readLayerPanelState(firstProjectId, 'b').selectedIds).toEqual(['a', 'b']);
+ expect(readLayerPanelState(secondProject.id, null).selectedIds).toEqual([]);
+ });
+
+ it("clears every project's panel state on hydration", () => {
+ const store = createWorkbenchStore();
+ const projectId = store.getSnapshot().activeProject.id;
+ store.commands.canvas.apply(projectId, {
+ anchor: stackTopAnchor(projectId),
+ layer: paintLayer('a'),
+ type: 'addCanvasLayer',
+ });
+ store.commands.canvas.apply(projectId, {
+ anchor: stackTopAnchor(projectId),
+ layer: paintLayer('b'),
+ type: 'addCanvasLayer',
+ });
+ publishLayerPanelSelection({ primaryId: 'b', projectId, selectedIds: ['a', 'b'] });
+ toggleLayerStackCollapsed(projectId, 'b', 'raster');
+ expect(readLayerPanelState(projectId, 'b')).toMatchObject({ collapsedStacks: ['raster'], selectedIds: ['a', 'b'] });
+
+ store.internal.persistence.hydrate(createInitialWorkbenchState());
+
+ expect(readLayerPanelState(projectId, 'b')).toMatchObject({ collapsedStacks: [], selectedIds: ['b'] });
});
it('does not resurrect stale secondaries after external primary changes in the same project', () => {
@@ -107,12 +130,12 @@ describe('createWorkbenchStore', () => {
// its new primary, so the store preserves the selected set.
publishLayerPanelSelection({ primaryId: 'c', projectId, selectedIds: ['a', 'c'] });
store.commands.canvas.apply(projectId, { id: 'c', type: 'setCanvasSelectedLayer' });
- expect(readLayerPanelSelection(projectId, 'c').selectedIds).toEqual(['a', 'c']);
+ expect(readLayerPanelState(projectId, 'c').selectedIds).toEqual(['a', 'c']);
store.commands.canvas.apply(projectId, { id: 'b', type: 'setCanvasSelectedLayer' });
store.commands.canvas.apply(projectId, { id: 'c', type: 'setCanvasSelectedLayer' });
- expect(readLayerPanelSelection(projectId, 'c').selectedIds).toEqual(['c']);
+ expect(readLayerPanelState(projectId, 'c').selectedIds).toEqual(['c']);
});
it('coordinates layout preset activation across every command caller', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index fcbc42c9fb..093af777c4 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -13,6 +13,7 @@ import type { CanvasEditIntent } from './autoRoutePolicy';
import type { CanvasProjectMutation } from './canvasProjectMutations';
import { recordDiagnosticEntry } from './diagnostics/logger';
+import { clearLayerPanelStates, reconcileLayerPanelStates } from './layerPanelState';
import { createLayoutPresetActivator, loadLayoutPresetWidgets } from './layoutPresetActivation';
import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';
import { getLayoutWidgetTypeIds } from './layoutWidgetSet';
@@ -28,51 +29,6 @@ type WorkbenchAction = __WorkbenchReducerActionInternal;
type ActionPayload<Type extends WorkbenchAction['type']> = Omit<Extract<WorkbenchAction, { type: Type }>, 'type'>;
type WorkbenchDispatch = (action: WorkbenchAction) => void;
-/** Event-time bridge from the transient Layers-panel selection to canvas-wide hotkeys. */
-export interface LayerPanelSelectionSnapshot {
- primaryId: string | null;
- projectId: string;
- selectedIds: readonly string[];
-}
-
-let activeLayerPanelSelection: LayerPanelSelectionSnapshot = { primaryId: null, projectId: '', selectedIds: [] };
-
-export const publishLayerPanelSelection = (selection: LayerPanelSelectionSnapshot): void => {
- activeLayerPanelSelection = {
- primaryId: selection.primaryId,
- projectId: selection.projectId,
- selectedIds: [...selection.selectedIds],
- };
-};
-
-export const resetLayerPanelSelection = (projectId: string, primaryId: string | null): void => {
- activeLayerPanelSelection = { primaryId, projectId, selectedIds: primaryId ? [primaryId] : [] };
-};
-
-const reconcileLayerPanelSelection = (project: Project): void => {
- const { layers, selectedLayerId } = project.canvas.document;
- if (activeLayerPanelSelection.projectId !== project.id || activeLayerPanelSelection.primaryId !== selectedLayerId) {
- resetLayerPanelSelection(project.id, selectedLayerId);
- return;
- }
- const existing = new Set(layers.map((layer) => layer.id));
- const selectedIds = activeLayerPanelSelection.selectedIds.filter((id) => existing.has(id));
- if (selectedLayerId && !selectedIds.includes(selectedLayerId)) {
- selectedIds.push(selectedLayerId);
- }
- if (
- selectedIds.length !== activeLayerPanelSelection.selectedIds.length ||
- selectedIds.some((id, index) => id !== activeLayerPanelSelection.selectedIds[index])
- ) {
- activeLayerPanelSelection = { ...activeLayerPanelSelection, selectedIds };
- }
-};
-
-export const readLayerPanelSelection = (projectId: string, primaryId: string | null): LayerPanelSelectionSnapshot =>
- activeLayerPanelSelection.projectId === projectId && activeLayerPanelSelection.primaryId === primaryId
- ? activeLayerPanelSelection
- : { primaryId, projectId, selectedIds: primaryId ? [primaryId] : [] };
-
type MechanicalCommand<Type extends WorkbenchAction['type']> = keyof ActionPayload<Type> extends never
? () => void
: (payload: ActionPayload<Type>) => void;
@@ -701,15 +657,13 @@ export const createWorkbenchStore = (
invalidateLayoutPresetActivation();
}
- const activeProject = getActiveProject(nextState);
if (action.type === 'hydrateWorkbench') {
- resetLayerPanelSelection(activeProject.id, activeProject.canvas.document.selectedLayerId);
- } else {
- // Panel-originated primary changes publish before dispatch and therefore
- // survive this reconciliation. Any external primary change, project
- // switch, or layer removal collapses/filter stale secondaries here at the
- // always-live store boundary, even while the Layers widget is unmounted.
- reconcileLayerPanelSelection(activeProject);
+ clearLayerPanelStates();
+ } else if (nextState !== previousState) {
+ // The always-live store boundary collapses stale secondaries after an
+ // external primary change or layer removal, even while the Layers widget
+ // is unmounted.
+ reconcileLayerPanelStates(nextState.projects);
}
setSnapshotState(nextState);