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(layers): make the tree one accessible composite

Josh Corbett6b539f23e6a5
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 8aa64f3b60..1867671805 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2508,6 +2508,7 @@
"extractMaskedArea": "Extract masked area",
"fitToBbox": "Fit to bbox",
"hide": "Hide layer",
+ "hideOnCanvas": "Hide on canvas",
"intersect": "Intersect with layer below",
"mergeSelected": "Merge selected layers",
"lock": "Lock layer",
@@ -2535,6 +2536,7 @@
"selectedCount_other": "{{count}} layers selected",
"selectObject": "Select object",
"show": "Show layer",
+ "showOnCanvas": "Show on canvas",
"toggleAutoNegative": "Toggle auto-negative",
"toggleHidden": "Show/hide on canvas",
"toggleLock": "Toggle lock",
diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
index 220d7d5f7c..6dedf03896 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts
@@ -116,6 +116,18 @@ describe('layer panel selection', () => {
expect(reconcileLayerPanelState(collapsed, 'other', indexOf(ids), 'b').collapsedStacks).toEqual([]);
});
+ it('opens the collapsed stack of a primary selected outside the panel', () => {
+ const index = indexStacks(stacksFrom([layerContract('c', 'control'), layerContract('a')]));
+ const collapsed = {
+ ...createLayerPanelState('p', 'a'),
+ collapsedStacks: ['control' as const, 'inpaint_mask' as const],
+ };
+ expect(reconcileLayerPanelState(collapsed, 'p', index, 'c').collapsedStacks).toEqual(['inpaint_mask']);
+ const stale = { ...collapsed, expandedGroupIds: ['gone'] };
+ expect(reconcileLayerPanelState(stale, 'p', index, 'c').expandedGroupIds).toEqual([]);
+ expect(reconcileLayerPanelState(collapsed, 'p', index, 'a')).toBe(collapsed);
+ });
+
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 e388a30859..53ad9cbfc6 100644
--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts
@@ -186,14 +186,24 @@ export const reconcileLayerPanelState = (
): LayerPanelState => {
const primary = primaryId ? index.byId.get(primaryId) : undefined;
const validPrimaryId = primary ? primary.node.id : null;
- const expandedGroupIds = state.expandedGroupIds.filter((id) => index.byId.has(id));
if (state.projectId !== projectId || state.primaryId !== validPrimaryId) {
- const revealed = primary ? [...new Set([...expandedGroupIds, ...primary.path])] : expandedGroupIds;
- return state.projectId === projectId
- ? createLayerPanelState(projectId, validPrimaryId, { ...carryOf(state), expandedGroupIds: revealed })
- : createLayerPanelState(projectId, validPrimaryId, { expandedGroupIds: primary ? [...primary.path] : [] });
+ if (state.projectId !== projectId) {
+ return createLayerPanelState(projectId, validPrimaryId, { expandedGroupIds: primary ? [...primary.path] : [] });
+ }
+ // The new primary is revealed: its stack opens and every group on its path expands.
+ const carry = carryOf(state);
+ return createLayerPanelState(projectId, validPrimaryId, {
+ ...carry,
+ collapsedStacks: primary
+ ? carry.collapsedStacks.filter((stack) => stack !== primary.stack)
+ : carry.collapsedStacks,
+ expandedGroupIds: [
+ ...new Set([...carry.expandedGroupIds.filter((id) => index.byId.has(id)), ...(primary?.path ?? [])]),
+ ],
+ });
}
const existing = index.byId;
+ const expandedGroupIds = state.expandedGroupIds.filter((id) => existing.has(id));
const selectedIds = [...new Set(state.selectedIds)].filter((id) => existing.has(id));
if (validPrimaryId && !selectedIds.includes(validPrimaryId)) {
selectedIds.push(validPrimaryId);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
index 6b2b9c1c6a..72bd178aee 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
@@ -103,7 +103,7 @@ export const ToolOptionsBar = ({ engine }: { engine: CanvasToolOptionsEngine })
) : OptionsComponent ? (
<OptionsComponent engine={engine} />
) : (
- <Text color="fg.subtle" fontSize="xs" minW="0" truncate>
+ <Text color="fg.muted" fontSize="xs" minW="0" truncate>
{t(`widgets.canvas.toolHints.${activeTool}`)}
</Text>
)}
@@ -141,7 +141,7 @@ const LeafToolOptions = ({
}
return (
<HStack gap="2" minW="0">
- <Text color="fg.subtle" fontSize="xs" minW="0" truncate>
+ <Text color="fg.muted" fontSize="xs" minW="0" truncate>
{t('widgets.layers.groupSelectedHint')}
</Text>
{selectedGroup.firstLeafId ? (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index f189c2c4be..452645e51f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -15,7 +15,13 @@ import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { galleryTransfers } from '@features/gallery';
import { useModelsSelector } from '@features/models';
import { IconButton, MenuContent, RenameDialog, Tooltip } from '@platform/ui';
-import { getDocumentLayer, getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';
+import {
+ getDocumentLayer,
+ getSourceContentRect,
+ isNodeHidden,
+ lookupDocumentNodeState,
+ renderableSourceOf,
+} from '@workbench/canvas-engine/api';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
@@ -263,9 +269,12 @@ const LayerMenu = ({
);
const canGroup = canGroupSelection(engine?.document.model() ?? null, actionTargets({ layer, selectedIds }));
+ const hiddenByAncestor =
+ (lookupDocumentNodeState(document, layer.id)?.documentHidden ?? false) && !isNodeHidden(layer);
const actionState = useMemo<LayerContextActionState>(
() => ({
canGroupSelection: canGroup,
+ hiddenByAncestor,
canRunWorkflow: workflowAvailability.canRunWorkflow,
document,
hasEngine: engine !== null,
@@ -276,6 +285,7 @@ const LayerMenu = ({
selectedIds,
}),
[
+ hiddenByAncestor,
canGroup,
document,
engine,
@@ -408,6 +418,12 @@ const LayerMenu = ({
patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: !layer.isEnabled });
}, [layer.isEnabled, patchBase, t]);
+ const handleToggleHidden = useCallback(() => {
+ commitPrepared(t('widgets.layers.actions.toggleHidden'), (model) =>
+ model.prepare({ type: 'set-hidden', updates: [{ id: layer.id, isHidden: !isNodeHidden(layer) }] })
+ );
+ }, [commitPrepared, layer, t]);
+
const handleToggleLock = useCallback(() => {
patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked });
}, [layer.isLocked, patchBase, t]);
@@ -659,6 +675,7 @@ const LayerMenu = ({
reorder: (kind, actionId) => reorder(kind, getActionLabel(actionId)),
saveToAssets: handleSaveToAssets,
toggleLock: handleToggleLock,
+ toggleHidden: handleToggleHidden,
toggleVisibility: handleToggleVisibility,
transform: handleTransform,
}),
@@ -680,6 +697,7 @@ const LayerMenu = ({
handleRasterize,
handleSaveToAssets,
handleToggleLock,
+ handleToggleHidden,
handleToggleVisibility,
handleTransform,
openRename,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
index a8fd7021b6..2e5f9193ae 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
@@ -1,5 +1,6 @@
import type { CanvasDocumentContractV3, LayerStackMoveKind } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+import type { KeyboardEvent } from 'react';
import { HStack, Text } from '@chakra-ui/react';
import { toaster } from '@platform/ui';
@@ -24,7 +25,7 @@ import {
MergeIcon,
Trash2Icon,
} from 'lucide-react';
-import { useCallback, useMemo } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { groupLayers, ungroupLayers } from './layerGroupCommands';
@@ -157,113 +158,197 @@ export const LayerMultiSelectionActions = ({
);
}, [commitPrepared, selectedIds, t]);
+ const actions = useMemo<readonly BulkAction[]>(
+ () => [
+ {
+ disabled: editingLocked || none,
+ icon: ChevronsUpIcon,
+ id: 'front',
+ label: t('widgets.layers.actions.moveSelectedToFront'),
+ run: moveToFront,
+ },
+ {
+ disabled: editingLocked || none,
+ icon: ArrowUpIcon,
+ id: 'forward',
+ label: t('widgets.layers.actions.moveSelectedForward'),
+ run: moveForward,
+ },
+ {
+ disabled: editingLocked || none,
+ icon: ArrowDownIcon,
+ id: 'backward',
+ label: t('widgets.layers.actions.moveSelectedBackward'),
+ run: moveBackward,
+ },
+ {
+ disabled: editingLocked || none,
+ icon: ChevronsDownIcon,
+ id: 'back',
+ label: t('widgets.layers.actions.moveSelectedToBack'),
+ run: moveToBack,
+ },
+ {
+ disabled: editingLocked || !engine || !canGroup,
+ icon: FolderPlusIcon,
+ id: 'group',
+ label: t('widgets.layers.actions.groupSelected'),
+ run: groupSelected,
+ },
+ {
+ disabled: editingLocked || !engine || !canUngroup,
+ icon: FolderMinusIcon,
+ id: 'ungroup',
+ label: t('widgets.layers.actions.ungroupSelected'),
+ run: ungroupSelected,
+ },
+ {
+ disabled: editingLocked || none,
+ icon: allEnabled ? EyeOffIcon : EyeIcon,
+ id: 'enable',
+ label: t(allEnabled ? 'widgets.layers.actions.disableSelected' : 'widgets.layers.actions.enableSelected'),
+ run: toggleEnabled,
+ },
+ {
+ disabled: editingLocked || none,
+ icon: allLocked ? LockOpenIcon : LockIcon,
+ id: 'lock',
+ label: t(allLocked ? 'widgets.layers.actions.unlockSelected' : 'widgets.layers.actions.lockSelected'),
+ run: toggleLocked,
+ },
+ {
+ disabled: editingLocked || !engine || none,
+ icon: CopyIcon,
+ id: 'duplicate',
+ label: t('widgets.layers.actions.duplicateSelected'),
+ run: duplicateSelected,
+ },
+ {
+ disabled: editingLocked || !engine || !canMergeSelected,
+ icon: MergeIcon,
+ id: 'merge',
+ label: t('widgets.layers.actions.mergeSelected'),
+ run: mergeSelected,
+ },
+ {
+ colorPalette: 'red',
+ disabled: editingLocked || !canDelete,
+ icon: Trash2Icon,
+ id: 'delete',
+ label: t('widgets.layers.actions.deleteSelected'),
+ run: deleteSelected,
+ },
+ ],
+ [
+ allEnabled,
+ allLocked,
+ canDelete,
+ canGroup,
+ canMergeSelected,
+ canUngroup,
+ deleteSelected,
+ duplicateSelected,
+ editingLocked,
+ engine,
+ groupSelected,
+ mergeSelected,
+ moveBackward,
+ moveForward,
+ moveToBack,
+ moveToFront,
+ none,
+ t,
+ toggleEnabled,
+ toggleLocked,
+ ungroupSelected,
+ ]
+ );
return (
- <HStack
- aria-label={t('widgets.layers.actions.selectedCount', { count: selected.length })}
- gap="0.5"
- minH="10"
- px="2"
- role="toolbar"
- >
- <Text color="fg.muted" flex="1" fontSize="2xs" fontWeight="700">
- {t('widgets.layers.actions.selectedCount', { count: selected.length })}
- </Text>
- <BulkActionButton
- disabled={editingLocked || none}
- icon={ChevronsUpIcon}
- label={t('widgets.layers.actions.moveSelectedToFront')}
- onClick={moveToFront}
- />
- <BulkActionButton
- disabled={editingLocked || none}
- icon={ArrowUpIcon}
- label={t('widgets.layers.actions.moveSelectedForward')}
- onClick={moveForward}
- />
- <BulkActionButton
- disabled={editingLocked || none}
- icon={ArrowDownIcon}
- label={t('widgets.layers.actions.moveSelectedBackward')}
- onClick={moveBackward}
- />
- <BulkActionButton
- disabled={editingLocked || none}
- icon={ChevronsDownIcon}
- label={t('widgets.layers.actions.moveSelectedToBack')}
- onClick={moveToBack}
- />
- <BulkActionButton
- disabled={editingLocked || !engine || !canGroup}
- icon={FolderPlusIcon}
- label={t('widgets.layers.actions.groupSelected')}
- onClick={groupSelected}
- />
- <BulkActionButton
- disabled={editingLocked || !engine || !canUngroup}
- icon={FolderMinusIcon}
- label={t('widgets.layers.actions.ungroupSelected')}
- onClick={ungroupSelected}
- />
- <BulkActionButton
- disabled={editingLocked || none}
- icon={allEnabled ? EyeOffIcon : EyeIcon}
- label={t(allEnabled ? 'widgets.layers.actions.disableSelected' : 'widgets.layers.actions.enableSelected')}
- onClick={toggleEnabled}
- />
- <BulkActionButton
- disabled={editingLocked || none}
- icon={allLocked ? LockOpenIcon : LockIcon}
- label={t(allLocked ? 'widgets.layers.actions.unlockSelected' : 'widgets.layers.actions.lockSelected')}
- onClick={toggleLocked}
- />
- <BulkActionButton
- disabled={editingLocked || !engine || none}
- icon={CopyIcon}
- label={t('widgets.layers.actions.duplicateSelected')}
- onClick={duplicateSelected}
- />
- <BulkActionButton
- disabled={editingLocked || !engine || !canMergeSelected}
- icon={MergeIcon}
- label={t('widgets.layers.actions.mergeSelected')}
- onClick={mergeSelected}
- />
- <BulkActionButton
- colorPalette="red"
- disabled={editingLocked || !canDelete}
- icon={Trash2Icon}
- label={t('widgets.layers.actions.deleteSelected')}
- onClick={deleteSelected}
- />
- </HStack>
+ <BulkActionToolbar
+ actions={actions}
+ label={t('widgets.layers.actions.selectedCount', { count: selected.length })}
+ />
);
};
export default LayerMultiSelectionActions;
-const BulkActionButton = ({
- colorPalette,
- disabled,
- icon: Icon,
- label,
- onClick,
-}: {
+interface BulkAction {
colorPalette?: string;
disabled: boolean;
icon: typeof ArrowUpIcon;
+ id: string;
label: string;
- onClick: () => void;
-}) => (
- <Tooltip content={label} positioning={BULK_TOOLTIP_POSITIONING}>
- <IconButton
- aria-label={label}
- colorPalette={colorPalette}
- disabled={disabled}
- size="xs"
- variant="ghost"
- onClick={onClick}
- >
- <Icon />
- </IconButton>
- </Tooltip>
-);
+ run: () => void;
+}
+
+/**
+ * One tab stop for the whole toolbar; arrows, Home and End move between the enabled buttons. The focus
+ * bookkeeping lives here so tracking it never re-runs the eligibility above.
+ */
+const BulkActionToolbar = ({ actions, label }: { actions: readonly BulkAction[]; label: string }) => {
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const enabled = actions.filter((action) => !action.disabled);
+ const tabStopId = enabled.some((action) => action.id === activeId) ? activeId : (enabled[0]?.id ?? null);
+ const onKeyDown = useCallback((event: KeyboardEvent<HTMLElement>) => {
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
+ return;
+ }
+ const buttons = [...event.currentTarget.querySelectorAll<HTMLButtonElement>('button:not(:disabled)')];
+ const current = buttons.indexOf(event.target as HTMLButtonElement);
+ if (buttons.length === 0 || current === -1) {
+ return;
+ }
+ event.preventDefault();
+ const next =
+ event.key === 'Home'
+ ? 0
+ : event.key === 'End'
+ ? buttons.length - 1
+ : (current + (event.key === 'ArrowRight' ? 1 : buttons.length - 1)) % buttons.length;
+ buttons[next]!.focus();
+ }, []);
+ return (
+ <HStack aria-label={label} gap="0.5" minH="10" px="2" role="toolbar" onKeyDown={onKeyDown}>
+ <Text color="fg.muted" flex="1" fontSize="2xs" fontWeight="700">
+ {label}
+ </Text>
+ {actions.map((action) => (
+ <BulkActionButton
+ key={action.id}
+ action={action}
+ tabIndex={action.id === tabStopId ? 0 : -1}
+ onFocus={setActiveId}
+ />
+ ))}
+ </HStack>
+ );
+};
+
+const BulkActionButton = ({
+ action: { colorPalette, disabled, icon: Icon, id, label, run },
+ onFocus,
+ tabIndex,
+}: {
+ action: BulkAction;
+ onFocus: (id: string) => void;
+ tabIndex: number;
+}) => {
+ const handleFocus = useCallback(() => onFocus(id), [id, onFocus]);
+ return (
+ <Tooltip content={label} positioning={BULK_TOOLTIP_POSITIONING}>
+ <IconButton
+ aria-label={label}
+ colorPalette={colorPalette}
+ disabled={disabled}
+ size="xs"
+ tabIndex={tabIndex}
+ variant="ghost"
+ onClick={run}
+ onFocus={handleFocus}
+ >
+ <Icon />
+ </IconButton>
+ </Tooltip>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
index d2f48dc72f..b98b5708d1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx
@@ -1,8 +1,8 @@
import type { CanvasLayerContract, SemanticNode } from '@workbench/canvas-engine/api';
import type { LayerPanelDensity } from '@workbench/layerPanelState';
-import type { KeyboardEvent, MouseEvent } from 'react';
+import type { FocusEvent, KeyboardEvent, MouseEvent } from 'react';
-import { Badge, Box, chakra, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { Badge, Box, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
import { useDraggable, useDroppable } from '@dnd-kit/core';
import { IconButton, Row, ToggleDot, Tooltip } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
@@ -19,19 +19,19 @@ import {
MoreVerticalIcon,
SlidersHorizontalIcon,
} from 'lucide-react';
-import { memo, useCallback, useMemo, useRef } from 'react';
+import { memo, useCallback, useLayoutEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { LayerRowCommands } from './layerRowCommands';
import type { LayerTreeRow } from './layerTreeRows';
import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';
+import { recordLayerRowCommit } from './layerPanelDiagnostics';
import { LAYER_TREE_INDENT_PX } from './layerPanelRows';
import { anchorFromPoint, anchorFromRect } from './layerRowCommands';
import { layerRowSummary } from './layerRowSummary';
import { LayerThumbnail, type LayerThumbnailEngine } from './LayerThumbnail';
-const ROW_INTERACTIVE_DESCENDANTS = { '& button, & input': { pointerEvents: 'auto' } };
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 = {
@@ -77,6 +77,11 @@ interface LayerRowProps {
const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();
+/**
+ * One tree item. The row element itself carries the tree role, the roving tab stop and the
+ * keyboard model; every control inside it is pointer-only (`tabIndex={-1}`) and reachable from the
+ * keyboard through the row's menu, so the tree stays a single tab stop.
+ */
const LayerRowComponent = ({
commands,
density,
@@ -102,8 +107,10 @@ const LayerRowComponent = ({
id: row.id,
});
const { setNodeRef: setDropRef } = useDroppable({ data: { stack: vm.stack }, disabled: dragDisabled, id: row.id });
+ const rowElement = useRef<HTMLDivElement | null>(null);
const setRowRef = useCallback(
- (element: HTMLElement | null) => {
+ (element: HTMLDivElement | null) => {
+ rowElement.current = element;
setDragRef(element);
setDropRef(element);
},
@@ -112,18 +119,36 @@ const LayerRowComponent = ({
const nameInput = useRef<HTMLInputElement | null>(null);
// Escape abandons the draft; the blur that follows refocusing the row must not commit it.
const renameCancelled = useRef(false);
- const treeItem = useRef<HTMLButtonElement | null>(null);
+
+ useLayoutEffect(() => {
+ recordLayerRowCommit(row.id);
+ });
const indentStyle = useMemo(() => ({ paddingLeft: `${vm.depth * LAYER_TREE_INDENT_PX}px` }), [vm.depth]);
const handleSelect = useCallback(
- (event: MouseEvent<HTMLButtonElement>) =>
+ (event: MouseEvent<HTMLElement>) =>
commands.select(row.id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey }),
[commands, row.id]
);
const handleFocus = useCallback(() => commands.focus(row.id), [commands, row.id]);
+ // A pressed control never takes focus from the tree item; the row it belongs to keeps the tab stop.
+ const keepRowFocus = useCallback((event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ rowElement.current?.focus();
+ }, []);
const handleKeyDown = useCallback(
- (event: KeyboardEvent<HTMLButtonElement>) => commands.keyDown(row.id, event),
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (event.target !== event.currentTarget) {
+ return;
+ }
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ commands.select(row.id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey });
+ return;
+ }
+ commands.keyDown(row.id, event);
+ },
[commands, row.id]
);
const handleToggleExpanded = useCallback(
@@ -180,27 +205,51 @@ const LayerRowComponent = ({
commands.startRename(row.id);
}
}, [commands, editingLocked, row.id]);
- const finishRename = useCallback(() => {
- commands.endRename();
- treeItem.current?.focus();
- }, [commands]);
- const commitName = useCallback(() => {
- const name = nameInput.current?.value.trim() ?? '';
- const cancelled = renameCancelled.current;
- finishRename();
- if (!cancelled && name && name !== node.name) {
- commands.rename(row.id, name);
- }
- }, [commands, finishRename, node.name, row.id]);
+ const finishRename = useCallback(
+ (refocus: boolean) => {
+ commands.endRename();
+ if (refocus) {
+ rowElement.current?.focus();
+ }
+ },
+ [commands]
+ );
+ const commitName = useCallback(
+ (refocus: boolean) => {
+ const name = nameInput.current?.value.trim() ?? '';
+ const cancelled = renameCancelled.current;
+ finishRename(refocus);
+ if (!cancelled && name && name !== node.name) {
+ commands.rename(row.id, name);
+ }
+ },
+ [commands, finishRename, node.name, row.id]
+ );
+ // Focus that dropped returns to the row. Focus that left for another element stays there, and is
+ // set explicitly: committing unmounts the input while the browser is still moving focus, and that
+ // move is dropped along with the input.
+ const handleNameBlur = useCallback(
+ (event: FocusEvent<HTMLInputElement>) => {
+ const next = event.relatedTarget;
+ // The window losing focus is not a decision; the draft waits for it to come back.
+ if (next === null && !window.document.hasFocus()) {
+ return;
+ }
+ commitName(next === null);
+ if (next instanceof HTMLElement) {
+ next.focus();
+ }
+ },
+ [commitName]
+ );
const handleNameKeyDown = useCallback(
(event: KeyboardEvent<HTMLInputElement>) => {
+ event.stopPropagation();
if (event.key === 'Enter') {
- event.stopPropagation();
- commitName();
+ commitName(true);
} else if (event.key === 'Escape') {
- event.stopPropagation();
renameCancelled.current = true;
- finishRename();
+ finishRename(true);
}
},
[commitName, finishRename]
@@ -212,8 +261,8 @@ const LayerRowComponent = ({
input?.select();
}, []);
- // Pointer listeners only: the tree item owns its role, focus and keyboard model, and dnd-kit's
- // keyboard activator, roledescription and instructions stay out of the accessibility tree.
+ // Pointer listeners only: the tree item owns its keyboard model; dnd-kit's keyboard activator,
+ // roledescription and instructions stay out of the accessibility tree.
const dragListeners = useMemo(() => {
if (dragDisabled || !listeners) {
return {};
@@ -232,10 +281,26 @@ const LayerRowComponent = ({
<Box
ref={setRowRef}
{...dragListeners}
+ aria-current={primary ? 'true' : undefined}
+ aria-expanded={group ? row.expanded : undefined}
+ aria-label={node.name}
+ aria-level={vm.depth + 2}
+ aria-posinset={row.posInSet}
+ aria-selected={selected}
+ aria-setsize={row.setSize}
data-layer-row-id={row.id}
+ data-primary={primary || undefined}
h="full"
opacity={drag ? 0.4 : undefined}
+ role="treeitem"
+ rounded="sm"
+ tabIndex={focused ? 0 : -1}
+ _focusVisible={ROW_SELECTION_FOCUS}
+ onClick={handleSelect}
onContextMenu={handleContextMenu}
+ onDoubleClick={startRename}
+ onFocus={handleFocus}
+ onKeyDown={handleKeyDown}
>
<Row
active={selected ? 'muted' : undefined}
@@ -246,43 +311,21 @@ const LayerRowComponent = ({
gap="1.5"
h="full"
px="1.5"
- position="relative"
style={indentStyle}
transition={LAYER_ROW_BACKGROUND_TRANSITION}
>
- {/* No grip: the whole row is the pointer drag target; this row-covering button is the tree item. */}
- <chakra.button
- ref={treeItem}
- aria-current={primary ? 'true' : undefined}
- aria-expanded={group ? row.expanded : undefined}
- aria-label={t('widgets.layers.actions.select', { name: node.name })}
- aria-level={vm.depth + 1}
- aria-posinset={row.posInSet}
- aria-selected={selected}
- aria-setsize={row.setSize}
- data-primary={primary || undefined}
- inset="0"
- position="absolute"
- role="treeitem"
- rounded="sm"
- tabIndex={focused ? 0 : -1}
- type="button"
- _focusVisible={ROW_SELECTION_FOCUS}
- onClick={handleSelect}
- onDoubleClick={startRename}
- onFocus={handleFocus}
- onKeyDown={handleKeyDown}
- />
- <HStack css={ROW_INTERACTIVE_DESCENDANTS} gap="1.5" h="full" pointerEvents="none" position="relative" w="full">
+ <HStack gap="1.5" h="full" w="full">
{group ? (
<IconButton
aria-label={t(
row.expanded ? 'widgets.layers.actions.collapseGroup' : 'widgets.layers.actions.expandGroup'
)}
- color="fg.subtle"
+ color="fg.muted"
size="2xs"
+ tabIndex={-1}
variant="ghost"
onClick={handleToggleExpanded}
+ onMouseDown={keepRowFocus}
onPointerDown={stopPropagation}
>
<Icon
@@ -321,7 +364,8 @@ const LayerRowComponent = ({
aria-label={t('widgets.layers.actions.rename')}
defaultValue={node.name}
size="2xs"
- onBlur={commitName}
+ onBlur={handleNameBlur}
+ onClick={stopPropagation}
onKeyDown={handleNameKeyDown}
onPointerDown={stopPropagation}
/>
@@ -336,14 +380,14 @@ const LayerRowComponent = ({
{density !== 'compact' ? (
<HStack gap="1" minW="0">
{group ? (
- <Text color="fg.subtle" fontSize="2xs">
+ <Text color="fg.muted" fontSize="2xs">
{vm.leafCount === 0
? t('widgets.layers.groupEmpty')
: t('widgets.layers.groupSummary', { count: vm.leafCount })}
</Text>
) : (
<>
- <Text color="fg.subtle" fontSize="2xs" minW="0" truncate>
+ <Text color="fg.muted" fontSize="2xs" minW="0" truncate>
{layerRowSummary(layer!, t)}
</Text>
<ControlLayerWarningIcon contributing={vm.contributionEnabled} layer={layer!} />
@@ -353,7 +397,7 @@ const LayerRowComponent = ({
) : null}
</Stack>
{/* One control cluster on the same rhythm as the stack header; slots a row cannot use are held open. */}
- <HStack flexShrink="0" gap="0.5">
+ <HStack flexShrink="0" gap="0.5" onClick={stopPropagation} onMouseDown={keepRowFocus}>
{hideable ? (
<Tooltip
content={
@@ -363,9 +407,10 @@ const LayerRowComponent = ({
<IconButton
aria-label={t('widgets.layers.actions.toggleHidden')}
aria-pressed={!ownHidden}
- color={vm.documentHidden ? 'fg.subtle' : 'fg'}
+ color={vm.documentHidden ? 'fg.muted' : 'fg'}
disabled={editingLocked || hiddenByAncestor}
size="2xs"
+ tabIndex={-1}
variant="ghost"
onClick={handleToggleHidden}
onPointerDown={stopPropagation}
@@ -376,7 +421,7 @@ const LayerRowComponent = ({
) : (
<Box boxSize="6" />
)}
- <Box display="flex" flexShrink="0" onClick={stopPropagation} onPointerDown={stopPropagation}>
+ <Box display="flex" flexShrink="0" onPointerDown={stopPropagation}>
<ToggleDot
_before={
node.isEnabled
@@ -395,6 +440,7 @@ const LayerRowComponent = ({
h="6"
label={t('widgets.layers.actions.toggleVisibility')}
position="relative"
+ tabIndex={-1}
tooltip={disabledByAncestor ? t('widgets.layers.actions.groupDisabled') : undefined}
transition="none"
w="6"
@@ -408,9 +454,10 @@ const LayerRowComponent = ({
>
<IconButton
aria-label={t('widgets.layers.actions.toggleLock')}
- color={node.isLocked ? 'fg' : vm.effectiveLocked ? 'fg.muted' : 'fg.subtle'}
+ color={node.isLocked ? 'fg' : 'fg.muted'}
disabled={editingLocked || lockedByAncestor}
size="2xs"
+ tabIndex={-1}
variant="ghost"
onClick={handleToggleLock}
onPointerDown={stopPropagation}
@@ -421,9 +468,10 @@ const LayerRowComponent = ({
{layer ? (
<IconButton
aria-label={t('widgets.layers.properties')}
- color="fg.subtle"
+ color="fg.muted"
disabled={editingLocked}
size="2xs"
+ tabIndex={-1}
variant="ghost"
onClick={handleOpenProperties}
onPointerDown={stopPropagation}
@@ -437,6 +485,7 @@ const LayerRowComponent = ({
aria-label={t('widgets.layers.options')}
color="fg.muted"
size="2xs"
+ tabIndex={-1}
variant="ghost"
onClick={handleOpenMenu}
onPointerDown={stopPropagation}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
index 20271bd14e..29de5842b2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx
@@ -1,220 +1,160 @@
import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';
-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
-import type { LucideIcon } from 'lucide-react';
+import type { KeyboardEvent, MouseEvent } from 'react';
-import { HStack, Icon, Text } from '@chakra-ui/react';
-import { IconButton, toaster, Tooltip } from '@platform/ui';
-import { canMergeVisibleRasters, compileDocumentNodes, getDocumentLeaves } from '@workbench/canvas-engine/api';
-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { useActiveProjectName } from '@workbench/WorkbenchContext';
-import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
-import { memo, useCallback } from 'react';
+import { Box, HStack, Icon, Text } from '@chakra-ui/react';
+import { IconButton, Tooltip } from '@platform/ui';
+import { ChevronDownIcon } from 'lucide-react';
+import { memo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { stackAddItemId } from './addLayerMenu';
-import {
- canExportRasterPsd,
- getStackActions,
- isStackAllVisible,
- planStackVisibilityToggle,
- stackVisibilityAxis,
-} from './layerStackActions';
-import { getPsdExportNoticeKey } from './psdExportNotice';
-import { useAddLayer } from './useAddLayer';
+import type { LayerRowCommands } from './layerRowCommands';
-export type LayerStackHeaderEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
+import { anchorFromPoint } from './layerRowCommands';
+import { useLayerStackActions, type LayerStackActionsEngine } from './useLayerStackActions';
+
+const HEADER_FOCUS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' };
interface LayerStackHeaderProps {
collapsed: boolean;
+ commands: LayerRowCommands;
document: CanvasDocumentContractV3;
editingLocked: boolean;
- engine: LayerStackHeaderEngine | null;
+ engine: LayerStackActionsEngine | null;
+ focused: boolean;
leafCount: number;
+ /** The header's tree key, the id the tree addresses it by. */
+ rowKey: string;
+ posInSet: number;
+ setSize: number;
stack: LayerStackKind;
- onToggleCollapse: (stack: LayerStackKind) => void;
+ /** A pinned copy is visual only; the tree's own header stays the accessible one. */
+ pinned?: boolean;
}
-/** One stack's header row: chevron, name, count, and the right-aligned action cluster. */
+const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();
+
+/**
+ * One stack's header: a level-one tree item that expands or collapses the stack, with the stack's
+ * actions as pointer-only buttons inside it. The same actions reach the keyboard through the
+ * stack menu (Shift+F10) so nothing here is a tab stop of its own.
+ */
const LayerStackHeaderComponent = ({
collapsed,
+ commands,
document,
editingLocked,
engine,
+ focused,
leafCount,
+ pinned = false,
+ posInSet,
+ rowKey,
+ setSize,
stack,
- onToggleCollapse,
}: LayerStackHeaderProps) => {
const { t } = useTranslation();
- const handleToggle = useCallback(() => onToggleCollapse(stack), [onToggleCollapse, stack]);
- return (
- <HStack bg="bg.panel" gap="1" h="full" px="2.5">
- <IconButton
- aria-label={t(collapsed ? 'widgets.layers.groupActions.expand' : 'widgets.layers.groupActions.collapse')}
- color="fg.subtle"
- size="2xs"
- variant="ghost"
- onClick={handleToggle}
- >
- <Icon
- as={ChevronDownIcon}
- boxSize="3.5"
- transform={collapsed ? 'rotate(-90deg)' : undefined}
- transitionDuration="fast"
- transitionProperty="transform"
- />
- </IconButton>
- <Text
- color="fg.muted"
- cursor="pointer"
- flex="1"
- fontSize="2xs"
- fontWeight="700"
- textTransform="uppercase"
- truncate
- userSelect="none"
- onClick={handleToggle}
- >
- {t(`widgets.layers.groups.${stack}`)} ({leafCount})
- </Text>
- <StackActions document={document} editingLocked={editingLocked} engine={engine} stack={stack} />
- </HStack>
+ const actions = useLayerStackActions(stack, document, engine, editingLocked);
+ const handleToggle = useCallback(
+ (event: { stopPropagation: () => void }) => {
+ event.stopPropagation();
+ commands.toggleCollapse(stack);
+ },
+ [commands, stack]
);
-};
-
-export const LayerStackHeader = memo(LayerStackHeaderComponent);
-
-/** The right-aligned stack-header action cluster; the set of actions is data (`getStackActions`). */
-const StackActions = ({
- document,
- editingLocked,
- engine,
- stack,
-}: {
- document: CanvasDocumentContractV3;
- editingLocked: boolean;
- engine: LayerStackHeaderEngine | null;
- stack: LayerStackKind;
-}) => {
- const commitPrepared = usePreparedCommit(engine);
- const { t } = useTranslation();
- const addLayer = useAddLayer();
- const projectName = useActiveProjectName();
- const axis = stackVisibilityAxis(stack);
- const nodes = compileDocumentNodes(document).filter((node) => node.stack === stack);
- const allVisible = isStackAllVisible(nodes, axis);
- const canMerge =
- !editingLocked &&
- !!engine &&
- stack === 'raster' &&
- canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent);
- const canExport = !!engine && stack === 'raster' && canExportRasterPsd(getDocumentLeaves(document));
-
- const handleNew = useCallback(() => addLayer(stackAddItemId(stack)), [addLayer, stack]);
- const handleToggleVisibility = useCallback(() => {
- const { ids, nextVisible } = planStackVisibilityToggle(nodes, axis);
- if (ids.length === 0) {
- return;
- }
- if (axis === 'hidden') {
- commitPrepared(t('widgets.layers.groupActions.toggleHidden'), (model) =>
- model.prepare({ type: 'set-hidden', updates: ids.map((id) => ({ id, isHidden: !nextVisible })) })
- );
- return;
- }
- commitPrepared(t('widgets.layers.groupActions.toggleVisibility'), (model) =>
- model.prepare({ type: 'set-enabled', updates: ids.map((id) => ({ id, isEnabled: nextVisible })) })
- );
- }, [axis, commitPrepared, nodes, t]);
- const handleMergeVisible = useCallback(() => {
- if (!engine) {
- return;
- }
- void engine.layers.mergeVisibleRasterLayers().then((result) => {
- if (result === 'not-ready') {
- toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });
- } else if (result === 'over-budget') {
- toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });
+ const handleClick = useCallback(() => commands.toggleCollapse(stack), [commands, stack]);
+ const handleFocus = useCallback(() => commands.focus(rowKey), [commands, rowKey]);
+ const element = useRef<HTMLDivElement | null>(null);
+ // A pressed control never takes focus from the tree item.
+ const keepFocus = useCallback((event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ element.current?.focus();
+ }, []);
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (event.target === event.currentTarget) {
+ commands.keyDown(rowKey, event);
}
- });
- }, [engine, t]);
- const handleExportPsd = useCallback(async () => {
- if (!engine) {
- return;
- }
- try {
- const noticeKey = getPsdExportNoticeKey(await engine.exports.exportRasterLayersToPsd(projectName));
- if (noticeKey) {
- toaster.create({ title: t(noticeKey), type: 'warning' });
- }
- } catch {
- toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' });
- }
- }, [engine, projectName, t]);
-
+ },
+ [commands, rowKey]
+ );
+ const handleContextMenu = useCallback(
+ (event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ commands.openStackMenu(stack, anchorFromPoint(event.clientX, event.clientY));
+ },
+ [commands, stack]
+ );
return (
- <HStack gap="0.5">
- {getStackActions(stack).map((action) => {
- switch (action) {
- case 'mergeVisible':
- return (
- <StackActionButton
- key={action}
- disabled={!canMerge}
- icon={LayersIcon}
- label={t('widgets.layers.groupActions.mergeVisible')}
- onClick={handleMergeVisible}
- />
- );
- case 'exportPsd':
- return (
- <StackActionButton
- key={action}
- disabled={editingLocked || !canExport}
- icon={FileDownIcon}
- label={t('widgets.layers.groupActions.exportPsd')}
- onClick={handleExportPsd}
- />
- );
- case 'toggleVisibility':
- return (
- <StackActionButton
- key={action}
- disabled={editingLocked}
- icon={allVisible ? EyeIcon : EyeOffIcon}
- label={t(allVisible ? 'widgets.layers.groupActions.hideAll' : 'widgets.layers.groupActions.showAll')}
- onClick={handleToggleVisibility}
- />
- );
- case 'new':
- return (
- <StackActionButton
- key={action}
- disabled={editingLocked}
- icon={PlusIcon}
- label={t('widgets.layers.groupActions.new')}
- onClick={handleNew}
- />
- );
- }
- })}
- </HStack>
+ <Box
+ ref={element}
+ aria-expanded={!collapsed}
+ aria-hidden={pinned || undefined}
+ aria-label={t(`widgets.layers.groups.${stack}`)}
+ aria-level={1}
+ aria-posinset={posInSet}
+ aria-setsize={setSize}
+ bg="bg.panel"
+ data-layer-row-id={pinned ? undefined : rowKey}
+ h="full"
+ role={pinned ? undefined : 'treeitem'}
+ rounded="sm"
+ tabIndex={pinned ? undefined : focused ? 0 : -1}
+ _focusVisible={HEADER_FOCUS}
+ onClick={handleClick}
+ onContextMenu={handleContextMenu}
+ onFocus={pinned ? undefined : handleFocus}
+ onKeyDown={pinned ? undefined : handleKeyDown}
+ >
+ <HStack gap="1" h="full" px="2.5">
+ <IconButton
+ aria-label={t(collapsed ? 'widgets.layers.groupActions.expand' : 'widgets.layers.groupActions.collapse')}
+ color="fg.muted"
+ size="2xs"
+ tabIndex={-1}
+ variant="ghost"
+ onClick={handleToggle}
+ onMouseDown={keepFocus}
+ >
+ <Icon
+ as={ChevronDownIcon}
+ boxSize="3.5"
+ transform={collapsed ? 'rotate(-90deg)' : undefined}
+ transitionDuration="fast"
+ transitionProperty="transform"
+ />
+ </IconButton>
+ <Text
+ color="fg.muted"
+ cursor="pointer"
+ flex="1"
+ fontSize="2xs"
+ fontWeight="700"
+ textTransform="uppercase"
+ truncate
+ userSelect="none"
+ >
+ {t(`widgets.layers.groups.${stack}`)} ({leafCount})
+ </Text>
+ <HStack gap="0.5" onClick={stopPropagation} onMouseDown={keepFocus}>
+ {actions.map((action) => (
+ <Tooltip key={action.id} content={action.label}>
+ <IconButton
+ aria-label={action.label}
+ color="fg.muted"
+ disabled={action.disabled}
+ size="2xs"
+ tabIndex={-1}
+ variant="ghost"
+ onClick={action.run}
+ >
+ <Icon as={action.icon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ ))}
+ </HStack>
+ </HStack>
+ </Box>
);
};
-const StackActionButton = ({
- disabled,
- icon,
- label,
- onClick,
-}: {
- disabled?: boolean;
- icon: LucideIcon;
- label: string;
- onClick: () => void;
-}) => (
- <Tooltip content={label}>
- <IconButton aria-label={label} color="fg.subtle" disabled={disabled} size="2xs" variant="ghost" onClick={onClick}>
- <Icon as={icon} boxSize="3.5" />
- </IconButton>
- </Tooltip>
-);
+export const LayerStackHeader = memo(LayerStackHeaderComponent);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx
new file mode 100644
index 0000000000..cf17b4a82e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx
@@ -0,0 +1,58 @@
+import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';
+import type { ComponentProps } from 'react';
+
+import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { MenuContent } from '@platform/ui';
+import { useCallback, useMemo } from 'react';
+
+import type { LayerSurfaceAnchor } from './layerRowCommands';
+
+import { useLayerStackActions, type LayerStackActionsEngine } from './useLayerStackActions';
+
+type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];
+
+interface LayerStackMenuProps {
+ anchor: LayerSurfaceAnchor;
+ document: CanvasDocumentContractV3;
+ editingLocked: boolean;
+ engine: LayerStackActionsEngine | null;
+ stack: LayerStackKind;
+ onClose: () => void;
+}
+
+/** The stack header's actions as a menu, so the keyboard reaches them from the header tree item. */
+export const LayerStackMenu = ({ anchor, document, editingLocked, engine, stack, onClose }: LayerStackMenuProps) => {
+ const actions = useLayerStackActions(stack, document, engine, editingLocked);
+ const positioning = useMemo<MenuPositioning>(
+ () => ({ getAnchorRect: () => anchor, placement: 'bottom-start' }),
+ [anchor]
+ );
+ const handleOpenChange = useCallback(
+ (details: { open: boolean }) => {
+ if (!details.open) {
+ onClose();
+ }
+ },
+ [onClose]
+ );
+ return (
+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="13rem" py="1">
+ {actions.map((action) => (
+ <Menu.Item key={action.id} disabled={action.disabled} value={action.id} onSelect={action.run}>
+ <HStack gap="2" minW="0" w="full">
+ <Icon as={action.icon} boxSize="3.5" color="fg.muted" flexShrink={0} />
+ <Text flex="1" fontSize="xs">
+ {action.label}
+ </Text>
+ </HStack>
+ </Menu.Item>
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
index 67f4b13c0d..4cdad28339 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
@@ -1,4 +1,4 @@
-import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/api';
+import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
import type { Dispatch } from 'react';
@@ -11,18 +11,17 @@ import type { LayerSurfaceAnchor } from './layerRowCommands';
import { CanvasLayerContextMenu, type LayerContextMenuEngine } from './LayerContextMenu';
import { LayerGroupContextMenu, type LayerGroupContextMenuEngine } from './LayerGroupContextMenu';
import { LayerPropertiesPopover, type LayerPropertiesEngine } from './LayerPropertiesPopover';
+import { LayerStackMenu } from './LayerStackMenu';
export type LayerSurfaceEngine = LayerContextMenuEngine &
LayerGroupContextMenuEngine &
LayerPropertiesEngine &
- Pick<CanvasEngineHandle, 'projectId'>;
+ Pick<CanvasEngineHandle, 'exports' | 'projectId'>;
/** What the panel currently shows beside a row, addressed by node id rather than owned by the row. */
-export interface LayerSurfaceRequest {
- readonly kind: 'menu' | 'properties';
- readonly id: string;
- readonly anchor: LayerSurfaceAnchor;
-}
+export type LayerSurfaceRequest =
+ | { readonly kind: 'menu' | 'properties'; readonly id: string; readonly anchor: LayerSurfaceAnchor }
+ | { readonly kind: 'stack-menu'; readonly stack: LayerStackKind; readonly anchor: LayerSurfaceAnchor };
interface LayerSurfaceHostProps {
dispatch: Dispatch<CanvasProjectMutation>;
@@ -46,7 +45,7 @@ export const LayerSurfaceHost = ({
surface,
onClose,
}: LayerSurfaceHostProps) => {
- const node = surface ? getDocumentNode(document, surface.id) : null;
+ const node = surface && surface.kind !== 'stack-menu' ? getDocumentNode(document, surface.id) : null;
const menuTarget = useMemo(
() =>
surface?.kind === 'menu' && node && node.type !== 'group'
@@ -55,6 +54,18 @@ export const LayerSurfaceHost = ({
[node, surface]
);
const handleMenuClose = useCallback(() => onClose(), [onClose]);
+ if (surface?.kind === 'stack-menu') {
+ return (
+ <LayerStackMenu
+ anchor={surface.anchor}
+ document={document}
+ editingLocked={editingLocked}
+ engine={engine}
+ stack={surface.stack}
+ onClose={onClose}
+ />
+ );
+ }
if (surface && !node) {
return null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
index d04a7df02f..f449ddcb27 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
@@ -52,7 +52,7 @@ const LayersPanelFooterComponent = ({
value={filter}
onChange={handleFilter}
/>
- <Text color="fg.subtle" flexShrink={0} fontSize="2xs" whiteSpace="nowrap">
+ <Text color="fg.muted" flexShrink={0} fontSize="2xs" whiteSpace="nowrap">
{degraded
? t('widgets.layers.footer.degraded')
: `${t('widgets.layers.footer.layers', { count: leafCount })} · ${t('widgets.layers.footer.groups', { count: groupCount })} · ${t('widgets.layers.footer.selected', { count: selectedCount })}`}
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 ccf8cd0e1d..72a1596cef 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
@@ -16,25 +16,54 @@ import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
import {
clearLayerPanelStates,
readLayerPanelState,
+ reconcileLayerPanelStates,
setLayerPanelFilter,
+ toggleLayerStackCollapsed,
useLayerPanelState,
} from '@workbench/layerPanelState';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { createInstance } from 'i18next';
-import { act, useCallback, useMemo, useState } from 'react';
+import { act, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
-import { LAYER_ROW_HEIGHT_PX } from './layerPanelRows';
+import { getLayerRowCommits, resetLayerRowCommits } from './layerPanelDiagnostics';
+import { LAYER_PANEL_DEGRADE_THRESHOLD, LAYER_ROW_HEIGHT_PX } from './layerPanelRows';
import { LayersTree, type LayersTreeEngine } from './LayersTree';
import { buildLayerStackRows } from './layerTreeRows';
vi.mock('./ControlLayerWarningIcon', () => ({ ControlLayerWarningIcon: () => null }));
vi.mock('./LayerThumbnail', () => ({ LayerThumbnail: () => <span data-testid="thumbnail" /> }));
vi.mock('./LayerStackHeader', () => ({
- LayerStackHeader: ({ stack }: { stack: string }) => <div data-testid="stack-header">{stack}</div>,
+ LayerStackHeader: ({
+ commands,
+ focused,
+ pinned,
+ rowKey,
+ stack,
+ }: {
+ commands: { focus(key: string): void; keyDown(key: string, event: React.KeyboardEvent<HTMLElement>): void };
+ focused: boolean;
+ pinned?: boolean;
+ rowKey: string;
+ stack: string;
+ }) => (
+ <div
+ aria-label={stack}
+ aria-level={1}
+ data-layer-row-id={pinned ? undefined : rowKey}
+ aria-hidden={pinned || undefined}
+ data-testid="stack-header"
+ role="treeitem"
+ tabIndex={pinned ? undefined : focused ? 0 : -1}
+ onFocus={() => commands.focus(rowKey)}
+ onKeyDown={(event) => commands.keyDown(rowKey, event)}
+ >
+ {stack}
+ </div>
+ ),
}));
vi.mock('./LayerSurfaceHost', () => ({
LayerSurfaceHost: ({ surface }: { surface: { kind: string; id: string } | null }) => (
@@ -66,6 +95,7 @@ void i18n.use(initReactI18next).init({
},
groupSummary_one: '{{count}} layer',
groupSummary_other: '{{count}} layers',
+ groups: { raster: 'Raster Layers' },
options: 'Layer options',
properties: 'Layer properties',
tree: 'Layer tree',
@@ -83,7 +113,11 @@ const paint = (id: string, name = id) => layerContract(id, 'raster', { name });
const manyLayers = (count: number): CanvasNodeContract[] =>
Array.from({ length: count }, (_, index) => paint(`l${index}`, `Layer ${index}`));
-const Harness = ({ degraded = false, initialNodes }: { degraded?: boolean; initialNodes: CanvasNodeContract[] }) => {
+let dispatchExternal: (mutation: CanvasProjectMutation) => void = () => undefined;
+const thumbnailRequests = vi.fn();
+const refusalChecks = vi.fn();
+
+const Harness = ({ initialNodes }: { initialNodes: CanvasNodeContract[] }) => {
const [project, setProject] = useState<Project>(() => {
const initial = { ...createInitialWorkbenchState().projects[0]!, id: PROJECT_ID };
return applyCanvasProjectMutation(initial, {
@@ -92,16 +126,35 @@ const Harness = ({ degraded = false, initialNodes }: { degraded?: boolean; initi
});
});
const document = project.canvas.document;
+ // Production reconciles the panel against every document change before the panel reads it.
+ useLayoutEffect(() => reconcileLayerPanelStates([project]), [project]);
const panel = useLayerPanelState(PROJECT_ID, document.selectedLayerId);
const dispatch = useCallback((mutation: CanvasProjectMutation) => {
setProject((current) => applyCanvasProjectMutation(current, mutation));
return true;
}, []);
+ useEffect(() => {
+ dispatchExternal = dispatch;
+ }, [dispatch]);
+ // The real engine handle is stable across document changes; the harness reads the document through a ref.
+ const documentRef = useRef(document);
+ useEffect(() => {
+ documentRef.current = document;
+ }, [document]);
const engine = useMemo(
() =>
({
document: {
- model: () => createDocumentModel(document, { editRevision: 0, projectId: PROJECT_ID }),
+ model: () => {
+ const model = createDocumentModel(documentRef.current, { editRevision: 0, projectId: PROJECT_ID });
+ return {
+ ...model,
+ refusalFor: (command: Parameters<typeof model.refusalFor>[0]) => {
+ refusalChecks(command);
+ return model.refusalFor(command);
+ },
+ };
+ },
},
exports: { hasExportableLayerContent: () => false },
interaction: { get: () => false },
@@ -111,20 +164,20 @@ const Harness = ({ degraded = false, initialNodes }: { degraded?: boolean; initi
return { status: 'committed' as const };
},
},
- previews: { drawLayerThumbnail: () => false, requestLayerThumbnail: () => undefined },
+ previews: { drawLayerThumbnail: () => false, requestLayerThumbnail: thumbnailRequests },
projectId: PROJECT_ID,
}) as unknown as LayersTreeEngine,
- [dispatch, document]
+ [dispatch]
);
const expanded = useMemo(() => new Set(panel.expandedGroupIds), [panel.expandedGroupIds]);
const stacks = useMemo(
- () => buildLayerStackRows(document, expanded, panel.filter),
+ () => buildLayerStackRows(document.stacks, expanded, panel.filter),
[document, expanded, panel.filter]
);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: 320, width: 480 }}>
<LayersTree
- degraded={degraded}
+ degraded={initialNodes.length > LAYER_PANEL_DEGRADE_THRESHOLD}
dispatch={dispatch}
document={document}
editingLocked={false}
@@ -152,7 +205,7 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const renderTree = async (initialNodes: CanvasNodeContract[], degraded = false) => {
+const renderTree = async (initialNodes: CanvasNodeContract[]) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -160,7 +213,7 @@ const renderTree = async (initialNodes: CanvasNodeContract[], degraded = false)
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <Harness degraded={degraded} initialNodes={initialNodes} />
+ <Harness initialNodes={initialNodes} />
</ChakraProvider>
</I18nextProvider>
);
@@ -177,9 +230,14 @@ const settle = () =>
})
);
-const treeitems = (): HTMLButtonElement[] => Array.from(host!.querySelectorAll<HTMLButtonElement>('[role="treeitem"]'));
-const treeitem = (name: string): HTMLButtonElement =>
- host!.querySelector<HTMLButtonElement>(`[role="treeitem"][aria-label="Select ${name}"]`)!;
+const treeitems = (): HTMLElement[] => Array.from(host!.querySelectorAll<HTMLElement>('[role="treeitem"]'));
+const treeitem = (name: string): HTMLElement =>
+ host!.querySelector<HTMLElement>(`[role="treeitem"][aria-label="${name}"]`)!;
+/** Every element inside the tree a Tab press could land on. */
+const tabStops = (): HTMLElement[] =>
+ Array.from(
+ host!.querySelectorAll<HTMLElement>('[role="tree"] button, [role="tree"] input, [role="tree"] [tabindex]')
+ ).filter((element) => element.tabIndex >= 0);
const output = (id: string): string => host!.querySelector<HTMLOutputElement>(`[data-testid="${id}"]`)!.value;
const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {
target.dispatchEvent(
@@ -191,7 +249,12 @@ const centre = (element: Element) => {
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
};
-beforeEach(() => clearLayerPanelStates());
+beforeEach(() => {
+ clearLayerPanelStates();
+ resetLayerRowCommits();
+ thumbnailRequests.mockClear();
+ refusalChecks.mockClear();
+});
afterEach(async () => {
await act(() => root?.unmount());
@@ -205,36 +268,51 @@ describe('LayersTree virtualization', () => {
it('mounts only the rows near the viewport of a 2,000-layer document and keeps the tree height exact', async () => {
await renderTree(manyLayers(2000));
const visible = Math.ceil(320 / LAYER_ROW_HEIGHT_PX.comfortable);
- expect(treeitems().length).toBeLessThanOrEqual(visible + 12 + 1);
+ expect(treeitems().length).toBeLessThanOrEqual(visible + 12 + 2);
expect(treeitems().length).toBeGreaterThanOrEqual(visible);
+ // Thumbnails are asked for once per mounted leaf and never again for the rest of the list.
+ expect(thumbnailRequests.mock.calls.length).toBeLessThanOrEqual(treeitems().length);
const tree = host!.querySelector<HTMLElement>('[role="tree"]')!;
expect(tree.getAttribute('aria-multiselectable')).toBe('true');
expect(getComputedStyle(tree).height).toBe(`${2000 * LAYER_ROW_HEIGHT_PX.comfortable + 28}px`);
});
- it('commits only the rows a selection change touches', async () => {
+ it('commits only the rows a selection change touches, and nothing on scroll', async () => {
await renderTree(manyLayers(2000));
await act(() => userEvent.click(treeitem('Layer 1')));
- const touched = new Set<string>();
- const observer = new MutationObserver((records) => {
- for (const record of records) {
- const row = (record.target as Element).closest?.('[data-layer-row-id]') as HTMLElement | null;
- if (row) {
- touched.add(row.dataset.layerRowId!);
- }
- }
- });
- observer.observe(host!.querySelector('[role="tree"]')!, { attributes: true, childList: true, subtree: true });
+ resetLayerRowCommits();
+ thumbnailRequests.mockClear();
await act(() => userEvent.click(treeitem('Layer 3')));
- observer.disconnect();
expect(output('selected-layer')).toBe('l3');
- expect([...touched].sort()).toEqual(['l1', 'l3']);
+ expect(Object.keys(getLayerRowCommits()).sort()).toEqual(['l1', 'l3']);
+ expect(thumbnailRequests).not.toHaveBeenCalled();
+
+ resetLayerRowCommits();
+ const scroller = host!.querySelector<HTMLElement>('[role="tree"]')!.parentElement!;
+ await act(() => {
+ scroller.scrollTop = 7;
+ scroller.dispatchEvent(new Event('scroll'));
+ });
+ await settle();
+ expect(getLayerRowCommits()).toEqual({});
});
- it('keeps thumbnails and drag off in degraded mode', async () => {
- await renderTree(manyLayers(3), true);
+ it('degrades a document above the threshold: no thumbnails, no drag, every command intact', async () => {
+ await renderTree(manyLayers(LAYER_PANEL_DEGRADE_THRESHOLD + 1));
expect(host!.querySelectorAll('[data-testid="thumbnail"]')).toHaveLength(0);
- expect(treeitem('Layer 0').getAttribute('aria-roledescription')).toBeNull();
+ expect(thumbnailRequests).not.toHaveBeenCalled();
+ const first = host!.querySelector<HTMLElement>('[data-layer-row-id="l0"]')!;
+ const second = host!.querySelector<HTMLElement>('[data-layer-row-id="l1"]')!;
+ const start = centre(first);
+ const end = centre(second);
+ await act(() => pointer('pointerdown', first, start.x, start.y));
+ await act(() => pointer('pointermove', document, start.x + 8, start.y));
+ await act(() => pointer('pointermove', document, end.x, end.y + 12));
+ await act(() => pointer('pointerup', document, end.x, end.y + 12));
+ expect(output('layer-order').startsWith('l0,l1,l2')).toBe(true);
+ treeitem('Layer 0').focus();
+ await act(() => userEvent.keyboard('{Alt>}{ArrowDown}{/Alt}'));
+ expect(output('layer-order').startsWith('l1,l0,l2')).toBe(true);
});
});
@@ -252,11 +330,14 @@ describe('LayersTree keyboard and accessibility', () => {
paint('bottom', 'Bottom'),
];
- it('exposes one tab stop and full tree semantics', async () => {
+ it('exposes one tab stop across every control and full tree semantics', async () => {
await renderTree(nested());
- expect(treeitems().filter((item) => item.tabIndex === 0)).toHaveLength(1);
+ expect(tabStops()).toHaveLength(1);
+ expect(host!.querySelectorAll('[role="tree"] > *')).toHaveLength(
+ host!.querySelectorAll('[role="tree"] > [role="presentation"]').length
+ );
const group = treeitem('Group');
- expect(group).toHaveAttribute('aria-level', '1');
+ expect(group).toHaveAttribute('aria-level', '2');
expect(group).toHaveAttribute('aria-posinset', '2');
expect(group).toHaveAttribute('aria-setsize', '3');
expect(group).toHaveAttribute('aria-expanded', 'false');
@@ -274,13 +355,19 @@ describe('LayersTree keyboard and accessibility', () => {
expect(treeitem('Group')).toHaveAttribute('aria-expanded', 'true');
await act(() => userEvent.keyboard('{ArrowRight}'));
expect(document.activeElement).toBe(treeitem('Inner'));
- expect(treeitem('Inner')).toHaveAttribute('aria-level', '2');
+ expect(treeitem('Inner')).toHaveAttribute('aria-level', '3');
await act(() => userEvent.keyboard('{ArrowLeft}'));
expect(document.activeElement).toBe(treeitem('Group'));
await act(() => userEvent.keyboard('{End}'));
expect(document.activeElement).toBe(treeitem('Bottom'));
await act(() => userEvent.keyboard('{Home}'));
+ expect(document.activeElement).toBe(treeitem('raster'));
+ await act(() => userEvent.keyboard('{ArrowLeft}'));
+ expect(host!.querySelectorAll('[role="treeitem"]')).toHaveLength(1);
+ await act(() => userEvent.keyboard('{ArrowRight}{ArrowRight}'));
expect(document.activeElement).toBe(treeitem('Top'));
+ await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));
+ expect(output('surface')).toBe('menu:top');
});
it('keeps the focused row mounted and focused while scrolled far away', async () => {
@@ -354,6 +441,71 @@ describe('LayersTree selection, surfaces and structure', () => {
expect(output('selected-layer')).toBe('third');
});
+ it('reveals a primary that changed outside the panel once, even inside a collapsed stack', async () => {
+ await renderTree([layerContract('c1', 'control', { name: 'Control' }), ...manyLayers(2000)]);
+ const scroller = host!.querySelector<HTMLElement>('[role="tree"]')!.parentElement!;
+ expect(scroller.scrollTop).toBe(0);
+ await act(() => dispatchExternal({ id: 'l1500', type: 'setCanvasSelectedLayer' }));
+ await settle();
+ expect(scroller.scrollTop).toBeGreaterThan(1000 * LAYER_ROW_HEIGHT_PX.comfortable);
+ expect(treeitem('Layer 1500')).not.toBeNull();
+
+ // Later list changes leave the scroll position alone.
+ await act(() => toggleLayerStackCollapsed(PROJECT_ID, 'l1500', 'control'));
+ scroller.scrollTop = 0;
+ await act(() => toggleLayerStackCollapsed(PROJECT_ID, 'l1500', 'control'));
+ await settle();
+ expect(scroller.scrollTop).toBe(0);
+
+ // A panel selection reveals nothing, but a later external change back to it does.
+ scroller.scrollTop = 1500 * LAYER_ROW_HEIGHT_PX.comfortable;
+ await settle();
+ await act(() => userEvent.click(treeitem('Layer 1501')));
+ const outside = document.createElement('input');
+ document.body.append(outside);
+ outside.focus();
+ scroller.scrollTop = 0;
+ await act(() => dispatchExternal({ id: 'l1500', type: 'setCanvasSelectedLayer' }));
+ await settle();
+ scroller.scrollTop = 0;
+ await act(() => dispatchExternal({ id: 'l1501', type: 'setCanvasSelectedLayer' }));
+ await settle();
+ expect(scroller.scrollTop).toBeGreaterThan(1000 * LAYER_ROW_HEIGHT_PX.comfortable);
+ outside.remove();
+
+ // A primary inside a collapsed stack opens the stack and lands in view.
+ await act(() => toggleLayerStackCollapsed(PROJECT_ID, 'l1500', 'control'));
+ await act(() => dispatchExternal({ id: 'c1', type: 'setCanvasSelectedLayer' }));
+ await settle();
+ expect(readLayerPanelState(PROJECT_ID, 'c1').collapsedStacks).toEqual([]);
+ expect(treeitem('Control')).not.toBeNull();
+ expect(scroller.scrollTop).toBe(0);
+ });
+
+ it('scrolls the list while a drag rests in the edge band and asks the model once per target', async () => {
+ await renderTree(manyLayers(200));
+ const scroller = host!.querySelector<HTMLElement>('[role="tree"]')!.parentElement!;
+ const first = host!.querySelector<HTMLElement>('[data-layer-row-id="l0"]')!;
+ const start = centre(first);
+ const rect = scroller.getBoundingClientRect();
+ await act(() => pointer('pointerdown', first, start.x, start.y));
+ await act(() => pointer('pointermove', document, start.x + 8, start.y));
+ await act(() => pointer('pointermove', document, start.x, rect.bottom - 4));
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 120);
+ });
+ const scrolled = scroller.scrollTop;
+ expect(scrolled).toBeGreaterThan(0);
+ await act(() => pointer('pointermove', document, start.x, rect.top + rect.height / 2));
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 60);
+ });
+ expect(scroller.scrollTop).toBe(scrolled);
+ const checks = refusalChecks.mock.calls.length;
+ await act(() => pointer('pointerup', document, start.x, rect.top + rect.height / 2));
+ expect(checks).toBeLessThanOrEqual(6);
+ });
+
it('reorders with a pointer drag and reparents from the keyboard', async () => {
await renderTree([
paint('first', 'First'),
@@ -374,7 +526,7 @@ describe('LayersTree selection, surfaces and structure', () => {
await act(() => userEvent.keyboard('{Alt>}{ArrowRight}{/Alt}'));
expect(output('layer-order')).toBe('inner,third,first');
expect(readLayerPanelState(PROJECT_ID, null).expandedGroupIds).toContain('g');
- expect(treeitem('Third')).toHaveAttribute('aria-level', '2');
+ expect(treeitem('Third')).toHaveAttribute('aria-level', '3');
});
});
@@ -398,6 +550,67 @@ describe('LayersTree list changes', () => {
expect(treeitems().length).toBeGreaterThan(8);
});
+ it('keeps the focused node and its rename draft when rows above it come and go', async () => {
+ await renderTree([layerContract('c1', 'control', { name: 'Control' }), ...manyLayers(30)]);
+ const row = treeitem('Layer 3');
+ row.focus();
+ await act(() => userEvent.keyboard('{F2}'));
+ const input = host!.querySelector<HTMLInputElement>('input[aria-label="Rename"]')!;
+ await act(() => userEvent.keyboard('abc'));
+ await act(() => toggleLayerStackCollapsed(PROJECT_ID, readLayerPanelState(PROJECT_ID, null).primaryId, 'control'));
+ await settle();
+ expect(host!.querySelector<HTMLInputElement>('input[aria-label="Rename"]')).toBe(input);
+ expect(input.value).toBe('abc');
+ await act(() => userEvent.keyboard('{Escape}'));
+ expect(treeitem('Layer 3')).toBe(row);
+ expect(document.activeElement).toBe(row);
+ await act(() => toggleLayerStackCollapsed(PROJECT_ID, readLayerPanelState(PROJECT_ID, null).primaryId, 'control'));
+ await settle();
+ expect(document.activeElement).toBe(treeitem('Layer 3'));
+ expect(treeitem('Control')).not.toBeNull();
+ });
+
+ it('keeps the tree item focused when one of its controls is clicked, and lets a rename blur follow a click', async () => {
+ await renderTree(manyLayers(3));
+ await act(() => userEvent.click(treeitem('Layer 1').querySelector('button[aria-label="Toggle lock"]')!));
+ expect(document.activeElement).toBe(treeitem('Layer 1'));
+ expect(tabStops()).toEqual([treeitem('Layer 1')]);
+ await act(() => userEvent.keyboard('{F2}'));
+ await act(() => userEvent.keyboard('New'));
+ await act(() => userEvent.click(treeitem('Layer 2')));
+ expect(treeitem('New')).not.toBeNull();
+ expect(document.activeElement).toBe(treeitem('Layer 2'));
+ expect(output('selected-layer')).toBe('l2');
+ });
+
+ it('carries the selection with a keyboard move', async () => {
+ await renderTree(manyLayers(3));
+ await act(() => userEvent.click(treeitem('Layer 0')));
+ await act(() => userEvent.click(treeitem('Layer 1'), { modifiers: ['Shift'] }));
+ expect(output('selected-layers')).toBe('l0,l1');
+ treeitem('Layer 0').focus();
+ await act(() => userEvent.keyboard('{Alt>}{ArrowDown}{/Alt}'));
+ expect(output('layer-order')).toBe('l2,l0,l1');
+ });
+
+ it('leaves a locked group closed when an indent into it is refused, and ignores an empty move', async () => {
+ await renderTree([
+ groupContract('g', [paint('inner', 'Inner')], { isLocked: true, name: 'Group' }),
+ paint('bottom', 'Bottom'),
+ ]);
+ treeitem('Bottom').focus();
+ await act(() => userEvent.keyboard('{Alt>}{ArrowRight}{/Alt}'));
+ expect(output('layer-order')).toBe('inner,bottom');
+ expect(readLayerPanelState(PROJECT_ID, null).expandedGroupIds).toEqual([]);
+ await act(() => userEvent.keyboard('{ArrowUp}{ArrowRight}{ArrowDown}'));
+ expect(document.activeElement).toBe(treeitem('Inner'));
+ await act(() => userEvent.click(treeitem('Group')));
+ await act(() => userEvent.click(treeitem('Inner'), { modifiers: ['Control'] }));
+ treeitem('Inner').focus();
+ await act(() => userEvent.keyboard('{Alt>}{ArrowLeft}{/Alt}'));
+ expect(output('layer-order')).toBe('inner,bottom');
+ });
+
it('renames from the keyboard, reseeds the draft each time, and hands focus back to the row', async () => {
await renderTree(manyLayers(3));
treeitem('Layer 1').focus();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 15a5fd257f..981d74bd8a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -25,24 +25,28 @@ import { useTranslation } from 'react-i18next';
import type { LayerRowCommands, LayerSurfaceAnchor } from './layerRowCommands';
import type { LayerStackRowsByKind } from './layerTreeRows';
+import type { LayerStackActionsEngine } from './useLayerStackActions';
import {
flattenPanelRows,
+ isHeaderKey,
isTreeNavigationKey,
LAYER_HEADER_HEIGHT_PX,
LAYER_TREE_INDENT_PX,
navigateTree,
panelRowHeight,
+ stackOfHeaderKey,
type PanelRow,
} from './layerPanelRows';
import { clearLayerPropertiesRequest, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';
import { LayerDragGhost, LayerRow, type LayerRowDragState } from './LayerRow';
import { anchorFromRect } from './layerRowCommands';
-import { LayerStackHeader, type LayerStackHeaderEngine } from './LayerStackHeader';
+import { LayerStackHeader } from './LayerStackHeader';
import { LayerSurfaceHost, type LayerSurfaceEngine, type LayerSurfaceRequest } from './LayerSurfaceHost';
+import { createLayerTreeAutoScroller, type LayerTreeAutoScroller } from './layerTreeAutoScroll';
import { outermostRowIds, projectLayerDrop, type LayerDropTarget } from './layerTreeDrop';
-export type LayersTreeEngine = LayerStackHeaderEngine & LayerSurfaceEngine & Pick<CanvasEngineHandle, 'previews'>;
+export type LayersTreeEngine = LayerStackActionsEngine & LayerSurfaceEngine & Pick<CanvasEngineHandle, 'previews'>;
const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;
const OVERLAY_MODIFIERS = [restrictToVerticalAxis];
@@ -78,23 +82,20 @@ interface LayersTreeProps {
const edgeOf = (rect: { top: number; height: number } | undefined, y: number): 'above' | 'below' =>
rect && y >= rect.top + rect.height / 2 ? 'below' : 'above';
-const isNodeRow = (row: PanelRow | undefined): row is Extract<PanelRow, { kind: 'node' }> => row?.kind === 'node';
+const isMenuKey = (event: KeyboardEvent<HTMLElement>): boolean =>
+ event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey);
+
+/** The viewport box of a rendered item, the anchor a keyboard-opened menu uses. */
+const anchorOfItem = (host: HTMLElement | null, key: string): LayerSurfaceAnchor | null => {
+ const element = host?.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(key)}"]`);
+ return element ? anchorFromRect(element.getBoundingClientRect()) : null;
+};
/** One absolutely positioned slot of the virtual list; the style object is built once per offset. */
-const VirtualSlot = ({
- children,
- header,
- size,
- start,
-}: {
- children: ReactNode;
- header: boolean;
- size: number;
- start: number;
-}) => {
+const VirtualSlot = ({ children, size, start }: { children: ReactNode; size: number; start: number }) => {
const style = useMemo(() => ({ height: size, top: start }), [size, start]);
return (
- <Box left="0" position="absolute" right="0" role={header ? 'presentation' : undefined} style={style}>
+ <Box left="0" position="absolute" right="0" role="presentation" style={style}>
{children}
</Box>
);
@@ -102,8 +103,8 @@ const VirtualSlot = ({
/**
* The virtualized, keyboard-first layer tree: one scroll container, one drag context, one menu
- * host, fixed row heights per density, and a roving tab stop. Rows receive a view model and a
- * command handle; every subscription and commit lives here.
+ * host, fixed row heights per density, and a single roving tab stop over stack headers and rows.
+ * Rows receive a view model and a command handle; every subscription and commit lives here.
*/
export const LayersTree = ({
degraded,
@@ -135,6 +136,9 @@ export const LayersTree = ({
const pendingProperties = useRef<{ id: string; token: number; scrolled: boolean; opened: boolean } | null>(null);
// Whether keyboard focus lives in the tree; read by the repair effect after the focused row is gone.
const treeOwnsFocus = useRef(false);
+ // The primary the panel itself selected last; any other primary change came from outside and is revealed.
+ const panelSelectedPrimary = useRef<string | null>(null);
+ const revealedPrimary = useRef<string | null>(null);
const { density, selectedIds, primaryId } = panel;
const requestedId = propertiesRequest?.layerId ?? null;
@@ -147,15 +151,8 @@ export const LayersTree = ({
() => flattenPanelRows(stacks, panel.collapsedStacks, forceOpen),
[forceOpen, panel.collapsedStacks, stacks]
);
- const rowIndexById = useMemo(() => {
- const map = new Map<string, number>();
- panelRows.forEach((row, index) => {
- if (row.kind === 'node') {
- map.set(row.row.id, index);
- }
- });
- return map;
- }, [panelRows]);
+ // Every item, header or node, by its tree key.
+ const rowIndexByKey = useMemo(() => new Map(panelRows.map((row, index) => [row.key, index])), [panelRows]);
const offsets = useMemo(() => {
const starts = new Float64Array(panelRows.length + 1);
panelRows.forEach((row, index) => {
@@ -163,24 +160,25 @@ export const LayersTree = ({
});
return starts;
}, [density, panelRows]);
- const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]);
- const allNodeIds = useMemo(
- () => Object.values(stacks).flatMap((stack) => (stack.nodeIds.length > 0 ? stack.nodeIds : [])),
- [stacks]
+ const headerIndexes = useMemo(
+ () => panelRows.flatMap((row, index) => (row.kind === 'header' ? [index] : [])),
+ [panelRows]
);
+ const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]);
+ const allNodeIds = useMemo(() => Object.values(stacks).flatMap((stack) => stack.nodeIds), [stacks]);
const visibleRowIds = useMemo(
() => panelRows.flatMap((row) => (row.kind === 'node' ? [row.row.id] : [])),
[panelRows]
);
- const focusId =
- panel.focusId && rowIndexById.has(panel.focusId)
+ const focusKey =
+ panel.focusId && rowIndexByKey.has(panel.focusId)
? panel.focusId
- : primaryId && rowIndexById.has(primaryId)
+ : primaryId && rowIndexByKey.has(primaryId)
? primaryId
- : (visibleRowIds[0] ?? null);
- const focusIndex = focusId ? (rowIndexById.get(focusId) ?? -1) : -1;
+ : (panelRows[0]?.key ?? null);
+ const focusIndex = focusKey ? (rowIndexByKey.get(focusKey) ?? -1) : -1;
- // The focused row stays mounted whatever the scroll position: focus must never fall off the tree.
+ // The focused item stays mounted whatever the scroll position: focus must never fall off the tree.
const rangeExtractor = useCallback(
(range: Range) => {
const indexes = defaultRangeExtractor(range);
@@ -193,6 +191,8 @@ export const LayersTree = ({
[focusIndex]
);
const getScrollElement = useCallback(() => scrollRef.current, []);
+ // Created once the scroll element exists; handlers reach it through the ref.
+ const autoScroller = useRef<LayerTreeAutoScroller | null>(null);
const estimateSize = useCallback((index: number) => panelRowHeight(panelRows[index]!, density), [density, panelRows]);
const getItemKey = useCallback((index: number) => panelRows[index]?.key ?? index, [panelRows]);
const virtualizer = useVirtualizer({
@@ -202,6 +202,8 @@ export const LayersTree = ({
getScrollElement,
overscan: OVERSCAN_ROWS,
rangeExtractor,
+ // A revealed row lands below the pinned header, never under it.
+ scrollPaddingStart: LAYER_HEADER_HEIGHT_PX,
});
const virtualItems = virtualizer.virtualItems;
// Fixed sizes change only with the row list or the density; re-measure then, never per snapshot.
@@ -211,16 +213,12 @@ export const LayersTree = ({
useLayoutEffect(() => {
measureVirtualizer();
}, [density, panelRows]);
-
- const handleScroll = useCallback(() => setScrollTop(scrollRef.current?.scrollTop ?? 0), []);
const virtualizerRef = useRef(virtualizer);
useLayoutEffect(() => {
virtualizerRef.current = virtualizer;
});
- const headerIndexes = useMemo(
- () => panelRows.flatMap((row, index) => (row.kind === 'header' ? [index] : [])),
- [panelRows]
- );
+
+ const handleScroll = useCallback(() => setScrollTop(scrollRef.current?.scrollTop ?? 0), []);
// Event handlers read the latest render through this ref, so the command handle never changes identity.
const latest = useRef({
@@ -232,7 +230,8 @@ export const LayersTree = ({
panel,
panelRows,
projectId,
- rowIndexById,
+ rowIndexByKey,
+ stacks,
visibleRowIds,
});
useLayoutEffect(() => {
@@ -245,53 +244,89 @@ export const LayersTree = ({
panel,
panelRows,
projectId,
- rowIndexById,
+ rowIndexByKey,
+ stacks,
visibleRowIds,
};
});
+ // A keyboard move on a selected row carries the selection, exactly as a drag of it would.
+ const movingIds = useCallback((key: string, stack: LayerStackKind): readonly string[] => {
+ const { panel: current, stacks: forests } = latest.current;
+ return current.selectedIds.includes(key)
+ ? outermostRowIds(forests[stack].rows, new Set(current.selectedIds))
+ : [key];
+ }, []);
- const focusRow = useCallback((id: string) => {
- const { panel: current, projectId: project, rowIndexById: rows } = latest.current;
- setLayerPanelFocus(project, current.primaryId, id);
- const index = rows.get(id);
+ const focusItem = useCallback((key: string) => {
+ const { panel: current, projectId: project, rowIndexByKey: keys } = latest.current;
+ setLayerPanelFocus(project, current.primaryId, key);
+ const index = keys.get(key);
if (index !== undefined) {
virtualizerRef.current.scrollToIndex(index);
}
- pendingFocus.current = id;
+ pendingFocus.current = key;
}, []);
const runStructural = useCallback((label: string, command: DocumentCommand) => {
const { commitPrepared: commit } = latest.current;
- commit(label, (model) => model.prepare(command));
+ return commit(label, (model) => model.prepare(command));
}, []);
- // One handle for every row; it reads the latest render through a ref so rows never re-render for it.
+ // 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>(
() => ({
endRename: () => setRenamingId(null),
- focus: (id) => {
+ focus: (key) => {
const { panel: current, projectId: project } = latest.current;
- if (current.focusId !== id) {
- setLayerPanelFocus(project, current.primaryId, id);
+ if (current.focusId !== key) {
+ setLayerPanelFocus(project, current.primaryId, key);
}
},
- keyDown: (id, event: KeyboardEvent<HTMLElement>) => {
+ keyDown: (key, event: KeyboardEvent<HTMLElement>) => {
const { document: currentDocument, panel: current, panelRows: rows, projectId: project } = latest.current;
- if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
+ 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' }
+ );
+ }
+ return;
+ }
+ if (isHeaderKey(key)) {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ toggleLayerStackCollapsed(project, current.primaryId, stackOfHeaderKey(key));
+ return;
+ }
+ } else if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
event.preventDefault();
+ const vm = lookupDocumentNodeState(currentDocument, key);
+ if (!vm) {
+ return;
+ }
runStructural(t('widgets.layers.actions.reorder'), {
- ids: [id],
+ ids: movingIds(key, vm.stack),
kind: event.key === 'ArrowUp' ? 'forward' : 'backward',
type: 'move',
});
return;
- }
- if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
+ } else if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
event.preventDefault();
- const vm = lookupDocumentNodeState(currentDocument, id);
+ const vm = lookupDocumentNodeState(currentDocument, key);
if (!vm) {
return;
}
+ // Only siblings of the focused row can follow it into or out of a group.
+ const ids = movingIds(key, vm.stack).filter(
+ (id) => lookupDocumentNodeState(currentDocument, id)?.parentId === vm.parentId
+ );
+ if (ids.length === 0) {
+ return;
+ }
if (event.key === 'ArrowLeft') {
if (vm.parentId === null) {
return;
@@ -305,7 +340,7 @@ export const LayersTree = ({
const beforeId = grandSiblings[parent.siblingIndex + 1]?.id ?? null;
runStructural(t('widgets.layers.actions.outdent'), {
beforeId,
- ids: [id],
+ ids,
parentId: parent.parentId,
type: 'reparent',
});
@@ -320,26 +355,27 @@ export const LayersTree = ({
if (!above || above.type !== 'group') {
return;
}
- setLayerGroupExpanded(project, current.primaryId, [above.id], true);
- runStructural(t('widgets.layers.actions.indent'), {
+ const outcome = runStructural(t('widgets.layers.actions.indent'), {
beforeId: null,
- ids: [id],
+ ids,
parentId: above.id,
type: 'reparent',
});
+ if (outcome.status === 'committed') {
+ setLayerGroupExpanded(project, current.primaryId, [above.id], true);
+ }
return;
- }
- if (event.key === 'F2') {
+ } else if (event.key === 'F2') {
event.preventDefault();
if (!latest.current.editingLocked) {
- setRenamingId(id);
+ setRenamingId(key);
}
return;
}
if (!isTreeNavigationKey(event.key)) {
return;
}
- const navigation = navigateTree(rows, id, event.key);
+ const navigation = navigateTree(rows, key, event.key);
if (!navigation) {
return;
}
@@ -348,10 +384,17 @@ export const LayersTree = ({
setLayerGroupExpanded(project, current.primaryId, [navigation.expand], navigation.expanded);
return;
}
- focusRow(navigation.focus);
+ if ('collapseStack' in navigation) {
+ if (current.collapsedStacks.includes(navigation.collapseStack) !== navigation.collapsed) {
+ toggleLayerStackCollapsed(project, current.primaryId, navigation.collapseStack);
+ }
+ return;
+ }
+ focusItem(navigation.focus);
},
openMenu: (id, anchor: LayerSurfaceAnchor) => setSurface({ anchor, id, kind: 'menu' }),
openProperties: (id, anchor: LayerSurfaceAnchor) => setSurface({ anchor, id, kind: 'properties' }),
+ openStackMenu: (stack, anchor: LayerSurfaceAnchor) => setSurface({ anchor, kind: 'stack-menu', stack }),
rename: (id, name) => runStructural(t('widgets.layers.actions.rename'), { id, patch: { name }, type: 'patch' }),
select: (id, modifiers: LayerSelectionModifiers) => {
const {
@@ -364,6 +407,7 @@ export const LayersTree = ({
const next = selectLayerInPanel(current, id, modifiers.range ? visible : all, modifiers);
publishLayerPanelSelection(next);
setLayerPanelFocus(project, next.primaryId, id);
+ panelSelectedPrimary.current = next.primaryId;
if (next.primaryId !== current.primaryId) {
send({ id: next.primaryId, type: 'setCanvasSelectedLayer' });
}
@@ -378,6 +422,10 @@ export const LayersTree = ({
setLocked: (id, isLocked) =>
runStructural(t('widgets.layers.actions.toggleLock'), { type: 'set-locked', updates: [{ id, isLocked }] }),
startRename: (id) => setRenamingId(id),
+ toggleCollapse: (stack) => {
+ const { panel: current, projectId: project } = latest.current;
+ toggleLayerStackCollapsed(project, current.primaryId, stack);
+ },
toggleExpanded: (id) => {
const { panel: current, projectId: project } = latest.current;
// A filter decides expansion itself; the chevron is inert until it is cleared.
@@ -386,13 +434,9 @@ export const LayersTree = ({
}
},
}),
- [focusRow, runStructural, t]
+ [focusItem, movingIds, runStructural, t]
);
- const handleToggleCollapse = useCallback(
- (stack: LayerStackKind) => toggleLayerStackCollapsed(projectId, primaryId, stack),
- [primaryId, projectId]
- );
const closeSurface = useCallback(() => {
setSurface(null);
if (pendingProperties.current) {
@@ -401,6 +445,24 @@ export const LayersTree = ({
}
}, []);
+ // A primary that changed outside the panel (canvas, undo, a new layer) is scrolled into view once,
+ // as soon as it has a row; later list changes leave the scroll position alone.
+ useLayoutEffect(() => {
+ if (!primaryId || revealedPrimary.current === primaryId) {
+ return;
+ }
+ if (panelSelectedPrimary.current === primaryId) {
+ panelSelectedPrimary.current = null;
+ revealedPrimary.current = primaryId;
+ return;
+ }
+ const index = rowIndexByKey.get(primaryId);
+ if (index !== undefined) {
+ revealedPrimary.current = primaryId;
+ virtualizerRef.current.scrollToIndex(index);
+ }
+ }, [primaryId, rowIndexByKey]);
+
// A properties request from elsewhere (a menu, a hotkey) reveals its row, scrolls to it once it is
// rendered, and then opens the surface on it exactly once; a request for a node that is gone is dropped.
useLayoutEffect(() => {
@@ -422,12 +484,12 @@ export const LayersTree = ({
setLayerGroupExpanded(projectId, primaryId, [...vm.parentIds], true);
}
}
- const index = rowIndexById.get(pending.id);
+ const index = rowIndexByKey.get(pending.id);
if (!pending.scrolled && index !== undefined) {
pendingProperties.current = { ...pending, scrolled: true };
virtualizerRef.current.scrollToIndex(index);
}
- }, [document, primaryId, projectId, propertiesRequest, rowIndexById]);
+ }, [document, primaryId, projectId, propertiesRequest, rowIndexByKey]);
// After paint: land a pending focus, and open a pending properties surface on its now-rendered row.
useLayoutEffect(() => {
@@ -436,9 +498,7 @@ export const LayersTree = ({
return;
}
if (pendingFocus.current) {
- const target = host.querySelector<HTMLElement>(
- `[data-layer-row-id="${CSS.escape(pendingFocus.current)}"] [role="treeitem"]`
- );
+ const target = host.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(pendingFocus.current)}"]`);
if (target) {
target.focus();
pendingFocus.current = null;
@@ -455,7 +515,7 @@ export const LayersTree = ({
}, [panelRows, virtualItems]);
// Focus repair: the browser drops focus to the body when a focused row unmounts, so the tree
- // remembers whether it owned focus and puts it back on the row that now holds the tab stop.
+ // remembers whether it owned focus and puts it back on the item that now holds the tab stop.
const handleFocusCapture = useCallback(() => {
treeOwnsFocus.current = true;
}, []);
@@ -466,14 +526,14 @@ export const LayersTree = ({
}, []);
useLayoutEffect(() => {
const host = scrollRef.current;
- if (!host || !focusId || !treeOwnsFocus.current || renamingId !== null) {
+ if (!host || !focusKey || !treeOwnsFocus.current || renamingId !== null) {
return;
}
if (host.contains(window.document.activeElement) && window.document.activeElement !== window.document.body) {
return;
}
- host.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(focusId)}"] [role="treeitem"]`)?.focus();
- }, [focusId, panelRows, renamingId, virtualItems]);
+ host.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(focusKey)}"]`)?.focus();
+ }, [focusKey, panelRows, renamingId, virtualItems]);
const clearHoverTimer = useCallback(() => {
if (hoverTimer.current !== null) {
@@ -481,7 +541,13 @@ export const LayersTree = ({
hoverTimer.current = null;
}
}, []);
- useMountEffect(() => clearHoverTimer);
+ useMountEffect(() => {
+ autoScroller.current = createLayerTreeAutoScroller(scrollRef);
+ return () => {
+ clearHoverTimer();
+ autoScroller.current?.stop();
+ };
+ });
const sensors = useSensors(useSensor(PointerSensor, POINTER_SENSOR_OPTIONS));
const dragDisabled = editingLocked || degraded || panel.filter.trim() !== '';
@@ -538,6 +604,7 @@ export const LayersTree = ({
const handleDragMove = useCallback((event: DragMoveEvent) => {
const depthOffset = Math.round(event.delta.x / LAYER_TREE_INDENT_PX);
pointerY.current = pointerStart.current.y + event.delta.y;
+ autoScroller.current?.update(pointerY.current);
const edge = edgeOf(event.over?.rect, pointerY.current);
setDrag((current) =>
current && (current.depthOffset !== depthOffset || current.edge !== edge)
@@ -595,6 +662,7 @@ export const LayersTree = ({
const finishDrag = useCallback(() => {
clearHoverTimer();
+ autoScroller.current?.stop();
setDrag(null);
}, [clearHoverTimer]);
const handleDragEnd = useCallback(
@@ -619,13 +687,13 @@ export const LayersTree = ({
const stackRows = stacks[drag.stack].rows;
let top: number;
if (target.beforeRowId) {
- top = offsets[rowIndexById.get(target.beforeRowId)!]!;
+ top = offsets[rowIndexByKey.get(target.beforeRowId)!]!;
} else {
const last = stackRows[stackRows.length - 1]!;
- top = offsets[rowIndexById.get(last.id)! + 1]!;
+ top = offsets[rowIndexByKey.get(last.id)! + 1]!;
}
return { left: target.depth * LAYER_TREE_INDENT_PX + 8, top };
- }, [drag, offsets, rowIndexById, stacks, target]);
+ }, [drag, offsets, rowIndexByKey, stacks, target]);
const refusalReason = refusal
? t(
@@ -639,7 +707,6 @@ export const LayersTree = ({
)
: null;
- // The stack whose header has scrolled out of view keeps a pinned copy at the top of the viewport.
// The stack whose header scrolled out keeps a pinned copy; the next header pushes it up as it arrives.
const pinnedHeader = useMemo(() => {
let low = 0;
@@ -673,8 +740,26 @@ export const LayersTree = ({
const dragStateOf = (id: string): LayerRowDragState =>
drag ? (id === drag.activeId ? 'source' : drag.travelling.has(id) ? 'travelling' : null) : null;
+ const renderHeader = (row: Extract<PanelRow, { kind: 'header' }>, pinned: boolean) => (
+ <LayerStackHeader
+ collapsed={row.collapsed}
+ commands={commands}
+ document={document}
+ editingLocked={editingLocked}
+ engine={engine}
+ focused={row.key === focusKey}
+ leafCount={row.stack.leafCount}
+ pinned={pinned}
+ posInSet={row.posInSet}
+ rowKey={row.key}
+ setSize={row.setSize}
+ stack={row.stack.stack}
+ />
+ );
+
return (
<DndContext
+ autoScroll={false}
collisionDetection={collisionDetection}
sensors={sensors}
onDragCancel={finishDrag}
@@ -703,14 +788,16 @@ export const LayersTree = ({
w="full"
>
{virtualItems.map((item) => {
- // The window can lag a shrinking list by one render; a stale index draws nothing.
- const panelRow = panelRows[item.index];
+ // The window applies a changed key set one commit late; a slot draws the row its key
+ // names, never the row at its index, so no node is relabelled in between.
+ const rowIndex = rowIndexByKey.get(String(item.key));
+ const panelRow = rowIndex === undefined ? undefined : panelRows[rowIndex];
if (!panelRow) {
return null;
}
return (
- <VirtualSlot key={item.key} header={panelRow.kind === 'header'} size={item.size} start={item.start}>
- {isNodeRow(panelRow) ? (
+ <VirtualSlot key={item.key} size={item.size} start={item.start}>
+ {panelRow.kind === 'node' ? (
<LayerRow
commands={commands}
density={density}
@@ -718,7 +805,7 @@ export const LayersTree = ({
dragDisabled={dragDisabled}
editingLocked={editingLocked}
engine={engine}
- focused={panelRow.row.id === focusId}
+ focused={panelRow.row.id === focusKey}
primary={panelRow.row.id === primaryId}
renaming={panelRow.row.id === renamingId}
row={panelRow.row}
@@ -726,15 +813,7 @@ export const LayersTree = ({
thumbnails={!degraded}
/>
) : (
- <LayerStackHeader
- collapsed={panelRow.collapsed}
- document={document}
- editingLocked={editingLocked}
- engine={engine}
- leafCount={panelRow.stack.leafCount}
- stack={panelRow.stack.stack}
- onToggleCollapse={handleToggleCollapse}
- />
+ renderHeader(panelRow, false)
)}
</VirtualSlot>
);
@@ -782,15 +861,7 @@ export const LayersTree = ({
top="0"
zIndex="1"
>
- <LayerStackHeader
- collapsed={pinnedHeader.row.collapsed}
- document={document}
- editingLocked={editingLocked}
- engine={engine}
- leafCount={pinnedHeader.row.stack.leafCount}
- stack={pinnedHeader.row.stack.stack}
- onToggleCollapse={handleToggleCollapse}
- />
+ {renderHeader(pinnedHeader.row, true)}
</Box>
) : null}
<DragOverlay dropAnimation={null} modifiers={OVERLAY_MODIFIERS}>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 91ff8a6b0b..81048b0f07 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -35,9 +35,10 @@ export const LayersWidgetView = () => {
const panel = useLayerPanelState(projectId, selectedLayerId);
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(
- () => buildLayerStackRows(document, expandedGroupIds, panel.filter),
- [document, expandedGroupIds, panel.filter]
+ () => buildLayerStackRows(document.stacks, expandedGroupIds, panel.filter),
+ [document.stacks, expandedGroupIds, panel.filter]
);
const nodeCount = getDocumentIndex(document).nodes.length;
const degraded = nodeCount > LAYER_PANEL_DEGRADE_THRESHOLD;
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 d0d7a0feea..e9270de1d2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -74,6 +74,7 @@ const makeState = (
canRunWorkflow: true,
document,
hasEngine: true,
+ hiddenByAncestor: false,
hasSupportedContent: true,
hasWorkflowBindings: true,
interactionLocked: false,
@@ -86,6 +87,7 @@ const makeState = (
const makeEffects = (): LayerContextActionEffects => ({
booleanMerge: vi.fn(() => Promise.resolve()),
+ toggleHidden: vi.fn(),
copyTo: vi.fn(),
copyToClipboard: vi.fn(() => Promise.resolve()),
cropToBbox: vi.fn(() => Promise.resolve()),
@@ -470,6 +472,7 @@ describe('getLayerContextActions', () => {
'inpaint-denoise-limit',
'merge-down',
'toggle-visibility',
+ 'toggle-hidden',
'toggle-lock',
'delete',
];
@@ -770,3 +773,20 @@ describe('getLayerContextActions', () => {
);
});
});
+
+describe('toggle-hidden', () => {
+ it('offers hide-on-canvas to overlay layers only and yields to a hiding ancestor', () => {
+ expect(idsFor(rasterLayer)).not.toContain('toggle-hidden');
+ const control = getLayerContextActions(makeState(nonEmptyControlLayer));
+ expect(byId(control, 'toggle-hidden').isDisabled).toBe(false);
+ expect(byId(control, 'toggle-hidden').labelKey).toBe('widgets.layers.actions.hideOnCanvas');
+ expect(getEnglishTranslation('widgets.layers.actions.hideOnCanvas')).toBe('Hide on canvas');
+ const hidden = getLayerContextActions(makeState({ ...nonEmptyControlLayer, isHidden: true }));
+ expect(byId(hidden, 'toggle-hidden').labelKey).toBe('widgets.layers.actions.showOnCanvas');
+ const gated = getLayerContextActions(makeState(nonEmptyControlLayer, { hiddenByAncestor: true }));
+ expect(byId(gated, 'toggle-hidden').isDisabled).toBe(true);
+ const runtime = makeRuntimeContext(nonEmptyControlLayer);
+ void LAYER_CONTEXT_ACTION_DEFINITIONS.find((definition) => definition.id === 'toggle-hidden')!.handler(runtime);
+ expect(runtime.effects.toggleHidden).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 59ce0241dd..8ef7921e65 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -9,6 +9,8 @@ import type { LucideIcon } from 'lucide-react';
import {
getDocumentIndex,
getSourceContentRect,
+ isHideableLayer,
+ isNodeHidden,
isPixelBackedLayer,
lookupLayerBelow,
} from '@workbench/canvas-engine/api';
@@ -78,6 +80,7 @@ export type LayerContextActionId =
| 'inpaint-denoise-limit'
| 'merge-down'
| 'toggle-visibility'
+ | 'toggle-hidden'
| 'toggle-lock'
| 'delete';
@@ -97,6 +100,8 @@ export interface LayerContextActionState {
selectedIds: readonly string[];
/** The model's answer for grouping `actionTargets`, asked by the menu that owns the engine. */
canGroupSelection: boolean;
+ /** A group above the layer hides it on the canvas; the layer's own flag cannot override that. */
+ hiddenByAncestor: boolean;
}
export interface LayerContextActionEffects {
@@ -121,6 +126,7 @@ export interface LayerContextActionEffects {
patchConfig(kind: LayerConfigPatchKind): void;
mergeDown(): void;
toggleVisibility(): void;
+ toggleHidden(): void;
toggleLock(): void;
delete(): void;
}
@@ -767,6 +773,22 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'state',
supportedLayerTypes: ALL_LAYER_TYPES,
},
+ {
+ defaultLabel: 'Toggle canvas visibility',
+ getDefaultLabel: (context) => (isNodeHidden(context.layer) ? 'Show on canvas' : 'Hide on canvas'),
+ getIcon: (context) => (isNodeHidden(context.layer) ? EyeIcon : EyeOffIcon),
+ getLabelKey: (context) =>
+ isNodeHidden(context.layer) ? 'widgets.layers.actions.showOnCanvas' : 'widgets.layers.actions.hideOnCanvas',
+ handler: ({ effects }) => effects.toggleHidden(),
+ icon: EyeOffIcon,
+ id: 'toggle-hidden',
+ isEnabled: (context) => isInteractionFree(context) && !context.hiddenByAncestor,
+ isVisible: (context) => isHideableLayer(context.layer),
+ labelKey: 'widgets.layers.actions.toggleHidden',
+ order: 5,
+ section: 'state',
+ supportedLayerTypes: ALL_LAYER_TYPES,
+ },
{
defaultLabel: 'Toggle lock',
getDefaultLabel: (context) => (context.layer.isLocked ? 'Unlock' : 'Lock'),
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 ea8386581e..7050a66c91 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -42,6 +42,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
getLayerContextActions({
canRunWorkflow: true,
document: makeDocument([...layers]),
+ hiddenByAncestor: false,
hasEngine: true,
hasSupportedContent: true,
hasWorkflowBindings: true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelDiagnostics.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelDiagnostics.ts
new file mode 100644
index 0000000000..ec038f363d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelDiagnostics.ts
@@ -0,0 +1,16 @@
+/**
+ * Deterministic counters for the panel's performance contract: how many times each row committed
+ * and how many thumbnails were requested. Read by budget tests only; production never reads them.
+ */
+const rowCommits = new Map<string, number>();
+
+export const recordLayerRowCommit = (id: string): void => {
+ rowCommits.set(id, (rowCommits.get(id) ?? 0) + 1);
+};
+
+/** Commits per row since the last reset, as a plain object for assertions. */
+export const getLayerRowCommits = (): Record<string, number> => Object.fromEntries(rowCommits);
+
+export const resetLayerRowCommits = (): void => {
+ rowCommits.clear();
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
index f7bb4088ae..ff7190640b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPanelRows.ts
@@ -14,9 +14,23 @@ export const LAYER_TREE_INDENT_PX = 16;
export const LAYER_PANEL_DEGRADE_THRESHOLD = 2_000;
export type PanelRow =
- | { readonly kind: 'header'; readonly key: string; readonly stack: LayerStackRows; readonly collapsed: boolean }
+ | {
+ readonly kind: 'header';
+ readonly key: string;
+ readonly stack: LayerStackRows;
+ readonly collapsed: boolean;
+ /** The header's place among the non-empty stacks, for `aria-posinset` / `aria-setsize`. */
+ readonly posInSet: number;
+ readonly setSize: number;
+ }
| { readonly kind: 'node'; readonly key: string; readonly stack: LayerStackKind; readonly row: LayerTreeRow };
+export const headerKey = (stack: LayerStackKind): string => `header:${stack}`;
+
+export const isHeaderKey = (key: string): boolean => key.startsWith('header:');
+
+export const stackOfHeaderKey = (key: string): LayerStackKind => key.slice('header:'.length) as LayerStackKind;
+
/**
* The one flat list the panel virtualizes: a header per non-empty stack followed by its rendered
* rows unless the stack is collapsed. `forceOpen` keeps a collapsed stack open while something
@@ -28,13 +42,18 @@ export const flattenPanelRows = (
forceOpen: (stack: LayerStackKind) => boolean
): PanelRow[] => {
const rows: PanelRow[] = [];
- for (const kind of LAYER_STACKS_TOP_FIRST) {
+ const present = LAYER_STACKS_TOP_FIRST.filter((kind) => stacks[kind].nodeIds.length > 0);
+ for (const kind of present) {
const stack = stacks[kind];
- if (stack.nodeIds.length === 0) {
- continue;
- }
const collapsed = collapsedStacks.includes(kind) && !forceOpen(kind);
- rows.push({ collapsed, key: `header:${kind}`, kind: 'header', stack });
+ rows.push({
+ collapsed,
+ key: headerKey(kind),
+ kind: 'header',
+ posInSet: present.indexOf(kind) + 1,
+ setSize: present.length,
+ stack,
+ });
if (!collapsed) {
for (const row of stack.rows) {
rows.push({ key: row.id, kind: 'node', row, stack: kind });
@@ -49,62 +68,74 @@ export const panelRowHeight = (row: PanelRow, density: LayerPanelDensity): numbe
export type TreeNavigationKey = 'ArrowDown' | 'ArrowUp' | 'Home' | 'End' | 'ArrowLeft' | 'ArrowRight';
-export type TreeNavigation = { readonly focus: string } | { readonly expand: string; readonly expanded: boolean };
+export type TreeNavigation =
+ | { readonly focus: string }
+ | { readonly expand: string; readonly expanded: boolean }
+ | { readonly collapseStack: LayerStackKind; readonly collapsed: boolean };
-/**
- * The WAI-ARIA tree keyboard model over the flat list: vertical keys walk rendered node rows,
- * Home/End jump, Right opens a group or enters it, Left closes a group or climbs to the parent.
- */
-type NodePanelRow = Extract<PanelRow, { kind: 'node' }>;
+const positionsCache = new WeakMap<readonly PanelRow[], Map<string, number>>();
-const nodeRowsCache = new WeakMap<readonly PanelRow[], { rows: NodePanelRow[]; positions: Map<string, number> }>();
-
-/** The node rows of a list and their positions, computed once per list identity. */
-const nodeRowsOf = (rows: readonly PanelRow[]) => {
- let cached = nodeRowsCache.get(rows);
+const positionsOf = (rows: readonly PanelRow[]): Map<string, number> => {
+ let cached = positionsCache.get(rows);
if (!cached) {
- const nodeRows = rows.filter((row): row is NodePanelRow => row.kind === 'node');
- cached = { positions: new Map(nodeRows.map((row, index) => [row.row.id, index])), rows: nodeRows };
- nodeRowsCache.set(rows, cached);
+ cached = new Map(rows.map((row, index) => [row.key, index]));
+ positionsCache.set(rows, cached);
}
return cached;
};
+/**
+ * The WAI-ARIA tree keyboard model over the flat list, headers included: vertical keys walk every
+ * rendered item, Home/End jump, Right opens a stack or group or enters it, Left closes one or
+ * climbs to the parent (a root node's parent is its stack header).
+ */
export const navigateTree = (
rows: readonly PanelRow[],
- currentId: string,
+ currentKey: string,
key: TreeNavigationKey
): TreeNavigation | null => {
- const { positions, rows: nodeRows } = nodeRowsOf(rows);
- const position = positions.get(currentId) ?? -1;
+ const position = positionsOf(rows).get(currentKey) ?? -1;
if (position < 0) {
- return nodeRows[0] ? { focus: nodeRows[0].row.id } : null;
+ return rows[0] ? { focus: rows[0].key } : null;
}
- const current = nodeRows[position]!.row;
+ const current = rows[position]!;
switch (key) {
case 'ArrowDown':
- return nodeRows[position + 1] ? { focus: nodeRows[position + 1]!.row.id } : null;
+ return rows[position + 1] ? { focus: rows[position + 1]!.key } : null;
case 'ArrowUp':
- return nodeRows[position - 1] ? { focus: nodeRows[position - 1]!.row.id } : null;
+ return rows[position - 1] ? { focus: rows[position - 1]!.key } : null;
case 'Home':
- return { focus: nodeRows[0]!.row.id };
+ return { focus: rows[0]!.key };
case 'End':
- return { focus: nodeRows[nodeRows.length - 1]!.row.id };
+ return { focus: rows[rows.length - 1]!.key };
case 'ArrowRight': {
- if (current.vm.kind !== 'group' || current.vm.childCount === 0) {
+ if (current.kind === 'header') {
+ if (current.collapsed) {
+ return { collapsed: false, collapseStack: current.stack.stack };
+ }
+ const first = rows[position + 1];
+ return first && first.kind === 'node' ? { focus: first.key } : null;
+ }
+ const { row } = current;
+ if (row.vm.kind !== 'group' || row.vm.childCount === 0) {
return null;
}
- if (!current.expanded) {
- return { expand: current.id, expanded: true };
+ if (!row.expanded) {
+ return { expand: row.id, expanded: true };
}
- const child = nodeRows[position + 1];
- return child && child.row.vm.parentId === current.id ? { focus: child.row.id } : null;
+ const child = rows[position + 1];
+ return child && child.kind === 'node' && child.row.vm.parentId === row.id ? { focus: child.key } : null;
}
- case 'ArrowLeft':
- if (current.vm.kind === 'group' && current.expanded) {
- return { expand: current.id, expanded: false };
+ case 'ArrowLeft': {
+ if (current.kind === 'header') {
+ return current.collapsed ? null : { collapsed: true, collapseStack: current.stack.stack };
+ }
+ const { row } = current;
+ if (row.vm.kind === 'group' && row.expanded) {
+ return { expand: row.id, expanded: false };
}
- return current.vm.parentId ? { focus: current.vm.parentId } : null;
+ 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 2f49842daf..99db4344fb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts
@@ -1,3 +1,4 @@
+import type { LayerStackKind } from '@workbench/canvas-engine/api';
import type { LayerSelectionModifiers } from '@workbench/layerPanelState';
import type { KeyboardEvent } from 'react';
@@ -25,6 +26,9 @@ export interface LayerRowCommands {
endRename(): void;
openMenu(id: string, anchor: LayerSurfaceAnchor): void;
openProperties(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. */
keyDown(id: string, event: KeyboardEvent<HTMLElement>): void;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeAutoScroll.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeAutoScroll.ts
new file mode 100644
index 0000000000..54b4d869e3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeAutoScroll.ts
@@ -0,0 +1,79 @@
+/** The band at each edge of the list where a drag scrolls it, and the fastest it scrolls. */
+export const AUTO_SCROLL_ZONE_PX = 36;
+export const AUTO_SCROLL_MAX_PX_PER_FRAME = 14;
+
+export interface LayerTreeAutoScroller {
+ /** Reads the pointer's viewport y and scrolls while it rests in an edge band; stops the moment it leaves. */
+ update(clientY: number): void;
+ stop(): void;
+}
+
+/**
+ * Deterministic edge scrolling for drags: velocity grows linearly with depth into the band and the
+ * loop runs only while there is velocity, so a pointer that leaves the band stops scrolling on the
+ * next frame and a finished drag stops it at once.
+ */
+export const createLayerTreeAutoScroller = (
+ element: { readonly current: HTMLElement | null },
+ schedule: (callback: () => void) => number = (callback) => requestAnimationFrame(callback),
+ cancel: (handle: number) => void = (handle) => cancelAnimationFrame(handle)
+): LayerTreeAutoScroller => {
+ let frame: number | null = null;
+ let velocity = 0;
+ let carry = 0;
+ const stop = (): void => {
+ if (frame !== null) {
+ cancel(frame);
+ }
+ frame = null;
+ velocity = 0;
+ carry = 0;
+ };
+ // Sub-pixel velocity accumulates until it moves a whole pixel; a list that cannot move any further
+ // parks the loop, and the next pointer movement restarts it.
+ const step = (): void => {
+ const host = element.current;
+ if (!host || velocity === 0) {
+ frame = null;
+ return;
+ }
+ const total = velocity + carry;
+ const whole = Math.trunc(total);
+ carry = total - whole;
+ if (whole !== 0) {
+ const before = host.scrollTop;
+ host.scrollTop = before + whole;
+ if (host.scrollTop === before) {
+ frame = null;
+ return;
+ }
+ }
+ frame = schedule(step);
+ };
+ return {
+ stop,
+ update: (clientY) => {
+ const host = element.current;
+ if (!host) {
+ return;
+ }
+ const rect = host.getBoundingClientRect();
+ const fromTop = clientY - rect.top;
+ const fromBottom = rect.bottom - clientY;
+ let next = 0;
+ if (fromTop < AUTO_SCROLL_ZONE_PX) {
+ next = -AUTO_SCROLL_MAX_PX_PER_FRAME * (1 - Math.max(0, fromTop) / AUTO_SCROLL_ZONE_PX);
+ } else if (fromBottom < AUTO_SCROLL_ZONE_PX) {
+ next = AUTO_SCROLL_MAX_PX_PER_FRAME * (1 - Math.max(0, fromBottom) / AUTO_SCROLL_ZONE_PX);
+ }
+ if (next === 0) {
+ stop();
+ return;
+ }
+ velocity = next;
+ if (frame === null) {
+ frame = schedule(step);
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts
index 2e4318e6e5..8e649fb8ab 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts
@@ -25,20 +25,20 @@ const outline = (rows: readonly { id: string; vm: { depth: number } }[]) =>
describe('buildLayerStackRows', () => {
it('lists rendered rows per stack, hiding the children of collapsed groups', () => {
- const collapsed = buildLayerStackRows(document(), new Set());
+ const collapsed = buildLayerStackRows(document().stacks, new Set());
expect(outline(collapsed.raster.rows)).toEqual(['r1', 'G', 'r5']);
expect(collapsed.raster.nodeIds).toEqual(['r1', 'G', 'r2', 'H', 'r3', 'r4', 'r5']);
expect(collapsed.raster.leafCount).toBe(5);
expect(outline(collapsed.control.rows)).toEqual(['c1']);
expect(collapsed.inpaint_mask.rows).toEqual([]);
- const expanded = buildLayerStackRows(document(), new Set(['G', 'H']));
+ const expanded = buildLayerStackRows(document().stacks, new Set(['G', 'H']));
expect(outline(expanded.raster.rows)).toEqual(['r1', 'G', ' r2', ' H', ' r3', ' r4', 'r5']);
- expect(outline(buildLayerStackRows(document(), new Set(['H'])).raster.rows)).toEqual(['r1', 'G', 'r5']);
+ expect(outline(buildLayerStackRows(document().stacks, new Set(['H'])).raster.rows)).toEqual(['r1', 'G', 'r5']);
});
it('carries effective state and counts on each row', () => {
- const rows = buildLayerStackRows(document(), new Set(['G', 'H'])).raster.rows;
+ const rows = buildLayerStackRows(document().stacks, new Set(['G', 'H'])).raster.rows;
const byId = Object.fromEntries(rows.map((row) => [row.id, row]));
expect(byId.G).toMatchObject({
expanded: true,
@@ -63,25 +63,25 @@ describe('buildLayerStackRows', () => {
});
it('keeps row identity for untouched nodes across an unrelated edit and a toggle elsewhere', () => {
- const before = buildLayerStackRows(document(), new Set(['G'])).raster.rows;
+ const before = buildLayerStackRows(document().stacks, new Set(['G'])).raster.rows;
const renamed = documentFrom([
layer('c1', 'control'),
layer('r1', 'raster', { name: 'renamed' }),
before[1]!.vm.node,
layer('r5'),
]);
- const after = buildLayerStackRows(renamed, new Set(['G'])).raster.rows;
+ const after = buildLayerStackRows(renamed.stacks, new Set(['G'])).raster.rows;
expect(after[1]).toBe(before[1]);
expect(after[2]).toBe(before[2]);
expect(after[0]).not.toBe(before[0]);
- const toggled = buildLayerStackRows(renamed, new Set(['G', 'H'])).raster.rows;
+ const toggled = buildLayerStackRows(renamed.stacks, new Set(['G', 'H'])).raster.rows;
expect(toggled.find((row) => row.id === 'G')).toBe(after[1]);
expect(toggled.find((row) => row.id === 'H')).not.toBe(after.find((row) => row.id === 'H'));
});
});
describe('projectLayerDrop', () => {
- const rows = () => buildLayerStackRows(document(), new Set(['G', 'H'])).raster.rows;
+ const rows = () => buildLayerStackRows(document().stacks, new Set(['G', 'H'])).raster.rows;
it('drops between siblings at the same depth', () => {
expect(
@@ -181,7 +181,7 @@ describe('projectLayerDrop', () => {
});
it('treats a collapsed group as a leaf for indentation and refuses past the depth limit', () => {
- const collapsed = buildLayerStackRows(document(), new Set()).raster.rows;
+ const collapsed = buildLayerStackRows(document().stacks, new Set()).raster.rows;
expect(
projectLayerDrop({ activeIds: ['r5'], depthOffset: 1, edge: 'below', overId: 'G', rows: collapsed })
).toMatchObject({ depth: 0, parentId: null });
@@ -189,7 +189,7 @@ describe('projectLayerDrop', () => {
depth === 0 ? layer('leaf') : group(`n${depth}`, [nest(depth - 1)]);
const deep = documentFrom([nest(10), group('S', [layer('s')])]);
const ids = new Set(Array.from({ length: 10 }, (_, index) => `n${index + 1}`).concat(['S']));
- const deepRows = buildLayerStackRows(deep, ids).raster.rows;
+ const deepRows = buildLayerStackRows(deep.stacks, ids).raster.rows;
expect(
projectLayerDrop({ activeIds: ['S'], depthOffset: 10, edge: 'below', overId: 'leaf', rows: deepRows })
).toMatchObject({ depth: 9, parentId: 'n2' });
@@ -204,11 +204,11 @@ describe('projectLayerDrop', () => {
describe('buildLayerStackRows filter', () => {
it('keeps matches and their ancestors, opens only groups with a match beneath, and leaves a matching group closed', () => {
- const filtered = buildLayerStackRows(document(), new Set(), 'r3');
+ const filtered = buildLayerStackRows(document().stacks, new Set(), 'r3');
expect(outline(filtered.raster.rows)).toEqual(['G', ' H', ' r3']);
expect(filtered.raster.rows.map((row) => row.expanded)).toEqual([true, true, false]);
expect(filtered.control.rows).toEqual([]);
- const groupMatch = buildLayerStackRows(document(), new Set(['G']), 'g');
+ const groupMatch = buildLayerStackRows(document().stacks, new Set(['G']), 'g');
expect(outline(groupMatch.raster.rows)).toEqual(['G']);
expect(groupMatch.raster.rows[0]!.expanded).toBe(false);
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
index 12d98d9162..221bae341e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts
@@ -1,4 +1,4 @@
-import type { CanvasDocumentContractV3, LayerStackKind, SemanticNode } from '@workbench/canvas-engine/api';
+import type { CanvasStackForests, LayerStackKind, SemanticNode } from '@workbench/canvas-engine/api';
import { compileDocumentNodes, LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/api';
@@ -69,17 +69,17 @@ const filteredIds = (
* components skip unaffected rows. Every node is visited once.
*/
export const buildLayerStackRows = (
- document: CanvasDocumentContractV3,
+ stacks: CanvasStackForests,
expandedGroupIds: ReadonlySet<string>,
filter?: string
): LayerStackRowsByKind => {
- const nodes = compileDocumentNodes(document);
+ const nodes = compileDocumentNodes({ stacks });
const query = normalizeFilter(filter);
const filtered = query ? filteredIds(nodes, query) : null;
const kept = filtered?.kept ?? null;
const byId = new Map(nodes.map((node) => [node.id, node]));
const setSizeOf = (node: SemanticNode): number =>
- node.parentId === null ? document.stacks[node.stack].length : (byId.get(node.parentId)?.childCount ?? 0);
+ node.parentId === null ? stacks[node.stack].length : (byId.get(node.parentId)?.childCount ?? 0);
const result = Object.fromEntries(
LAYER_STACKS_TOP_FIRST.map((stack) => [
stack,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
index 67713d6f06..806c05c5b2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersPanel.budget.test.ts
@@ -37,11 +37,13 @@ describe(`layers panel budgets over ${NODE_COUNT} nodes`, () => {
const index = getDocumentIndex(document);
const roots = index.nodes.filter((entry) => entry.parentId === null).length;
resetDocumentModelDiagnostics();
- const collapsed = timed(annotate, 'collapsed rows', () => buildLayerStackRows(document, new Set()));
+ const collapsed = timed(annotate, 'collapsed rows', () => buildLayerStackRows(document.stacks, new Set()));
expect(Object.values(collapsed).reduce((total, stack) => total + stack.rows.length, 0)).toBe(roots);
expect(getDocumentModelDiagnostics().nodesCompiled).toBe(NODE_COUNT);
- const expanded = timed(annotate, 'expanded rows', () => buildLayerStackRows(document, new Set(groupIds(document))));
+ const expanded = timed(annotate, 'expanded rows', () =>
+ buildLayerStackRows(document.stacks, new Set(groupIds(document)))
+ );
expect(Object.values(expanded).reduce((total, stack) => total + stack.rows.length, 0)).toBe(NODE_COUNT);
expect(getDocumentModelDiagnostics().nodesCompiled).toBe(NODE_COUNT);
const flat = flattenPanelRows(expanded, [], () => false);
@@ -53,16 +55,16 @@ describe(`layers panel budgets over ${NODE_COUNT} nodes`, () => {
const document = createLargeTreeDocument(NODE_COUNT);
const groups = groupIds(document);
const expanded = new Set(groups);
- const before = buildLayerStackRows(document, expanded);
+ const before = buildLayerStackRows(document.stacks, expanded);
// Selection lives beside the document, so nothing here can change.
- const again = buildLayerStackRows(document, expanded);
+ const again = buildLayerStackRows(document.stacks, expanded);
for (const stack of Object.keys(before) as (keyof typeof before)[]) {
before[stack].rows.forEach((row, position) => expect(again[stack].rows[position]).toBe(row));
}
const target = groups.find((id) => getDocumentIndex(document).byId.get(id)!.path.length === 1)!;
const collapsedOne = new Set(groups);
collapsedOne.delete(target);
- const after = buildLayerStackRows(document, collapsedOne);
+ const after = buildLayerStackRows(document.stacks, collapsedOne);
const descendants = new Set(
getDocumentIndex(document)
.nodes.filter((entry) => entry.path.includes(target))
@@ -86,7 +88,7 @@ describe(`layers panel budgets over ${NODE_COUNT} nodes`, () => {
it('projects a large multi-selection drag in linear time and keeps semantic order', ({ annotate }) => {
const document = createLargeFlatDocument(NODE_COUNT * 2, null);
- const rows = buildLayerStackRows(document, new Set()).raster.rows;
+ const rows = buildLayerStackRows(document.stacks, new Set()).raster.rows;
const selected = new Set(rows.filter((_, position) => position % 2 === 0).map((row) => row.id));
const activeIds = timed(annotate, 'outermost rows', () => outermostRowIds(rows, selected));
expect(activeIds).toHaveLength(selected.size);
@@ -99,10 +101,11 @@ describe(`layers panel budgets over ${NODE_COUNT} nodes`, () => {
it('navigates the flat list in bounded steps', () => {
const document = createLargeTreeDocument(NODE_COUNT);
- const rows = flattenPanelRows(buildLayerStackRows(document, new Set(groupIds(document))), [], () => false);
+ const rows = flattenPanelRows(buildLayerStackRows(document.stacks, new Set(groupIds(document))), [], () => false);
const first = rows.find((row) => row.kind === 'node')!;
expect(navigateTree(rows, first.key, 'End')).toEqual({ focus: rows[rows.length - 1]!.key });
- expect(navigateTree(rows, rows[rows.length - 1]!.key, 'Home')).toEqual({ focus: first.key });
+ expect(navigateTree(rows, rows[rows.length - 1]!.key, 'Home')).toEqual({ focus: rows[0]!.key });
+ expect(navigateTree(rows, rows[0]!.key, 'ArrowRight')).toEqual({ focus: first.key });
const nodes = compileDocumentNodes(document);
const nested = nodes.find((node) => node.depth >= 2 && node.kind === 'leaf')!;
expect(navigateTree(rows, nested.id, 'ArrowLeft')).toEqual({ focus: nested.parentId });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
new file mode 100644
index 0000000000..86a755c3a0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
@@ -0,0 +1,149 @@
+import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';
+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+import type { LucideIcon } from 'lucide-react';
+
+import { toaster } from '@platform/ui';
+import { canMergeVisibleRasters, compileDocumentNodes, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { useActiveProjectName } from '@workbench/WorkbenchContext';
+import { EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { stackAddItemId } from './addLayerMenu';
+import {
+ canExportRasterPsd,
+ getStackActions,
+ isStackAllVisible,
+ planStackVisibilityToggle,
+ stackVisibilityAxis,
+ type StackActionId,
+} from './layerStackActions';
+import { getPsdExportNoticeKey } from './psdExportNotice';
+import { useAddLayer } from './useAddLayer';
+
+export type LayerStackActionsEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
+
+/** One stack action as the header buttons and the stack menu both render it. */
+export interface LayerStackAction {
+ readonly id: StackActionId;
+ readonly label: string;
+ readonly icon: LucideIcon;
+ readonly disabled: boolean;
+ run(): void;
+}
+
+/** The stack's actions with their enablement and handlers, shared by every surface that offers them. */
+export const useLayerStackActions = (
+ stack: LayerStackKind,
+ document: CanvasDocumentContractV3,
+ engine: LayerStackActionsEngine | null,
+ editingLocked: boolean
+): readonly LayerStackAction[] => {
+ const commitPrepared = usePreparedCommit(engine);
+ const { t } = useTranslation();
+ const addLayer = useAddLayer();
+ const projectName = useActiveProjectName();
+ const axis = stackVisibilityAxis(stack);
+ const { stacks } = document;
+ // Read from the forests, so selection and other document-level changes cost nothing here.
+ const { allVisible, exportable, nodes } = useMemo(() => {
+ const own = compileDocumentNodes({ stacks }).filter((node) => node.stack === stack);
+ return {
+ allVisible: isStackAllVisible(own, axis),
+ exportable: stack === 'raster' && canExportRasterPsd(getDocumentLeaves({ stacks })),
+ nodes: own,
+ };
+ }, [axis, stack, stacks]);
+ const canMerge =
+ !editingLocked &&
+ !!engine &&
+ stack === 'raster' &&
+ canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent);
+ const canExport = !!engine && exportable;
+
+ return useMemo(() => {
+ const actions: Record<StackActionId, LayerStackAction> = {
+ exportPsd: {
+ disabled: editingLocked || !canExport,
+ icon: FileDownIcon,
+ id: 'exportPsd',
+ label: t('widgets.layers.groupActions.exportPsd'),
+ run: () => {
+ if (!engine) {
+ return;
+ }
+ void engine.exports
+ .exportRasterLayersToPsd(projectName)
+ .then((result) => {
+ const noticeKey = getPsdExportNoticeKey(result);
+ if (noticeKey) {
+ toaster.create({ title: t(noticeKey), type: 'warning' });
+ }
+ })
+ .catch(() => toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' }));
+ },
+ },
+ mergeVisible: {
+ disabled: !canMerge,
+ icon: LayersIcon,
+ id: 'mergeVisible',
+ label: t('widgets.layers.groupActions.mergeVisible'),
+ run: () => {
+ if (!engine) {
+ return;
+ }
+ void engine.layers.mergeVisibleRasterLayers().then((result) => {
+ if (result === 'not-ready') {
+ toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });
+ } else if (result === 'over-budget') {
+ toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });
+ }
+ });
+ },
+ },
+ new: {
+ disabled: editingLocked,
+ icon: PlusIcon,
+ id: 'new',
+ label: t('widgets.layers.groupActions.new'),
+ run: () => addLayer(stackAddItemId(stack)),
+ },
+ toggleVisibility: {
+ disabled: editingLocked,
+ icon: allVisible ? EyeIcon : EyeOffIcon,
+ id: 'toggleVisibility',
+ label: t(allVisible ? 'widgets.layers.groupActions.hideAll' : 'widgets.layers.groupActions.showAll'),
+ run: () => {
+ const { ids, nextVisible } = planStackVisibilityToggle(nodes, axis);
+ if (ids.length === 0) {
+ return;
+ }
+ if (axis === 'hidden') {
+ commitPrepared(t('widgets.layers.groupActions.toggleHidden'), (model) =>
+ model.prepare({ type: 'set-hidden', updates: ids.map((id) => ({ id, isHidden: !nextVisible })) })
+ );
+ return;
+ }
+ commitPrepared(t('widgets.layers.groupActions.toggleVisibility'), (model) =>
+ model.prepare({ type: 'set-enabled', updates: ids.map((id) => ({ id, isEnabled: nextVisible })) })
+ );
+ },
+ },
+ };
+ return getStackActions(stack).map((id) => actions[id]);
+ }, [
+ addLayer,
+ allVisible,
+ axis,
+ canExport,
+ canMerge,
+ commitPrepared,
+ editingLocked,
+ engine,
+ nodes,
+ projectName,
+ stack,
+ t,
+ ]);
+};