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): export raster groups as PSD folders

Josh Corbett9ded96a4d45d
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 1aa8c66089..1116dc916b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -136,7 +136,7 @@ Undo removes the accepted layer and restores the prior selection. Redo restores
## PSD export
-PSD export is a planner/executor transaction over immutable snapshots. `PsdExportController` captures one `CanvasDocumentSnapshot`, plans exportable raster layers and their transformed world-space bounds, then obtains a `CanvasRasterSnapshot` including disabled layers. Execution reads only those detached surfaces; it cannot mix live layer caches from different document generations.
+PSD export is a planner/executor transaction over immutable snapshots. `PsdExportController` captures one `CanvasDocumentSnapshot`, walks the raster tree into planner inputs (groups as pass-through folders, exportable leaves with their captured content rects), then obtains a `CanvasRasterSnapshot` including disabled layers. `planPsdExport` reverses every level of the top-first tree into ag-psd's bottom-to-top order, writes each node's own visibility flag (a disabled group is a hidden folder), and flattens the merged preview from the leaves that contribute (enabled with every ancestor enabled), which is what Photoshop renders for the same flags. Folders whose subtree exports nothing are dropped. Execution reads only the detached surfaces; it cannot mix live layer caches from different document generations.
The controller retains the 30,000-pixel side cap and also derives a pixel-area limit from currently available reserved bytes. It accounts for the flattened composite plus each transformed layer surface, budgets eight bytes per required pixel, and reserves the full execution allocation before creating PSD surfaces. A final freshness check occurs before that reservation; once execution starts it uses only frozen pixels. Capture and execution reservations are released in `finally`, and cancellation aborts before the next allocation or side effect.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
index 96429204e2..85a286e1fd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
@@ -1,10 +1,11 @@
import type {
- CanvasDocumentContractV2,
+ CanvasDocumentContractV3,
CanvasLayerSourceContract,
CanvasRasterLayerContractV2,
} from '@workbench/canvas-engine/contracts';
import type { Mat2d } from '@workbench/canvas-engine/types';
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';
@@ -45,13 +46,13 @@ const rasterLayer = (
...overrides,
});
-const documentWith = (layers: CanvasRasterLayerContractV2[]): CanvasDocumentContractV2 => ({
+const documentWith = (layers: CanvasRasterLayerContractV2[]): CanvasDocumentContractV3 => ({
background: 'transparent',
bbox: { height: 8, width: 8, x: 0, y: 0 },
height: 8,
- layers,
+ stacks: stacksFrom(layers),
selectedLayerId: layers[0]?.id ?? null,
- version: 2,
+ version: 3,
width: 8,
});
@@ -190,21 +191,28 @@ describe('real browser raster acceptance', () => {
expectPixel(surface, 0, 0, [0, 0, 255, 255]);
});
- it('round-trips a small real PSD with layer and composite pixels', async () => {
+ it('round-trips a small real PSD with a folder, layer pixels and a merged preview of the contributing leaves', async () => {
const backend = createDomRasterBackend();
- const layerSurface = backend.createSurface(2, 2);
- layerSurface.ctx.fillStyle = '#ff0000';
- layerSurface.ctx.fillRect(0, 0, 2, 2);
+ const fill = (color: string) => {
+ const surface = backend.createSurface(2, 2);
+ surface.ctx.fillStyle = color;
+ surface.ctx.fillRect(0, 0, 2, 2);
+ return surface;
+ };
+ const surfaces = { blue: fill('#0000ff'), red: fill('#ff0000') };
+ const leaf = (id: string, name: string) => ({
+ blendMode: 'normal' as const,
+ contentRect: { height: 2, width: 2, x: 0, y: 0 },
+ id,
+ isEnabled: true,
+ name,
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ });
+ // A disabled folder above the red base: its blue leaf is exported but stays out of the preview.
const plan = planPsdExport([
- {
- blendMode: 'normal',
- contentRect: { height: 2, width: 2, x: 0, y: 0 },
- id: 'red',
- isEnabled: true,
- name: 'Red',
- opacity: 1,
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- },
+ { children: [leaf('blue', 'Blue')], id: 'g', isEnabled: false, name: 'Group', type: 'group' },
+ leaf('red', 'Red'),
]);
let bytes: ArrayBuffer | null = null;
@@ -213,10 +221,10 @@ describe('real browser raster acceptance', () => {
download: (data) => {
bytes = data;
},
- getLayerSurface: () =>
+ getLayerSurface: (id) =>
Promise.resolve({
rect: { height: 2, width: 2, x: 0, y: 0 },
- surface: layerSurface,
+ surface: surfaces[id as keyof typeof surfaces],
}),
});
@@ -225,8 +233,11 @@ describe('real browser raster acceptance', () => {
const parsed = readPsd(bytes!, { useImageData: true });
expect(parsed.width).toBe(2);
expect(parsed.height).toBe(2);
- expect(parsed.children?.map((child) => child.name)).toEqual(['Red']);
+ expect(parsed.children?.map((child) => child.name)).toEqual(['Red', 'Group']);
+ expect(parsed.children![1]).toMatchObject({ hidden: true });
+ expect(parsed.children![1]!.children?.map((child) => child.name)).toEqual(['Blue']);
expect(Array.from(parsed.imageData!.data.slice(0, 4))).toEqual([255, 0, 0, 255]);
expect(Array.from(parsed.children![0]!.imageData!.data.slice(0, 4))).toEqual([255, 0, 0, 255]);
+ expect(Array.from(parsed.children![1]!.children![0]!.imageData!.data.slice(0, 4))).toEqual([0, 0, 255, 255]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts
index 136fd73557..9a79a7eb74 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.test.ts
@@ -1,22 +1,24 @@
import type { CanvasDocumentSnapshot } from '@workbench/canvas-engine/capabilities';
import type {
- CanvasDocumentContractV2,
+ CanvasDocumentContractV3,
CanvasRasterLayerContractV2,
- CanvasStateContractV2,
+ CanvasStateContractV3,
} from '@workbench/canvas-engine/contracts';
import type { ExecutePsdExportDeps, PsdExportPlan } from '@workbench/canvas-engine/export/psdExport';
import type { CanvasRasterSnapshot } from '@workbench/canvas-engine/rasterTransactions';
+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import { describe, expect, it, vi } from 'vitest';
import { derivePsdPixelAreaLimit, PSD_ALLOCATION_BYTES_PER_PIXEL, PsdExportController } from './psdExportController';
-const document: CanvasDocumentContractV2 = {
+const document: CanvasDocumentContractV3 = {
background: 'transparent',
bbox: { height: 100, width: 100, x: 0, y: 0 },
height: 100,
- layers: [
+ stacks: stacksFrom([
{
blendMode: 'normal',
id: 'layer',
@@ -28,13 +30,13 @@ const document: CanvasDocumentContractV2 = {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
},
- ],
+ ]),
selectedLayerId: null,
- version: 2,
+ version: 3,
width: 100,
};
-const canvas: CanvasStateContractV2 = {
+const canvas: CanvasStateContractV3 = {
document,
documentRevision: 0,
snapshots: [],
@@ -46,10 +48,10 @@ const canvas: CanvasStateContractV2 = {
pendingImages: [],
selectedImageIndex: 0,
},
- version: 2,
+ version: 3,
};
-const canvasWithDocument = (nextDocument: CanvasDocumentContractV2): CanvasStateContractV2 => ({
+const canvasWithDocument = (nextDocument: CanvasDocumentContractV3): CanvasStateContractV3 => ({
...canvas,
document: nextDocument,
});
@@ -99,9 +101,9 @@ describe('PsdExportController', () => {
it('plans a new bitmap-less paint layer from its captured unflushed live pixels', async () => {
const backend = createTestStubRasterBackend();
- const paintDocument: CanvasDocumentContractV2 = {
+ const paintDocument: CanvasDocumentContractV3 = {
...document,
- layers: [
+ stacks: stacksFrom([
{
blendMode: 'normal',
id: 'paint',
@@ -113,7 +115,7 @@ describe('PsdExportController', () => {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
},
- ],
+ ]),
};
const paintCanvas = canvasWithDocument(paintDocument);
const documentSnapshot: CanvasDocumentSnapshot = { canvas: paintCanvas, documentGeneration: 6 };
@@ -152,12 +154,12 @@ describe('PsdExportController', () => {
it('plans and reserves from a grown live-cache rect instead of smaller persisted source bounds', async () => {
const backend = createTestStubRasterBackend();
const smallLayer: CanvasRasterLayerContractV2 = {
- ...(document.layers[0] as CanvasRasterLayerContractV2),
+ ...(getDocumentLeaves(document)[0] as CanvasRasterLayerContractV2),
source: { image: { height: 10, imageName: 'small.png', width: 10 }, type: 'image' },
};
- const smallDocument: CanvasDocumentContractV2 = {
+ const smallDocument: CanvasDocumentContractV3 = {
...document,
- layers: [smallLayer],
+ stacks: stacksFrom([smallLayer]),
};
const grownCanvas = canvasWithDocument(smallDocument);
const documentSnapshot: CanvasDocumentSnapshot = { canvas: grownCanvas, documentGeneration: 7 };
@@ -196,14 +198,14 @@ describe('PsdExportController', () => {
it('exports valid captured pixels while skipping a confirmed-empty paint layer', async () => {
const backend = createTestStubRasterBackend();
- const validLayer = document.layers[0] as CanvasRasterLayerContractV2;
+ const validLayer = getDocumentLeaves(document)[0] as CanvasRasterLayerContractV2;
const blankLayer: CanvasRasterLayerContractV2 = {
...validLayer,
id: 'blank',
name: 'Blank',
source: { bitmap: null, type: 'paint' },
};
- const mixedCanvas = canvasWithDocument({ ...document, layers: [validLayer, blankLayer] });
+ const mixedCanvas = canvasWithDocument({ ...document, stacks: stacksFrom([validLayer, blankLayer]) });
const documentSnapshot: CanvasDocumentSnapshot = { canvas: mixedCanvas, documentGeneration: 8 };
const execute = vi.fn((plan: PsdExportPlan) => {
if (plan.status !== 'ok') {
@@ -246,12 +248,12 @@ describe('PsdExportController', () => {
it('returns nothing when every requested raster layer is confirmed empty', async () => {
const backend = createTestStubRasterBackend();
const blankLayer: CanvasRasterLayerContractV2 = {
- ...(document.layers[0] as CanvasRasterLayerContractV2),
+ ...(getDocumentLeaves(document)[0] as CanvasRasterLayerContractV2),
id: 'blank',
name: 'Blank',
source: { bitmap: null, type: 'paint' },
};
- const blankCanvas = canvasWithDocument({ ...document, layers: [blankLayer] });
+ const blankCanvas = canvasWithDocument({ ...document, stacks: stacksFrom([blankLayer]) });
const documentSnapshot: CanvasDocumentSnapshot = { canvas: blankCanvas, documentGeneration: 9 };
const release = vi.fn();
const controller = new PsdExportController({
@@ -406,3 +408,61 @@ describe('PsdExportController', () => {
expect(reservationRelease).toHaveBeenCalledOnce();
});
});
+
+describe('PsdExportController — raster tree', () => {
+ it('plans the raster tree as folders with own flags and skips leaves with nothing captured', async () => {
+ const backend = createTestStubRasterBackend();
+ const surface = backend.createSurface(100, 100);
+ const rect = { height: 100, width: 100, x: 0, y: 0 };
+ const leaf = (id: string, isEnabled = true): CanvasRasterLayerContractV2 => ({
+ ...(getDocumentLeaves(document)[0] as CanvasRasterLayerContractV2),
+ id,
+ isEnabled,
+ name: id,
+ });
+ const treeDocument: CanvasDocumentContractV3 = {
+ ...document,
+ stacks: stacksFrom([
+ groupContract('G', [leaf('inner', false), groupContract('empty', [leaf('blank')])], { isEnabled: false }),
+ leaf('root'),
+ ]),
+ };
+ const documentSnapshot: CanvasDocumentSnapshot = {
+ canvas: canvasWithDocument(treeDocument),
+ documentGeneration: 1,
+ };
+ const rasterSnapshot: CanvasRasterSnapshot = {
+ ...documentSnapshot,
+ emptyLayerIds: new Set(['blank']),
+ layerSurfaces: new Map([
+ ['inner', { rect, surface }],
+ ['root', { rect, surface }],
+ ]),
+ release: vi.fn(),
+ };
+ const execute = vi.fn((_plan: PsdExportPlan) => Promise.resolve());
+ const controller = new PsdExportController({
+ backend,
+ captureDocumentSnapshot: () => documentSnapshot,
+ captureRasterSnapshot: () => Promise.resolve({ snapshot: rasterSnapshot, status: 'ok' as const }),
+ execute,
+ getAvailableBytes: () => 10_000_000,
+ isDocumentSnapshotCurrent: () => true,
+ reserve: () => ({ lease: { release: vi.fn() }, status: 'ok' }),
+ });
+
+ await expect(controller.export('tree')).resolves.toBe('exported');
+ const plan = execute.mock.calls[0]![0];
+ if (plan.status !== 'ok') {
+ throw new Error(plan.status);
+ }
+ expect(plan.tree.map((node) => (node.kind === 'folder' ? `${node.name}/` : node.id))).toEqual(['root', 'G/']);
+ const folder = plan.tree[1];
+ expect(folder.kind === 'folder' && folder.hidden).toBe(true);
+ expect(folder.kind === 'folder' && folder.children.map((node) => node.id)).toEqual(['inner']);
+ expect(plan.layers.map((layer) => [layer.id, layer.hidden, layer.contributes])).toEqual([
+ ['root', false, true],
+ ['inner', true, false],
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
index 1b5c054d48..67d8973b80 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
@@ -1,16 +1,18 @@
import type { CanvasDocumentSnapshot, PsdExportResult } from '@workbench/canvas-engine/capabilities';
+import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';
import type {
CanvasDetachedLayerSurface,
CaptureRasterSnapshotResult,
} from '@workbench/canvas-engine/rasterTransactions';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';
+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
+import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';
import {
executePsdExport,
planPsdExport,
type ExecutePsdExportDeps,
- type PsdExportLayerInput,
+ type PsdExportNodeInput,
type PsdExportPlan,
} from '@workbench/canvas-engine/export/psdExport';
import { isExportableRasterLayer } from '@workbench/canvas-engine/layerExportGuards';
@@ -66,9 +68,8 @@ export class PsdExportController {
return 'stale';
}
const document = documentSnapshot.canvas.document;
- const layers = compileDocumentLeaves(document)
- .map((leaf) => leaf.layer)
- .filter(isExportableRasterLayer);
+ const leaves = compileDocumentLeaves(document).filter((leaf) => isExportableRasterLayer(leaf.layer));
+ const layers = leaves.map((leaf) => leaf.layer);
if (layers.length === 0) {
return 'nothing';
}
@@ -88,25 +89,48 @@ export class PsdExportController {
if (!this.deps.isDocumentSnapshotCurrent(documentSnapshot)) {
return 'stale';
}
- const inputs: PsdExportLayerInput[] = [];
- for (const layer of layers) {
- const detached = rasterSnapshot.layerSurfaces.get(layer.id);
- if (!detached) {
- if (rasterSnapshot.emptyLayerIds.has(layer.id)) {
- continue;
+ // The raster tree as it stands, minus leaves with nothing captured; the planner derives
+ // effective visibility from the own flags, the same way Photoshop will.
+ let missing: string | null = null;
+ const toInputs = (nodes: readonly CanvasNodeContract[]): PsdExportNodeInput[] =>
+ nodes.flatMap((node): PsdExportNodeInput[] => {
+ if (isGroupNode(node)) {
+ return [
+ {
+ children: toInputs(node.children),
+ id: node.id,
+ isEnabled: node.isEnabled,
+ name: node.name,
+ type: 'group',
+ },
+ ];
}
- return 'not-ready';
- }
- inputs.push({
- adjustments: layer.type === 'raster' ? layer.adjustments : undefined,
- blendMode: layer.blendMode,
- contentRect: detached.rect,
- id: layer.id,
- isEnabled: layer.isEnabled,
- name: layer.name,
- opacity: layer.opacity,
- transform: layer.transform,
+ if (!isExportableRasterLayer(node)) {
+ return [];
+ }
+ const detached = rasterSnapshot.layerSurfaces.get(node.id);
+ if (!detached) {
+ if (!rasterSnapshot.emptyLayerIds.has(node.id)) {
+ missing ??= node.id;
+ }
+ return [];
+ }
+ return [
+ {
+ adjustments: node.type === 'raster' ? node.adjustments : undefined,
+ blendMode: node.blendMode,
+ contentRect: detached.rect,
+ id: node.id,
+ isEnabled: node.isEnabled,
+ name: node.name,
+ opacity: node.opacity,
+ transform: node.transform,
+ },
+ ];
});
+ const inputs = toInputs(document.stacks.raster);
+ if (missing !== null) {
+ return 'not-ready';
}
const plan = planPsdExport(inputs);
if (plan.status === 'empty') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
index a8ac429cba..80cc0d4d3c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
@@ -1,11 +1,19 @@
import type { CanvasBlendMode } from '@workbench/canvas-engine/contracts';
import type { Rect } from '@workbench/canvas-engine/types';
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { readPsd, writePsd } from 'ag-psd';
import { describe, expect, it } from 'vitest';
-import type { PsdExportLayerInput } from './psdExport';
+import type {
+ PsdExportGroupInput,
+ PsdExportLayerInput,
+ PsdExportNodeInput,
+ PsdPlanFolder,
+ PsdPlanNode,
+} from './psdExport';
-import { blendModeToPsd, planPsdExport, PSD_MAX_DIMENSION } from './psdExport';
+import { blendModeToPsd, executePsdExport, planPsdExport, PSD_MAX_DIMENSION } from './psdExport';
const IDENTITY = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
@@ -163,3 +171,94 @@ describe('planPsdExport', () => {
expect(plan.status).toBe('ok');
});
});
+
+describe('planPsdExport — folders', () => {
+ const group = (id: string, children: PsdExportNodeInput[], isEnabled = true): PsdExportGroupInput => ({
+ children,
+ id,
+ isEnabled,
+ name: id,
+ type: 'group',
+ });
+ const names = (nodes: readonly PsdPlanNode[]): unknown[] =>
+ nodes.map((node) => (node.kind === 'folder' ? { [node.name]: names(node.children) } : node.name));
+
+ it('mirrors the tree as folders, reversing every level, and flattens leaves in visual order', () => {
+ const plan = planPsdExport([
+ layer({ id: 'top', name: 'Top' }),
+ group('G', [
+ layer({ id: 'g1', name: 'G1' }),
+ group('H', [layer({ id: 'h1', name: 'H1' })]),
+ layer({ id: 'g2', name: 'G2' }),
+ ]),
+ layer({ id: 'bottom', name: 'Bottom' }),
+ ]);
+ expect(plan.status).toBe('ok');
+ if (plan.status !== 'ok') {
+ return;
+ }
+ expect(names(plan.tree)).toEqual(['Bottom', { G: ['G2', { H: ['H1'] }, 'G1'] }, 'Top']);
+ expect(plan.layers.map((entry) => entry.id)).toEqual(['bottom', 'g2', 'h1', 'g1', 'top']);
+ });
+
+ it('writes own visibility on folders and leaves while the preview flattens only contributing leaves', () => {
+ const plan = planPsdExport([
+ group(
+ 'off',
+ [layer({ id: 'inner', name: 'Inner' }), layer({ id: 'dark', isEnabled: false, name: 'Dark' })],
+ false
+ ),
+ layer({ id: 'root', name: 'Root' }),
+ ]);
+ if (plan.status !== 'ok') {
+ throw new Error(plan.status);
+ }
+ const folder = plan.tree[1] as PsdPlanFolder;
+ expect(folder).toMatchObject({ hidden: true, kind: 'folder', name: 'off' });
+ expect(findLayer(plan, 'inner')).toMatchObject({ contributes: false, hidden: false });
+ expect(findLayer(plan, 'dark')).toMatchObject({ contributes: false, hidden: true });
+ expect(findLayer(plan, 'root')).toMatchObject({ contributes: true, hidden: false });
+ });
+
+ it('drops a folder whose subtree exports nothing', () => {
+ const empty = { height: 0, width: 0, x: 0, y: 0 };
+ const plan = planPsdExport([
+ group('hollow', [group('deeper', [layer({ contentRect: empty, id: 'nothing' })])]),
+ layer({ id: 'root', name: 'Root' }),
+ ]);
+ if (plan.status !== 'ok') {
+ throw new Error(plan.status);
+ }
+ expect(names(plan.tree)).toEqual(['Root']);
+ });
+
+ it('round-trips folder hierarchy, order, names and leaf properties through ag-psd', async () => {
+ const plan = planPsdExport([
+ group('Shading', [layer({ blendMode: 'multiply', id: 'shade', name: 'Shade', opacity: 0.5 })], false),
+ layer({ id: 'base', name: 'Base' }),
+ ]);
+ const backend = createTestStubRasterBackend();
+ const imageDataOf = (width: number, height: number): ImageData =>
+ ({ data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;
+ let bytes: ArrayBuffer | null = null;
+ await executePsdExport(plan, 'tree.psd', {
+ backend,
+ download: (data) => {
+ bytes = data;
+ },
+ getLayerSurface: () =>
+ Promise.resolve({ rect: { height: 50, width: 100, x: 0, y: 0 }, surface: backend.createSurface(100, 50) }),
+ readImageData: (_surface, rect) => imageDataOf(rect.width, rect.height),
+ writeImageData: () => undefined,
+ writePsd: (psd) => Promise.resolve(writePsd(psd, { generateThumbnail: false })),
+ });
+ const parsed = readPsd(bytes!, { skipCompositeImageData: true, skipLayerImageData: true, skipThumbnail: true });
+ expect(parsed.children?.map((child) => child.name)).toEqual(['Base', 'Shading']);
+ const folder = parsed.children![1]!;
+ expect(folder.hidden).toBe(true);
+ expect(folder.children?.map((child) => child.name)).toEqual(['Shade']);
+ expect(folder.children![0]).toMatchObject({ blendMode: 'multiply', hidden: false });
+ // Opacity rides an 8-bit field in the file.
+ expect(folder.children![0]!.opacity).toBeCloseTo(0.5, 2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
index 5ee63ec0e0..0cf4b24f37 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
@@ -14,18 +14,26 @@
* triggers a browser download. Verified by types + manual QA (opening the PSD).
*
* ### Conventions
- * - **Order.** The canvas document stores layers top-first (index 0 = top-most).
- * ag-psd's `children` array is BOTTOM-to-top (`children[0]` is the bottom-most
- * layer, written first to the PSD layer records, which the format stores
- * bottom-up). So the plan reverses the top-first input into bottom-to-top.
+ * - **Order.** The canvas document stores nodes top-first (index 0 = top-most) at
+ * every level of the raster tree. ag-psd's `children` array is BOTTOM-to-top
+ * (`children[0]` is the bottom-most layer, written first to the PSD layer
+ * records, which the format stores bottom-up). So the plan reverses every
+ * level of the top-first input into bottom-to-top.
+ * - **Folders.** Groups become pass-through PSD folders with their own name and
+ * visibility; a folder whose subtree exports nothing is dropped with it. The
+ * flat leaf order is the depth-first order of the tree, which is also the
+ * visual order because groups do not composite in isolation.
* - **Bounds.** The PSD canvas is the union of every EXPORTED layer's
* world-space (document-space) content AABB — document/bbox-independent. An
* empty union means nothing to export.
* - **Opacity.** ag-psd's `Layer.opacity` is 0..1 (the writer multiplies by 255
* internally), NOT 0..255. Our `layer.opacity` is already 0..1, so it passes
* through unchanged (clamped).
- * - **Hidden.** Every raster layer with content is exported; hidden (disabled)
- * layers are written with `hidden: true` rather than dropped.
+ * - **Hidden.** Every raster layer with content is exported; a layer disabled in
+ * its own right is written with `hidden: true` rather than dropped, and a
+ * disabled group becomes a hidden folder. The merged preview flattens only the
+ * leaves that contribute (enabled with every ancestor enabled), which is what
+ * Photoshop shows for the same flags.
* - **Adjustments.** Non-destructive raster adjustments are BAKED into the
* layer's pixels (PSD has no matching non-destructive representation we emit),
* exactly as `compositeForGeneration` bakes them, so the PSD matches what the
@@ -87,7 +95,7 @@ const BLEND_MODE_TO_PSD: Record<CanvasBlendMode, BlendMode> = {
/** The ag-psd blend key for a document blend mode ('normal' for anything unmapped). */
export const blendModeToPsd = (mode: CanvasBlendMode): BlendMode => BLEND_MODE_TO_PSD[mode] ?? 'normal';
-/** One raster layer's export-relevant facts, in the document's top-first order. */
+/** One raster layer's export-relevant facts, at its place in the top-first tree. */
export interface PsdExportLayerInput {
id: string;
name: string;
@@ -97,14 +105,30 @@ export interface PsdExportLayerInput {
/** 0..1. */
opacity: number;
blendMode: CanvasBlendMode;
- /** Hidden (disabled) layers are exported with `hidden: true`, not dropped. */
+ /** The layer's own flag; a disabled layer is exported with `hidden: true`, not dropped. */
isEnabled: boolean;
/** Non-destructive adjustments to bake into the layer's pixels, if any. */
adjustments?: CanvasAdjustmentsContract;
}
+/** A raster group: a pass-through folder in the PSD, children top-first. */
+export interface PsdExportGroupInput {
+ type: 'group';
+ id: string;
+ name: string;
+ /** The group's own flag; a disabled group is a hidden folder. */
+ isEnabled: boolean;
+ children: readonly PsdExportNodeInput[];
+}
+
+export type PsdExportNodeInput = PsdExportLayerInput | PsdExportGroupInput;
+
+const isGroupInput = (input: PsdExportNodeInput): input is PsdExportGroupInput =>
+ 'type' in input && input.type === 'group';
+
/** A single planned PSD layer (already in ag-psd bottom-to-top order). */
export interface PsdPlanLayer {
+ kind: 'layer';
id: string;
name: string;
/** Position within the PSD canvas (relative to the union origin). */
@@ -122,10 +146,24 @@ export interface PsdPlanLayer {
blendMode: BlendMode;
/** Canvas `globalCompositeOperation` for the flattened composite preview. */
compositeBlend: GlobalCompositeOperation;
+ /** The layer's own visibility flag, as the PSD stores it. */
hidden: boolean;
+ /** Enabled with every folder above it enabled: the leaves the merged preview flattens. */
+ contributes: boolean;
adjustments?: CanvasAdjustmentsContract;
}
+/** A planned PSD folder; `children` are in ag-psd bottom-to-top order. */
+export interface PsdPlanFolder {
+ kind: 'folder';
+ id: string;
+ name: string;
+ hidden: boolean;
+ children: PsdPlanNode[];
+}
+
+export type PsdPlanNode = PsdPlanLayer | PsdPlanFolder;
+
/** A successful export plan. */
export interface PsdExportOk {
status: 'ok';
@@ -134,8 +172,10 @@ export interface PsdExportOk {
height: number;
/** The union bounds in document space (origin is the PSD's (0,0)). */
canvasRect: Rect;
- /** Layers in ag-psd order (bottom-to-top). */
+ /** Every exported layer, flattened, in ag-psd order (bottom-to-top). */
layers: PsdPlanLayer[];
+ /** The folder tree the PSD carries, bottom-to-top at every level; `layers` are its leaves. */
+ tree: PsdPlanNode[];
/** Distinct blend modes that had no PSD equivalent (fell back to 'normal'). */
unmappedBlends: string[];
}
@@ -155,28 +195,39 @@ const layerMatrix = (t: PsdLayerTransform): Mat2d => fromTRS({ x: t.x, y: t.y },
const clamp01 = (value: number): number => (value < 0 ? 0 : value > 1 ? 1 : value);
/**
- * Plans a PSD export from raster layers (top-first). Computes each layer's
- * world-space AABB, unions them for the PSD canvas, and produces per-layer PSD
- * entries in bottom-to-top order. Layers with no content (empty rect, or a
- * degenerate zero-area transform) contribute nothing and are omitted. Returns
- * `empty` when nothing has content and `too-large` when the union exceeds the
- * dimension cap.
+ * Plans a PSD export from the raster tree (top-first at every level). Computes
+ * each layer's world-space AABB, unions them for the PSD canvas, and produces
+ * per-layer PSD entries in bottom-to-top order plus the folder tree they sit in.
+ * Layers with no content (empty rect, or a degenerate zero-area transform)
+ * contribute nothing and are omitted, and so is any folder left without a leaf.
+ * Returns `empty` when nothing has content and `too-large` when the union
+ * exceeds the dimension cap.
*/
export const planPsdExport = (
- inputs: readonly PsdExportLayerInput[],
+ inputs: readonly PsdExportNodeInput[],
options: PlanPsdExportOptions = {}
): PsdExportPlan => {
const maxDimension = options.maxDimension ?? PSD_MAX_DIMENSION;
- // World-space AABB per layer (null = no content: empty local rect or a
- // zero-area transform that collapses the bounds).
- const withBounds = inputs.map((input) => {
- if (isEmpty(input.contentRect)) {
- return { input, worldRect: null as Rect | null };
+ // Leaves in depth-first (visual, top-first) order with their effective enablement, and the
+ // world-space AABB of each (null = no content: empty local rect or a zero-area transform).
+ const withBounds: { input: PsdExportLayerInput; contributes: boolean; worldRect: Rect | null }[] = [];
+ const walk = (nodes: readonly PsdExportNodeInput[], enabled: boolean): void => {
+ for (const node of nodes) {
+ if (isGroupInput(node)) {
+ walk(node.children, enabled && node.isEnabled);
+ continue;
+ }
+ const contributes = enabled && node.isEnabled;
+ if (isEmpty(node.contentRect)) {
+ withBounds.push({ contributes, input: node, worldRect: null });
+ continue;
+ }
+ const worldRect = roundOut(transformBounds(layerMatrix(node.transform), node.contentRect));
+ withBounds.push({ contributes, input: node, worldRect: isEmpty(worldRect) ? null : worldRect });
}
- const worldRect = roundOut(transformBounds(layerMatrix(input.transform), input.contentRect));
- return { input, worldRect: isEmpty(worldRect) ? null : worldRect };
- });
+ };
+ walk(inputs, true);
let bounds: Rect | null = null;
for (const { worldRect } of withBounds) {
@@ -193,11 +244,12 @@ export const planPsdExport = (
}
const unmappedBlends = new Set<string>();
- // ag-psd order is bottom-to-top; inputs are top-first, so reverse. Layers
+ // ag-psd order is bottom-to-top; leaves are top-first, so reverse. Layers
// without content are dropped.
const layers: PsdPlanLayer[] = [];
+ const byId = new Map<string, PsdPlanLayer>();
for (let i = withBounds.length - 1; i >= 0; i -= 1) {
- const { input, worldRect } = withBounds[i]!;
+ const { contributes, input, worldRect } = withBounds[i]!;
if (!worldRect) {
continue;
}
@@ -207,14 +259,16 @@ export const planPsdExport = (
}
const left = worldRect.x - canvasRect.x;
const top = worldRect.y - canvasRect.y;
- layers.push({
+ const layer: PsdPlanLayer = {
adjustments: input.adjustments,
blendMode: mapped ?? 'normal',
bottom: top + worldRect.height,
compositeBlend: blendToComposite(input.blendMode),
contentRect: input.contentRect,
+ contributes,
hidden: !input.isEnabled,
id: input.id,
+ kind: 'layer',
left,
name: input.name,
opacity: clamp01(input.opacity),
@@ -222,14 +276,37 @@ export const planPsdExport = (
top,
transform: input.transform,
worldRect,
- });
+ };
+ layers.push(layer);
+ byId.set(input.id, layer);
}
+ // The same reversal at every level of the tree; folders keep only what survived.
+ const buildTree = (nodes: readonly PsdExportNodeInput[]): PsdPlanNode[] => {
+ const out: PsdPlanNode[] = [];
+ for (let i = nodes.length - 1; i >= 0; i -= 1) {
+ const node = nodes[i]!;
+ if (isGroupInput(node)) {
+ const children = buildTree(node.children);
+ if (children.length > 0) {
+ out.push({ children, hidden: !node.isEnabled, id: node.id, kind: 'folder', name: node.name });
+ }
+ continue;
+ }
+ const layer = byId.get(node.id);
+ if (layer) {
+ out.push(layer);
+ }
+ }
+ return out;
+ };
+
return {
canvasRect,
height: canvasRect.height,
layers,
status: 'ok',
+ tree: buildTree(inputs),
unmappedBlends: [...unmappedBlends],
width: canvasRect.width,
};
@@ -357,14 +434,14 @@ export const executePsdExport = async (
const writePsdFn = deps.writePsd ?? defaultWritePsd;
const download = deps.download ?? defaultDownload;
- const children: AgPsdLayer[] = [];
+ const bakedById = new Map<string, AgPsdLayer>();
const baked: { planLayer: PsdPlanLayer; surface: RasterSurface }[] = [];
for (const planLayer of plan.layers) {
throwIfAborted(deps.signal);
const { imageData, surface } = await bakeLayer(planLayer, deps, read, write);
baked.push({ planLayer, surface });
- children.push({
+ bakedById.set(planLayer.id, {
blendMode: planLayer.blendMode,
bottom: planLayer.bottom,
hidden: planLayer.hidden,
@@ -376,8 +453,15 @@ export const executePsdExport = async (
top: planLayer.top,
});
}
-
- // Flatten the enabled layers (bottom-to-top = plan order) into the merged
+ const toChildren = (nodes: readonly PsdPlanNode[]): AgPsdLayer[] =>
+ nodes.map((node) =>
+ node.kind === 'folder'
+ ? { children: toChildren(node.children), hidden: node.hidden, name: node.name, opened: true }
+ : bakedById.get(node.id)!
+ );
+ const children = toChildren(plan.tree);
+
+ // Flatten the contributing layers (bottom-to-top = plan order) into the merged
// composite the PSD carries as its full-document preview.
throwIfAborted(deps.signal);
const composite = deps.backend.createSurface(plan.width, plan.height);
@@ -385,7 +469,7 @@ export const executePsdExport = async (
setTransform(cctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
cctx.clearRect(0, 0, plan.width, plan.height);
for (const { planLayer, surface } of baked) {
- if (planLayer.hidden) {
+ if (!planLayer.contributes) {
continue;
}
cctx.globalAlpha = planLayer.opacity;