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): project reference images as layer child rows

Josh Corbett7844d592316d
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 0f3780e361..1defb1b755 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -995,9 +995,7 @@
"src/features/queue/ui/launchpad/QueueStatusBand.tsx",
"src/workbench/launchpad/home/livePanels.ts"
],
- "editorForbiddenInitialChunkNames": [
- "ag-psd"
- ],
+ "editorForbiddenInitialChunkNames": ["ag-psd"],
"inactiveWidgetGateOwner": "deepen-widget-registry-loading"
}
}
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 0e506f70b3..fe25676eff 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,13 +25,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 112.90000000223517,
+ "domContentLoadedMedianMs": 121.70000000298023,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113,
- "longestTaskMaxMs": 68,
+ "loadMedianMs": 121.79999999701977,
+ "longestTaskMaxMs": 71,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -41,24 +41,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 38,
- "scriptRawBytes": 1632821,
+ "scriptRawBytes": 1633476,
"scriptRequestCount": 34,
- "totalRawBytes": 1816775
+ "totalRawBytes": 1817321
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 38,
- "scriptRawBytes": 1649150,
+ "scriptRawBytes": 1649811,
"scriptRequestCount": 34,
- "totalRawBytes": 1834943
+ "totalRawBytes": 1835495
},
- "routeReadyMedianMs": 246.90000000223517,
+ "routeReadyMedianMs": 274.90000000596046,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -85,13 +85,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 108.89999999850988,
+ "domContentLoadedMedianMs": 122.59999999403954,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 109,
- "longestTaskMaxMs": 66,
+ "loadMedianMs": 122.59999999403954,
+ "longestTaskMaxMs": 73,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -101,24 +101,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 38,
- "scriptRawBytes": 1632821,
+ "scriptRawBytes": 1633476,
"scriptRequestCount": 34,
- "totalRawBytes": 1816775
+ "totalRawBytes": 1817321
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 38,
- "scriptRawBytes": 1649150,
+ "scriptRawBytes": 1649811,
"scriptRequestCount": 34,
- "totalRawBytes": 1834943
+ "totalRawBytes": 1835495
},
- "routeReadyMedianMs": 258.5,
+ "routeReadyMedianMs": 294.8999999985099,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -145,15 +145,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 112.39999999850988,
+ "domContentLoadedMedianMs": 116.5,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 112.5,
- "longestTaskMaxMs": 95,
+ "loadMedianMs": 116.5,
+ "longestTaskMaxMs": 102,
"owner": "workbench",
- "projectSwitchMedianMs": 32.5,
+ "projectSwitchMedianMs": 35.599999994039536,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -161,24 +161,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 115,
- "scriptRawBytes": 3264438,
+ "scriptRawBytes": 3265126,
"scriptRequestCount": 110,
- "totalRawBytes": 3604768
+ "totalRawBytes": 3605347
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 115,
- "scriptRawBytes": 3297083,
+ "scriptRawBytes": 3297778,
"scriptRequestCount": 110,
- "totalRawBytes": 3640816
+ "totalRawBytes": 3641401
},
- "routeReadyMedianMs": 648.1999999992549,
+ "routeReadyMedianMs": 666.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -205,15 +205,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 115.30000000074506,
+ "domContentLoadedMedianMs": 123.89999999850988,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 115.39999999850988,
- "longestTaskMaxMs": 173,
+ "loadMedianMs": 124.10000000149012,
+ "longestTaskMaxMs": 208,
"owner": "workbench",
- "projectSwitchMedianMs": 67.80000000074506,
+ "projectSwitchMedianMs": 70.20000000298023,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -221,24 +221,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 115,
- "scriptRawBytes": 3264438,
+ "scriptRawBytes": 3265126,
"scriptRequestCount": 110,
- "totalRawBytes": 3604768
+ "totalRawBytes": 3605347
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 115,
- "scriptRawBytes": 3297083,
+ "scriptRawBytes": 3297778,
"scriptRequestCount": 110,
- "totalRawBytes": 3640816
+ "totalRawBytes": 3641401
},
- "routeReadyMedianMs": 430.79999999701977,
+ "routeReadyMedianMs": 469.20000000298023,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -247,31 +247,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 254333,
+ "largestAssetRawBytes": 264292,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 410982,
+ "scriptRawBytes": 419536,
"scriptRequestCount": 7,
- "totalRawBytes": 410982
+ "totalRawBytes": 419536
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 256877,
+ "largestAssetRawBytes": 266935,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 415092,
+ "scriptRawBytes": 423732,
"scriptRequestCount": 7,
- "totalRawBytes": 415092
+ "totalRawBytes": 423732
},
- "domContentLoadedMedianMs": 114.19999999925494,
+ "domContentLoadedMedianMs": 118.79999999701977,
"id": "editor-canvas",
- "layoutAckMedianMs": 1.9000000022351742,
- "layoutReturnSwitchMedianMs": 50,
- "layoutSwitchMedianMs": 81.29999999701977,
- "loadMedianMs": 114.29999999701977,
- "longestTaskMaxMs": 116,
+ "layoutAckMedianMs": 2.2000000029802322,
+ "layoutReturnSwitchMedianMs": 58.5,
+ "layoutSwitchMedianMs": 92.30000000447035,
+ "loadMedianMs": 118.89999999850988,
+ "longestTaskMaxMs": 137,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -281,24 +281,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 122,
- "scriptRawBytes": 3675420,
+ "scriptRawBytes": 3684662,
"scriptRequestCount": 117,
- "totalRawBytes": 4015750
+ "totalRawBytes": 4024883
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 122,
- "scriptRawBytes": 3712175,
+ "scriptRawBytes": 3721509,
"scriptRequestCount": 117,
- "totalRawBytes": 4055908
+ "totalRawBytes": 4065132
},
- "routeReadyMedianMs": 1008.7000000029802,
+ "routeReadyMedianMs": 1068.8999999985099,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -307,31 +307,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 254333,
+ "largestAssetRawBytes": 264292,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 410982,
+ "scriptRawBytes": 419536,
"scriptRequestCount": 7,
- "totalRawBytes": 410982
+ "totalRawBytes": 419536
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 256877,
+ "largestAssetRawBytes": 266935,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 415092,
+ "scriptRawBytes": 423732,
"scriptRequestCount": 7,
- "totalRawBytes": 415092
+ "totalRawBytes": 423732
},
- "domContentLoadedMedianMs": 112.30000000074506,
+ "domContentLoadedMedianMs": 122.60000000149012,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 48.100000001490116,
- "layoutSwitchMedianMs": 83.19999999925494,
- "loadMedianMs": 112.40000000223517,
- "longestTaskMaxMs": 185,
+ "layoutAckMedianMs": 2.399999998509884,
+ "layoutReturnSwitchMedianMs": 46.79999999701977,
+ "layoutSwitchMedianMs": 88.40000000596046,
+ "loadMedianMs": 122.69999999552965,
+ "longestTaskMaxMs": 207,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -341,24 +341,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 122,
- "scriptRawBytes": 3675420,
+ "scriptRawBytes": 3684662,
"scriptRequestCount": 117,
- "totalRawBytes": 4015750
+ "totalRawBytes": 4024883
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 122,
- "scriptRawBytes": 3712175,
+ "scriptRawBytes": 3721509,
"scriptRequestCount": 117,
- "totalRawBytes": 4055908
+ "totalRawBytes": 4065132
},
- "routeReadyMedianMs": 1114.4000000022352,
+ "routeReadyMedianMs": 1184.6999999955297,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -370,9 +370,9 @@
"largestAssetRawBytes": 173980,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 364247,
+ "scriptRawBytes": 364237,
"scriptRequestCount": 6,
- "totalRawBytes": 379660
+ "totalRawBytes": 379650
},
"activatedResourceLimits": {
"cssRawBytes": 15568,
@@ -381,17 +381,17 @@
"largestAssetRawBytes": 175720,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 367890,
+ "scriptRawBytes": 367880,
"scriptRequestCount": 6,
- "totalRawBytes": 383457
+ "totalRawBytes": 383447
},
- "domContentLoadedMedianMs": 115.09999999776483,
+ "domContentLoadedMedianMs": 120.30000000447035,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 38.599999997764826,
- "layoutSwitchMedianMs": 100.80000000074506,
- "loadMedianMs": 115.19999999925494,
- "longestTaskMaxMs": 157,
+ "layoutAckMedianMs": 2.399999998509884,
+ "layoutReturnSwitchMedianMs": 35.19999999552965,
+ "layoutSwitchMedianMs": 92.5,
+ "loadMedianMs": 120.5,
+ "longestTaskMaxMs": 108,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -401,24 +401,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 122,
- "scriptRawBytes": 3628685,
+ "scriptRawBytes": 3629363,
"scriptRequestCount": 116,
- "totalRawBytes": 3984428
+ "totalRawBytes": 3984997
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 122,
- "scriptRawBytes": 3664972,
+ "scriptRawBytes": 3665657,
"scriptRequestCount": 116,
- "totalRawBytes": 4024273
+ "totalRawBytes": 4024847
},
- "routeReadyMedianMs": 1143.699999999255,
+ "routeReadyMedianMs": 1067.5,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -430,9 +430,9 @@
"largestAssetRawBytes": 173980,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 364247,
+ "scriptRawBytes": 364237,
"scriptRequestCount": 6,
- "totalRawBytes": 379660
+ "totalRawBytes": 379650
},
"activatedResourceLimits": {
"cssRawBytes": 15568,
@@ -441,17 +441,17 @@
"largestAssetRawBytes": 175720,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 367890,
+ "scriptRawBytes": 367880,
"scriptRequestCount": 6,
- "totalRawBytes": 383457
+ "totalRawBytes": 383447
},
- "domContentLoadedMedianMs": 112.20000000298023,
+ "domContentLoadedMedianMs": 124.70000000298023,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.300000000745058,
- "layoutReturnSwitchMedianMs": 39.19999999925494,
- "layoutSwitchMedianMs": 124.60000000149012,
- "loadMedianMs": 112.40000000223517,
- "longestTaskMaxMs": 338,
+ "layoutAckMedianMs": 2.899999998509884,
+ "layoutReturnSwitchMedianMs": 43.30000000447035,
+ "layoutSwitchMedianMs": 136.10000000149012,
+ "loadMedianMs": 124.80000000447035,
+ "longestTaskMaxMs": 388,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -461,24 +461,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 122,
- "scriptRawBytes": 3628685,
+ "scriptRawBytes": 3629363,
"scriptRequestCount": 116,
- "totalRawBytes": 3984428
+ "totalRawBytes": 3984997
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 122,
- "scriptRawBytes": 3664972,
+ "scriptRawBytes": 3665657,
"scriptRequestCount": 116,
- "totalRawBytes": 4024273
+ "totalRawBytes": 4024847
},
- "routeReadyMedianMs": 1156.5999999977648,
+ "routeReadyMedianMs": 1259.2999999970198,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -505,13 +505,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 110.19999999925494,
+ "domContentLoadedMedianMs": 123.89999999850988,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 23.300000000745058,
- "loadMedianMs": 110.30000000074506,
- "longestTaskMaxMs": 92,
+ "layoutSwitchMedianMs": 29.19999999552965,
+ "loadMedianMs": 124,
+ "longestTaskMaxMs": 106,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -521,24 +521,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 115,
- "scriptRawBytes": 3264438,
+ "scriptRawBytes": 3265126,
"scriptRequestCount": 110,
- "totalRawBytes": 3604768
+ "totalRawBytes": 3605347
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 115,
- "scriptRawBytes": 3297083,
+ "scriptRawBytes": 3297778,
"scriptRequestCount": 110,
- "totalRawBytes": 3640816
+ "totalRawBytes": 3641401
},
- "routeReadyMedianMs": 1213.699999999255,
+ "routeReadyMedianMs": 1306.2999999970198,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -565,13 +565,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 111.80000000074506,
+ "domContentLoadedMedianMs": 123.10000000149012,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 79.69999999925494,
- "loadMedianMs": 111.89999999850988,
- "longestTaskMaxMs": 160,
+ "layoutSwitchMedianMs": 95.10000000149012,
+ "loadMedianMs": 123.30000000447035,
+ "longestTaskMaxMs": 197,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -581,24 +581,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746376,
- "otherRawBytes": 158131,
+ "otherRawBytes": 158022,
"requestCount": 115,
- "scriptRawBytes": 3264438,
+ "scriptRawBytes": 3265126,
"scriptRequestCount": 110,
- "totalRawBytes": 3604768
+ "totalRawBytes": 3605347
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753840,
- "otherRawBytes": 159713,
+ "otherRawBytes": 159603,
"requestCount": 115,
- "scriptRawBytes": 3297083,
+ "scriptRawBytes": 3297778,
"scriptRequestCount": 110,
- "totalRawBytes": 3640816
+ "totalRawBytes": 3641401
},
- "routeReadyMedianMs": 1388.8999999985099,
+ "routeReadyMedianMs": 1506.2999999970198,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -2852,7 +2852,10 @@
"source:src/workbench/widgets/layers/ControlLayerSettings.tsx",
"source:src/workbench/widgets/layers/ControlLayerWarningIcon.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",
"source:src/workbench/widgets/layers/LayerContextMenu.tsx",
"source:src/workbench/widgets/layers/LayerFilterControls.tsx",
"source:src/workbench/widgets/layers/LayerFilterOperationButton.tsx",
@@ -2867,6 +2870,7 @@
"source:src/workbench/widgets/layers/LayersTree.tsx",
"source:src/workbench/widgets/layers/LayersWidgetView.tsx",
"source:src/workbench/widgets/layers/RasterLayerFilterSection.tsx",
+ "source:src/workbench/widgets/layers/ReferenceImageSettings.tsx",
"source:src/workbench/widgets/layers/RegionalGuidanceSettings.tsx",
"source:src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx",
"source:src/workbench/widgets/layers/addLayerMenu.ts",
@@ -2874,6 +2878,8 @@
"source:src/workbench/widgets/layers/curveEditorMath.ts",
"source:src/workbench/widgets/layers/implementation.ts",
"source:src/workbench/widgets/layers/layerActionSession.ts",
+ "source:src/workbench/widgets/layers/layerChildRows.ts",
+ "source:src/workbench/widgets/layers/layerChildSelection.ts",
"source:src/workbench/widgets/layers/layerContextActions.ts",
"source:src/workbench/widgets/layers/layerContextMenuLayout.ts",
"source:src/workbench/widgets/layers/layerExportActions.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 4969369dd3..cdc5a25a6e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2593,7 +2593,9 @@
"showSelected": "Show selected",
"hideSelectedOnCanvas": "Hide selected on canvas",
"showSelectedOnCanvas": "Show selected on canvas",
- "toggleActive": "Toggle layer active"
+ "toggleActive": "Toggle layer active",
+ "hideModifiers": "Hide modifiers",
+ "showModifiers": "Show modifiers"
},
"control": {
"apply": "Apply",
@@ -3015,7 +3017,13 @@
"overviewPane": {
"pan": "Pan the canvas view"
},
- "treeTabs": "Layer panel views"
+ "treeTabs": "Layer panel views",
+ "modifiers": {
+ "disable": "Disable",
+ "enable": "Enable",
+ "parentDisabled": "Layer is disabled",
+ "toggleActive": "Toggle active"
+ }
},
"gallery": {
"alwaysShowDimensions": "Always show dimensions",
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
index af38d39e4c..05da1c0be2 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
@@ -127,6 +127,19 @@ describe('layer panel selection', () => {
expect(reconcileLayerPanelState(collapsed, 'p', index, 'a')).toBe(collapsed);
});
+ it('keeps a child-row focus while its owner exists and drops it with the owner', () => {
+ const focused = { ...createLayerPanelState('project', 'a'), focusId: 'child:b:ref1' };
+ expect(reconcileLayerPanelState(focused, 'project', indexOf(ids), 'a')).toBe(focused);
+ expect(reconcileLayerPanelState(focused, 'project', indexOf(['a', 'c']), 'a').focusId).toBe('a');
+ });
+
+ it('carries child-row collapse through a primary change and prunes removed owners', () => {
+ const collapsed = { ...createLayerPanelState('project', 'a'), collapsedChildLayerIds: ['a', 'gone'] };
+ expect(reconcileLayerPanelState(collapsed, 'project', indexOf(ids), 'b').collapsedChildLayerIds).toEqual(['a']);
+ expect(reconcileLayerPanelState(collapsed, 'project', indexOf(ids), 'a').collapsedChildLayerIds).toEqual(['a']);
+ expect(reconcileLayerPanelState(collapsed, 'other', indexOf(ids), 'b').collapsedChildLayerIds).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', indexOf(ids), 'd').selectedIds).toEqual(['d']);
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
index 99317b6e74..2042aeef00 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
@@ -18,6 +18,8 @@ export interface LayerPanelState {
readonly collapsedStacks: readonly LayerStackKind[];
/** Groups whose children the panel shows; every other group is collapsed. */
readonly expandedGroupIds: readonly string[];
+ /** Layers whose projected child rows are hidden; every other owner shows them. */
+ readonly collapsedChildLayerIds: readonly string[];
/** The row that holds keyboard focus (roving tabindex); falls back to the primary. */
readonly focusId: string | null;
/** A name filter; empty shows everything. */
@@ -25,9 +27,13 @@ export interface LayerPanelState {
}
/** Panel preferences that survive a primary change and a project switch. */
-type LayerPanelCarry = Pick<LayerPanelState, 'collapsedStacks' | 'expandedGroupIds' | 'filter'>;
+type LayerPanelCarry = Pick<
+ LayerPanelState,
+ 'collapsedStacks' | 'expandedGroupIds' | 'collapsedChildLayerIds' | 'filter'
+>;
const DEFAULT_CARRY: LayerPanelCarry = {
+ collapsedChildLayerIds: [],
collapsedStacks: [],
expandedGroupIds: [],
filter: '',
@@ -38,6 +44,18 @@ export interface LayerSelectionModifiers {
range: boolean;
}
+/** Tree key of a projected child row; the panel's focus state holds these beside node ids. */
+export const layerChildRowKey = (layerId: string, itemId: string): string => `child:${layerId}:${itemId}`;
+
+export const parseChildRowKey = (key: string): { layerId: string; itemId: string } | null => {
+ if (!key.startsWith('child:')) {
+ return null;
+ }
+ const rest = key.slice('child:'.length);
+ const separator = rest.indexOf(':');
+ return separator > 0 ? { itemId: rest.slice(separator + 1), layerId: rest.slice(0, separator) } : null;
+};
+
export interface LayerPanelSelectionUpdate {
projectId: string;
primaryId: string | null;
@@ -66,6 +84,7 @@ export const createLayerPanelState = (
});
const carryOf = (state: LayerPanelState): LayerPanelCarry => ({
+ collapsedChildLayerIds: state.collapsedChildLayerIds,
collapsedStacks: state.collapsedStacks,
expandedGroupIds: state.expandedGroupIds,
filter: state.filter,
@@ -82,7 +101,8 @@ export const isSameLayerPanelState = (left: LayerPanelState, right: LayerPanelSt
left.filter === right.filter &&
sameIds(left.selectedIds, right.selectedIds) &&
sameIds(left.collapsedStacks, right.collapsedStacks) &&
- sameIds(left.expandedGroupIds, right.expandedGroupIds);
+ sameIds(left.expandedGroupIds, right.expandedGroupIds) &&
+ sameIds(left.collapsedChildLayerIds, right.collapsedChildLayerIds);
const stateFor = (snapshot: LayerPanelStore, projectId: string, primaryId: string | null): LayerPanelState => {
const stored = snapshot.byProject[projectId];
@@ -147,6 +167,23 @@ export const setLayerGroupExpanded = (
write({ ...current, expandedGroupIds: [...next] });
};
+/** Shows or hides a layer's projected child rows; `collapsed` forces a state instead of toggling. */
+export const setLayerChildrenCollapsed = (
+ projectId: string,
+ primaryId: string | null,
+ layerId: string,
+ collapsed?: boolean
+): void => {
+ const current = readLayerPanelState(projectId, primaryId);
+ const next = new Set(current.collapsedChildLayerIds);
+ if (collapsed ?? !next.has(layerId)) {
+ next.add(layerId);
+ } else {
+ next.delete(layerId);
+ }
+ write({ ...current, collapsedChildLayerIds: [...next] });
+};
+
export const setLayerPanelFocus = (projectId: string, primaryId: string | null, focusId: string | null): void => {
const current = readLayerPanelState(projectId, primaryId);
if (current.focusId !== focusId) {
@@ -182,6 +219,7 @@ export const reconcileLayerPanelState = (
const carry = carryOf(state);
return createLayerPanelState(projectId, validPrimaryId, {
...carry,
+ collapsedChildLayerIds: carry.collapsedChildLayerIds.filter((id) => index.byId.has(id)),
collapsedStacks: primary
? carry.collapsedStacks.filter((stack) => stack !== primary.stack)
: carry.collapsedStacks,
@@ -192,21 +230,25 @@ export const reconcileLayerPanelState = (
}
const existing = index.byId;
const expandedGroupIds = state.expandedGroupIds.filter((id) => existing.has(id));
+ const collapsedChildLayerIds = state.collapsedChildLayerIds.filter((id) => existing.has(id));
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;
- const focusId = state.focusId && existing.has(state.focusId) ? state.focusId : validPrimaryId;
+ // A child-row focus survives while its owner exists; the panel falls back itself if the item is gone.
+ const focusOwnerId = state.focusId ? (parseChildRowKey(state.focusId)?.layerId ?? state.focusId) : null;
+ const focusId = state.focusId && focusOwnerId && existing.has(focusOwnerId) ? state.focusId : validPrimaryId;
if (
anchorId === state.anchorId &&
focusId === state.focusId &&
sameIds(selectedIds, state.selectedIds) &&
- sameIds(expandedGroupIds, state.expandedGroupIds)
+ sameIds(expandedGroupIds, state.expandedGroupIds) &&
+ sameIds(collapsedChildLayerIds, state.collapsedChildLayerIds)
) {
return state;
}
- return { ...state, anchorId, expandedGroupIds, focusId, selectedIds };
+ return { ...state, anchorId, collapsedChildLayerIds, expandedGroupIds, focusId, selectedIds };
};
/**
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx
new file mode 100644
index 0000000000..af6146e199
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx
@@ -0,0 +1,77 @@
+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' };
+
+const DOT_BASE = {
+ borderRadius: 'full',
+ borderWidth: '1px',
+ content: '""',
+ h: '3',
+ inset: '50% auto auto 50%',
+ 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();
+
+/**
+ * The rows' leading active-toggle dot: solid when contributing, outlined in
+ * accent when enabled but gated by an ancestor, plain when off. The wrapper
+ * keeps clicks and 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' : 'pointer'}
+ 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/LayerChildMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx
new file mode 100644
index 0000000000..454544be09
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx
@@ -0,0 +1,68 @@
+import type { ComponentProps } from 'react';
+
+import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { MenuContent } from '@platform/ui';
+import { CircleIcon, CircleOffIcon, XIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ProjectedChildRow } from './layerChildRows';
+import type { LayerRowCommands, LayerSurfaceAnchor } from './layerRowCommands';
+
+type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];
+
+/** The context menu of a projected child row: toggle it, or remove it. */
+export const LayerChildMenu = ({
+ anchor,
+ child,
+ commands,
+ editingLocked,
+ onClose,
+}: {
+ anchor: LayerSurfaceAnchor;
+ child: ProjectedChildRow;
+ commands: LayerRowCommands;
+ editingLocked: boolean;
+ onClose: () => void;
+}) => {
+ const { t } = useTranslation();
+ const positioning = useMemo<MenuPositioning>(
+ () => ({ getAnchorRect: () => anchor, placement: 'bottom-start' }),
+ [anchor]
+ );
+ const handleOpenChange = useCallback(
+ (details: { open: boolean }) => {
+ if (!details.open) {
+ onClose();
+ }
+ },
+ [onClose]
+ );
+ const handleToggle = useCallback(() => commands.setChildEnabled(child, !child.isEnabled), [child, commands]);
+ const handleRemove = useCallback(() => commands.removeChild(child), [child, commands]);
+
+ return (
+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="10rem">
+ <Menu.Item disabled={editingLocked} value="toggle" onSelect={handleToggle}>
+ <HStack gap="2">
+ <Icon as={child.isEnabled ? CircleOffIcon : CircleIcon} boxSize="3.5" color="fg.muted" />
+ <Text fontSize="xs">
+ {t(child.isEnabled ? 'widgets.layers.modifiers.disable' : 'widgets.layers.modifiers.enable')}
+ </Text>
+ </HStack>
+ </Menu.Item>
+ <Menu.Item color="fg.error" disabled={editingLocked} value="remove" onSelect={handleRemove}>
+ <HStack gap="2">
+ <Icon as={XIcon} boxSize="3.5" />
+ <Text fontSize="xs">{t('widgets.layers.regionalGuidance.removeReferenceImage')}</Text>
+ </HStack>
+ </Menu.Item>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
new file mode 100644
index 0000000000..5c313de1bd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
@@ -0,0 +1,162 @@
+import type { CSSProperties, KeyboardEvent, MouseEvent } from 'react';
+
+import { Box, Icon, Text } from '@chakra-ui/react';
+import { useDroppable } from '@dnd-kit/core';
+import { Row } from '@platform/ui';
+import { ImageIcon } from 'lucide-react';
+import { memo, useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ProjectedChildRow } from './layerChildRows';
+import type { LayerRowCommands } from './layerRowCommands';
+
+import { LayerActiveDot, ROW_SELECTION_FOCUS } from './LayerActiveDot';
+import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
+import { anchorFromPoint } from './layerRowCommands';
+
+const THUMBNAIL_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'cover', width: '100%' };
+
+interface LayerChildRowProps {
+ child: ProjectedChildRow;
+ commands: LayerRowCommands;
+ /** The owning layer travels in the current drag; the row dims with it. */
+ dimmed: boolean;
+ dragDisabled: boolean;
+ editingLocked: boolean;
+ focused: boolean;
+ selected: boolean;
+}
+
+/**
+ * One projected child row: a modifier the layer above owns, on the tree's
+ * roving tab stop. The dot toggles it, selecting it routes the Properties
+ * pane to its editor, and Delete removes it; hide/lock do not apply. The row
+ * registers a drop target so a layer drag over it lands below its owner.
+ */
+const LayerChildRowComponent = ({
+ child,
+ commands,
+ dimmed,
+ dragDisabled,
+ editingLocked,
+ focused,
+ selected,
+}: LayerChildRowProps) => {
+ const { t } = useTranslation();
+ const rowElement = useRef<HTMLDivElement | null>(null);
+ const { setNodeRef: setDropRef } = useDroppable({
+ data: { stack: child.stack },
+ disabled: dragDisabled,
+ id: child.key,
+ });
+ const setRowRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ rowElement.current = element;
+ setDropRef(element);
+ },
+ [setDropRef]
+ );
+ const name = `${t('widgets.layers.regionalGuidance.referenceImage')} ${child.posInSet}`;
+
+ 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 handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (event.target !== event.currentTarget) {
+ return;
+ }
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ commands.selectChild(child);
+ return;
+ }
+ commands.keyDown(child.key, event);
+ },
+ [child, commands]
+ );
+ const handleContextMenu = useCallback(
+ (event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ if (!selected) {
+ commands.selectChild(child, { reveal: false });
+ }
+ commands.openChildMenu(child, anchorFromPoint(event.clientX, event.clientY));
+ },
+ [child, commands, selected]
+ );
+
+ const muted = !child.isEnabled || !child.parentContributing;
+
+ return (
+ <Box
+ ref={setRowRef}
+ aria-label={name}
+ aria-level={child.depth + 2}
+ aria-posinset={child.posInSet}
+ aria-selected={selected}
+ aria-setsize={child.setSize}
+ data-layer-row-id={child.key}
+ h="full"
+ opacity={dimmed ? 0.4 : undefined}
+ pb="0.5"
+ role="treeitem"
+ rounded="sm"
+ tabIndex={focused ? 0 : -1}
+ _focusVisible={ROW_SELECTION_FOCUS}
+ onClick={handleSelect}
+ onContextMenu={handleContextMenu}
+ onFocus={handleFocus}
+ onKeyDown={handleKeyDown}
+ >
+ <Row
+ active={selected ? 'emphasized' : undefined}
+ alignItems="center"
+ display="flex"
+ gap="1.5"
+ h="full"
+ px="1.5"
+ style={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}
+ />
+ <Box
+ alignItems="center"
+ bg="bg.muted"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="6"
+ color="fg.muted"
+ display="flex"
+ flexShrink={0}
+ justifyContent="center"
+ overflow="hidden"
+ rounded="sm"
+ >
+ {child.image ? (
+ <img alt="" draggable={false} src={child.image.thumbnailUrl} style={THUMBNAIL_IMG_STYLE} />
+ ) : (
+ <Icon as={ImageIcon} boxSize="3" />
+ )}
+ </Box>
+ <Text color={muted ? 'fg.muted' : undefined} flex="1" fontSize="2xs" fontWeight="600" minW="0" truncate>
+ {name}
+ </Text>
+ </Row>
+ </Box>
+ );
+};
+
+export const LayerChildRow = memo(LayerChildRowComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index c3e0e1748e..a2512d3600 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -97,6 +97,7 @@ import {
copyRasterToRegionalGuidance,
copyRegionalGuidanceToInpaintMask,
createLayerId,
+ createRegionalReferenceImage,
fitLayerTransformToBbox,
getControlTransparencyEffectPatch,
getRegionalGuidanceAutoNegativePatch,
@@ -302,9 +303,11 @@ const LayerMenu = ({
hasWorkflowBindings: workflowAvailability.hasWorkflowBindings,
interactionLocked,
layer,
+ modelBase: base,
selectedIds,
}),
[
+ base,
hiddenByAncestor,
canDeleteSelection,
canGroup,
@@ -699,8 +702,26 @@ const LayerMenu = ({
[getActionLabel, layer, patchConfig]
);
+ const handleAddReferenceImage = useCallback(() => {
+ if (layer.type !== 'regional_guidance') {
+ return;
+ }
+ commitPrepared(t('widgets.layers.regionalGuidance.referenceImages'), (model) =>
+ model.prepare({
+ before: { layerType: 'regional_guidance', referenceImages: [...layer.referenceImages] },
+ config: {
+ layerType: 'regional_guidance',
+ referenceImages: [...layer.referenceImages, createRegionalReferenceImage(base)],
+ },
+ id: layer.id,
+ type: 'patch-config',
+ })
+ );
+ }, [base, commitPrepared, layer, t]);
+
const effects = useMemo<LayerContextActionEffects>(
() => ({
+ addReferenceImage: handleAddReferenceImage,
booleanMerge: handleBooleanRaster,
convertTo: (target) => {
const actionId: LayerContextActionId =
@@ -740,6 +761,7 @@ const LayerMenu = ({
[
convert,
getActionLabel,
+ handleAddReferenceImage,
handleBooleanRaster,
handleCopyTo,
handleCopyToClipboard,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
index c978986fa2..1a7bc49b43 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
@@ -1,9 +1,9 @@
import type { CanvasLayerContract, CanvasNodeContract, SemanticNode } from '@workbench/canvas-engine/api';
import type { FocusEvent, KeyboardEvent, MouseEvent } from 'react';
-import { Badge, Box, HStack, Icon, Input, Text } from '@chakra-ui/react';
+import { Badge, Box, chakra, HStack, Icon, Input, Text } from '@chakra-ui/react';
import { useDraggable, useDroppable } from '@dnd-kit/core';
-import { IconButton, Row, ToggleDot, Tooltip } from '@platform/ui';
+import { IconButton, Row, Tooltip } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { isGroupNode, isHideableLayer, isNodeHidden, isOverlayStack } from '@workbench/canvas-engine/api';
import {
@@ -23,6 +23,7 @@ import type { LayerRowCommands } from './layerRowCommands';
import type { LayerTreeRow } from './layerTreeRows';
import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';
+import { LayerActiveDot, ROW_SELECTION_FOCUS } from './LayerActiveDot';
import { recordLayerRowCommit } from './layerPanelDiagnostics';
import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
import { anchorFromPoint } from './layerRowCommands';
@@ -30,25 +31,8 @@ import { layerRowSummary } from './layerRowSummary';
import { LayerThumbnail, type LayerThumbnailEngine } from './LayerThumbnail';
import { layerTypeIcon } from './layerTypeIcon';
-const ROW_SELECTION_FOCUS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' };
const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';
-const VISIBILITY_DOT_BASE = {
- borderRadius: 'full',
- borderWidth: '1px',
- content: '""',
- h: '3',
- inset: '50% auto auto 50%',
- position: 'absolute',
- transform: 'translate(-50%, -50%)',
- transition: 'background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)',
- w: '3',
-};
-const VISIBILITY_DOT_CHECKED = { ...VISIBILITY_DOT_BASE, bg: 'accent.solid', borderColor: 'accent.solid' };
-/** Enabled on its own, but an ancestor keeps it out of the composite. */
-const VISIBILITY_DOT_GATED = { ...VISIBILITY_DOT_BASE, bg: 'transparent', borderColor: 'accent.solid' };
-const VISIBILITY_DOT_UNCHECKED = { ...VISIBILITY_DOT_BASE, bg: 'transparent', borderColor: 'border.emphasized' };
-const VISIBILITY_DOT_CHECKED_HOVER = { _before: { bg: 'accent.emphasized', borderColor: 'accent.emphasized' } };
-const VISIBILITY_DOT_UNCHECKED_HOVER = { _before: { borderColor: 'fg.muted' } };
+const CHEVRON_HOVER = { bg: 'bg.muted', color: 'fg' };
const THUMBNAIL_SIZE = '8';
@@ -56,6 +40,9 @@ const THUMBNAIL_SIZE = '8';
export type LayerRowDragState = 'source' | 'travelling' | null;
interface LayerRowProps {
+ /** Projected child rows the layer owns; a chevron appears above zero. */
+ childCount: number;
+ childrenExpanded: boolean;
commands: LayerRowCommands;
drag: LayerRowDragState;
/** Drag reordering is off: the editing lock or degraded mode. */
@@ -79,6 +66,8 @@ const stopPropagation = (event: { stopPropagation: () => void }): void => event.
* keyboard through the row's menu, so the tree stays a single tab stop.
*/
const LayerRowComponent = ({
+ childCount,
+ childrenExpanded,
commands,
drag,
dragDisabled,
@@ -153,6 +142,13 @@ const LayerRowComponent = ({
},
[commands, row.id]
);
+ const handleToggleChildren = useCallback(
+ (event: { stopPropagation: () => void }) => {
+ event.stopPropagation();
+ commands.toggleChildren(row.id);
+ },
+ [commands, row.id]
+ );
const handleToggleVisible = useCallback(
(checked: boolean) => commands.setEnabled(row.id, checked),
[commands, row.id]
@@ -263,7 +259,7 @@ const LayerRowComponent = ({
ref={setRowRef}
{...dragListeners}
aria-current={primary ? 'true' : undefined}
- aria-expanded={group ? row.expanded : undefined}
+ aria-expanded={group ? row.expanded : childCount > 0 ? childrenExpanded : undefined}
aria-label={node.name}
aria-level={vm.depth + 2}
aria-posinset={row.posInSet}
@@ -295,38 +291,15 @@ const LayerRowComponent = ({
style={indentStyle}
transition={LAYER_ROW_BACKGROUND_TRANSITION}
>
- <Box
- display="flex"
- flexShrink="0"
- onClick={stopPropagation}
- onMouseDown={keepRowFocus}
- onPointerDown={stopPropagation}
- >
- <ToggleDot
- _before={
- node.isEnabled
- ? disabledByAncestor
- ? VISIBILITY_DOT_GATED
- : VISIBILITY_DOT_CHECKED
- : VISIBILITY_DOT_UNCHECKED
- }
- _focusVisible={ROW_SELECTION_FOCUS}
- _hover={node.isEnabled ? VISIBILITY_DOT_CHECKED_HOVER : VISIBILITY_DOT_UNCHECKED_HOVER}
- bg="transparent"
- borderWidth="0"
- checked={node.isEnabled}
- cursor={editingLocked ? 'not-allowed' : 'pointer'}
- disabled={editingLocked}
- h="6"
- label={t('widgets.layers.actions.toggleActive')}
- position="relative"
- tabIndex={-1}
- tooltip={disabledByAncestor ? t('widgets.layers.actions.groupDisabled') : undefined}
- transition="none"
- w="6"
- onCheckedChange={handleToggleVisible}
- />
- </Box>
+ <LayerActiveDot
+ checked={node.isEnabled}
+ disabled={editingLocked}
+ gated={disabledByAncestor}
+ label={t('widgets.layers.actions.toggleActive')}
+ tooltip={disabledByAncestor ? t('widgets.layers.actions.groupDisabled') : undefined}
+ onCheckedChange={handleToggleVisible}
+ onKeepRowFocus={keepRowFocus}
+ />
{group ? (
<GroupPreview engine={engine} expanded={row.expanded} node={node} thumbnails={thumbnails} />
) : !thumbnails ? (
@@ -349,7 +322,9 @@ const LayerRowComponent = ({
<LayerThumbnail engine={engine} layer={layer!} />
</Box>
)}
- {/* The identity slot: a group's disclosure chevron and a layer's type glyph share one box. */}
+ {/* The identity slot: a group's disclosure chevron, or the layer's type
+ glyph — with a small modifier chevron stacked beneath it, Krita-style,
+ when the layer projects child rows. */}
{group ? (
<IconButton
aria-label={t(row.expanded ? 'widgets.layers.actions.collapseGroup' : 'widgets.layers.actions.expandGroup')}
@@ -370,8 +345,44 @@ const LayerRowComponent = ({
/>
</IconButton>
) : (
- <Box alignItems="center" boxSize="6" display="flex" flexShrink={0} justifyContent="center">
+ <Box
+ alignItems="center"
+ boxSize="6"
+ display="flex"
+ flexDirection="column"
+ flexShrink={0}
+ justifyContent="center"
+ >
<Icon as={layerTypeIcon(layer!)} boxSize="3" color="fg.subtle" />
+ {childCount > 0 ? (
+ <chakra.button
+ aria-label={t(
+ childrenExpanded ? 'widgets.layers.actions.hideModifiers' : 'widgets.layers.actions.showModifiers'
+ )}
+ alignItems="center"
+ color="fg.muted"
+ cursor="pointer"
+ display="flex"
+ h="3"
+ justifyContent="center"
+ rounded="xs"
+ tabIndex={-1}
+ type="button"
+ w="4"
+ _hover={CHEVRON_HOVER}
+ onClick={handleToggleChildren}
+ onMouseDown={keepRowFocus}
+ onPointerDown={stopPropagation}
+ >
+ <Icon
+ as={ChevronRightIcon}
+ boxSize="3"
+ transform={childrenExpanded ? 'rotate(90deg)' : undefined}
+ transitionDuration="fast"
+ transitionProperty="transform"
+ />
+ </chakra.button>
+ ) : null}
</Box>
)}
<Box
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
index a913a185c2..f2e7e27458 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
@@ -3,11 +3,13 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
import type { Dispatch } from 'react';
-import { getDocumentNode } from '@workbench/canvas-engine/api';
+import { getDocumentLayer, getDocumentNode } from '@workbench/canvas-engine/api';
import { useCallback, useMemo } from 'react';
-import type { LayerSurfaceAnchor } from './layerRowCommands';
+import type { ProjectedChildRow } from './layerChildRows';
+import type { LayerRowCommands, LayerSurfaceAnchor } from './layerRowCommands';
+import { LayerChildMenu } from './LayerChildMenu';
import { CanvasLayerContextMenu, type LayerContextMenuEngine } from './LayerContextMenu';
import { LayerGroupContextMenu, type LayerGroupContextMenuEngine } from './LayerGroupContextMenu';
import { LayerStackMenu } from './LayerStackMenu';
@@ -19,9 +21,11 @@ export type LayerSurfaceEngine = LayerContextMenuEngine &
/** What the panel currently shows beside a row, addressed by node id rather than owned by the row. */
export type LayerSurfaceRequest =
| { readonly kind: 'menu'; readonly id: string; readonly anchor: LayerSurfaceAnchor }
- | { readonly kind: 'stack-menu'; readonly stack: LayerStackKind; readonly anchor: LayerSurfaceAnchor };
+ | { readonly kind: 'stack-menu'; readonly stack: LayerStackKind; readonly anchor: LayerSurfaceAnchor }
+ | { readonly kind: 'child-menu'; readonly child: ProjectedChildRow; readonly anchor: LayerSurfaceAnchor };
interface LayerSurfaceHostProps {
+ commands: LayerRowCommands;
dispatch: Dispatch<CanvasProjectMutation>;
document: CanvasDocumentContractV3;
editingLocked: boolean;
@@ -36,6 +40,7 @@ interface LayerSurfaceHostProps {
* closes itself.
*/
export const LayerSurfaceHost = ({
+ commands,
dispatch,
document,
editingLocked,
@@ -43,7 +48,7 @@ export const LayerSurfaceHost = ({
surface,
onClose,
}: LayerSurfaceHostProps) => {
- const node = surface && surface.kind !== 'stack-menu' ? getDocumentNode(document, surface.id) : null;
+ const node = surface?.kind === 'menu' ? getDocumentNode(document, surface.id) : null;
const menuTarget = useMemo(
() =>
surface?.kind === 'menu' && node && node.type !== 'group'
@@ -52,6 +57,20 @@ export const LayerSurfaceHost = ({
[node, surface]
);
const handleMenuClose = useCallback(() => onClose(), [onClose]);
+ // The child menu labels and toggles the item's LIVE state, not its state at open.
+ const liveChild = useMemo(() => {
+ if (surface?.kind !== 'child-menu') {
+ return null;
+ }
+ const { child } = surface;
+ const owner = getDocumentLayer(document, child.layerId);
+ const item =
+ owner?.type === 'regional_guidance' ? owner.referenceImages.find((ref) => ref.id === child.itemId) : undefined;
+ if (!item) {
+ return null;
+ }
+ return item.isEnabled === child.isEnabled ? child : { ...child, isEnabled: item.isEnabled };
+ }, [document, surface]);
if (surface?.kind === 'stack-menu') {
return (
<LayerStackMenu
@@ -64,6 +83,20 @@ export const LayerSurfaceHost = ({
/>
);
}
+ if (surface?.kind === 'child-menu') {
+ if (!liveChild) {
+ return null;
+ }
+ return (
+ <LayerChildMenu
+ anchor={surface.anchor}
+ child={liveChild}
+ commands={commands}
+ editingLocked={editingLocked}
+ onClose={onClose}
+ />
+ );
+ }
if (surface && !node) {
return null;
}
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 364c267d1f..da2ecb6189 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
@@ -5,7 +5,7 @@ import type { Project } from '@workbench/projectContracts';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
-import { createDocumentModel, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { createDocumentModel, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/api';
import {
groupContract,
layerContract,
@@ -29,6 +29,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
+import { clearLayerChildSelection, getLayerChildSelection } from './layerChildSelection';
import { getLayerRowCommits, resetLayerRowCommits } from './layerPanelDiagnostics';
import { LAYER_PANEL_DEGRADE_THRESHOLD, LAYER_ROW_HEIGHT_PX } from './layerPanelRows';
import { LayersTree, type LayersTreeEngine } from './LayersTree';
@@ -66,8 +67,8 @@ vi.mock('./LayerStackHeader', () => ({
),
}));
vi.mock('./LayerSurfaceHost', () => ({
- LayerSurfaceHost: ({ surface }: { surface: { kind: string; id: string } | null }) => (
- <output data-testid="surface">{surface ? `${surface.kind}:${surface.id}` : 'none'}</output>
+ LayerSurfaceHost: ({ surface }: { surface: { kind: string; id?: string; child?: { key: string } } | null }) => (
+ <output data-testid="surface">{surface ? `${surface.kind}:${surface.child?.key ?? surface.id}` : 'none'}</output>
),
}));
@@ -85,15 +86,23 @@ void i18n.use(initReactI18next).init({
collapseGroup: 'Collapse group',
expandGroup: 'Expand group',
groupLocked: 'Locked by a group',
+ hideModifiers: 'Hide modifiers',
indent: 'Move into the group above',
outdent: 'Move out of the group',
rename: 'Rename',
reorder: 'Reorder layer',
select: 'Select {{name}}',
+ showModifiers: 'Show modifiers',
toggleLock: 'Toggle lock',
toggleActive: 'Toggle layer active',
toggleVisibility: 'Toggle visibility',
},
+ modifiers: { disable: 'Disable', enable: 'Enable', toggleActive: 'Toggle active' },
+ regionalGuidance: {
+ referenceImage: 'Reference image',
+ referenceImages: 'Reference images',
+ removeReferenceImage: 'Remove reference image',
+ },
groupSummary_one: '{{count}} layer',
groupSummary_other: '{{count}} layers',
groups: { raster: 'Raster Layers' },
@@ -116,6 +125,7 @@ const manyLayers = (count: number): CanvasNodeContract[] =>
let dispatchExternal: (mutation: CanvasProjectMutation) => void = () => undefined;
const thumbnailRequests = vi.fn();
const refusalChecks = vi.fn();
+const revealRequests = vi.fn();
const Harness = ({ initialNodes }: { initialNodes: CanvasNodeContract[] }) => {
const [project, setProject] = useState<Project>(() => {
@@ -183,13 +193,21 @@ const Harness = ({ initialNodes }: { initialNodes: CanvasNodeContract[] }) => {
editingLocked={false}
engine={engine}
panel={panel}
- onRevealProperties={() => undefined}
+ onRevealProperties={revealRequests}
projectId={PROJECT_ID}
stacks={stacks}
/>
<output data-testid="selected-layer" style={HIDDEN}>
{document.selectedLayerId ?? 'none'}
</output>
+ <output data-testid="regional-refs" style={HIDDEN}>
+ {(() => {
+ const layer = getDocumentLayer(document, 'rg');
+ return layer?.type === 'regional_guidance'
+ ? layer.referenceImages.map((ref) => `${ref.id}:${ref.isEnabled ? 'on' : 'off'}`).join(',') || 'empty'
+ : 'none';
+ })()}
+ </output>
<output data-testid="selected-layers" style={HIDDEN}>
{panel.selectedIds.join(',') || 'none'}
</output>
@@ -252,9 +270,11 @@ const centre = (element: Element) => {
beforeEach(() => {
clearLayerPanelStates();
+ clearLayerChildSelection();
resetLayerRowCommits();
thumbnailRequests.mockClear();
refusalChecks.mockClear();
+ revealRequests.mockClear();
});
afterEach(async () => {
@@ -531,6 +551,79 @@ describe('LayersTree selection, surfaces and structure', () => {
});
});
+describe('LayersTree projected child rows', () => {
+ const referenceImage = (id: string, isEnabled = true) => ({
+ config: {
+ beginEndStepPct: [0, 1] as [number, number],
+ clipVisionModel: 'ViT-H' as const,
+ image: null,
+ method: 'full' as const,
+ model: null,
+ type: 'ip_adapter' as const,
+ weight: 1,
+ },
+ id,
+ isEnabled,
+ });
+ const regionWithRefs = (): CanvasNodeContract[] => [
+ layerContract('rg', 'regional_guidance', {
+ name: 'Region',
+ referenceImages: [referenceImage('ref1'), referenceImage('ref2')],
+ }),
+ paint('r1', 'Raster'),
+ ];
+
+ it('renders one row per reference image with tree semantics, and the chevron hides them', async () => {
+ await renderTree(regionWithRefs());
+ const ref1 = treeitem('Reference image 1');
+ expect(ref1).toHaveAttribute('aria-level', '3');
+ expect(ref1).toHaveAttribute('aria-posinset', '1');
+ expect(ref1).toHaveAttribute('aria-setsize', '2');
+ expect(treeitem('Region')).toHaveAttribute('aria-expanded', 'true');
+ await act(() => userEvent.click(host!.querySelector('button[aria-label="Hide modifiers"]')!));
+ expect(host!.querySelector('[role="treeitem"][aria-label="Reference image 1"]')).toBeNull();
+ expect(treeitem('Region')).toHaveAttribute('aria-expanded', 'false');
+ await act(() => userEvent.click(host!.querySelector('button[aria-label="Show modifiers"]')!));
+ expect(treeitem('Reference image 2')).not.toBeNull();
+ });
+
+ it('toggles the item from the dot 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));
+ expect(output('regional-refs')).toBe('ref1:off,ref2:on');
+ expect(output('selected-layer')).toBe('none');
+ treeitem('Reference image 2').focus();
+ await act(() => userEvent.keyboard('{Delete}'));
+ expect(output('regional-refs')).toBe('ref1:off');
+ });
+
+ it('selecting a child selects its owner, records the sub-selection, and reveals Properties', async () => {
+ await renderTree(regionWithRefs());
+ await act(() => userEvent.click(treeitem('Reference image 2')));
+ expect(output('selected-layer')).toBe('rg');
+ expect(getLayerChildSelection()).toMatchObject({ itemId: 'ref2', layerId: 'rg' });
+ expect(revealRequests).toHaveBeenCalledWith('rg');
+ // Selecting a layer row clears the sub-selection again.
+ await act(() => userEvent.click(treeitem('Raster')));
+ expect(getLayerChildSelection()).toBeNull();
+ });
+
+ it('walks child rows from the keyboard and routes their context menu', async () => {
+ await renderTree(regionWithRefs());
+ treeitem('Region').focus();
+ await act(() => userEvent.keyboard('{ArrowRight}'));
+ expect(document.activeElement).toBe(treeitem('Reference image 1'));
+ await act(() => userEvent.keyboard('{ArrowLeft}'));
+ expect(document.activeElement).toBe(treeitem('Region'));
+ await act(() => userEvent.keyboard('{ArrowLeft}'));
+ expect(treeitem('Region')).toHaveAttribute('aria-expanded', 'false');
+ await act(() => userEvent.keyboard('{ArrowRight}{ArrowRight}'));
+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));
+ expect(output('surface')).toBe('child-menu:child:rg:ref1');
+ });
+});
+
describe('LayersTree list changes', () => {
it('survives the list shrinking under the virtual window and repairs focus onto the tab stop', async () => {
await renderTree(manyLayers(50));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 149d04e47e..e794c01a0c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -14,6 +14,7 @@ import { getDocumentIndex, getDocumentNode, lookupDocumentNodeState } from '@wor
import {
publishLayerPanelSelection,
selectLayerInPanel,
+ setLayerChildrenCollapsed,
setLayerGroupExpanded,
setLayerPanelFocus,
toggleLayerStackCollapsed,
@@ -27,6 +28,14 @@ import type { LayerRowCommands, LayerSurfaceAnchor } from './layerRowCommands';
import type { LayerStackRowsByKind } from './layerTreeRows';
import type { LayerStackActionsEngine } from './useLayerStackActions';
+import { LayerChildRow } from './LayerChildRow';
+import {
+ layerChildRowCommand,
+ layerChildRowKey,
+ projectLayerChildRows,
+ type ProjectedChildRow,
+} from './layerChildRows';
+import { clearLayerChildSelection, selectLayerChild, useLayerChildSelection } from './layerChildSelection';
import {
flattenPanelRows,
isHeaderKey,
@@ -36,6 +45,7 @@ import {
navigateTree,
panelRowHeight,
stackOfHeaderKey,
+ type PanelChildRowsSource,
type PanelRow,
} from './layerPanelRows';
import { clearLayerPropertiesRequest, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';
@@ -64,6 +74,8 @@ interface DragState {
readonly selectedCount: number;
readonly overId: string | null;
readonly overIsGroup: boolean;
+ /** The pointer sits on a projected child row; the drop is pinned below its owner. */
+ readonly overIsChild: boolean;
readonly edge: 'above' | 'inside' | 'below';
readonly depthOffset: number;
}
@@ -169,12 +181,29 @@ export const LayersTree = ({
[document, requestedId]
);
const forceOpen = useCallback((stack: LayerStackKind) => stack === requestedStack, [requestedStack]);
+ // A name filter matches layers; child rows sit out until it clears.
+ const childRowsSource = useMemo<PanelChildRowsSource | undefined>(
+ () =>
+ panel.filter.trim() === ''
+ ? { collapsedLayerIds: new Set(panel.collapsedChildLayerIds), rowsFor: (row) => projectLayerChildRows(row.vm) }
+ : undefined,
+ [panel.collapsedChildLayerIds, panel.filter]
+ );
const panelRows = useMemo(
- () => flattenPanelRows(stacks, panel.collapsedStacks, forceOpen),
- [forceOpen, panel.collapsedStacks, stacks]
+ () => flattenPanelRows(stacks, panel.collapsedStacks, forceOpen, childRowsSource),
+ [childRowsSource, forceOpen, panel.collapsedStacks, stacks]
);
// Every item, header or node, by its tree key.
const rowIndexByKey = useMemo(() => new Map(panelRows.map((row, index) => [row.key, index])), [panelRows]);
+ const childRowByKey = useMemo(
+ () => new Map(panelRows.flatMap((row) => (row.kind === 'child' ? [[row.key, row.child] as const] : []))),
+ [panelRows]
+ );
+ const childSelection = useLayerChildSelection();
+ const selectedChildKey =
+ childSelection && childSelection.projectId === projectId
+ ? layerChildRowKey(childSelection.layerId, childSelection.itemId)
+ : null;
const offsets = useMemo(() => {
const starts = new Float64Array(panelRows.length + 1);
panelRows.forEach((row, index) => {
@@ -245,10 +274,12 @@ export const LayersTree = ({
// Event handlers read the latest render through this ref, so the command handle never changes identity.
const latest = useRef({
allNodeIds,
+ childRowByKey,
commitPrepared,
dispatch,
document,
editingLocked,
+ onRevealProperties,
panel,
panelRows,
projectId,
@@ -259,10 +290,12 @@ export const LayersTree = ({
useLayoutEffect(() => {
latest.current = {
allNodeIds,
+ childRowByKey,
commitPrepared,
dispatch,
document,
editingLocked,
+ onRevealProperties,
panel,
panelRows,
projectId,
@@ -293,6 +326,21 @@ export const LayersTree = ({
const { commitPrepared: commit } = latest.current;
return commit(label, (model) => model.prepare(command));
}, []);
+ const removeChildRow = useCallback(
+ (child: ProjectedChildRow) => {
+ const command = layerChildRowCommand(latest.current.document, child, { type: 'remove' });
+ if (!command) {
+ return;
+ }
+ const { panel: current, projectId: project } = latest.current;
+ const outcome = runStructural(t('widgets.layers.regionalGuidance.removeReferenceImage'), command);
+ // The removed row's focus lands on its owner, not wherever the primary sits.
+ if (outcome.status === 'committed' && current.focusId === child.key) {
+ setLayerPanelFocus(project, current.primaryId, child.layerId);
+ }
+ },
+ [runStructural, t]
+ );
// One handle for every row and header; it reads the latest render through a ref so items never re-render for it.
const commands = useMemo<LayerRowCommands>(
@@ -305,19 +353,35 @@ export const LayersTree = ({
}
},
keyDown: (key, event: KeyboardEvent<HTMLElement>) => {
- const { document: currentDocument, panel: current, panelRows: rows, projectId: project } = latest.current;
+ const {
+ childRowByKey: childRows,
+ document: currentDocument,
+ panel: current,
+ panelRows: rows,
+ projectId: project,
+ } = latest.current;
+ const childRow = childRows.get(key);
if (isMenuKey(event)) {
event.preventDefault();
const anchor = anchorOfItem(scrollRef.current, key);
if (anchor) {
setSurface(
- isHeaderKey(key)
- ? { anchor, kind: 'stack-menu', stack: stackOfHeaderKey(key) }
- : { anchor, id: key, kind: 'menu' }
+ childRow
+ ? { anchor, child: childRow, kind: 'child-menu' }
+ : isHeaderKey(key)
+ ? { anchor, kind: 'stack-menu', stack: stackOfHeaderKey(key) }
+ : { anchor, id: key, kind: 'menu' }
);
}
return;
}
+ if (childRow && (event.key === 'Delete' || event.key === 'Backspace')) {
+ event.preventDefault();
+ if (!latest.current.editingLocked) {
+ removeChildRow(childRow);
+ }
+ return;
+ }
if (isHeaderKey(key)) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
@@ -389,7 +453,7 @@ export const LayersTree = ({
return;
} else if (event.key === 'F2') {
event.preventDefault();
- if (!latest.current.editingLocked) {
+ if (!latest.current.editingLocked && !childRow) {
setRenamingId(key);
}
return;
@@ -406,6 +470,10 @@ export const LayersTree = ({
setLayerGroupExpanded(project, current.primaryId, [navigation.expand], navigation.expanded);
return;
}
+ if ('expandChildren' in navigation) {
+ setLayerChildrenCollapsed(project, current.primaryId, navigation.expandChildren, !navigation.expanded);
+ return;
+ }
if ('collapseStack' in navigation) {
if (current.collapsedStacks.includes(navigation.collapseStack) !== navigation.collapsed) {
toggleLayerStackCollapsed(project, current.primaryId, navigation.collapseStack);
@@ -414,8 +482,10 @@ export const LayersTree = ({
}
focusItem(navigation.focus);
},
+ openChildMenu: (child, anchor: LayerSurfaceAnchor) => setSurface({ anchor, child, kind: 'child-menu' }),
openMenu: (id, anchor: LayerSurfaceAnchor) => setSurface({ anchor, id, kind: 'menu' }),
openStackMenu: (stack, anchor: LayerSurfaceAnchor) => setSurface({ anchor, kind: 'stack-menu', stack }),
+ removeChild: (child) => removeChildRow(child),
rename: (id, name) => runStructural(t('widgets.layers.actions.rename'), { id, patch: { name }, type: 'patch' }),
select: (id, modifiers: LayerSelectionModifiers) => {
const {
@@ -425,6 +495,7 @@ export const LayersTree = ({
projectId: project,
visibleRowIds: visible,
} = latest.current;
+ clearLayerChildSelection();
const next = selectLayerInPanel(current, id, modifiers.range ? visible : all, modifiers);
publishLayerPanelSelection(next);
setLayerPanelFocus(project, next.primaryId, id);
@@ -433,6 +504,27 @@ export const LayersTree = ({
send({ id: next.primaryId, type: 'setCanvasSelectedLayer' });
}
},
+ selectChild: (child, options) => {
+ const { dispatch: send, panel: current, projectId: project } = latest.current;
+ // The owner becomes the single selected layer, published before the
+ // dispatch so reconciliation keeps it.
+ publishLayerPanelSelection({ primaryId: child.layerId, projectId: project, selectedIds: [child.layerId] });
+ panelSelectedPrimary.current = child.layerId;
+ if (current.primaryId !== child.layerId) {
+ send({ id: child.layerId, type: 'setCanvasSelectedLayer' });
+ }
+ selectLayerChild(project, child.layerId, child.itemId);
+ setLayerPanelFocus(project, child.layerId, child.key);
+ if (options?.reveal !== false) {
+ latest.current.onRevealProperties(child.layerId);
+ }
+ },
+ setChildEnabled: (child, isEnabled) => {
+ const command = layerChildRowCommand(latest.current.document, child, { isEnabled, type: 'set-enabled' });
+ if (command) {
+ runStructural(t('widgets.layers.modifiers.toggleActive'), command);
+ }
+ },
setEnabled: (id, isEnabled) =>
runStructural(t('widgets.layers.actions.toggleActive'), {
type: 'set-enabled',
@@ -443,6 +535,10 @@ export const LayersTree = ({
setLocked: (id, isLocked) =>
runStructural(t('widgets.layers.actions.toggleLock'), { type: 'set-locked', updates: [{ id, isLocked }] }),
startRename: (id) => setRenamingId(id),
+ toggleChildren: (id) => {
+ const { panel: current, projectId: project } = latest.current;
+ setLayerChildrenCollapsed(project, current.primaryId, id);
+ },
toggleCollapse: (stack) => {
const { panel: current, projectId: project } = latest.current;
toggleLayerStackCollapsed(project, current.primaryId, stack);
@@ -455,7 +551,7 @@ export const LayersTree = ({
}
},
}),
- [focusItem, movingIds, runStructural, t]
+ [focusItem, movingIds, removeChildRow, runStructural, t]
);
const closeSurface = useCallback(() => {
@@ -579,12 +675,17 @@ export const LayersTree = ({
const current = dragRef.current;
const stack = args.active.data.current?.stack as LayerStackKind | undefined;
// Only a row of the same stack under the pointer counts: nothing snaps across stacks or gaps.
+ // A child row counts as its owner, so it is out whenever the owner travels.
return pointerWithin({
...args,
- droppableContainers: args.droppableContainers.filter(
- (container) =>
- container.data.current?.stack === stack && !(current?.travelling.has(String(container.id)) ?? false)
- ),
+ droppableContainers: args.droppableContainers.filter((container) => {
+ if (container.data.current?.stack !== stack) {
+ return false;
+ }
+ const id = String(container.id);
+ const owner = latest.current.childRowByKey.get(id)?.layerId ?? id;
+ return !(current?.travelling.has(owner) ?? false);
+ }),
});
}, []);
@@ -618,6 +719,7 @@ export const LayersTree = ({
depthOffset: 0,
edge: 'above',
overId: null,
+ overIsChild: false,
overIsGroup: false,
selectedCount: [...travelling].filter((id) => selected.has(id)).length,
stack,
@@ -634,13 +736,16 @@ export const LayersTree = ({
if (!current) {
return current;
}
- const edge = edgeOf(event.over?.rect, pointerY.current, current.overIsGroup);
+ const edge = current.overIsChild ? 'below' : edgeOf(event.over?.rect, pointerY.current, current.overIsGroup);
return current.depthOffset !== depthOffset || current.edge !== edge ? { ...current, depthOffset, edge } : current;
});
}, []);
const handleDragOver = useCallback(
(event: DragOverEvent) => {
- const overId = event.over ? String(event.over.id) : null;
+ const rawOverId = event.over ? String(event.over.id) : null;
+ // A child row stands in for its owner: the only landing beside it is below the owner.
+ const overChild = rawOverId ? childRowByKey.get(rawOverId) : undefined;
+ const overId = overChild ? overChild.layerId : rawOverId;
clearHoverTimer();
const current = dragRef.current;
const over =
@@ -649,10 +754,15 @@ export const LayersTree = ({
: undefined;
const overIsGroup = over?.vm.kind === 'group';
// The pointer may enter a row between move events; the edge follows the row it is over now.
- const edge = edgeOf(event.over?.rect, pointerY.current, overIsGroup);
+ const edge = overChild ? 'below' : edgeOf(event.over?.rect, pointerY.current, overIsGroup);
+ const overIsChild = overChild !== undefined;
setDrag((state) =>
- state && (state.overId !== overId || state.edge !== edge || state.overIsGroup !== overIsGroup)
- ? { ...state, edge, overId, overIsGroup }
+ state &&
+ (state.overId !== overId ||
+ state.edge !== edge ||
+ state.overIsGroup !== overIsGroup ||
+ state.overIsChild !== overIsChild)
+ ? { ...state, edge, overId, overIsChild, overIsGroup }
: state
);
if (over && over.vm.kind === 'group' && !over.expanded && over.vm.childCount > 0) {
@@ -662,7 +772,7 @@ export const LayersTree = ({
);
}
},
- [clearHoverTimer, primaryId, projectId, stacks]
+ [childRowByKey, clearHoverTimer, primaryId, projectId, stacks]
);
const target = useMemo((): LayerDropTarget | null => {
@@ -718,11 +828,16 @@ export const LayersTree = ({
if (target.beforeRowId) {
top = offsets[rowIndexByKey.get(target.beforeRowId)!]!;
} else {
+ // Below the stack's last node — and past any child rows it projects.
const last = stackRows[stackRows.length - 1]!;
- top = offsets[rowIndexByKey.get(last.id)! + 1]!;
+ let index = rowIndexByKey.get(last.id)!;
+ while (panelRows[index + 1]?.kind === 'child') {
+ index += 1;
+ }
+ top = offsets[index + 1]!;
}
return { left: target.depth * LAYER_TREE_INDENT_PX + 14, top };
- }, [drag, offsets, rowIndexByKey, stacks, target]);
+ }, [drag, offsets, panelRows, rowIndexByKey, stacks, target]);
const refusalReason = refusal
? t(
@@ -828,6 +943,8 @@ export const LayersTree = ({
<VirtualSlot key={item.key} size={item.size} start={item.start}>
{panelRow.kind === 'node' ? (
<LayerRow
+ childCount={panelRow.childCount}
+ childrenExpanded={panelRow.childrenExpanded}
commands={commands}
drag={dragStateOf(panelRow.row.id)}
dragDisabled={dragDisabled}
@@ -840,6 +957,16 @@ export const LayersTree = ({
selected={selectedSet.has(panelRow.row.id)}
thumbnails={!degraded}
/>
+ ) : panelRow.kind === 'child' ? (
+ <LayerChildRow
+ child={panelRow.child}
+ commands={commands}
+ dimmed={drag?.travelling.has(panelRow.child.layerId) ?? false}
+ dragDisabled={dragDisabled}
+ editingLocked={editingLocked}
+ focused={panelRow.key === focusKey}
+ selected={panelRow.key === selectedChildKey}
+ />
) : (
renderHeader(panelRow, false)
)}
@@ -897,6 +1024,7 @@ export const LayersTree = ({
</DragOverlay>
</Box>
<LayerSurfaceHost
+ commands={commands}
dispatch={dispatch}
document={document}
editingLocked={editingLocked}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 0e7e4f3cbe..1a3efeea0b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -16,6 +16,7 @@ import type { LayerSurfaceAnchor } from './layerRowCommands';
import type { LayerColorPaneLayout, LayerEditorPaneLayout, LayerTreeTabId } from './panes/editorPaneLayout';
import { LayerBlendRow } from './LayerBlendRow';
+import { reconcileLayerChildSelection } from './layerChildSelection';
import { LAYER_PANEL_DEGRADE_THRESHOLD } from './layerPanelRows';
import { useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';
import { anchorFromPoint } from './layerRowCommands';
@@ -57,6 +58,8 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {
const { selectedLayerId } = document;
const panel = useLayerPanelState(projectId, selectedLayerId);
+ // The sub-selection survives only while its owner stays the selected layer.
+ useEffect(() => reconcileLayerChildSelection(projectId, document), [document, projectId]);
const expandedGroupIds = useMemo(() => new Set(panel.expandedGroupIds), [panel.expandedGroupIds]);
// Keyed on the forests, so a selection or bbox change never rebuilds a row.
const stacks = useMemo(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx
new file mode 100644
index 0000000000..92d6e142ce
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.tsx
@@ -0,0 +1,445 @@
+import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
+import type { ModelConfig } from '@features/models';
+import type {
+ CanvasRegionalGuidanceLayerContract,
+ RegionalGuidanceIPAdapterMethod,
+ RegionalGuidanceReferenceImage,
+ RegionalGuidanceReferenceImageAsset,
+} from '@workbench/canvas-engine/api';
+import type { ChangeEvent, CSSProperties } from 'react';
+
+import { Box, createListCollection, HStack, IconButton, Input, Stack, Text } from '@chakra-ui/react';
+import { useDndMonitor } from '@dnd-kit/core';
+import { galleryImages, galleryTransfers } from '@features/gallery';
+import { invalidateGallery } from '@features/gallery/queries';
+import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';
+import { FluxReduxControls } from '@features/generation/components';
+import { useModelsSelector } from '@features/models';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { DropZone, Field, Select, Slider } from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
+import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { ImageIcon, XIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useSelectedModelBase } from './useSelectedModelBase';
+
+/**
+ * The dedicated Properties editor of one regional reference image — the view a
+ * Layers-tree sub-selection opens. The region's own settings never list these:
+ * the tree rows are the only inventory, their dot the only enable toggle, and
+ * their menu the removal path. Every edit commits the layer's whole
+ * `referenceImages` array through one `patch-config`.
+ */
+
+const IP_ADAPTER_METHODS: readonly RegionalGuidanceIPAdapterMethod[] = [
+ 'full',
+ 'style',
+ 'composition',
+ 'style_strong',
+ 'style_precise',
+];
+
+const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
+
+const COVER_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'cover', width: '100%' };
+
+const formatWeight = (value: number): string => value.toFixed(2);
+
+/** DnD droppable id for a specific region's reference-image slot (all-image gallery-item drop target). */
+export const referenceImageDropId = (layerId: string, refId: string): string =>
+ `regional-ref-image:${layerId}:${refId}`;
+
+interface ReferenceImageEditing {
+ commitReferenceImages(next: RegionalGuidanceReferenceImage[]): void;
+ setReferenceImageAsset(refId: string, image: RegionalGuidanceReferenceImageAsset | null): void;
+ uploadReferenceImageAsset(refId: string, file: File): void;
+}
+
+/**
+ * The commit surface for a region's reference images, plus the drag monitor
+ * that routes gallery-image drops onto the per-ref drop zones.
+ */
+const useReferenceImageEditing = (
+ engine: CanvasPreparedEngine | null,
+ layer: CanvasRegionalGuidanceLayerContract
+): ReferenceImageEditing => {
+ const { t } = useTranslation();
+ const commitPrepared = usePreparedCommit(engine);
+ const { notifications } = useWorkbenchCommands();
+ const queryClient = useQueryClient();
+ const referenceImages = layer.referenceImages;
+
+ const commitReferenceImages = useCallback(
+ (next: RegionalGuidanceReferenceImage[]) => {
+ commitPrepared(t('widgets.layers.regionalGuidance.referenceImages'), (model) =>
+ model.prepare({
+ before: { layerType: 'regional_guidance', referenceImages: [...referenceImages] },
+ config: { layerType: 'regional_guidance', referenceImages: next },
+ id: layer.id,
+ type: 'patch-config',
+ })
+ );
+ },
+ [commitPrepared, layer.id, referenceImages, t]
+ );
+
+ // Assigning the image goes through the same undo path as the other ref edits
+ // (`commitReferenceImages` → `updateCanvasLayerConfig`), so a drop/upload/clear
+ // is a single, undoable document change.
+ const setReferenceImageAsset = useCallback(
+ (refId: string, image: RegionalGuidanceReferenceImageAsset | null) => {
+ commitReferenceImages(
+ referenceImages.map((ref) => (ref.id === refId ? { ...ref, config: { ...ref.config, image } } : ref))
+ );
+ },
+ [commitReferenceImages, referenceImages]
+ );
+
+ const uploadReferenceImageAsset = useCallback(
+ (refId: string, file: File) => {
+ const owner = captureAccountScope();
+ void (async () => {
+ try {
+ const uploaded = await galleryTransfers.upload(file, 'none', { signal: owner.signal });
+ assertAccountScopeCurrent(owner);
+ setReferenceImageAsset(refId, uploaded);
+ void invalidateGallery(queryClient, owner);
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ notifications.reportError({
+ area: 'regional-guidance',
+ message: error instanceof Error ? error.message : String(error),
+ namespace: 'generation',
+ });
+ }
+ })();
+ },
+ [notifications, queryClient, setReferenceImageAsset]
+ );
+
+ // Routes all-image gallery-item drops to the ref slot the drop landed on.
+ useDndMonitor({
+ onDragEnd: (event) => {
+ const overId = event.over?.id;
+ const prefix = `regional-ref-image:${layer.id}:`;
+ if (typeof overId !== 'string' || !overId.startsWith(prefix)) {
+ return;
+ }
+ const data = event.active.data.current;
+ if (!isGalleryImageDragData(data)) {
+ return;
+ }
+ const refId = overId.slice(prefix.length);
+ const [first] = data.items;
+ void galleryImages.resolveMany([first.name]).then((images) => {
+ if (images[0]) {
+ setReferenceImageAsset(refId, images[0]);
+ }
+ });
+ },
+ });
+
+ return useMemo(
+ () => ({ commitReferenceImages, setReferenceImageAsset, uploadReferenceImageAsset }),
+ [commitReferenceImages, setReferenceImageAsset, uploadReferenceImageAsset]
+ );
+};
+
+type ModelCollection = ReturnType<typeof createListCollection<{ label: string; value: string }>>;
+
+interface ReferenceImageCollections {
+ fluxRedux: ModelCollection;
+ ipAdapter: ModelCollection;
+ method: ModelCollection;
+ models: readonly ModelConfig[];
+}
+
+/** The model/method option collections the editor selects from. */
+const useReferenceImageCollections = (): ReferenceImageCollections => {
+ const { t } = useTranslation();
+ const models = useModelsSelector((snapshot) => snapshot.models);
+ const base = useSelectedModelBase();
+
+ const ipAdapter = useMemo(
+ () =>
+ createListCollection({
+ items: models
+ .filter((model) => model.type === 'ip_adapter' && (!base || model.base === base))
+ .map((model) => ({ label: model.name, value: model.key })),
+ }),
+ [base, models]
+ );
+ const fluxRedux = useMemo(
+ () =>
+ createListCollection({
+ items: models
+ .filter((model) => model.type === 'flux_redux' && (!base || model.base === base))
+ .map((model) => ({ label: model.name, value: model.key })),
+ }),
+ [base, models]
+ );
+ const method = useMemo(
+ () =>
+ createListCollection({
+ items: IP_ADAPTER_METHODS.map((value) => ({
+ label: t(`widgets.layers.regionalGuidance.methods.${value}`),
+ value: value as string,
+ })),
+ }),
+ [t]
+ );
+
+ return useMemo(() => ({ fluxRedux, ipAdapter, method, models }), [fluxRedux, ipAdapter, method, models]);
+};
+
+/**
+ * Resolves the sub-selected reference image; renders nothing once the item is
+ * gone — the sub-selection reconciler hands the pane back to the layer.
+ */
+export const ReferenceImageSettings = ({
+ engine,
+ layer,
+ refId,
+}: {
+ engine: CanvasPreparedEngine | null;
+ layer: CanvasRegionalGuidanceLayerContract;
+ refId: string;
+}) => {
+ const index = layer.referenceImages.findIndex((ref) => ref.id === refId);
+ const referenceImage = layer.referenceImages[index];
+ if (!referenceImage) {
+ return null;
+ }
+ return <ReferenceImageEditor engine={engine} index={index} layer={layer} referenceImage={referenceImage} />;
+};
+
+const ReferenceImageEditor = ({
+ engine,
+ index,
+ layer,
+ referenceImage,
+}: {
+ engine: CanvasPreparedEngine | null;
+ index: number;
+ layer: CanvasRegionalGuidanceLayerContract;
+ referenceImage: RegionalGuidanceReferenceImage;
+}) => {
+ const { t } = useTranslation();
+ const editing = useReferenceImageEditing(engine, layer);
+ const collections = useReferenceImageCollections();
+ const { config } = referenceImage;
+ const referenceImages = layer.referenceImages;
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const { isOver, setNodeRef } = useGalleryImageDroppable({
+ data: { kind: 'regional-reference-image' },
+ id: referenceImageDropId(layer.id, referenceImage.id),
+ });
+
+ const replaceRef = useCallback(
+ (next: RegionalGuidanceReferenceImage) => {
+ editing.commitReferenceImages(referenceImages.map((entry, i) => (i === index ? next : entry)));
+ },
+ [editing, index, referenceImages]
+ );
+
+ const openUpload = useCallback(() => fileInputRef.current?.click(), []);
+
+ const handleFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+ if (file) {
+ editing.uploadReferenceImageAsset(referenceImage.id, file);
+ }
+ event.currentTarget.value = '';
+ },
+ [editing, referenceImage.id]
+ );
+
+ const handleClearImage = useCallback(
+ () => editing.setReferenceImageAsset(referenceImage.id, null),
+ [editing, referenceImage.id]
+ );
+
+ const handleModel = useCallback(
+ ({ value }: SelectValueChangeDetails) => {
+ if (config.type !== 'ip_adapter' && config.type !== 'flux_redux') {
+ return;
+ }
+ const key = value[0];
+ const model = collections.models.find((entry) => entry.key === key) ?? null;
+ const modelIdentity = model ? { base: model.base, key: model.key, name: model.name, type: model.type } : null;
+ replaceRef({ ...referenceImage, config: { ...config, model: modelIdentity } });
+ },
+ [collections.models, config, referenceImage, replaceRef]
+ );
+
+ const handleMethod = useCallback(
+ ({ value }: SelectValueChangeDetails) => {
+ if (config.type !== 'ip_adapter') {
+ return;
+ }
+ const method = value[0] as RegionalGuidanceIPAdapterMethod | undefined;
+ if (method) {
+ replaceRef({ ...referenceImage, config: { ...config, method } });
+ }
+ },
+ [config, referenceImage, replaceRef]
+ );
+
+ // Local live value while dragging the weight slider — the thumb tracks the
+ // pointer without pushing a history entry / re-committing the ref per tick. The
+ // single commit lands on drag end. `null` ⇒ not dragging (show the stored value).
+ const [liveWeight, setLiveWeight] = useState<number | null>(null);
+
+ const handleWeight = useCallback(({ value }: SliderValueChangeDetails) => {
+ const next = value[0];
+ if (next === undefined || !Number.isFinite(next)) {
+ return;
+ }
+ setLiveWeight(next);
+ }, []);
+
+ const handleWeightEnd = useCallback(
+ ({ value }: SliderValueChangeDetails) => {
+ const next = value[0];
+ setLiveWeight(null);
+ if (config.type !== 'ip_adapter' || next === undefined || !Number.isFinite(next)) {
+ return;
+ }
+ replaceRef({ ...referenceImage, config: { ...config, weight: next } });
+ },
+ [config, referenceImage, replaceRef]
+ );
+
+ const handleFluxReduxConfig = useCallback(
+ (nextConfig: RegionalGuidanceReferenceImage['config']) => {
+ replaceRef({ ...referenceImage, config: nextConfig });
+ },
+ [referenceImage, replaceRef]
+ );
+
+ const modelCollection = config.type === 'flux_redux' ? collections.fluxRedux : collections.ipAdapter;
+ const modelValue = useMemo(
+ () =>
+ config.type === 'ip_adapter' || config.type === 'flux_redux' ? (config.model ? [config.model.key] : []) : [],
+ [config]
+ );
+ const methodValue = useMemo(() => (config.type === 'ip_adapter' ? [config.method] : []), [config]);
+ const weightValue = useMemo(
+ () => (liveWeight !== null ? [liveWeight] : config.type === 'ip_adapter' ? [config.weight] : [1]),
+ [config, liveWeight]
+ );
+ const weightAria = useMemo(() => [t('widgets.layers.regionalGuidance.weight')], [t]);
+
+ const image = config.image;
+ const modelName =
+ 'model' in config && config.model ? config.model.name : t('widgets.layers.regionalGuidance.selectModel');
+
+ return (
+ <Stack gap="2">
+ <HStack align="flex-start" gap="2">
+ <DropZone
+ ref={setNodeRef}
+ borderStyle={image ? 'solid' : 'dashed'}
+ flexShrink="0"
+ h="16"
+ isOver={isOver}
+ overflow="hidden"
+ position="relative"
+ w="16"
+ >
+ <Box
+ as="button"
+ alignItems="center"
+ aria-label={t('widgets.layers.regionalGuidance.setReferenceImage')}
+ bg="bg.muted"
+ color="fg.muted"
+ cursor="pointer"
+ display="flex"
+ h="full"
+ justifyContent="center"
+ w="full"
+ onClick={openUpload}
+ >
+ {image ? (
+ <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />
+ ) : (
+ <ImageIcon size="20" />
+ )}
+ </Box>
+ {image ? (
+ <IconButton
+ aria-label={t('widgets.layers.regionalGuidance.clearReferenceImage')}
+ colorPalette="red"
+ position="absolute"
+ right="0.5"
+ size="2xs"
+ top="0.5"
+ variant="solid"
+ onClick={handleClearImage}
+ >
+ <XIcon />
+ </IconButton>
+ ) : null}
+ </DropZone>
+ <Text color="fg.muted" flex="1" fontSize="2xs" minW="0">
+ {t('widgets.layers.regionalGuidance.referenceImageHelp')}
+ </Text>
+ <Input ref={fileInputRef} accept="image/*" display="none" type="file" onChange={handleFileChange} />
+ </HStack>
+
+ <Field label={t('widgets.layers.regionalGuidance.model')}>
+ <Select
+ aria-label={t('widgets.layers.regionalGuidance.model')}
+ collection={modelCollection}
+ positioning={SELECT_POSITIONING}
+ size="xs"
+ value={modelValue}
+ valueText={modelName}
+ onValueChange={handleModel}
+ />
+ </Field>
+
+ {config.type === 'ip_adapter' ? (
+ <>
+ <Field label={t('widgets.layers.regionalGuidance.method')}>
+ <Select
+ aria-label={t('widgets.layers.regionalGuidance.method')}
+ collection={collections.method}
+ positioning={SELECT_POSITIONING}
+ size="xs"
+ value={methodValue}
+ valueText={t(`widgets.layers.regionalGuidance.methods.${config.method}`)}
+ onValueChange={handleMethod}
+ />
+ </Field>
+ <Field label={t('widgets.layers.regionalGuidance.weight')}>
+ <Slider
+ aria-label={weightAria}
+ formatValue={formatWeight}
+ max={2}
+ min={-1}
+ size="sm"
+ step={0.01}
+ value={weightValue}
+ withThumbTooltip
+ onValueChange={handleWeight}
+ onValueChangeEnd={handleWeightEnd}
+ />
+ </Field>
+ </>
+ ) : config.type === 'flux_redux' ? (
+ <FluxReduxControls config={config} disabled={false} onChange={handleFluxReduxConfig} />
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index 3bbee73924..20b434b00c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -1,39 +1,23 @@
-import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
-import type { ModelConfig } from '@features/models';
+import type { SelectValueChangeDetails } from '@chakra-ui/react';
import type {
CanvasMaskContract,
CanvasMaskFillContract,
CanvasRegionalGuidanceLayerContract,
- RegionalGuidanceIPAdapterMethod,
- RegionalGuidanceReferenceImage,
- RegionalGuidanceReferenceImageAsset,
} from '@workbench/canvas-engine/api';
import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
-import type { ChangeEvent, CSSProperties, FocusEvent } from 'react';
+import type { ChangeEvent, FocusEvent } from 'react';
-import { Box, createListCollection, HStack, IconButton, Input, Stack, Switch, Text } from '@chakra-ui/react';
-import { useDndMonitor } from '@dnd-kit/core';
-import { galleryImages, galleryTransfers } from '@features/gallery';
-import { invalidateGallery } from '@features/gallery/queries';
-import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';
-import { FluxReduxControls, PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';
-import { useModelsSelector } from '@features/models';
-import {
- assertAccountScopeCurrent,
- captureAccountScope,
- isAccountScopeCurrent,
-} from '@platform/state/accountLifecycle';
-import { Button, ColorPicker, DropZone, Field, Select, Slider, Tooltip } from '@platform/ui';
-import { useQueryClient } from '@tanstack/react-query';
+import { createListCollection, HStack, IconButton, Stack, Switch, Text } from '@chakra-ui/react';
+import { PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';
+import { Button, ColorPicker, Field, Select, Tooltip } from '@platform/ui';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';
import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { ImageIcon, PlusIcon, XIcon, PaletteIcon } from 'lucide-react';
+import { PaletteIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructuralPreview, createRegionalReferenceImage } from './layerOps';
+import { applyStructuralPreview } from './layerOps';
import { useSelectedModelBase } from './useSelectedModelBase';
/** The regional-guidance fields patchable via `updateCanvasLayerConfig`. */
@@ -42,7 +26,6 @@ interface RegionalConfigPatch {
positivePrompt?: string | null;
negativePrompt?: string | null;
autoNegative?: boolean;
- referenceImages?: RegionalGuidanceReferenceImage[];
}
/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */
@@ -55,51 +38,27 @@ const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
'vertical',
];
-const IP_ADAPTER_METHODS: readonly RegionalGuidanceIPAdapterMethod[] = [
- 'full',
- 'style',
- 'composition',
- 'style_strong',
- 'style_precise',
-];
-
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
-const COVER_IMG_STYLE: CSSProperties = { height: '100%', objectFit: 'cover', width: '100%' };
-
-const formatWeight = (value: number): string => value.toFixed(2);
-
const REGIONAL_PROMPT_HEIGHT_PX = 72;
-/** DnD droppable id for a specific region's reference-image slot (all-image gallery-item drop target). */
-const referenceImageDropId = (layerId: string, refId: string): string => `regional-ref-image:${layerId}:${refId}`;
-
-/**
- * A fresh regional reference image for the currently selected model's base. Shared
- * with the header add-layer menu via `layerOps.createRegionalReferenceImage`.
- */
-const createReferenceImage = (base: string | null): RegionalGuidanceReferenceImage =>
- createRegionalReferenceImage(base);
-
interface RegionalGuidanceSettingsProps {
engine: (CanvasStructuralEngine & CanvasPreparedEngine) | null;
layer: CanvasRegionalGuidanceLayerContract;
}
/**
- * Per-layer settings for a selected regional-guidance region (plan §1.3): a
- * positive + negative prompt, an Auto-Negative toggle, the mask fill colour/style
- * + invert, and a per-region reference-images section (add/remove/enable + model
- * + weight, mirroring the generate widget's IP-Adapter fields). Prompt/toggle/fill
- * edits go through the canvas undo stack as prepared `patch-config` edits;
- * invert is an engine pixel op.
+ * Per-layer settings for a selected regional-guidance region: a positive +
+ * negative prompt, an Auto-Negative toggle, and the mask fill colour/style +
+ * invert. Reference images are NOT listed here — they live as child rows in
+ * the Layers tree, each opening its own dedicated Properties editor
+ * (`ReferenceImageSettings`); the same policy applies to every future
+ * layer modifier. Prompt/toggle/fill edits go through the canvas undo stack
+ * as prepared `patch-config` edits; invert is an engine pixel op.
*/
export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {
const { t } = useTranslation();
const commitPrepared = usePreparedCommit(engine);
- const { notifications } = useWorkbenchCommands();
- const queryClient = useQueryClient();
- const models = useModelsSelector((snapshot) => snapshot.models);
const base = useSelectedModelBase();
const showSyntaxHighlighting = useWorkbenchPreferenceSelector(
(preferences) => preferences.showPromptSyntaxHighlighting
@@ -113,7 +72,6 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
const isFlux2 = base === 'flux2';
const isFluxFamily = isFlux || isFlux2;
const showNegativeControls = !isFluxFamily || Boolean(layer.negativePrompt) || layer.autoNegative;
- const showReferenceImages = !isFlux2 || layer.referenceImages.length > 0;
const commitConfig = useCallback(
(label: string, next: RegionalConfigPatch, before: RegionalConfigPatch) => {
@@ -244,117 +202,6 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
engine?.layers.invertMask(layer.id);
}, [engine, layer.id]);
- // Reference-image helpers ---------------------------------------------------
- const referenceImages = layer.referenceImages;
-
- const commitReferenceImages = useCallback(
- (next: RegionalGuidanceReferenceImage[]) => {
- commitConfig(
- t('widgets.layers.regionalGuidance.referenceImages'),
- { referenceImages: next },
- {
- referenceImages: referenceImages,
- }
- );
- },
- [commitConfig, referenceImages, t]
- );
-
- const handleAddReferenceImage = useCallback(() => {
- commitReferenceImages([...referenceImages, createReferenceImage(base)]);
- }, [base, commitReferenceImages, referenceImages]);
-
- // Assigning the image goes through the same undo path as the other ref edits
- // (`commitReferenceImages` → `updateCanvasLayerConfig`), so a drop/upload/clear
- // is a single, undoable document change.
- const setReferenceImageAsset = useCallback(
- (refId: string, image: RegionalGuidanceReferenceImageAsset | null) => {
- commitReferenceImages(
- referenceImages.map((ref) => (ref.id === refId ? { ...ref, config: { ...ref.config, image } } : ref))
- );
- },
- [commitReferenceImages, referenceImages]
- );
-
- const uploadReferenceImageAsset = useCallback(
- async (refId: string, file: File) => {
- const owner = captureAccountScope();
-
- try {
- const uploaded = await galleryTransfers.upload(file, 'none', { signal: owner.signal });
-
- assertAccountScopeCurrent(owner);
- setReferenceImageAsset(refId, uploaded);
- void invalidateGallery(queryClient, owner);
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notifications.reportError({
- area: 'regional-guidance',
- message: error instanceof Error ? error.message : String(error),
- namespace: 'generation',
- });
- }
- },
- [notifications, queryClient, setReferenceImageAsset]
- );
-
- // A single monitor routes all-image gallery-item drops to the region's ref slot the drop
- // landed on (each row registers a droppable keyed by layer + ref id).
- useDndMonitor({
- onDragEnd: (event) => {
- const overId = event.over?.id;
- const prefix = `regional-ref-image:${layer.id}:`;
- if (typeof overId !== 'string' || !overId.startsWith(prefix)) {
- return;
- }
- const data = event.active.data.current;
- if (!isGalleryImageDragData(data)) {
- return;
- }
- const refId = overId.slice(prefix.length);
- const [first] = data.items;
- void galleryImages.resolveMany([first.name]).then((images) => {
- if (images[0]) {
- setReferenceImageAsset(refId, images[0]);
- }
- });
- },
- });
-
- const ipAdapterModelCollection = useMemo(
- () =>
- createListCollection({
- items: models
- .filter((model) => model.type === 'ip_adapter' && (!base || model.base === base))
- .map((model) => ({ label: model.name, value: model.key })),
- }),
- [base, models]
- );
-
- const fluxReduxModelCollection = useMemo(
- () =>
- createListCollection({
- items: models
- .filter((model) => model.type === 'flux_redux' && (!base || model.base === base))
- .map((model) => ({ label: model.name, value: model.key })),
- }),
- [base, models]
- );
-
- const methodCollection = useMemo(
- () =>
- createListCollection({
- items: IP_ADAPTER_METHODS.map((method) => ({
- label: t(`widgets.layers.regionalGuidance.methods.${method}`),
- value: method as string,
- })),
- }),
- [t]
- );
-
const styleValue = useMemo(() => [fill.style], [fill.style]);
return (
@@ -444,311 +291,6 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
<Button disabled={!engine} size="xs" variant="outline" onClick={handleInvert}>
{t('widgets.layers.maskFill.invert')}
</Button>
-
- {showReferenceImages && (
- <Stack gap="2">
- <HStack justify="space-between">
- <Text fontSize="xs" fontWeight="medium">
- {t('widgets.layers.regionalGuidance.referenceImages')}
- </Text>
- {!isFlux2 && (
- <IconButton
- aria-label={t('widgets.layers.regionalGuidance.addReferenceImage')}
- size="2xs"
- variant="ghost"
- onClick={handleAddReferenceImage}
- >
- <PlusIcon />
- </IconButton>
- )}
- </HStack>
- {referenceImages.map((ref, index) => (
- <ReferenceImageRow
- dropId={referenceImageDropId(layer.id, ref.id)}
- index={index}
- ipAdapterModelCollection={ipAdapterModelCollection}
- fluxReduxModelCollection={fluxReduxModelCollection}
- key={ref.id}
- methodCollection={methodCollection}
- models={models}
- referenceImage={ref}
- referenceImages={referenceImages}
- onCommit={commitReferenceImages}
- onSetImage={setReferenceImageAsset}
- onUpload={uploadReferenceImageAsset}
- />
- ))}
- </Stack>
- )}
- </Stack>
- );
-};
-
-interface ReferenceImageRowProps {
- dropId: string;
- index: number;
- referenceImage: RegionalGuidanceReferenceImage;
- referenceImages: readonly RegionalGuidanceReferenceImage[];
- ipAdapterModelCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;
- fluxReduxModelCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;
- methodCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;
- models: readonly ModelConfig[];
- onCommit: (next: RegionalGuidanceReferenceImage[]) => void;
- onSetImage: (refId: string, image: RegionalGuidanceReferenceImageAsset | null) => void;
- onUpload: (refId: string, file: File) => void;
-}
-
-/**
- * One regional reference image: enable/remove, an image slot (gallery drop or
- * upload, mirroring the generate widget's mechanism), and the model + adapter
- * fields for its config kind — IP-Adapter (model/method/weight) for non-FLUX
- * regions, FLUX Redux (model/influence) for FLUX regions.
- */
-const ReferenceImageRow = ({
- dropId,
- index,
- ipAdapterModelCollection,
- fluxReduxModelCollection,
- methodCollection,
- models,
- referenceImage,
- referenceImages,
- onCommit,
- onSetImage,
- onUpload,
-}: ReferenceImageRowProps) => {
- const { t } = useTranslation();
- const { config } = referenceImage;
- const fileInputRef = useRef<HTMLInputElement | null>(null);
- const { isOver, setNodeRef } = useGalleryImageDroppable({
- data: { kind: 'regional-reference-image' },
- id: dropId,
- });
-
- const replaceRef = useCallback(
- (next: RegionalGuidanceReferenceImage) => {
- onCommit(referenceImages.map((entry, i) => (i === index ? next : entry)));
- },
- [index, onCommit, referenceImages]
- );
-
- const handleRemove = useCallback(() => {
- onCommit(referenceImages.filter((_, i) => i !== index));
- }, [index, onCommit, referenceImages]);
-
- const handleEnabled = useCallback(
- (details: { checked: boolean }) => {
- replaceRef({ ...referenceImage, isEnabled: details.checked });
- },
- [referenceImage, replaceRef]
- );
-
- const openUpload = useCallback(() => fileInputRef.current?.click(), []);
-
- const handleFileChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const file = event.currentTarget.files?.[0];
- if (file) {
- onUpload(referenceImage.id, file);
- }
- event.currentTarget.value = '';
- },
- [onUpload, referenceImage.id]
- );
-
- const handleClearImage = useCallback(() => onSetImage(referenceImage.id, null), [onSetImage, referenceImage.id]);
-
- const handleModel = useCallback(
- ({ value }: SelectValueChangeDetails) => {
- if (config.type !== 'ip_adapter' && config.type !== 'flux_redux') {
- return;
- }
- const key = value[0];
- const model = models.find((entry) => entry.key === key) ?? null;
- const modelIdentity = model ? { base: model.base, key: model.key, name: model.name, type: model.type } : null;
- replaceRef({ ...referenceImage, config: { ...config, model: modelIdentity } });
- },
- [config, models, referenceImage, replaceRef]
- );
-
- const handleMethod = useCallback(
- ({ value }: SelectValueChangeDetails) => {
- if (config.type !== 'ip_adapter') {
- return;
- }
- const method = value[0] as RegionalGuidanceIPAdapterMethod | undefined;
- if (method) {
- replaceRef({ ...referenceImage, config: { ...config, method } });
- }
- },
- [config, referenceImage, replaceRef]
- );
-
- // Local live value while dragging the weight slider — the thumb tracks the
- // pointer without pushing a history entry / re-committing the ref per tick. The
- // single commit lands on drag end. `null` ⇒ not dragging (show the stored value).
- const [liveWeight, setLiveWeight] = useState<number | null>(null);
-
- const handleWeight = useCallback(({ value }: SliderValueChangeDetails) => {
- const next = value[0];
- if (next === undefined || !Number.isFinite(next)) {
- return;
- }
- setLiveWeight(next);
- }, []);
-
- const handleWeightEnd = useCallback(
- ({ value }: SliderValueChangeDetails) => {
- const next = value[0];
- setLiveWeight(null);
- if (config.type !== 'ip_adapter' || next === undefined || !Number.isFinite(next)) {
- return;
- }
- replaceRef({ ...referenceImage, config: { ...config, weight: next } });
- },
- [config, referenceImage, replaceRef]
- );
-
- const handleFluxReduxConfig = useCallback(
- (nextConfig: RegionalGuidanceReferenceImage['config']) => {
- replaceRef({ ...referenceImage, config: nextConfig });
- },
- [referenceImage, replaceRef]
- );
-
- const modelCollection = config.type === 'flux_redux' ? fluxReduxModelCollection : ipAdapterModelCollection;
- const modelValue = useMemo(
- () =>
- config.type === 'ip_adapter' || config.type === 'flux_redux' ? (config.model ? [config.model.key] : []) : [],
- [config]
- );
- const methodValue = useMemo(() => (config.type === 'ip_adapter' ? [config.method] : []), [config]);
- const weightValue = useMemo(
- () => (liveWeight !== null ? [liveWeight] : config.type === 'ip_adapter' ? [config.weight] : [1]),
- [config, liveWeight]
- );
- const weightAria = useMemo(() => [t('widgets.layers.regionalGuidance.weight')], [t]);
-
- const image = config.image;
- const modelName =
- 'model' in config && config.model ? config.model.name : t('widgets.layers.regionalGuidance.selectModel');
-
- return (
- <Stack borderColor="border.subtle" borderWidth="1px" gap="2" p="2" rounded="md">
- <HStack justify="space-between">
- <Switch.Root checked={referenceImage.isEnabled} size="sm" onCheckedChange={handleEnabled}>
- <Switch.HiddenInput />
- <Switch.Control>
- <Switch.Thumb />
- </Switch.Control>
- <Switch.Label>
- <Text fontSize="xs">{`${t('widgets.layers.regionalGuidance.referenceImage')} ${index + 1}`}</Text>
- </Switch.Label>
- </Switch.Root>
- <IconButton
- aria-label={t('widgets.layers.regionalGuidance.removeReferenceImage')}
- size="2xs"
- variant="ghost"
- onClick={handleRemove}
- >
- <XIcon />
- </IconButton>
- </HStack>
-
- <HStack align="flex-start" gap="2">
- <DropZone
- ref={setNodeRef}
- borderStyle={image ? 'solid' : 'dashed'}
- flexShrink="0"
- h="16"
- isOver={isOver}
- overflow="hidden"
- position="relative"
- w="16"
- >
- <Box
- as="button"
- alignItems="center"
- aria-label={t('widgets.layers.regionalGuidance.setReferenceImage')}
- bg="bg.muted"
- color="fg.muted"
- cursor="pointer"
- display="flex"
- h="full"
- justifyContent="center"
- w="full"
- onClick={openUpload}
- >
- {image ? (
- <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />
- ) : (
- <ImageIcon size="20" />
- )}
- </Box>
- {image ? (
- <IconButton
- aria-label={t('widgets.layers.regionalGuidance.clearReferenceImage')}
- colorPalette="red"
- position="absolute"
- right="0.5"
- size="2xs"
- top="0.5"
- variant="solid"
- onClick={handleClearImage}
- >
- <XIcon />
- </IconButton>
- ) : null}
- </DropZone>
- <Text color="fg.muted" flex="1" fontSize="2xs" minW="0">
- {t('widgets.layers.regionalGuidance.referenceImageHelp')}
- </Text>
- <Input ref={fileInputRef} accept="image/*" display="none" type="file" onChange={handleFileChange} />
- </HStack>
-
- <Field label={t('widgets.layers.regionalGuidance.model')}>
- <Select
- aria-label={t('widgets.layers.regionalGuidance.model')}
- collection={modelCollection}
- positioning={SELECT_POSITIONING}
- size="xs"
- value={modelValue}
- valueText={modelName}
- onValueChange={handleModel}
- />
- </Field>
-
- {config.type === 'ip_adapter' ? (
- <>
- <Field label={t('widgets.layers.regionalGuidance.method')}>
- <Select
- aria-label={t('widgets.layers.regionalGuidance.method')}
- collection={methodCollection}
- positioning={SELECT_POSITIONING}
- size="xs"
- value={methodValue}
- valueText={t(`widgets.layers.regionalGuidance.methods.${config.method}`)}
- onValueChange={handleMethod}
- />
- </Field>
- <Field label={t('widgets.layers.regionalGuidance.weight')}>
- <Slider
- aria-label={weightAria}
- formatValue={formatWeight}
- max={2}
- min={-1}
- size="sm"
- step={0.01}
- value={weightValue}
- withThumbTooltip
- onValueChange={handleWeight}
- onValueChangeEnd={handleWeightEnd}
- />
- </Field>
- </>
- ) : config.type === 'flux_redux' ? (
- <FluxReduxControls config={config} disabled={false} onChange={handleFluxReduxConfig} />
- ) : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts
new file mode 100644
index 0000000000..ee53ed0292
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts
@@ -0,0 +1,115 @@
+import type { RegionalGuidanceReferenceImage } from '@workbench/canvas-engine/api';
+
+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { describe, expect, it } from 'vitest';
+
+import { layerChildRowCommand, layerChildRowKey, projectLayerChildRows } from './layerChildRows';
+import { buildLayerStackRows } from './layerTreeRows';
+
+const referenceImage = (id: string, overrides: Partial<RegionalGuidanceReferenceImage> = {}) => ({
+ config: {
+ beginEndStepPct: [0, 1] as [number, number],
+ clipVisionModel: 'ViT-H' as const,
+ image: null,
+ method: 'full' as const,
+ model: null,
+ type: 'ip_adapter' as const,
+ weight: 1,
+ },
+ id,
+ isEnabled: true,
+ ...overrides,
+});
+
+const regionalWith = (refs: RegionalGuidanceReferenceImage[], overrides = {}) =>
+ layerContract('rg1', 'regional_guidance', { referenceImages: refs, ...overrides });
+
+const rowsOf = (document: ReturnType<typeof documentFrom>, id = 'rg1') => {
+ const built = buildLayerStackRows(document.stacks, new Set());
+ return built.regional_guidance.rows.find((row) => row.id === id)!;
+};
+
+describe('projectLayerChildRows', () => {
+ it('projects one row per reference image, in order, with enablement and position facts', () => {
+ const withImage = referenceImage('ref2', {
+ config: { ...referenceImage('ref2').config, image: { imageName: 'img.png', thumbnailUrl: '/thumb.png' } },
+ isEnabled: false,
+ } as Partial<RegionalGuidanceReferenceImage>);
+ const document = documentFrom([regionalWith([referenceImage('ref1'), withImage])]);
+ const rows = projectLayerChildRows(rowsOf(document).vm);
+ expect(rows.map((row) => row.itemId)).toEqual(['ref1', 'ref2']);
+ expect(rows[0]).toMatchObject({
+ depth: 1,
+ image: null,
+ isEnabled: true,
+ key: layerChildRowKey('rg1', 'ref1'),
+ kind: 'reference-image',
+ layerId: 'rg1',
+ parentContributing: true,
+ posInSet: 1,
+ setSize: 2,
+ stack: 'regional_guidance',
+ });
+ expect(rows[1]).toMatchObject({
+ image: { imageName: 'img.png', thumbnailUrl: '/thumb.png' },
+ isEnabled: false,
+ posInSet: 2,
+ });
+ });
+
+ it('projects nothing for layers without reference images and for other layer types', () => {
+ const document = documentFrom([regionalWith([]), layerContract('r1'), layerContract('m1', 'inpaint_mask')]);
+ const built = buildLayerStackRows(document.stacks, new Set());
+ for (const stack of Object.values(built)) {
+ for (const row of stack.rows) {
+ expect(projectLayerChildRows(row.vm)).toEqual([]);
+ }
+ }
+ });
+
+ it('reports a disabled or ancestor-disabled parent as not contributing', () => {
+ const document = documentFrom([regionalWith([referenceImage('ref1')], { isEnabled: false })]);
+ expect(projectLayerChildRows(rowsOf(document).vm)[0]!.parentContributing).toBe(false);
+ });
+
+ it('returns the identical array for an unchanged node', () => {
+ const document = documentFrom([regionalWith([referenceImage('ref1')])]);
+ const vm = rowsOf(document).vm;
+ expect(projectLayerChildRows(vm)).toBe(projectLayerChildRows(vm));
+ });
+});
+
+describe('layerChildRowCommand', () => {
+ const target = { itemId: 'ref1', layerId: 'rg1' };
+
+ it('builds a patch-config toggling one item and leaving the others untouched', () => {
+ const document = documentFrom([regionalWith([referenceImage('ref1'), referenceImage('ref2')])]);
+ const command = layerChildRowCommand(document, target, { isEnabled: false, type: 'set-enabled' });
+ expect(command).toMatchObject({ id: 'rg1', type: 'patch-config' });
+ const config = command!.config as { referenceImages: RegionalGuidanceReferenceImage[] };
+ const before = command!.before as { referenceImages: RegionalGuidanceReferenceImage[] };
+ expect(config.referenceImages.map((ref) => [ref.id, ref.isEnabled])).toEqual([
+ ['ref1', false],
+ ['ref2', true],
+ ]);
+ expect(before.referenceImages.map((ref) => ref.isEnabled)).toEqual([true, true]);
+ // Untouched items keep identity; the toggled one is replaced, never mutated.
+ expect(config.referenceImages[1]).toBe(before.referenceImages[1]);
+ expect(before.referenceImages[0]!.isEnabled).toBe(true);
+ });
+
+ it('builds a removal that drops exactly the addressed item', () => {
+ const document = documentFrom([regionalWith([referenceImage('ref1'), referenceImage('ref2')])]);
+ const command = layerChildRowCommand(document, target, { type: 'remove' });
+ const config = command!.config as { referenceImages: RegionalGuidanceReferenceImage[] };
+ expect(config.referenceImages.map((ref) => ref.id)).toEqual(['ref2']);
+ });
+
+ it('returns null for a missing layer, a wrong-typed layer, a missing item, and a no-op toggle', () => {
+ const document = documentFrom([regionalWith([referenceImage('ref1')]), layerContract('r1')]);
+ expect(layerChildRowCommand(document, { itemId: 'ref1', layerId: 'gone' }, { type: 'remove' })).toBeNull();
+ expect(layerChildRowCommand(document, { itemId: 'ref1', layerId: 'r1' }, { type: 'remove' })).toBeNull();
+ expect(layerChildRowCommand(document, { itemId: 'gone', layerId: 'rg1' }, { type: 'remove' })).toBeNull();
+ expect(layerChildRowCommand(document, target, { isEnabled: true, type: 'set-enabled' })).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
new file mode 100644
index 0000000000..50a9e815f4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
@@ -0,0 +1,104 @@
+import type {
+ CanvasDocumentContractV3,
+ DocumentCommand,
+ LayerStackKind,
+ SemanticNode,
+} from '@workbench/canvas-engine/api';
+
+import { getDocumentLayer } from '@workbench/canvas-engine/api';
+import { layerChildRowKey } from '@workbench/layerPanelState';
+
+export { layerChildRowKey };
+
+/**
+ * The Layers panel's projected child rows: per-layer modifiers (reference
+ * images today) presented as rows beneath the layer that owns them. Rows are
+ * a pure projection of config the layer already carries — the document keeps
+ * its closed node union, and every edit round-trips through the same
+ * `patch-config` seam the Properties pane uses.
+ */
+
+export type LayerChildRowKind = 'reference-image';
+
+export interface ProjectedChildRow {
+ /** Tree key, also the row's DOM id: `child:{layerId}:{itemId}`. */
+ readonly key: string;
+ readonly kind: LayerChildRowKind;
+ readonly layerId: string;
+ readonly itemId: string;
+ readonly stack: LayerStackKind;
+ /** One level below the owning layer. */
+ readonly depth: number;
+ readonly posInSet: number;
+ readonly setSize: number;
+ readonly isEnabled: boolean;
+ /** The owning layer and its ancestors are enabled; a gated dot when not. */
+ readonly parentContributing: boolean;
+ readonly image: { readonly imageName: string; readonly thumbnailUrl: string } | null;
+}
+
+export type LayerChildRowAction = { type: 'set-enabled'; isEnabled: boolean } | { type: 'remove' };
+
+const EMPTY_CHILD_ROWS: readonly ProjectedChildRow[] = [];
+
+const childRowsByNode = new WeakMap<SemanticNode, readonly ProjectedChildRow[]>();
+
+/** The child rows a layer projects; the identical array while the node is unchanged. */
+export const projectLayerChildRows = (vm: SemanticNode): readonly ProjectedChildRow[] => {
+ const { node } = vm;
+ if (node.type !== 'regional_guidance' || node.referenceImages.length === 0) {
+ return EMPTY_CHILD_ROWS;
+ }
+ const cached = childRowsByNode.get(vm);
+ if (cached) {
+ return cached;
+ }
+ const setSize = node.referenceImages.length;
+ const rows = node.referenceImages.map((ref, index): ProjectedChildRow => ({
+ depth: vm.depth + 1,
+ image: ref.config.image
+ ? { imageName: ref.config.image.imageName, thumbnailUrl: ref.config.image.thumbnailUrl }
+ : null,
+ isEnabled: ref.isEnabled,
+ itemId: ref.id,
+ key: layerChildRowKey(node.id, ref.id),
+ kind: 'reference-image',
+ layerId: node.id,
+ parentContributing: vm.contributionEnabled,
+ posInSet: index + 1,
+ setSize,
+ stack: vm.stack,
+ }));
+ childRowsByNode.set(vm, rows);
+ return rows;
+};
+
+/**
+ * The document command a child-row action resolves to, or `null` when the
+ * layer or item is gone or the action changes nothing. Both sides of the patch
+ * carry the whole array, exactly as the Properties pane commits it.
+ */
+export const layerChildRowCommand = (
+ document: CanvasDocumentContractV3,
+ target: Pick<ProjectedChildRow, 'layerId' | 'itemId'>,
+ action: LayerChildRowAction
+): Extract<DocumentCommand, { type: 'patch-config' }> | null => {
+ const layer = getDocumentLayer(document, target.layerId);
+ if (layer?.type !== 'regional_guidance' || !layer.referenceImages.some((ref) => ref.id === target.itemId)) {
+ return null;
+ }
+ const before = layer.referenceImages;
+ const next =
+ action.type === 'remove'
+ ? before.filter((ref) => ref.id !== target.itemId)
+ : before.map((ref) => (ref.id === target.itemId ? { ...ref, isEnabled: action.isEnabled } : ref));
+ if (action.type === 'set-enabled' && before.every((ref, index) => next[index]!.isEnabled === ref.isEnabled)) {
+ return null;
+ }
+ return {
+ before: { layerType: 'regional_guidance', referenceImages: [...before] },
+ config: { layerType: 'regional_guidance', referenceImages: next },
+ id: target.layerId,
+ type: 'patch-config',
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.test.ts
new file mode 100644
index 0000000000..146c149173
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.test.ts
@@ -0,0 +1,54 @@
+import type { RegionalGuidanceReferenceImage } from '@workbench/canvas-engine/api';
+
+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ clearLayerChildSelection,
+ getLayerChildSelection,
+ reconcileLayerChildSelection,
+ selectLayerChild,
+} from './layerChildSelection';
+
+const referenceImage = (id: string): RegionalGuidanceReferenceImage => ({
+ config: {
+ beginEndStepPct: [0, 1],
+ clipVisionModel: 'ViT-H',
+ image: null,
+ method: 'full',
+ model: null,
+ type: 'ip_adapter',
+ weight: 1,
+ },
+ id,
+ isEnabled: true,
+});
+
+const documentWith = (refs: RegionalGuidanceReferenceImage[], selectedLayerId: string | null = 'rg1') =>
+ documentFrom([layerContract('rg1', 'regional_guidance', { referenceImages: refs })], selectedLayerId);
+
+describe('layer child selection', () => {
+ beforeEach(() => clearLayerChildSelection());
+
+ it('survives reconciliation while the owner is selected and the item exists', () => {
+ selectLayerChild('p', 'rg1', 'ref1');
+ reconcileLayerChildSelection('p', documentWith([referenceImage('ref1')]));
+ expect(getLayerChildSelection()).toMatchObject({ itemId: 'ref1', layerId: 'rg1' });
+ });
+
+ it('clears when the owner loses document selection or the item disappears', () => {
+ selectLayerChild('p', 'rg1', 'ref1');
+ reconcileLayerChildSelection('p', documentWith([referenceImage('ref1')], 'other'));
+ expect(getLayerChildSelection()).toBeNull();
+
+ selectLayerChild('p', 'rg1', 'ref1');
+ reconcileLayerChildSelection('p', documentWith([referenceImage('ref2')]));
+ expect(getLayerChildSelection()).toBeNull();
+ });
+
+ it("leaves another project's selection alone", () => {
+ selectLayerChild('other', 'rg1', 'ref1');
+ reconcileLayerChildSelection('p', documentWith([], null));
+ expect(getLayerChildSelection()).toMatchObject({ projectId: 'other' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.ts
new file mode 100644
index 0000000000..db2894027c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildSelection.ts
@@ -0,0 +1,50 @@
+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/api';
+
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+import { getDocumentLayer } from '@workbench/canvas-engine/api';
+
+/**
+ * The panel's sub-selection: the one projected child row being edited. Widget
+ * UI state, never document state — it creates no history, and it survives only
+ * while its owner stays the selected layer and the item still exists.
+ */
+export interface LayerChildSelection {
+ readonly projectId: string;
+ readonly layerId: string;
+ readonly itemId: string;
+}
+
+const store = createExternalStore<{ selection: LayerChildSelection | null }>({ selection: null });
+
+export const selectLayerChild = (projectId: string, layerId: string, itemId: string): void =>
+ store.setSnapshot({ selection: { itemId, layerId, projectId } });
+
+export const clearLayerChildSelection = (): void => {
+ if (store.getSnapshot().selection !== null) {
+ store.setSnapshot({ selection: null });
+ }
+};
+
+export const useLayerChildSelection = (): LayerChildSelection | null =>
+ store.useSelector((snapshot) => snapshot.selection, Object.is);
+
+export const getLayerChildSelection = (): LayerChildSelection | null => store.getSnapshot().selection;
+
+/** Clears a selection whose owner is no longer the selected layer or whose item is gone. */
+export const reconcileLayerChildSelection = (projectId: string, document: CanvasDocumentContractV3): void => {
+ const selection = store.getSnapshot().selection;
+ if (!selection || selection.projectId !== projectId) {
+ return;
+ }
+ if (document.selectedLayerId !== selection.layerId) {
+ clearLayerChildSelection();
+ return;
+ }
+ const layer = getDocumentLayer(document, selection.layerId);
+ if (layer?.type !== 'regional_guidance' || !layer.referenceImages.some((ref) => ref.id === selection.itemId)) {
+ clearLayerChildSelection();
+ }
+};
+
+registerAccountOwnedResource({ clear: clearLayerChildSelection, name: 'layer-child-selection' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 553f2d43a6..107c1d9068 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -82,12 +82,14 @@ const makeState = (
canDeleteSelection: true,
canMergeSelection: true,
layer,
+ modelBase: null,
selectedIds: [layer.id],
...overrides,
};
};
const makeEffects = (): LayerContextActionEffects => ({
+ addReferenceImage: vi.fn(),
booleanMerge: vi.fn(() => Promise.resolve()),
toggleHidden: vi.fn(),
copyTo: vi.fn(),
@@ -474,6 +476,7 @@ describe('getLayerContextActions', () => {
'convert-to-regional-guidance',
'control-transparency-effect',
'regional-auto-negative',
+ 'add-reference-image',
'merge-down',
'merge-selected',
'toggle-visibility',
@@ -487,6 +490,15 @@ describe('getLayerContextActions', () => {
expect([...new Set(actions.filter((action) => !action.isDisabled).map((action) => action.id))]).toEqual([]);
});
+ it('offers add-reference-image on regional layers unless the model base is flux2', () => {
+ const regional = makeLayer('regional_guidance');
+ expect(byId(getLayerContextActions(makeState(regional)), 'add-reference-image').isDisabled).toBe(false);
+ const flux2Actions = getLayerContextActions(makeState(regional, { modelBase: 'flux2' }));
+ expect(flux2Actions.some((action) => action.id === 'add-reference-image')).toBe(false);
+ const rasterActions = getLayerContextActions(makeState(makeLayer('raster')));
+ expect(rasterActions.some((action) => action.id === 'add-reference-image')).toBe(false);
+ });
+
it('still allows non-destructive copy and export from a locked layer when interaction is free', () => {
const actions = getLayerContextActions(makeState({ ...rasterLayer, isLocked: true }));
expect(byId(actions, 'copy-to-clipboard').isDisabled).toBe(false);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 3c491509d6..aa87489786 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -25,6 +25,7 @@ import {
EyeOffIcon,
FolderPlusIcon,
ImageIcon,
+ ImagePlusIcon,
LockIcon,
LockOpenIcon,
MergeIcon,
@@ -39,6 +40,7 @@ import {
import { canConvertRasterControl, canMergeLayerDown } from './layerOps';
export type LayerContextActionId =
+ | 'add-reference-image'
| 'merge-selected'
| 'move-to-front'
| 'move-forward'
@@ -90,6 +92,8 @@ export interface LayerContextActionState {
hasWorkflowBindings: boolean;
interactionLocked: boolean;
layer: CanvasLayerContract;
+ /** The selected generation model's base; gates model-dependent actions like reference images. */
+ modelBase: string | null;
/** The panel's selection; an action on a selected layer applies to every selected node. */
selectedIds: readonly string[];
/** The model's answer for grouping `actionTargets`, asked by the menu that owns the engine. */
@@ -123,6 +127,7 @@ export interface LayerContextActionEffects {
rasterize(): void;
convertTo(target: LayerType): void;
patchConfig(kind: LayerConfigPatchKind): void;
+ addReferenceImage(): void;
mergeDown(): void;
toggleVisibility(): void;
toggleHidden(): void;
@@ -484,6 +489,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'primary',
supportedLayerTypes: REGIONAL_ONLY,
},
+ {
+ defaultLabel: 'Add reference image',
+ handler: ({ effects }) => effects.addReferenceImage(),
+ icon: ImagePlusIcon,
+ id: 'add-reference-image',
+ isEnabled: isLayerMutable,
+ isVisible: (context) => context.modelBase !== 'flux2',
+ labelKey: 'widgets.layers.regionalGuidance.addReferenceImage',
+ order: 55,
+ section: 'primary',
+ supportedLayerTypes: REGIONAL_ONLY,
+ },
{
defaultLabel: 'Extract masked area',
handler: ({ effects }) => effects.extractMaskedArea(),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index a43bdb57be..e18e390dda 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -52,6 +52,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
canDeleteSelection: true,
canMergeSelection: true,
layer,
+ modelBase: null,
});
const layoutFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>
@@ -112,7 +113,7 @@ describe('getLayerContextMenuLayout', () => {
});
expect(summarize(regional)[1]).toEqual({
id: 'primary',
- items: ['rename', 'fit-to-bbox', 'regional-auto-negative'],
+ items: ['rename', 'fit-to-bbox', 'regional-auto-negative', 'add-reference-image'],
presentation: 'list',
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index 64e14591d1..7ca73ae46e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -253,9 +253,9 @@ export const createReferenceImageId = (): string =>
* actually consume: FLUX regions use FLUX Redux (the only kind resolved for FLUX
* in `resolveRegionalReferenceImages`), everything else uses an IP-Adapter (legacy
* `initialRegionalGuidanceIPAdapter`). The model is chosen by the user; the image
- * is assigned via drop/upload. Shared by `RegionalGuidanceSettings` (the in-popover
- * "add reference image" button) and the header add-layer menu's "Regional Reference
- * Image" item, so both mint the same shape.
+ * is assigned via drop/upload. Shared by the layer context menu's "Add reference
+ * image" action and the header add-layer menu's "Regional Reference Image" item,
+ * so both mint the same shape.
*/
export const createRegionalReferenceImage = (
base: string | null,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts
new file mode 100644
index 0000000000..bd49e51472
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.test.ts
@@ -0,0 +1,104 @@
+import type { RegionalGuidanceReferenceImage } from '@workbench/canvas-engine/api';
+
+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { describe, expect, it } from 'vitest';
+
+import type { PanelRow } from './layerPanelRows';
+
+import { projectLayerChildRows } from './layerChildRows';
+import { flattenPanelRows, navigateTree, panelRowHeight } from './layerPanelRows';
+import { buildLayerStackRows } from './layerTreeRows';
+
+const referenceImage = (id: string): RegionalGuidanceReferenceImage => ({
+ config: {
+ beginEndStepPct: [0, 1],
+ clipVisionModel: 'ViT-H',
+ image: null,
+ method: 'full',
+ model: null,
+ type: 'ip_adapter',
+ weight: 1,
+ },
+ id,
+ isEnabled: true,
+});
+
+/** regional: rg1[ref1, ref2], rg2 · raster: r1 */
+const stacks = () =>
+ buildLayerStackRows(
+ documentFrom([
+ layerContract('rg1', 'regional_guidance', { referenceImages: [referenceImage('ref1'), referenceImage('ref2')] }),
+ layerContract('rg2', 'regional_guidance'),
+ layerContract('r1'),
+ ]).stacks,
+ new Set()
+ );
+
+const open = () => false;
+
+const flatten = (collapsedLayerIds: ReadonlySet<string> = new Set()) =>
+ flattenPanelRows(stacks(), [], open, { collapsedLayerIds, rowsFor: (row) => projectLayerChildRows(row.vm) });
+
+const keys = (rows: readonly PanelRow[]) => rows.map((row) => row.key);
+
+describe('flattenPanelRows with child rows', () => {
+ it('inserts child rows after their layer, honoring per-layer collapse', () => {
+ expect(keys(flatten())).toEqual([
+ 'header:regional_guidance',
+ 'rg1',
+ 'child:rg1:ref1',
+ 'child:rg1:ref2',
+ 'rg2',
+ 'header:raster',
+ 'r1',
+ ]);
+ expect(keys(flatten(new Set(['rg1'])))).toEqual(['header:regional_guidance', 'rg1', 'rg2', 'header:raster', 'r1']);
+ });
+
+ it('marks owning rows with their child count and expansion, and leaves others bare', () => {
+ const rows = flatten();
+ const rg1 = rows.find((row) => row.key === 'rg1');
+ const rg2 = rows.find((row) => row.key === 'rg2');
+ expect(rg1).toMatchObject({ childCount: 2, childrenExpanded: true, kind: 'node' });
+ expect(rg2).toMatchObject({ childCount: 0, childrenExpanded: false });
+ expect(flatten(new Set(['rg1'])).find((row) => row.key === 'rg1')).toMatchObject({
+ childCount: 2,
+ childrenExpanded: false,
+ });
+ });
+
+ it('projects nothing without a child-rows source and sizes child rows below layer rows', () => {
+ expect(keys(flattenPanelRows(stacks(), [], open))).toEqual([
+ 'header:regional_guidance',
+ 'rg1',
+ 'rg2',
+ 'header:raster',
+ 'r1',
+ ]);
+ const child = flatten().find((row) => row.kind === 'child')!;
+ const node = flatten().find((row) => row.kind === 'node')!;
+ expect(panelRowHeight(child)).toBeLessThan(panelRowHeight(node));
+ });
+});
+
+describe('navigateTree over child rows', () => {
+ it('walks child rows vertically like any other row', () => {
+ const rows = flatten();
+ expect(navigateTree(rows, 'rg1', 'ArrowDown')).toEqual({ focus: 'child:rg1:ref1' });
+ expect(navigateTree(rows, 'child:rg1:ref2', 'ArrowDown')).toEqual({ focus: 'rg2' });
+ expect(navigateTree(rows, 'rg2', 'ArrowUp')).toEqual({ focus: 'child:rg1:ref2' });
+ });
+
+ it('ArrowRight expands then enters the children; ArrowLeft collapses or climbs to the layer', () => {
+ expect(navigateTree(flatten(new Set(['rg1'])), 'rg1', 'ArrowRight')).toEqual({
+ expandChildren: 'rg1',
+ expanded: true,
+ });
+ expect(navigateTree(flatten(), 'rg1', 'ArrowRight')).toEqual({ focus: 'child:rg1:ref1' });
+ expect(navigateTree(flatten(), 'rg1', 'ArrowLeft')).toEqual({ expandChildren: 'rg1', expanded: false });
+ expect(navigateTree(flatten(), 'child:rg1:ref2', 'ArrowLeft')).toEqual({ focus: 'rg1' });
+ expect(navigateTree(flatten(), 'child:rg1:ref1', 'ArrowRight')).toBeNull();
+ expect(navigateTree(flatten(), 'rg2', 'ArrowRight')).toBeNull();
+ expect(navigateTree(flatten(new Set(['rg1'])), 'rg1', 'ArrowLeft')).toEqual({ focus: 'header:regional_guidance' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
index 849cf5a2ee..63bbca9771 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
@@ -2,10 +2,12 @@ import type { LayerStackKind } from '@workbench/canvas-engine/api';
import { LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/api';
+import type { ProjectedChildRow } from './layerChildRows';
import type { LayerStackRows, LayerStackRowsByKind, LayerTreeRow } from './layerTreeRows';
/** Fixed row height: the virtualizer never measures. */
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;
@@ -22,7 +24,23 @@ export type PanelRow =
readonly posInSet: number;
readonly setSize: number;
}
- | { readonly kind: 'node'; readonly key: string; readonly stack: LayerStackKind; readonly row: LayerTreeRow };
+ | {
+ readonly kind: 'node';
+ readonly key: string;
+ readonly stack: LayerStackKind;
+ readonly row: LayerTreeRow;
+ /** Projected child rows the node owns; `0` for groups and bare leaves. */
+ readonly childCount: number;
+ readonly childrenExpanded: boolean;
+ }
+ | { readonly kind: 'child'; readonly key: string; readonly stack: LayerStackKind; readonly child: ProjectedChildRow };
+
+/** How a flattening projects child rows beneath the layers that own them. */
+export interface PanelChildRowsSource {
+ rowsFor(row: LayerTreeRow): readonly ProjectedChildRow[];
+ /** Layers whose child rows are hidden; every other owner shows them. */
+ collapsedLayerIds: ReadonlySet<string>;
+}
export const headerKey = (stack: LayerStackKind): string => `header:${stack}`;
@@ -38,7 +56,8 @@ export const stackOfHeaderKey = (key: string): LayerStackKind => key.slice('head
export const flattenPanelRows = (
stacks: LayerStackRowsByKind,
collapsedStacks: readonly LayerStackKind[],
- forceOpen: (stack: LayerStackKind) => boolean
+ forceOpen: (stack: LayerStackKind) => boolean,
+ childRows?: PanelChildRowsSource
): PanelRow[] => {
const rows: PanelRow[] = [];
const present = LAYER_STACKS_TOP_FIRST.filter((kind) => stacks[kind].nodeIds.length > 0);
@@ -55,7 +74,14 @@ export const flattenPanelRows = (
});
if (!collapsed) {
for (const row of stack.rows) {
- rows.push({ key: row.id, kind: 'node', row, stack: kind });
+ const children = childRows?.rowsFor(row) ?? [];
+ const childrenExpanded = children.length > 0 && !childRows!.collapsedLayerIds.has(row.id);
+ rows.push({ childCount: children.length, childrenExpanded, key: row.id, kind: 'node', row, stack: kind });
+ if (childrenExpanded) {
+ for (const child of children) {
+ rows.push({ child, key: child.key, kind: 'child', stack: kind });
+ }
+ }
}
}
}
@@ -63,13 +89,18 @@ export const flattenPanelRows = (
};
export const panelRowHeight = (row: PanelRow): number =>
- row.kind === 'header' ? LAYER_HEADER_HEIGHT_PX : LAYER_ROW_HEIGHT_PX;
+ row.kind === 'header'
+ ? LAYER_HEADER_HEIGHT_PX
+ : row.kind === 'child'
+ ? LAYER_CHILD_ROW_HEIGHT_PX
+ : LAYER_ROW_HEIGHT_PX;
export type TreeNavigationKey = 'ArrowDown' | 'ArrowUp' | 'Home' | 'End' | 'ArrowLeft' | 'ArrowRight';
export type TreeNavigation =
| { readonly focus: string }
| { readonly expand: string; readonly expanded: boolean }
+ | { readonly expandChildren: string; readonly expanded: boolean }
| { readonly collapseStack: LayerStackKind; readonly collapsed: boolean };
const positionsCache = new WeakMap<readonly PanelRow[], Map<string, number>>();
@@ -115,7 +146,17 @@ export const navigateTree = (
const first = rows[position + 1];
return first && first.kind === 'node' ? { focus: first.key } : null;
}
+ if (current.kind === 'child') {
+ return null;
+ }
const { row } = current;
+ if (current.childCount > 0) {
+ if (!current.childrenExpanded) {
+ return { expandChildren: row.id, expanded: true };
+ }
+ const first = rows[position + 1];
+ return first && first.kind === 'child' && first.child.layerId === row.id ? { focus: first.key } : null;
+ }
if (row.vm.kind !== 'group' || row.vm.childCount === 0) {
return null;
}
@@ -129,10 +170,16 @@ export const navigateTree = (
if (current.kind === 'header') {
return current.collapsed ? null : { collapsed: true, collapseStack: current.stack.stack };
}
+ if (current.kind === 'child') {
+ return { focus: current.child.layerId };
+ }
const { row } = current;
if (row.vm.kind === 'group' && row.expanded) {
return { expand: row.id, expanded: false };
}
+ if (current.childrenExpanded) {
+ return { expandChildren: row.id, expanded: false };
+ }
return { focus: row.vm.parentId ?? headerKey(row.vm.stack) };
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts
index 88525bfb74..28e8e91e1b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts
@@ -2,6 +2,8 @@ import type { LayerStackKind } from '@workbench/canvas-engine/api';
import type { LayerSelectionModifiers } from '@workbench/layerPanelState';
import type { KeyboardEvent } from 'react';
+import type { ProjectedChildRow } from './layerChildRows';
+
/** A point or box the surface host anchors a menu or popover to, in viewport pixels. */
export interface LayerSurfaceAnchor {
readonly x: number;
@@ -27,7 +29,18 @@ export interface LayerRowCommands {
openMenu(id: string, anchor: LayerSurfaceAnchor): void;
openStackMenu(stack: LayerStackKind, anchor: LayerSurfaceAnchor): void;
toggleCollapse(stack: LayerStackKind): void;
- /** `id` is a node id or a stack header key; the tree tells them apart. */
+ /** Shows or hides a layer's projected child rows. */
+ toggleChildren(id: string): void;
+ /**
+ * Sub-selects a child row: its owner becomes the selected layer and its
+ * editor opens in Properties, unless `reveal: false` (a context menu selects
+ * without yanking the pane open).
+ */
+ selectChild(child: ProjectedChildRow, options?: { reveal?: boolean }): void;
+ setChildEnabled(child: ProjectedChildRow, isEnabled: boolean): void;
+ removeChild(child: ProjectedChildRow): void;
+ openChildMenu(child: ProjectedChildRow, anchor: LayerSurfaceAnchor): void;
+ /** `id` is a node id, a child-row key, or a stack header key; the tree tells them apart. */
keyDown(id: string, event: KeyboardEvent<HTMLElement>): void;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index 750acb5a24..d0504309e8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -61,6 +61,7 @@ vi.mock('@workbench/WorkbenchContext', async () => {
const commands = { widgets: { patchValues } };
const queries = { getSnapshot: () => ({ activeProject: harness.project! }) };
return {
+ useActiveProjectId: () => harness.project!.id,
useActiveProjectSelector: (selector: (project: Project) => unknown) => {
const project = useSyncExternalStore(subscribe, () => harness.project!);
return selector(project);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
index 40e84151a3..a0525f6658 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
@@ -8,9 +8,11 @@ import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit
import { AdjustmentsPopover } from '@workbench/widgets/layers/AdjustmentsPopover';
import { ControlLayerSettings } from '@workbench/widgets/layers/ControlLayerSettings';
import { InpaintMaskSettings } from '@workbench/widgets/layers/InpaintMaskSettings';
+import { useLayerChildSelection } from '@workbench/widgets/layers/layerChildSelection';
import { RasterLayerFilterSection } from '@workbench/widgets/layers/RasterLayerFilterSection';
+import { ReferenceImageSettings } from '@workbench/widgets/layers/ReferenceImageSettings';
import { RegionalGuidanceSettings } from '@workbench/widgets/layers/RegionalGuidanceSettings';
-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -37,14 +39,30 @@ export const LayerSection = ({ disabled }: { disabled: boolean }) => {
const engine = useCanvasEngine();
const layer = useActiveProjectSelector(selectSelectedLayer);
const documentRevision = useActiveProjectSelector((project) => project.canvas.documentRevision);
+ // A sub-selected child row takes over the section: its own editor, its own name.
+ const projectId = useActiveProjectId();
+ const childSelection = useLayerChildSelection();
+ const childIndex =
+ layer?.type === 'regional_guidance' &&
+ childSelection?.projectId === projectId &&
+ childSelection.layerId === layer.id
+ ? layer.referenceImages.findIndex((ref) => ref.id === childSelection.itemId)
+ : -1;
+ const childRefId = childIndex >= 0 ? childSelection!.itemId : null;
return (
<PropertiesSection
disabled={disabled}
- subtitle={layer?.name ?? t('widgets.transform.noSelection')}
+ subtitle={
+ childRefId
+ ? `${t('widgets.layers.regionalGuidance.referenceImage')} ${childIndex + 1}`
+ : (layer?.name ?? t('widgets.transform.noSelection'))
+ }
title={t('widgets.properties.sections.layer')}
>
- {layer ? (
+ {layer?.type === 'regional_guidance' && childRefId ? (
+ <ReferenceImageSettings key={`${layer.id}:${childRefId}`} engine={engine} layer={layer} refId={childRefId} />
+ ) : layer ? (
<LayerTypeSettings documentRevision={documentRevision} engine={engine} layer={layer} />
) : (
<GroupSelectedNotice />