Skip to content

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

feat(canvas): size layers in pixels, with a reference point, aspect lock and flip (#10348)

Josh Corbettf08630f96549
diff --git a/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx b/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx
index ab2e1700a4..bb86f930f1 100644
--- a/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx
+++ b/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx
@@ -143,7 +143,7 @@ These work while the Canvas has focus. The tool, brush size, color and undo keys
| <kbd>Mod</kbd>+<kbd>Alt</kbd>+<kbd>N</kbd> | Clear canvas | Asks to clear the canvas |
| <kbd>Mod</kbd>+<kbd>1</kbd> to <kbd>Mod</kbd>+<kbd>4</kbd> | Zoom to 100%, 200%, 400%, 800% | Zooms around the center of the view |
-**Crop all layers to frame**, **Save Canvas to Gallery** and **Save Frame to Gallery** have no default keys.
+**Crop all layers to frame**, **Flip horizontal**, **Flip vertical**, **Save Canvas to Gallery** and **Save Frame to Gallery** have no default keys.
### Staging bar
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 6b676c97d4..f9d2f67ad3 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -140,11 +140,11 @@ The frame is the final footprint of the generation on the canvas. With **Render
Choose **Transform** from a layer's menu, or press **Shift+T**, to scale and rotate the selected layer. The handles appear at once, even when the Transform tool is already active; if a brush stroke is still being saved, the tool switches straight away and the handles appear when the stroke is saved. Transform works on any enabled layer with content, inpaint masks and regional guidance included. Painted pixels (a paint layer, or a control layer you have painted on) are redrawn at their new size; every other layer, inpaint masks and regional guidance included, keeps its pixels and only its placement changes. A transformed mask's fill pattern and new brush strokes follow its scale and rotation, and **Invert mask** on a rotated mask inverts the generation frame's bounding box as the mask sees it; generation reads the mask through its transform, so results are unaffected.
-* Drag a corner or edge handle to scale. **Shift** scales proportionally and **Alt**, held before or during the drag, scales from the center.
+* Drag a corner or edge handle to scale. While the aspect lock beside **Size** is on (the default), every handle keeps the layer's proportions; **Shift** scales freely for that drag, or proportionally while the lock is off. **Alt**, held before or during the drag, scales from the center.
* Drag just outside a corner to rotate. **Shift** rotates in 15° steps.
* Drag inside to move.
-Press **Enter** or click **Apply** to finish, or **Escape** or **Cancel** to undo the transform. The **Transform** tab of the Layers panel sets the position, scale and rotation numerically. A negative scale flips the layer.
+Press **Enter** or click **Apply** to finish, or **Escape** or **Cancel** to undo the transform. The tool's options and the **Transform** tab of the Layers panel set the position, size and rotation numerically. **Size** is the layer's own width and height in canvas pixels; with the aspect lock on, changing one changes the other by the same factor. Besides a number of pixels, **W** and **H** take a change of the current value: type `50%` for half, `*2` to double or `/4` for a quarter (or type the operator first, then the number), and press **Enter**. **Escape** drops the change. The reference point button beside **Position** picks which point of the layer (a corner, an edge's middle or the center, the center by default) **X** and **Y** show and place, and which point stays put when you type a size or rotation. The **Flip horizontal** and **Flip vertical** buttons beside **Rotation** mirror the layer in place across its center, whatever the reference point; they are also in the layer's menu under **Flip** and in the command palette, for the selected layer. While you are moving selected pixels, flipping their layer flips those pixels instead, until you apply or cancel the move.
To crop a layer to the generation frame, choose **Crop layer to frame** from its menu; a layer entirely outside the frame is left alone. **Fit to frame** scales a layer to fit inside the frame. To crop every layer at once, use **Crop all layers to frame** in the [canvas menu](#the-canvas-menu).
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index 07fe754ca0..fb3ca536ab 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -98,6 +98,7 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw
* **Delete layer**.
* **Raster layers:**
* **Transform** (**Shift+T**) — shows the transform handles at once. It works on any enabled layer with content: raster and control layers, inpaint masks and regional guidance.
+ * **Flip** — **Flip horizontal** or **Flip vertical** mirrors the layer in place across its center, as one undoable step. It works on raster, control and vector layers, inpaint masks and regional guidance.
* **Add adjustment** — Brightness/Contrast, Exposure, Levels, Curves, Saturation, Hue, Invert, Texture, Clarity, Dehaze or Noise. Adjustments are non-destructive and appear as child rows. Texture, Clarity and Dehaze change detail and contrast; Noise adds film grain.
* **Add regenerate region** — regenerates where the layer has content, as a live inpaint mask: everything on the layer marks the area to regenerate, and it follows the layer as you keep editing it. The menu sums this up under the item as "Inpaint where this layer has content."
* **Filter**, **Select object** and **Run workflow** — process the layer; see the [Canvas guide](/users-guide/canvas/canvas-guide/#filters-and-object-selection).
@@ -221,7 +222,7 @@ A regional guidance layer's reference image is a child row. Select it to set:
## Transform and Overview
-The **Transform** tab sets the selected layer's **Position**, **Scale** and **Rotation** as numbers. Each change is a separate undoable step.
+The **Transform** tab sets the selected layer's **Position**, **Size** and **Rotation** as numbers, as the Transform tool's options do: the reference point beside **Position** sets which point of the layer the numbers place and hold still, and the aspect lock beside **Size** keeps its proportions. **W** and **H** also take `50%`, `*2` or `/4` of the current size. The flip buttons beside **Rotation** mirror the layer in place across its center. Each change is a separate undoable step.
The **Overview** tab shows a thumbnail of the whole canvas with the visible area outlined. Click it to move the view.
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 5d7f5ff51d..8871ce66b3 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -159,12 +159,12 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 354247,
+ "largestAssetRawBytes": 360296,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 620765,
+ "scriptRawBytes": 626822,
"scriptRequestCount": 7,
- "totalRawBytes": 620765
+ "totalRawBytes": 626822
},
"domContentLoadedMedianMs": 133.89999999850988,
"id": "editor-canvas",
@@ -197,12 +197,12 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 354247,
+ "largestAssetRawBytes": 360296,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 620765,
+ "scriptRawBytes": 626822,
"scriptRequestCount": 7,
- "totalRawBytes": 620765
+ "totalRawBytes": 626822
},
"domContentLoadedMedianMs": 133.90000000037253,
"id": "editor-canvas",
@@ -3134,11 +3134,13 @@
"source:src/workbench/widgets/canvas/tool-options/FilterOptions.tsx",
"source:src/workbench/widgets/canvas/tool-options/GradientOptions.tsx",
"source:src/workbench/widgets/canvas/tool-options/OperationActions.tsx",
+ "source:src/workbench/widgets/canvas/tool-options/ReferencePointPicker.tsx",
"source:src/workbench/widgets/canvas/tool-options/SamOptions.tsx",
"source:src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx",
"source:src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx",
"source:src/workbench/widgets/canvas/tool-options/geometryForm.tsx",
"source:src/workbench/widgets/canvas/tool-options/gradientStops.ts",
+ "source:src/workbench/widgets/canvas/tool-options/layerTransformFields.tsx",
"source:src/workbench/widgets/canvas/tool-options/paintForm.tsx",
"source:src/workbench/widgets/canvas/tool-options/selectionForm.tsx",
"source:src/workbench/widgets/canvas/tool-options/textForm.tsx",
@@ -3146,6 +3148,7 @@
"source:src/workbench/widgets/canvas/tool-presentation/FormControls.tsx",
"source:src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx",
"source:src/workbench/widgets/canvas/tool-presentation/propertyGroupStore.ts",
+ "source:src/workbench/widgets/canvas/tool-presentation/relativeValue.ts",
"source:src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts",
"source:src/workbench/widgets/canvas/toolFamilyStore.ts",
"source:src/workbench/widgets/canvas/useCanvasGallerySave.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 1e85de7ae4..1d4406592a 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3040,8 +3040,22 @@
"hint": "Each field commits one undoable change to the selected layer.",
"noSelection": "No layer selected",
"position": "Position",
+ "referencePoint": "Reference point",
+ "referencePointValue": "Reference point: {{position}}",
+ "anchors": {
+ "topLeft": "Top left",
+ "top": "Top",
+ "topRight": "Top right",
+ "left": "Left",
+ "center": "Center",
+ "right": "Right",
+ "bottomLeft": "Bottom left",
+ "bottom": "Bottom",
+ "bottomRight": "Bottom right"
+ },
"rotation": "Rotation",
- "scale": "Scale",
+ "flipHorizontal": "Flip horizontal",
+ "flipVertical": "Flip vertical",
"session": "Transform in progress",
"title": "Transform"
},
@@ -4755,8 +4769,9 @@
"pressureAffectsOpacity": "Pen pressure affects opacity",
"pressureAffectsWidth": "Pen pressure affects width",
"rotation": "Rotation",
- "scaleHeight": "H %",
- "scaleWidth": "W %",
+ "relativePercent": "Percent of the current value",
+ "relativeMultiply": "Multiplies the current value",
+ "relativeDivide": "Divides the current value",
"selectAll": "Select all",
"selectionActions": "Actions",
"selectionAdd": "Add",
@@ -5824,6 +5839,7 @@
"arrange": "Arrange",
"booleanOperations": "Boolean operations",
"convertTo": "Convert to",
+ "flip": "Flip",
"copyTo": "Copy to",
"addAdjustment": "Add adjustment",
"colorLabel": "Color label"
@@ -7584,7 +7600,7 @@
"samOppositePoint": "Opposite label",
"samRemovePoint": "Remove point",
"samBox": "Draw / adjust search box",
- "constrainTransform": "Constrain move / scale; snap rotation",
+ "constrainTransform": "Constrain move; invert the aspect link while scaling; snap rotation",
"scaleCenter": "Scale from center",
"select": "Select region",
"addBeforeDrag": "Add (hold before drag)",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index e4eafe35c2..613996f381 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -55,9 +55,9 @@ Document mirror reports in leaf terms, in document order. For value edit it fold
### Properties and Transform
-Tool and operation settings live off the surface, as editor panes of Layers panel (`widgets/layers/panes`). Properties pane renders running operation first, then active tool, each as `ToolPropertyForm` / `OperationPropertyForm` (`widgets/canvas/tool-presentation`): named, collapsible groups of typed rows (optional preview card on top), each ending with its form's actions row inline in its section — no sticky footer. A running operation's row (`OperationActions`: Reset, Cancel, the manual run while auto-update is off, Apply with its save-as menu; while auto-update is on, Filter and Select Object also offer it as the retry after a failed run) follows its groups; the transform form's Apply/Cancel close the Tool section. An operation form's `useStatus` hook feeds its section: the busy phase sits beside the section title in a live region mounted for the operation's lifetime, the error comes last, after the actions, so no control moves, and the source layer is the subtitle's tooltip. Group ids are global so tools sharing a group's component keep its DOM and collapse state across the switch. Transform pane edits selected layer's transform without a tool — each field commits one undoable `patch`, and while Transform tool holds a session same fields drive its preview and Apply / Cancel land or drop it. Forms read engine's option stores and document transactions directly: no state mirror. A running operation locks the tool section, its actions included, in place (`inert`) and takes focus to its own Cancel, scrolled into view, keeping its own controls live; a generation or staged results lock nothing (see "Editing during generation"). Panes are fixed parts of panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through Layers widget's project state — not movable widgets. Same blocks host Color/Swatches workspace (project foreground/background pair), History pane (engine's labeled undo/redo stack via `history.getEntries()`/`stepBy`: a Start row stands for the canvas before the oldest kept step and notes `evicted` steps or the `dropped` ones a previous engine of the project was disposed with (the registry hands their count, evictions and cooldown trims included, to the next engine's history), both until the history is next cleared; jumps wait while `documentEditingLocked`; Clear history asks first; below the steps, the project's restore points), and Overview navigator (`previews.drawDocumentOverview` plus live viewport handle).
+Tool and operation settings live off the surface, as editor panes of Layers panel (`widgets/layers/panes`). Properties pane renders running operation first, then active tool, each as `ToolPropertyForm` / `OperationPropertyForm` (`widgets/canvas/tool-presentation`): named, collapsible groups of typed rows (optional preview card on top), each ending with its form's actions row inline in its section — no sticky footer. A running operation's row (`OperationActions`: Reset, Cancel, the manual run while auto-update is off, Apply with its save-as menu; while auto-update is on, Filter and Select Object also offer it as the retry after a failed run) follows its groups; the transform form's Apply/Cancel close the Tool section. An operation form's `useStatus` hook feeds its section: the busy phase sits beside the section title in a live region mounted for the operation's lifetime, the error comes last, after the actions, so no control moves, and the source layer is the subtitle's tooltip. Group ids are global so tools sharing a group's component keep its DOM and collapse state across the switch. Transform pane edits selected layer's transform without a tool, with the same rows as the Move and Transform tool forms (`widgets/canvas/tool-options/layerTransformFields.tsx`) — each field commits one undoable `patch`, and while Transform tool holds a session same fields drive its preview and Apply / Cancel land or drop it. Forms read engine's option stores and document transactions directly: no state mirror. A running operation locks the tool section, its actions included, in place (`inert`) and takes focus to its own Cancel, scrolled into view, keeping its own controls live; a generation or staged results lock nothing (see "Editing during generation"). Panes are fixed parts of panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through Layers widget's project state — not movable widgets. Same blocks host Color/Swatches workspace (project foreground/background pair), History pane (engine's labeled undo/redo stack via `history.getEntries()`/`stepBy`: a Start row stands for the canvas before the oldest kept step and notes `evicted` steps or the `dropped` ones a previous engine of the project was disposed with (the registry hands their count, evictions and cooldown trims included, to the next engine's history), both until the history is next cleared; jumps wait while `documentEditingLocked`; Clear history asks first; below the steps, the project's restore points), and Overview navigator (`previews.drawDocumentOverview` plus live viewport handle).
-The Transform tool's Smoothing, resampling kernel and Contain/Cover/Fill fit choice belong to the engine's transient options. Its Resampling group appears above Position in the Tool form. Fit to Frame and numeric edits update the tool's existing preview session; they stay disabled while that session is pending or processing. The separate layer Transform pane contains only its ordinary geometry fields and Apply/Cancel. Image and paint sources Apply through a 2x raster and the application's `img_resize` adapter using Bilinear, Bicubic, Hamming or Lanczos, then publish one paint conversion and undo step. Shape, gradient and text sources retain their editable types and do not expose smoothing; floating selections use their own Apply/Cancel and do not expose these options. The fit action resets rotation and centers the source content (including its local offset) in the generation frame; Cover preserves aspect ratio while extending beyond it, Fill stretches each axis.
+The Transform tool's Smoothing, resampling kernel, Contain/Cover/Fill fit choice, aspect link and reference point belong to the engine's transient options. Typed position, size and rotation act on the reference point of the content box the handles frame (`hittableLayerRect`): X/Y show and place that point (a placed origin stays on whole pixels), the rest hold it fixed, and a layer without a content box falls back to its origin with Size disabled; gestures keep their own pivots. Size is the layer's own box (`rect × |scale|`), not its rotated bounds. The aspect link governs the numeric size fields (the other axis' magnitude follows by the same factor; they also take `N%`, `*N` and `/N` of the current size) and every scale handle, layer sessions and floats alike; Shift inverts it for one drag. Flip horizontal and vertical mirror the layer in document space about its content-box centre, whatever the reference point. `layers.flipLayer(layerId, direction, label)` (`TransformEditingController.flip`) is the one write path the shared rows, the layer menu's Flip submenu and the `canvas.flipHorizontal` / `canvas.flipVertical` commands use: inside a transform session on that layer it flips the session preview, and with a floating selection lifted from that layer it flips the float's own layer-local transform about the float's centre (so along the layer's axes), Cancel restoring it (both `previewed`); otherwise it commits one structural transform step under the caller's label. It refuses a missing layer, a locked one and one without a content box as `missing`, `locked` and `empty`, which every entry point reports with the layer-action copy; locked document editing or a processing session is `busy`. Its Resampling group appears above Position in the Tool form. Fit to Frame and numeric edits update the tool's existing preview session; they stay disabled while that session is pending or processing. The separate layer Transform pane contains only its ordinary geometry fields and Apply/Cancel. Image and paint sources Apply through a 2x raster and the application's `img_resize` adapter using Bilinear, Bicubic, Hamming or Lanczos, then publish one paint conversion and undo step. Shape, gradient and text sources retain their editable types and do not expose smoothing; floating selections use their own Apply/Cancel and do not expose these options. The fit action resets rotation and centers the source content (including its local offset) in the generation frame; Cover preserves aspect ratio while extending beyond it, Fill stretches each axis.
A paint bake, with or without smoothing, evaluates the whole adjustment stack in layer-local space before transforming whenever Noise or a spatial adjustment contributes, and removes that baked stack; color-only adjustments stay editable. Undo restores the raw pixels and stack. The transform controller snapshots its source and reserves supersample, decode and undo/output pixel buffers before awaiting the application adapter; no edit transaction spans the network wait. Cancel, disposal, replay and document replacement abort the request; publication additionally requires the same selected layer, editable state, session and cache version. Refused or failed resampling keeps the preview open for retry. The application adapter owns encoding, upload, the utility graph, account/engine lifetime cancellation and decoded-bitmap disposal. The core owns memory admission and atomic history publication. Each initial publication or history replay prepares its cache replacement before changing the contract, so allocation failure keeps the previous layer and pixels intact. The application resize node is intermediate and requests front-of-queue execution. The session keeps its transform preview throughout preparation, queue waiting and resampling. Waiting for processing follows an observed pending item, and Resampling follows observed execution or decoding the returned result; preparation stays neutral while the queue state is unknown. Cancel remains live. A failed apply retains the transform and exposes Retry; a new edit or retry clears the failed marker. Request identity, abort, layer and cache freshness guard every progress callback as well as pixel publication, so an abandoned attempt cannot update its replacement's status.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 655000451d..beff6dd461 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -489,6 +489,11 @@ export type StructuralCommitResult =
| { status: SubsetOf<CanvasTransactionOutcome, 'stale'>; expectedRevision: number; actualRevision: number }
| { status: 'postcondition-failed'; recovered: 'reverted' | 'reverted-unmirrored' | 'unreverted' };
+export type FlipLayerResult =
+ | StructuralCommitResult
+ | { status: 'previewed' }
+ | { status: 'locked' | 'missing' | 'empty' };
+
export type CanvasFontReplacementResult =
| (CanvasFontReplacementSummary & { status: 'committed' | 'unchanged' })
| Exclude<StructuralCommitResult, { status: 'committed' }>;
@@ -728,6 +733,8 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {
mergeVisibleRasterLayers(): Promise<MergeVisibleResult>;
/** `dispatch-rejected` also covers a selection with nothing eligible to move. */
nudgeSelectedLayer(dx: number, dy: number): StructuralCommitResult;
+ /** Mirrors about the content centre; a live float or transform session on the layer flips as a preview instead. */
+ flipLayer(layerId: string, direction: 'horizontal' | 'vertical', label: string): FlipLayerResult;
openTextCreate(docPoint: Vec2): void;
openTextEdit(layerId: string): void;
rasterizeLayer(layerId: string): Promise<RasterizeLayerResult>;
@@ -833,7 +840,18 @@ export {
TEXT_FONT_FAMILIES,
TEXT_FONT_WEIGHTS,
} from './engineStores';
-export type { LayerTransform } from './transform/transformMath';
+export {
+ layerPointToDocument,
+ localHandlePoint,
+ moveLocalPointTo,
+ retransformAbout,
+ scaleAxis,
+ scaleForLength,
+ transformedSize,
+ type LayerTransform,
+ type TransformAnchor,
+} from './transform/transformMath';
+export { hittableLayerRect } from './tools/moveHitTest';
export { CanvasImageMissingError, type ImageResolver } from './render/rasterizers';
export type { Rect, SelectionOp, ToolId, Vec2 } from './types';
export { adjustmentsKey, buildCurveLut, isIdentityAdjustments } from './render/adjustments';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
index 44c1f473b2..f86f159d25 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
@@ -46,6 +46,8 @@ const createTransformOptions = () => ({
getDocument: () => null,
getUserToolId: () => 'brush' as const,
hasFloatingSelection: () => false,
+ getFloatingSelection: () => null,
+ setFloatingTransform: () => false,
invalidate: vi.fn(),
isGestureActive: () => false,
peekCacheRect: () => undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.browser.test.ts
index 019c44b421..57825982cf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.browser.test.ts
@@ -128,9 +128,17 @@ describe('Transform adjustment bakes', () => {
enterTool: vi.fn(),
getCache: (id) => h.layers.get(id) ?? null,
getDocument: h.document,
- getOptions: () => ({ smoothing, resampleMode: 'lanczos', fitMode: 'contain' }),
+ getOptions: () => ({
+ aspectLinked: true,
+ fitMode: 'contain',
+ referencePoint: 'center',
+ resampleMode: 'lanczos',
+ smoothing,
+ }),
getUserToolId: () => 'transform',
hasFloatingSelection: () => false,
+ getFloatingSelection: () => null,
+ setFloatingTransform: () => false,
invalidate: vi.fn(),
isGestureActive: () => false,
peekCacheRect: (id) => h.layers.peek(id)?.rect,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
index 751da58f87..1d4b4a9fd1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
@@ -1,6 +1,7 @@
import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { TransformSession } from '@workbench/canvas-engine/engineStores';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
import type { ToolId } from '@workbench/canvas-engine/types';
import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';
@@ -114,6 +115,7 @@ const createHarness = (
let pending: string | null = null;
const state = {
canEdit: true,
+ float: null as FloatingSelection | null,
floating: false,
gesture: false,
tool: 'brush' as ToolId,
@@ -127,11 +129,18 @@ const createHarness = (
reportRefusal: vi.fn(),
restoreCache: vi.fn(),
select: vi.fn((layerId: string) => dispatch({ id: layerId, type: 'setCanvasSelectedLayer' })),
+ setFloatingTransform: vi.fn(() => true),
setOverride: vi.fn(),
};
const controller = new TransformEditingController({
backend,
- getOptions: () => ({ fitMode: 'contain', resampleMode: 'lanczos', smoothing: !!options.resample }),
+ getOptions: () => ({
+ aspectLinked: true,
+ fitMode: 'contain',
+ referencePoint: 'center',
+ resampleMode: 'lanczos',
+ smoothing: !!options.resample,
+ }),
resample: options.resample,
canEdit: () => state.canEdit,
commitStructural: calls.commitStructural,
@@ -141,6 +150,8 @@ const createHarness = (
getDocument: () => mirror.getDocument(),
getUserToolId: () => state.tool,
hasFloatingSelection: () => state.floating,
+ getFloatingSelection: () => state.float,
+ setFloatingTransform: calls.setFloatingTransform,
invalidate: vi.fn(),
isGestureActive: () => state.gesture,
peekCacheRect: (layerId) => caches.peek(layerId)?.rect,
@@ -220,6 +231,20 @@ describe('TransformEditingController', () => {
expect(h.session()).toBeNull();
});
+ it('flips a live float on the layer as a preview, leaving the layer alone', () => {
+ const h = createHarness(shape);
+ h.state.float = {
+ layerId: 'shape',
+ pixels: { rect: { height: 2, width: 4, x: 0, y: 0 } },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 3, y: 0 },
+ } as FloatingSelection;
+
+ expect(h.controller.flip('shape', 'horizontal', 'Flip horizontal')).toEqual({ status: 'previewed' });
+ expect(h.calls.setFloatingTransform).toHaveBeenCalledWith(expect.objectContaining({ scaleX: -1, x: 7, y: 0 }));
+ expect(h.calls.commitStructural).not.toHaveBeenCalled();
+ expect(h.layer()?.transform).toEqual(shape.transform);
+ });
+
it('keeps the session open and reports a refused commit', () => {
const h = createHarness(shape, { commitStatus: 'busy' });
h.controller.begin('shape');
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
index 0648546837..96b99337b8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
@@ -1,6 +1,7 @@
import type {
BeginTransformResult,
CanvasEditRefusal,
+ FlipLayerResult,
StructuralCommitResult,
} from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
@@ -8,6 +9,7 @@ import type { TransformOptions, TransformSession } from '@workbench/canvas-engin
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { Rect, ToolId } from '@workbench/canvas-engine/types';
@@ -29,9 +31,9 @@ import {
imageDataOf,
type SpatialRunner,
} from '@workbench/canvas-engine/render/exactAdjustments';
-import { hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';
+import { hittableLayerRect, hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';
import { isTransformEligible } from '@workbench/canvas-engine/tools/transformTool';
-import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';
+import { bakeMatrix, flipTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { CanvasMutationContext, EditPublishResult, EditStep } from './mutationContext';
@@ -74,6 +76,8 @@ export interface TransformEditingControllerOptions {
readonly canEdit: () => boolean;
readonly isGestureActive: () => boolean;
readonly hasFloatingSelection: () => boolean;
+ readonly getFloatingSelection: () => FloatingSelection | null;
+ readonly setFloatingTransform: (transform: LayerTransform) => boolean;
/** The tool the user is on: a Space, Alt or C hold only lends the surface to another tool. */
readonly getUserToolId: () => ToolId;
/** Selects `layerId`; selecting cancels a session on another layer. */
@@ -252,6 +256,49 @@ export class TransformEditingController {
}
}
+ flip(layerId: string, direction: 'horizontal' | 'vertical', label: string): FlipLayerResult {
+ const document = this.deps.getDocument();
+ const leaf = lookupDocumentLeaf(document, layerId);
+ if (this.disposed || !document) {
+ return { status: 'not-ready' };
+ }
+ if (!leaf) {
+ return { status: 'missing' };
+ }
+ if (leaf.effectiveLocked) {
+ return { status: 'locked' };
+ }
+ const session = this.deps.session.get();
+ if (!this.deps.canEdit() || (session?.layerId === layerId && (session.processing || this.processing))) {
+ return { status: 'busy' };
+ }
+ // The float is in its layer's local space, so it mirrors along the layer's axes.
+ const float = this.deps.getFloatingSelection();
+ if (float?.layerId === layerId) {
+ const flipped = flipTransform(float.transform, float.pixels.rect, direction);
+ // A drag would overwrite the flip, and a refused float transform reports itself.
+ const applied = !this.deps.isGestureActive() && this.deps.setFloatingTransform(flipped);
+ return { status: applied ? 'previewed' : 'busy' };
+ }
+ const rect = hittableLayerRect(leaf.layer, document);
+ if (!rect) {
+ return { status: 'empty' };
+ }
+ if (session?.layerId === layerId) {
+ this.update(flipTransform(session.transform, rect, direction));
+ return { status: 'previewed' };
+ }
+ return this.deps.commitStructural(
+ label,
+ {
+ id: layerId,
+ patch: { transform: flipTransform(leaf.layer.transform, rect, direction) },
+ type: 'updateCanvasLayer',
+ },
+ { id: layerId, patch: { transform: leaf.layer.transform }, type: 'updateCanvasLayer' }
+ );
+ }
+
update(transform: LayerTransform): void {
const session = this.deps.session.get();
if (this.disposed || !session || this.processing) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts
index 9f19e6a1ef..ec8f390b4f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/vectorEditingController.ts
@@ -40,6 +40,7 @@ import {
applyMove,
applyRotate,
applyScale,
+ isCornerHandle,
layerTransformMatrix,
resizeCursorForHandle,
transformTargetAt,
@@ -851,7 +852,13 @@ export class VectorEditingController implements Tool {
0
)
: gesture.target.kind === 'scale'
- ? applyScale({ ...args, handle: gesture.target.handle, alt: input.modifiers.alt, grid: 0 })
+ ? applyScale({
+ ...args,
+ alt: input.modifiers.alt,
+ constrain: input.modifiers.shift && isCornerHandle(gesture.target.handle),
+ grid: 0,
+ handle: gesture.target.handle,
+ })
: applyRotate(args);
const matrix = layerTransformMatrix(transform);
const path = transformBezierPath(this.transformOrigin, matrix);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
index cd0de1284a..42c94c31e6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/sources.ts
@@ -80,7 +80,10 @@ export const isRenderableLayer = (layer: CanvasLayerContract): boolean => {
* Untransformed local cache extent: native image size, shape/text extent, explicit gradient extent (legacy: document
* dims), or paint bitmap size at its offset (legacy: zero). Empty paint is an empty rect; unsupported sources throw.
*/
-export const getSourceContentRect = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): Rect => {
+export const getSourceContentRect = (
+ layer: CanvasLayerContract,
+ doc: Pick<CanvasDocumentContractV3, 'width' | 'height'>
+): Rect => {
// Guide geometry owns no pixels, even when it has paths.
if (layer.type === 'vector') {
return { height: 0, width: 0, x: 0, y: 0 };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index c4fd26c7b1..439d2d5138 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -4413,6 +4413,31 @@ describe('nudgeSelectedLayer', () => {
});
});
+describe('flipLayer', () => {
+ it('commits one undoable flip, and inside the layer’s session flips only the preview', async () => {
+ const { store } = createReducerBackedStore(selectedImageDoc());
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: store.getState().projects[0]!.id,
+ store,
+ });
+ const transform = () => getDocumentLayer(engine.document.getDocument(), 'a')!.transform;
+
+ expect(engine.layers.flipLayer('a', 'horizontal', 'Flip horizontal')).toEqual({ status: 'committed' });
+ expect(transform()).toMatchObject({ scaleX: -1, scaleY: 1, x: 10, y: 0 });
+ await engine.history.undo();
+ expect(transform()).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+
+ engine.tools.setTool('transform');
+ expect(engine.layers.flipLayer('a', 'vertical', 'Flip vertical')).toEqual({ status: 'previewed' });
+ expect(engine.stores.transformSession.get()?.transform).toMatchObject({ scaleY: -1, y: 10 });
+ expect(transform()).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+ engine.lifecycle.dispose();
+ });
+});
+
describe('move tool: drag through the pipeline', () => {
it('commits one structural transform update and records an undoable entry', () => {
const raf = createControllableRaf();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index dcd6e83a0b..d67e85d3b4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -977,6 +977,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
getDocument: () => mirror.getDocument(),
getUserToolId: () => pipeline.heldRestoreToolId() ?? interactionController.getActiveToolId(),
hasFloatingSelection: () => floatingSelection.has(),
+ getFloatingSelection: () => floatingSelection.get(),
+ setFloatingTransform: (transform) => floatingSelection.setTransform(transform),
invalidate: (payload) => scheduler.invalidate(payload),
isGestureActive: () => pipeline.isGestureActive(),
peekCacheRect: (layerId) => layerCache.peek(layerId)?.rect,
@@ -3044,6 +3046,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
},
applyTransform,
beginTransform: (layerId) => editingController.transform.request(layerId),
+ flipLayer: (layerId, direction, label) => editingController.transform.flip(layerId, direction, label),
booleanMergeRasterLayers,
cancelTextEdit,
cancelTransform,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index c1316656f4..544578cb28 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -9,7 +9,7 @@ import type {
import type { AdjustedSurfaceStatus } from '@workbench/canvas-engine/render/spatialDisplay';
import type { VectorShapePreview } from '@workbench/canvas-engine/render/vectorGuides';
import type { SamInteractionState } from '@workbench/canvas-engine/samInteraction';
-import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
+import type { LayerTransform, TransformAnchor } from '@workbench/canvas-engine/transform/transformMath';
import type { Rect, SelectionOp, ToolId, Vec2 } from '@workbench/canvas-engine/types';
import type { VectorEditSession } from '@workbench/canvas-engine/vectorEditState';
@@ -229,6 +229,9 @@ export interface TransformOptions {
smoothing: boolean;
resampleMode: 'bilinear' | 'bicubic' | 'hamming' | 'lanczos';
fitMode: 'contain' | 'cover' | 'fill';
+ aspectLinked: boolean;
+ /** Only the numeric fields use it; gestures keep their own pivots. */
+ referencePoint: TransformAnchor;
}
/** Spans gestures until Apply or Cancel; `startTransform` is the undo and cancel baseline. */
@@ -675,6 +678,8 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
smoothing: false,
resampleMode: 'bicubic',
fitMode: 'contain',
+ aspectLinked: true,
+ referencePoint: 'center',
}),
transformSession: createScalarStore<TransformSession | null>(null, transformSessionEqual),
pendingTransformLayerId: createScalarStore<string | null>(null),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
index 4f04b0a0d6..9227d2aeab 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
@@ -20,7 +20,7 @@ type LayerTransform = CanvasLayerBaseContract['transform'];
/** Off-origin-aware local content bounds via {@link getSourceContentRect}; null for empty or unsupported layers. */
export const hittableLayerRect = (
layer: CanvasLayerContract,
- doc: CanvasDocumentContractV3,
+ doc: Pick<CanvasDocumentContractV3, 'width' | 'height'>,
liveRect?: Rect
): Rect | null => {
if (layer.type === 'vector') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
index 58ebe4d393..358c4c48b9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
@@ -276,6 +276,24 @@ describe('transform tool: gestures', () => {
expect(h.ctx.commitStructural).not.toHaveBeenCalled();
});
+ it('keeps an edge drag proportional while the aspect link is on, and Shift frees it', () => {
+ const dragEastEdge = (shift: boolean) => {
+ const h = createHarness(makeDoc([imageLayer('a', { width: 100, height: 100 })], 'a'));
+ const tool = createTransformTool();
+ activate(tool, h.ctx);
+ down(tool, h.ctx, pointer(100, 50));
+ move(tool, h.ctx, pointer(150, 50, { shift }));
+ return h.session()!.transform;
+ };
+
+ const linked = dragEastEdge(false);
+ expect(linked.scaleX).toBeCloseTo(1.5, 9);
+ expect(linked.scaleY).toBeCloseTo(1.5, 9);
+ const free = dragEastEdge(true);
+ expect(free.scaleX).toBeCloseTo(1.5, 9);
+ expect(free.scaleY).toBe(1);
+ });
+
it('moves via an interior drag', () => {
const doc = makeDoc([imageLayer('a', { width: 100, height: 100 })], 'a');
const h = createHarness(doc);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
index d9d5269a61..9d119b940e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
@@ -1,7 +1,7 @@
/**
* Transform sessions frame the selected eligible layer without retargeting and span multiple gestures/numeric edits.
- * Handles scale about opposite anchors (Alt center, Shift uniform); rotate zones use Shift 15-degree snap; interior
- * moves with axis lock.
+ * Handles scale about opposite anchors (Alt center; the aspect link, inverted by Shift, keeps proportions); rotate zones
+ * use Shift 15-degree snap; interior moves with axis lock.
*
* Layer origins/handles snap to the model grid; Alt bypasses move snapping but retains center-scale meaning.
* Local-space floats never snap. Apply makes one parameter edit or paint bake. Pointercancel reverts only its drag;
@@ -172,11 +172,11 @@ export const createTransformTool = (): Tool => {
case 'scale':
return applyScale({
alt: input.modifiers.alt,
+ constrain: ctx.stores.transformOptions.get().aspectLinked !== input.modifiers.shift,
// No alt bypass on a scale handle — alt already means scale-about-center.
grid: gridFor(false),
handle: state.target.handle,
pointerDoc: pointer,
- shift: input.modifiers.shift,
rect: state.rect,
start: state.startTransform,
startPointerDoc: state.startPointerDoc,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts
index e4f4287a6c..d22198ca82 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts
@@ -9,10 +9,16 @@ import {
applyScale,
bakeMatrix,
composeLayerTransforms,
+ flipTransform,
IDENTITY_TRANSFORM,
+ layerPointToDocument,
layerTransformMatrix,
localHandlePoint,
resizeCursorForHandle,
+ retransformAbout,
+ scaleAxis,
+ scaleForLength,
+ transformedSize,
ROTATE_SNAP_RAD,
TRANSFORM_ROTATE_NUB_PX,
transformOverlayGeometry,
@@ -59,7 +65,7 @@ describe('off-origin content rect (content-sized layers)', () => {
handle: 'se',
pointerDoc: { x: 130, y: 100 },
rect: offOrigin,
- shift: false,
+ constrain: false,
start: identity,
startPointerDoc: { x: 70, y: 60 },
});
@@ -121,7 +127,7 @@ describe('applyScale: about the opposite handle', () => {
alt: false,
handle: 'se',
pointerDoc: { x: 150, y: 100 },
- shift: false,
+ constrain: false,
rect,
start: identity,
startPointerDoc: { x: 100, y: 100 },
@@ -140,7 +146,7 @@ describe('applyScale: modifiers', () => {
alt: true,
handle: 'se',
pointerDoc: { x: 150, y: 150 },
- shift: false,
+ constrain: false,
rect,
start: identity,
startPointerDoc: { x: 100, y: 100 },
@@ -150,12 +156,12 @@ describe('applyScale: modifiers', () => {
expect(close(centerAfter.y, centerBefore.y)).toBe(true);
});
- it('shift keeps a uniform aspect on a corner drag', () => {
+ it('keeps a uniform aspect on a constrained corner drag', () => {
const next = applyScale({
alt: false,
handle: 'se',
pointerDoc: { x: 200, y: 110 },
- shift: true,
+ constrain: true,
rect,
start: identity,
startPointerDoc: { x: 100, y: 100 },
@@ -171,7 +177,7 @@ describe('applyScale: flip and clamp', () => {
alt: false,
handle: 'e',
pointerDoc: { x: -50, y: 50 },
- shift: false,
+ constrain: false,
rect,
start: identity,
startPointerDoc: { x: 100, y: 50 },
@@ -181,6 +187,50 @@ describe('applyScale: flip and clamp', () => {
});
});
+describe('numeric size about a reference point', () => {
+ it('lands the typed size on a rotated, flipped, off-origin layer and keeps the reference point in place', () => {
+ const box: TransformRect = { height: 40, width: 60, x: 25, y: -15 };
+ const start: LayerTransform = { rotation: 0.7, scaleX: -1.5, scaleY: 0.5, x: 12, y: 34 };
+ const anchor = localHandlePoint(box, 'ne');
+ const before = layerPointToDocument(start, anchor);
+
+ const scales = scaleAxis(start, 'x', scaleForLength(120, box.width, start.scaleX), true);
+ const next = retransformAbout(start, anchor, scales);
+
+ expect(transformedSize(next, box).width).toBeCloseTo(120, 9);
+ expect(transformedSize(next, box).height).toBeCloseTo(26 + 2 / 3, 9);
+ expect(next.scaleX).toBeLessThan(0);
+ expect(next.scaleY).toBeGreaterThan(0);
+ expect(next.rotation).toBe(start.rotation);
+ const after = layerPointToDocument(next, anchor);
+ expect(after.x).toBeCloseTo(before.x, 9);
+ expect(after.y).toBeCloseTo(before.y, 9);
+ });
+});
+
+describe('flipTransform', () => {
+ it('mirrors in place about the content centre, and twice restores the transform', () => {
+ const box: TransformRect = { height: 40, width: 60, x: 25, y: -15 };
+ const start: LayerTransform = { rotation: 0.7, scaleX: 1.5, scaleY: 0.5, x: 12, y: 34 };
+ const center = { x: 55, y: 5 };
+ for (const [direction, scaleX, scaleY] of [
+ ['horizontal', -1.5, 0.5],
+ ['vertical', 1.5, -0.5],
+ ] as const) {
+ const flipped = flipTransform(start, box, direction);
+ expect(flipped).toMatchObject({ rotation: -0.7, scaleX, scaleY });
+ const before = layerPointToDocument(start, center);
+ const after = layerPointToDocument(flipped, center);
+ expect(after.x).toBeCloseTo(before.x, 9);
+ expect(after.y).toBeCloseTo(before.y, 9);
+ const twice = flipTransform(flipped, box, direction);
+ for (const key of ['rotation', 'scaleX', 'scaleY', 'x', 'y'] as const) {
+ expect(twice[key]).toBeCloseTo(start[key], 9);
+ }
+ }
+ });
+});
+
describe('applyRotate', () => {
it('rotates about the center by the swept angle', () => {
const next = applyRotate({
@@ -235,7 +285,7 @@ describe('applyScale: grid snapping', () => {
grid,
handle: 'se',
pointerDoc,
- shift: false,
+ constrain: false,
rect,
start: identity,
startPointerDoc: { x: 100, y: 100 },
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts
index e05f3ab9d6..2d880f1678 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts
@@ -18,6 +18,8 @@ export interface TransformRect {
export type TransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
+export type TransformAnchor = TransformHandle | 'center';
+
export type TransformTarget =
| { kind: 'scale'; handle: TransformHandle }
| { kind: 'rotate'; handle: TransformHandle }
@@ -56,14 +58,14 @@ const OPPOSITE: Record<TransformHandle, TransformHandle> = {
w: 'e',
};
-const hasWest = (h: TransformHandle): boolean => h === 'nw' || h === 'w' || h === 'sw';
-const hasEast = (h: TransformHandle): boolean => h === 'ne' || h === 'e' || h === 'se';
-const hasNorth = (h: TransformHandle): boolean => h === 'nw' || h === 'n' || h === 'ne';
-const hasSouth = (h: TransformHandle): boolean => h === 'sw' || h === 's' || h === 'se';
+const hasWest = (h: TransformAnchor): boolean => h === 'nw' || h === 'w' || h === 'sw';
+const hasEast = (h: TransformAnchor): boolean => h === 'ne' || h === 'e' || h === 'se';
+const hasNorth = (h: TransformAnchor): boolean => h === 'nw' || h === 'n' || h === 'ne';
+const hasSouth = (h: TransformAnchor): boolean => h === 'sw' || h === 's' || h === 'se';
export const isCornerHandle = (h: TransformHandle): boolean => h.length === 2;
-export const localHandlePoint = (rect: TransformRect, handle: TransformHandle): Vec2 => ({
+export const localHandlePoint = (rect: TransformRect, handle: TransformAnchor): Vec2 => ({
x: rect.x + (hasWest(handle) ? 0 : hasEast(handle) ? rect.width : rect.width / 2),
y: rect.y + (hasNorth(handle) ? 0 : hasSouth(handle) ? rect.height : rect.height / 2),
});
@@ -87,6 +89,44 @@ const applyLinear = (m: { a: number; b: number; c: number; d: number }, v: Vec2)
y: m.b * v.x + m.d * v.y,
});
+type LinearTransform = Pick<LayerTransform, 'rotation' | 'scaleX' | 'scaleY'>;
+
+/** The translation that puts `local` at `doc`: T = doc − R·(sx·local.x, sy·local.y). */
+export const moveLocalPointTo = (linear: LinearTransform, local: Vec2, doc: Vec2): LayerTransform => {
+ const rs = applyLinear(rotationMat(linear.rotation), { x: linear.scaleX * local.x, y: linear.scaleY * local.y });
+ return { rotation: linear.rotation, scaleX: linear.scaleX, scaleY: linear.scaleY, x: doc.x - rs.x, y: doc.y - rs.y };
+};
+
+export const layerPointToDocument = (transform: LayerTransform, local: Vec2): Vec2 =>
+ applyToPoint(layerTransformMatrix(transform), local);
+
+export const retransformAbout = (start: LayerTransform, local: Vec2, next: Partial<LinearTransform>): LayerTransform =>
+ moveLocalPointTo({ ...start, ...next }, local, layerPointToDocument(start, local));
+
+/** Mirrors in document space about the content centre, so the angle negates and one local axis flips. */
+export const flipTransform = (
+ transform: LayerTransform,
+ rect: TransformRect,
+ direction: 'horizontal' | 'vertical'
+): LayerTransform => {
+ const center = localCenter(rect);
+ return moveLocalPointTo(
+ {
+ rotation: -transform.rotation,
+ scaleX: direction === 'horizontal' ? -transform.scaleX : transform.scaleX,
+ scaleY: direction === 'vertical' ? -transform.scaleY : transform.scaleY,
+ },
+ center,
+ layerPointToDocument(transform, center)
+ );
+};
+
+/** The layer's own box in document pixels (not its rotated bounds). */
+export const transformedSize = (transform: LayerTransform, rect: TransformRect): { width: number; height: number } => ({
+ height: rect.height * Math.abs(transform.scaleY),
+ width: rect.width * Math.abs(transform.scaleX),
+});
+
/** A handle's outward normal in LOCAL space (y-down, matching document/screen). */
const localOutward = (handle: TransformHandle): Vec2 => ({
x: hasWest(handle) ? -1 : hasEast(handle) ? 1 : 0,
@@ -212,6 +252,21 @@ const clampScale = (s: number): number => {
return Math.abs(s) < MIN_ABS_SCALE ? sign * MIN_ABS_SCALE : s;
};
+export const scaleForLength = (length: number, rectLength: number, current: number): number =>
+ (current < 0 ? -1 : 1) * Math.max(MIN_ABS_SCALE, length / rectLength);
+
+export const scaleAxis = (
+ start: LayerTransform,
+ axis: 'x' | 'y',
+ scale: number,
+ linked: boolean
+): Pick<LayerTransform, 'scaleX' | 'scaleY'> => {
+ const next = clampScale(scale);
+ const [own, other] = axis === 'x' ? [start.scaleX, start.scaleY] : [start.scaleY, start.scaleX];
+ const linkedOther = linked ? clampScale(other * Math.abs(next / own)) : other;
+ return axis === 'x' ? { scaleX: next, scaleY: linkedOther } : { scaleX: linkedOther, scaleY: next };
+};
+
export const constrainMoveDelta = (delta: Vec2, shift: boolean): Vec2 => {
if (!shift) {
return delta;
@@ -230,14 +285,14 @@ export interface ScaleParams {
handle: TransformHandle;
startPointerDoc: Vec2;
pointerDoc: Vec2;
- shift: boolean;
+ constrain: boolean;
alt: boolean;
grid?: number;
}
-/** Edges affect one axis, Shift corners keep aspect; flips allowed down to the minimum absolute scale. */
+/** Free edges affect one axis; flips allowed down to the minimum absolute scale. */
export const applyScale = (p: ScaleParams): LayerTransform => {
- const { alt, handle, rect, shift, start } = p;
+ const { alt, constrain, handle, rect, start } = p;
const m = layerTransformMatrix(start);
const handleLocal = localHandlePoint(rect, handle);
const anchorLocal = alt ? localCenter(rect) : localHandlePoint(rect, OPPOSITE[handle]);
@@ -262,26 +317,25 @@ export const applyScale = (p: ScaleParams): LayerTransform => {
let sx = dlx !== 0 ? vx / dlx : start.scaleX;
let sy = dly !== 0 ? vy / dly : start.scaleY;
- if (shift && isCornerHandle(handle)) {
+ if (constrain) {
const fx = start.scaleX !== 0 ? sx / start.scaleX : 1;
const fy = start.scaleY !== 0 ? sy / start.scaleY : 1;
- const f = Math.abs(fx) >= Math.abs(fy) ? fx : fy;
- sx = start.scaleX * f;
- sy = start.scaleY * f;
+ if (isCornerHandle(handle)) {
+ const f = Math.abs(fx) >= Math.abs(fy) ? fx : fy;
+ sx = start.scaleX * f;
+ sy = start.scaleY * f;
+ } else if (dlx !== 0) {
+ sy = start.scaleY * Math.abs(fx);
+ } else {
+ sx = start.scaleX * Math.abs(fy);
+ }
}
- sx = clampScale(sx);
- sy = clampScale(sy);
-
- // Keep the anchor fixed: T = anchorDoc − R·(sx·anchorLocal.x, sy·anchorLocal.y).
- const rs = applyLinear(rotationMat(start.rotation), { x: sx * anchorLocal.x, y: sy * anchorLocal.y });
- return {
- rotation: start.rotation,
- scaleX: sx,
- scaleY: sy,
- x: anchorDoc.x - rs.x,
- y: anchorDoc.y - rs.y,
- };
+ return moveLocalPointTo(
+ { rotation: start.rotation, scaleX: clampScale(sx), scaleY: clampScale(sy) },
+ anchorLocal,
+ anchorDoc
+ );
};
export const snapRotation = (rad: number): number => Math.round(rad / ROTATE_SNAP_RAD) * ROTATE_SNAP_RAD;
@@ -305,18 +359,7 @@ export const applyRotate = (p: RotateParams): LayerTransform => {
if (p.shift) {
rotation = snapRotation(rotation);
}
- // Keep the center fixed: T = center − R(rotation)·(sx·cx, sy·cy).
- const rs = applyLinear(rotationMat(rotation), {
- x: start.scaleX * centerLocal.x,
- y: start.scaleY * centerLocal.y,
- });
- return {
- rotation,
- scaleX: start.scaleX,
- scaleY: start.scaleY,
- x: center.x - rs.x,
- y: center.y - rs.y,
- };
+ return moveLocalPointTo({ rotation, scaleX: start.scaleX, scaleY: start.scaleY }, centerLocal, center);
};
export const bakeMatrix = (transform: LayerTransform): Mat2d => layerTransformMatrix(transform);
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 730f6cedf4..6aaa5b6b51 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -209,6 +209,8 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'layerToFront', ['mod+shift+]']),
hotkey('canvas', 'layerToBack', ['mod+shift+[']),
hotkey('canvas', 'cropAllLayersToFrame', []),
+ hotkey('canvas', 'flipHorizontal', []),
+ hotkey('canvas', 'flipVertical', []),
hotkey('canvas', 'fitBboxToLayers', ['shift+n'], { title: 'Fit Frame To Layers' }),
hotkey('canvas', 'fitBboxToMasks', ['shift+b'], { title: 'Fit Frame To Masks' }),
// The gallery saves have no default keys; they are assignable through the hotkeys settings.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 20082ee17b..ff692f8fc9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -23,11 +23,13 @@ import {
executeCanvasToolCommand,
isCanvasToolCommand,
mergeSelectedLayerDown,
+ showCanvasRefusalNotice,
type CanvasToolCommandContext,
type HotkeyTableEntry,
} from '@workbench/widgets/canvas/canvasToolCommands';
import {
commitPreparedEdit,
+ isFlipLayerRefusal,
type LayerOperationRefusal,
type PreparedCommitOutcome,
} from '@workbench/widgets/canvas/useStructuralCommit';
@@ -75,8 +77,15 @@ export const CANVAS_ONLY_HOTKEYS = [
['canvas.layerToBack', 'widgets.canvas.commands.layerToBack', ['mod+shift+[']],
// No default key — assignable through the hotkeys settings; the canvas menu offers the same action.
['canvas.cropAllLayersToFrame', 'widgets.canvas.contextMenu.cropAllLayersToBbox', []],
+ ['canvas.flipHorizontal', 'widgets.transform.flipHorizontal', []],
+ ['canvas.flipVertical', 'widgets.transform.flipVertical', []],
] as const satisfies readonly HotkeyTableEntry[];
+const FLIP_LABEL_KEYS = {
+ horizontal: 'widgets.transform.flipHorizontal',
+ vertical: 'widgets.transform.flipVertical',
+} as const;
+
/** Command id → document-space nudge delta (shift variants are ×10). */
const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
'canvas.nudgeDown': { dx: 0, dy: 1 },
@@ -239,6 +248,17 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
ctx.pasteFromClipboard();
} else if (commandId === 'canvas.cropAllLayersToFrame') {
ctx.cropAllLayers();
+ } else if (commandId === 'canvas.flipHorizontal' || commandId === 'canvas.flipVertical') {
+ const direction = commandId === 'canvas.flipHorizontal' ? 'horizontal' : 'vertical';
+ const flipped =
+ selectedLayer && engine?.layers.flipLayer(selectedLayer.id, direction, t(FLIP_LABEL_KEYS[direction]));
+ if (selected && isGroupNode(selected.node)) {
+ showCanvasRefusalNotice('flip:group', t('widgets.transform.noSelection'), t('widgets.transform.groupSelected'));
+ } else if (flipped && isFlipLayerRefusal(flipped)) {
+ ctx.reportLayerOperation(flipped.status);
+ } else if (flipped && flipped.status !== 'previewed') {
+ ctx.reportStructuralCommit(flipped);
+ }
} else if (commandId === 'canvas.toggleNonRasterLayers') {
// Hide overlays without disabling generation content; showing restores individually hidden nodes too.
const overlays = index.nodes.filter((entry) => isOverlayStack(entry.stack));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ReferencePointPicker.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ReferencePointPicker.tsx
new file mode 100644
index 0000000000..41765e1cb0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ReferencePointPicker.tsx
@@ -0,0 +1,160 @@
+import type { TransformAnchor } from '@workbench/canvas-engine/api';
+import type { KeyboardEvent } from 'react';
+
+import { Box, Grid, Popover, Portal } from '@chakra-ui/react';
+import { IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/** Row-major: the arrow keys derive row and column from the index. */
+const ANCHORS: readonly TransformAnchor[] = ['nw', 'n', 'ne', 'w', 'center', 'e', 'sw', 's', 'se'];
+
+const ANCHOR_LABEL_KEYS: Record<TransformAnchor, string> = {
+ center: 'widgets.transform.anchors.center',
+ e: 'widgets.transform.anchors.right',
+ n: 'widgets.transform.anchors.top',
+ ne: 'widgets.transform.anchors.topRight',
+ nw: 'widgets.transform.anchors.topLeft',
+ s: 'widgets.transform.anchors.bottom',
+ se: 'widgets.transform.anchors.bottomRight',
+ sw: 'widgets.transform.anchors.bottomLeft',
+ w: 'widgets.transform.anchors.left',
+};
+
+const STEPS: Record<string, [row: number, column: number]> = {
+ ArrowDown: [1, 0],
+ ArrowLeft: [0, -1],
+ ArrowRight: [0, 1],
+ ArrowUp: [-1, 0],
+};
+
+const POSITIONING = { placement: 'bottom-end' } as const;
+
+const clampCell = (value: number): number => Math.min(2, Math.max(0, value));
+
+const ReferencePointGlyph = ({ value }: { value: TransformAnchor }) => (
+ <svg aria-hidden fill="currentColor" height="16" viewBox="0 0 16 16" width="16">
+ {ANCHORS.map((anchor, index) => {
+ const cx = 3 + (index % 3) * 5;
+ const cy = 3 + Math.floor(index / 3) * 5;
+ return anchor === value ? (
+ <rect key={anchor} height="5" rx="1" width="5" x={cx - 2.5} y={cy - 2.5} />
+ ) : (
+ <circle key={anchor} cx={cx} cy={cy} opacity="0.55" r="1.25" />
+ );
+ })}
+ </svg>
+);
+
+const ReferencePointCell = ({
+ anchor,
+ checked,
+ label,
+ onChoose,
+}: {
+ anchor: TransformAnchor;
+ checked: boolean;
+ label: string;
+ onChoose: (anchor: TransformAnchor) => void;
+}) => {
+ const onClick = useCallback(() => onChoose(anchor), [anchor, onChoose]);
+ return (
+ <IconButton
+ aria-checked={checked}
+ aria-label={label}
+ colorPalette={checked ? 'accent' : undefined}
+ data-anchor={anchor}
+ role="radio"
+ tabIndex={checked ? 0 : -1}
+ tooltip={label}
+ variant={checked ? 'solid' : 'ghost'}
+ onClick={onClick}
+ >
+ <Box
+ bg={checked ? 'currentColor' : 'fg.muted'}
+ boxSize={checked ? '2.5' : '2'}
+ rounded={checked ? 'xs' : 'full'}
+ />
+ </IconButton>
+ );
+};
+
+export const ReferencePointPicker = ({
+ value,
+ onChange,
+}: {
+ value: TransformAnchor;
+ onChange: (anchor: TransformAnchor) => void;
+}) => {
+ const { t } = useTranslation();
+ const triggerIds = useTooltipTriggerIds();
+ const [open, setOpen] = useState(false);
+ const triggerLabel = t('widgets.transform.referencePointValue', { position: t(ANCHOR_LABEL_KEYS[value]) });
+ const onOpenChange = useCallback(({ open: next }: { open: boolean }) => setOpen(next), []);
+ const choose = useCallback(
+ (anchor: TransformAnchor) => {
+ onChange(anchor);
+ setOpen(false);
+ },
+ [onChange]
+ );
+ const onKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ const step = STEPS[event.key];
+ if (!step) {
+ return;
+ }
+ event.preventDefault();
+ const index = ANCHORS.indexOf(value);
+ const next = clampCell(Math.floor(index / 3) + step[0]) * 3 + clampCell((index % 3) + step[1]);
+ if (next !== index) {
+ onChange(ANCHORS[next]!);
+ event.currentTarget.querySelector<HTMLButtonElement>(`[data-anchor="${ANCHORS[next]}"]`)?.focus();
+ }
+ },
+ [onChange, value]
+ );
+ return (
+ <Popover.Root
+ ids={triggerIds}
+ lazyMount
+ open={open}
+ positioning={POSITIONING}
+ unmountOnExit
+ onOpenChange={onOpenChange}
+ >
+ <Tooltip content={triggerLabel} disabled={open} ids={triggerIds} keepsRootWhenDisabled>
+ <Popover.Trigger asChild>
+ <IconButton aria-label={triggerLabel} color="fg" flexShrink={0} variant="outline">
+ <ReferencePointGlyph value={value} />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent p="1.5" w="auto">
+ <Grid
+ aria-label={t('widgets.transform.referencePoint')}
+ gap="0.5"
+ role="radiogroup"
+ templateColumns="repeat(3, auto)"
+ onKeyDown={onKeyDown}
+ >
+ {ANCHORS.map((anchor) => (
+ <ReferencePointCell
+ key={anchor}
+ anchor={anchor}
+ checked={anchor === value}
+ label={t(ANCHOR_LABEL_KEYS[anchor])}
+ onChoose={choose}
+ />
+ ))}
+ </Grid>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
index 282312b757..9422bd247e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
@@ -1,11 +1,11 @@
-import type { CanvasLayerContract, LayerTransform, TransformOptions } from '@workbench/canvas-engine/api';
+import type { CanvasLayerContract, TransformOptions } from '@workbench/canvas-engine/api';
import type {
ToolFormProps,
ToolPropertyForm,
ToolPropertyGroup,
} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
-import { createListCollection, Flex, Stack, Text } from '@chakra-ui/react';
+import { createListCollection, Flex, Text } from '@chakra-ui/react';
import { AspectRatioLockButton, AspectRatioPicker } from '@features/generation/components';
import { getLockedAspectRatioSettings } from '@features/generation/settings';
import { Button } from '@platform/ui/Button';
@@ -23,129 +23,49 @@ import {
useTransformSession,
} from '@workbench/widgets/canvas/engineStoreHooks';
import {
- FormNumberField,
ApplyCancelBar,
+ FormNumberField,
useNumberCommit,
} from '@workbench/widgets/canvas/tool-presentation/FormControls';
import { PropertyControlRow, PropertySwitchRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { fitLayerTransformToBbox } from '@workbench/widgets/layers/layerOps';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { LayerTransformRows, layerPositionText, PositionFields, useLayerTransformEditor } from './layerTransformFields';
import { useBboxEditor } from './useBboxEditor';
-const RAD_TO_DEG = 180 / Math.PI;
-const DEG_TO_RAD = Math.PI / 180;
-const MIN_SCALE_PERCENT = 1;
-
-export const round2 = (n: number): number => Math.round(n * 100) / 100;
-/** Degrees in (-180, 180], so 270 reads and stores as -90. */
-export const wrapDegrees = (degrees: number): number => {
- const wrapped = ((((degrees + 180) % 360) + 360) % 360) - 180;
- return wrapped === -180 ? 180 : wrapped;
-};
-/** A flip is a negative scale; a zero or near-zero one is not a transform anyone can undo by eye. */
-export const clampScalePercent = (percent: number): number =>
- percent < 0 ? Math.min(percent, -MIN_SCALE_PERCENT) : Math.max(percent, MIN_SCALE_PERCENT);
-
-interface SelectedLeafTransform {
- id: string;
- locked: boolean;
- transform: LayerTransform;
-}
-
-/** The shared layer-transform write path: a live session absorbs edits; otherwise each field is one patch. */
-export const useLayerTransformEditor = (engine: ToolFormProps['engine'], labelKey = 'widgets.transform.edit') => {
- const { t } = useTranslation();
- const commitPrepared = usePreparedCommit(engine);
- const session = useTransformSession(engine);
- const activeTool = useCanvasActiveTool(engine);
- const hasFloat = useCanvasHasFloatingSelection(engine);
- const locked = useCanvasDocumentEditingLocked(engine);
- const selected = useActiveProjectSelector(
- (project): SelectedLeafTransform | null => {
- const { document } = project.canvas;
- const leaf = document.selectedLayerId ? lookupDocumentLeaf(document, document.selectedLayerId) : null;
- return leaf ? { id: leaf.id, locked: leaf.effectiveLocked, transform: leaf.layer.transform } : null;
- },
- (a, b) => a?.id === b?.id && a?.locked === b?.locked && a?.transform === b?.transform
- );
- const transform = session?.transform ?? (selected && !selected.locked ? selected.transform : null);
- const editable =
- !locked &&
- !session?.processing &&
- selected !== null &&
- !selected.locked &&
- (activeTool !== 'transform' || hasFloat || session?.layerId === selected.id);
- const patch = useCallback(
- (next: Partial<LayerTransform>) => {
- if (!editable) {
- return;
- }
- if (session) {
- engine.layers.updateTransformSession({ ...session.transform, ...next });
- return;
- }
- if (!selected || selected.locked) {
- return;
- }
- commitPrepared(t(labelKey), (model) =>
- model.prepare({ id: selected.id, patch: { transform: next }, type: 'patch' })
- );
- },
- [commitPrepared, editable, engine, labelKey, selected, session, t]
- );
- return { editable, patch, transform };
-};
-
/** Share geometry rows across frame, selected layer, and transform session to preserve X/Y DOM identity. */
const GeometryPositionSettings = ({ engine }: ToolFormProps) => {
- const { t } = useTranslation();
const activeTool = useCanvasActiveTool(engine);
const isFrame = activeTool === 'bbox';
- const isTransform = activeTool === 'transform';
// The move tool keeps its own undo verbiage; everything else is a transform edit.
const layerEditor = useLayerTransformEditor(
engine,
activeTool === 'move' ? 'widgets.canvas.toolOptions.movePosition' : undefined
);
const bboxEditor = useBboxEditor(engine);
- const x = isFrame ? bboxEditor.bbox.x : layerEditor.transform ? Math.round(layerEditor.transform.x) : null;
- const y = isFrame ? bboxEditor.bbox.y : layerEditor.transform ? Math.round(layerEditor.transform.y) : null;
- const onX = useNumberCommit(
- useCallback(
- (value: number) => (isFrame ? bboxEditor.setX(value) : layerEditor.patch({ x: Math.round(value) })),
- [bboxEditor, isFrame, layerEditor]
- )
+ const { setPosition } = layerEditor;
+ const onX = useCallback(
+ (value: number) => (isFrame ? bboxEditor.setX(value) : setPosition('x', value)),
+ [bboxEditor, isFrame, setPosition]
);
- const onY = useNumberCommit(
- useCallback(
- (value: number) => (isFrame ? bboxEditor.setY(value) : layerEditor.patch({ y: Math.round(value) })),
- [bboxEditor, isFrame, layerEditor]
- )
+ const onY = useCallback(
+ (value: number) => (isFrame ? bboxEditor.setY(value) : setPosition('y', value)),
+ [bboxEditor, isFrame, setPosition]
);
return (
- <Flex align={isTransform ? 'center' : undefined} gap="2" w="full">
- <Text color="fg.muted" flexShrink={0} hidden={!isTransform} w="6rem">
- {t('widgets.transform.position')}
- </Text>
- <FormNumberField
- aria-label={t('widgets.canvas.toolOptions.positionX')}
- disabled={x === null || (!isFrame && !layerEditor.editable)}
- label={t('widgets.canvas.toolOptions.positionX')}
- value={x === null ? '' : String(x)}
- onValueCommit={onX}
- />
- <FormNumberField
- aria-label={t('widgets.canvas.toolOptions.positionY')}
- disabled={y === null || (!isFrame && !layerEditor.editable)}
- label={t('widgets.canvas.toolOptions.positionY')}
- value={y === null ? '' : String(y)}
- onValueCommit={onY}
- />
- </Flex>
+ <PositionFields
+ disabled={!isFrame && (layerEditor.transform === null || !layerEditor.editable)}
+ showLabel={activeTool === 'transform'}
+ referencePoint={isFrame ? undefined : layerEditor.referencePoint}
+ x={isFrame ? String(bboxEditor.bbox.x) : layerPositionText(layerEditor, 'x')}
+ y={isFrame ? String(bboxEditor.bbox.y) : layerPositionText(layerEditor, 'y')}
+ onReferencePointChange={layerEditor.setReferencePoint}
+ onX={onX}
+ onY={onY}
+ />
);
};
@@ -289,54 +209,6 @@ const TransformResamplingSettings = ({ engine }: ToolFormProps) => {
);
};
-/** Scale percent pair and rotation for the transform session / selected leaf. */
-export const TransformScaleSettings = ({ engine }: ToolFormProps) => {
- const { t } = useTranslation();
- const { editable, patch, transform } = useLayerTransformEditor(engine);
- const onScaleX = useNumberCommit(
- useCallback((value: number) => patch({ scaleX: clampScalePercent(value) / 100 }), [patch])
- );
- const onScaleY = useNumberCommit(
- useCallback((value: number) => patch({ scaleY: clampScalePercent(value) / 100 }), [patch])
- );
- const onRotation = useNumberCommit(
- useCallback((value: number) => patch({ rotation: wrapDegrees(value) * DEG_TO_RAD }), [patch])
- );
- return (
- <Stack gap="2">
- <PropertyControlRow label={t('widgets.transform.scale')} labelWidth="6rem">
- <Flex gap="2" gridColumn="2 / -1">
- <FormNumberField
- aria-label={t('widgets.canvas.toolOptions.scaleWidth')}
- disabled={!editable}
- label={t('widgets.canvas.toolOptions.frameWidth')}
- suffix="%"
- value={transform ? String(round2(transform.scaleX * 100)) : ''}
- onValueCommit={onScaleX}
- />
- <FormNumberField
- aria-label={t('widgets.canvas.toolOptions.scaleHeight')}
- disabled={!editable}
- label={t('widgets.canvas.toolOptions.frameHeight')}
- suffix="%"
- value={transform ? String(round2(transform.scaleY * 100)) : ''}
- onValueCommit={onScaleY}
- />
- </Flex>
- </PropertyControlRow>
- <PropertyControlRow label={t('widgets.transform.rotation')} labelWidth="6rem">
- <FormNumberField
- aria-label={t('widgets.canvas.toolOptions.rotation')}
- disabled={!editable}
- suffix="°"
- value={transform ? String(round2(wrapDegrees(transform.rotation * RAD_TO_DEG))) : ''}
- onValueCommit={onRotation}
- />
- </PropertyControlRow>
- </Stack>
- );
-};
-
/** Frame size, aspect preset and lock; the lock is Generate's own while the canvas drives Generate. */
const FrameSizeSettings = ({ engine }: ToolFormProps) => {
const { t } = useTranslation();
@@ -500,7 +372,7 @@ export const transformForm: ToolPropertyForm = {
groups: [
{ body: TransformResamplingSettings, id: 'transform-resampling', labelKey: 'widgets.transform.resampling' },
{ ...POSITION_GROUP, hideLabel: true },
- { body: TransformScaleSettings, id: 'transform-scale', labelKey: 'widgets.transform.scale', hideLabel: true },
+ { body: LayerTransformRows, id: 'transform-geometry', labelKey: 'widgets.transform.title', hideLabel: true },
],
id: 'transform',
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/layerTransformFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/layerTransformFields.tsx
new file mode 100644
index 0000000000..18aecbc0b2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/layerTransformFields.tsx
@@ -0,0 +1,356 @@
+import type { CanvasLayerContract, LayerTransform, TransformAnchor, Vec2 } from '@workbench/canvas-engine/api';
+import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
+
+import { Box, Flex, Stack } from '@chakra-ui/react';
+import { AspectRatioLockButton } from '@features/generation/components';
+import { IconButton } from '@platform/ui/Button';
+import {
+ hittableLayerRect,
+ layerPointToDocument,
+ localHandlePoint,
+ lookupDocumentLeaf,
+ moveLocalPointTo,
+ retransformAbout,
+ scaleAxis,
+ scaleForLength,
+ transformedSize,
+} from '@workbench/canvas-engine/api';
+import { useNotify } from '@workbench/useNotify';
+import {
+ useCanvasActiveTool,
+ useCanvasDocumentEditingLocked,
+ useCanvasHasFloatingSelection,
+ useTransformOptions,
+ useTransformSession,
+} from '@workbench/widgets/canvas/engineStoreHooks';
+import { FormNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/FormControls';
+import { PropertyControlRow, PropertyRowLabel } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
+import { reportFlipLayer, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { TrianglesCenterlineDashedVerticalIcon, TrianglesCenterlineDashedHorizontalIcon } from 'lucide-react';
+import { type ReactNode, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ReferencePointPicker } from './ReferencePointPicker';
+
+const RAD_TO_DEG = 180 / Math.PI;
+const DEG_TO_RAD = Math.PI / 180;
+const LABEL_WIDTH = '6rem';
+const ORIGIN: Vec2 = { x: 0, y: 0 };
+const MIN_SIZE_PX = 1;
+
+const round2 = (n: number): number => Math.round(n * 100) / 100;
+/** Degrees in (-180, 180], so 270 reads and stores as -90. */
+const wrapDegrees = (degrees: number): number => {
+ const wrapped = ((((degrees + 180) % 360) + 360) % 360) - 180;
+ return wrapped === -180 ? 180 : wrapped;
+};
+
+interface SelectedLeaf {
+ layer: CanvasLayerContract;
+ locked: boolean;
+ /** Legacy gradients without an extent are document-sized, so the content box reads the document size. */
+ documentWidth: number;
+ documentHeight: number;
+}
+
+type Axis = 'x' | 'y';
+
+/** The shared layer-transform write path: a live session absorbs edits; otherwise each field is one patch. */
+export const useLayerTransformEditor = (engine: ToolFormProps['engine'], labelKey = 'widgets.transform.edit') => {
+ const { t } = useTranslation();
+ const commitPrepared = usePreparedCommit(engine);
+ const notify = useNotify();
+ const session = useTransformSession(engine);
+ const options = useTransformOptions(engine);
+ const activeTool = useCanvasActiveTool(engine);
+ const hasFloat = useCanvasHasFloatingSelection(engine);
+ const locked = useCanvasDocumentEditingLocked(engine);
+ const selected = useActiveProjectSelector(
+ (project): SelectedLeaf | null => {
+ const { document } = project.canvas;
+ const leaf = document.selectedLayerId ? lookupDocumentLeaf(document, document.selectedLayerId) : null;
+ return leaf
+ ? {
+ documentHeight: document.height,
+ documentWidth: document.width,
+ layer: leaf.layer,
+ locked: leaf.effectiveLocked,
+ }
+ : null;
+ },
+ (a, b) =>
+ a?.layer === b?.layer &&
+ a?.locked === b?.locked &&
+ a?.documentWidth === b?.documentWidth &&
+ a?.documentHeight === b?.documentHeight
+ );
+ const layer = selected?.layer ?? null;
+ const documentWidth = selected?.documentWidth ?? 0;
+ const documentHeight = selected?.documentHeight ?? 0;
+ // Walks a vector layer's paths, so it runs only when the layer contract or document size changes.
+ const contentRect = useMemo(
+ () => (layer ? hittableLayerRect(layer, { height: documentHeight, width: documentWidth }) : null),
+ [documentHeight, documentWidth, layer]
+ );
+ const transform = session?.transform ?? layer?.transform ?? null;
+ const rect = layer && (!session || session.layerId === layer.id) ? contentRect : null;
+ const editable =
+ !locked &&
+ !session?.processing &&
+ selected !== null &&
+ !selected.locked &&
+ (activeTool !== 'transform' || hasFloat || session?.layerId === selected.layer.id);
+ const local = rect ? localHandlePoint(rect, options.referencePoint) : ORIGIN;
+ const position = transform ? layerPointToDocument(transform, local) : null;
+ const size = transform && rect ? transformedSize(transform, rect) : null;
+
+ const patch = useCallback(
+ (next: Partial<LayerTransform>) => {
+ if (!editable) {
+ return;
+ }
+ if (session) {
+ engine.layers.updateTransformSession({ ...session.transform, ...next });
+ return;
+ }
+ if (!selected || selected.locked) {
+ return;
+ }
+ commitPrepared(t(labelKey), (model) =>
+ model.prepare({ id: selected.layer.id, patch: { transform: next }, type: 'patch' })
+ );
+ },
+ [commitPrepared, editable, engine, labelKey, selected, session, t]
+ );
+
+ // Moves keep the origin on whole pixels; the readout shows where the reference point actually lands.
+ const setPosition = useCallback(
+ (axis: Axis, value: number) => {
+ if (!transform || !position) {
+ return;
+ }
+ const moved = moveLocalPointTo(transform, local, { ...position, [axis]: value });
+ patch({ [axis]: Math.round(moved[axis]) });
+ },
+ [local, patch, position, transform]
+ );
+ const setSize = useCallback(
+ (axis: Axis, length: number) => {
+ if (!transform || !rect) {
+ return;
+ }
+ const own =
+ axis === 'x' ? { rect: rect.width, scale: transform.scaleX } : { rect: rect.height, scale: transform.scaleY };
+ const scale = scaleForLength(Math.max(MIN_SIZE_PX, length), own.rect, own.scale);
+ patch(retransformAbout(transform, local, scaleAxis(transform, axis, scale, options.aspectLinked)));
+ },
+ [local, options.aspectLinked, patch, rect, transform]
+ );
+ const flip = useCallback(
+ (direction: 'horizontal' | 'vertical') => {
+ if (!editable || !layer || !rect) {
+ return;
+ }
+ const label = t(
+ direction === 'horizontal' ? 'widgets.transform.flipHorizontal' : 'widgets.transform.flipVertical'
+ );
+ reportFlipLayer(engine.layers.flipLayer(layer.id, direction, label), notify.error, t);
+ },
+ [editable, engine, layer, notify, rect, t]
+ );
+ const setRotation = useCallback(
+ (degrees: number) => {
+ if (transform) {
+ patch(retransformAbout(transform, local, { rotation: wrapDegrees(degrees) * DEG_TO_RAD }));
+ }
+ },
+ [local, patch, transform]
+ );
+ const setReferencePoint = useCallback(
+ (referencePoint: TransformAnchor) => engine.interaction.set('transformOptions', { ...options, referencePoint }),
+ [engine, options]
+ );
+ const toggleAspectLink = useCallback(
+ () => engine.interaction.set('transformOptions', { ...options, aspectLinked: !options.aspectLinked }),
+ [engine, options]
+ );
+ return {
+ aspectLinked: options.aspectLinked,
+ editable,
+ flip,
+ hasContentBox: rect !== null,
+ position,
+ referencePoint: options.referencePoint,
+ setPosition,
+ setReferencePoint,
+ setRotation,
+ setSize,
+ size,
+ toggleAspectLink,
+ transform,
+ };
+};
+
+type LayerTransformEditor = ReturnType<typeof useLayerTransformEditor>;
+
+const LabelWithControl = ({
+ children,
+ label,
+ shown = true,
+}: {
+ children: ReactNode;
+ label: string;
+ shown?: boolean;
+}) => (
+ <Flex align="center" display={shown ? 'flex' : 'none'} flexShrink={0} gap="1" w={LABEL_WIDTH}>
+ <Box flex="1" minW="0">
+ <PropertyRowLabel label={label} />
+ </Box>
+ {children}
+ </Flex>
+);
+
+export const PositionFields = ({
+ disabled,
+ referencePoint,
+ showLabel,
+ x,
+ y,
+ onReferencePointChange,
+ onX,
+ onY,
+}: {
+ disabled: boolean;
+ referencePoint?: TransformAnchor;
+ showLabel: boolean;
+ x: string;
+ y: string;
+ onReferencePointChange?: (anchor: TransformAnchor) => void;
+ onX: (value: number) => void;
+ onY: (value: number) => void;
+}) => {
+ const { t } = useTranslation();
+ const onXCommit = useNumberCommit(onX);
+ const onYCommit = useNumberCommit(onY);
+ const picker =
+ referencePoint && onReferencePointChange ? (
+ <ReferencePointPicker value={referencePoint} onChange={onReferencePointChange} />
+ ) : null;
+ return (
+ <Flex align="center" gap="2" w="full">
+ <LabelWithControl label={t('widgets.transform.position')} shown={showLabel}>
+ {showLabel ? picker : null}
+ </LabelWithControl>
+ <FormNumberField
+ aria-label={t('widgets.canvas.toolOptions.positionX')}
+ disabled={disabled}
+ label={t('widgets.canvas.toolOptions.positionX')}
+ value={x}
+ onValueCommit={onXCommit}
+ />
+ <FormNumberField
+ aria-label={t('widgets.canvas.toolOptions.positionY')}
+ disabled={disabled}
+ label={t('widgets.canvas.toolOptions.positionY')}
+ value={y}
+ onValueCommit={onYCommit}
+ />
+ {showLabel ? null : picker}
+ </Flex>
+ );
+};
+
+export const layerPositionText = (editor: LayerTransformEditor, axis: Axis): string => {
+ if (!editor.position || !editor.transform) {
+ return '';
+ }
+ return String(editor.hasContentBox ? round2(editor.position[axis]) : Math.round(editor.transform[axis]));
+};
+
+export const LayerPositionRow = ({ engine, showLabel }: ToolFormProps & { showLabel: boolean }) => {
+ const editor = useLayerTransformEditor(engine);
+ const onX = useCallback((value: number) => editor.setPosition('x', value), [editor]);
+ const onY = useCallback((value: number) => editor.setPosition('y', value), [editor]);
+ return (
+ <PositionFields
+ disabled={editor.transform === null || !editor.editable}
+ showLabel={showLabel}
+ referencePoint={editor.referencePoint}
+ x={layerPositionText(editor, 'x')}
+ y={layerPositionText(editor, 'y')}
+ onReferencePointChange={editor.setReferencePoint}
+ onX={onX}
+ onY={onY}
+ />
+ );
+};
+
+export const LayerTransformRows = ({ engine }: ToolFormProps) => {
+ const { t } = useTranslation();
+ const editor = useLayerTransformEditor(engine);
+ const { editable, flip, setRotation, setSize, size, transform } = editor;
+ const onWidth = useNumberCommit(useCallback((value: number) => setSize('x', value), [setSize]));
+ const onHeight = useNumberCommit(useCallback((value: number) => setSize('y', value), [setSize]));
+ const onRotation = useNumberCommit(setRotation);
+ const onFlipHorizontal = useCallback(() => flip('horizontal'), [flip]);
+ const onFlipVertical = useCallback(() => flip('vertical'), [flip]);
+ const flipDisabled = !editable || !editor.hasContentBox;
+ return (
+ <Stack gap="2">
+ <Flex align="center" gap="2" w="full">
+ <LabelWithControl label={t('widgets.properties.rows.size')}>
+ <AspectRatioLockButton isLocked={editor.aspectLinked} onToggle={editor.toggleAspectLink} />
+ </LabelWithControl>
+ <FormNumberField
+ aria-label={t('widgets.canvas.toolOptions.frameWidth')}
+ disabled={!editable || !size}
+ label={t('widgets.canvas.toolOptions.frameWidth')}
+ min={MIN_SIZE_PX}
+ relative
+ value={size ? String(round2(size.width)) : ''}
+ onValueCommit={onWidth}
+ />
+ <FormNumberField
+ aria-label={t('widgets.canvas.toolOptions.frameHeight')}
+ disabled={!editable || !size}
+ label={t('widgets.canvas.toolOptions.frameHeight')}
+ min={MIN_SIZE_PX}
+ relative
+ value={size ? String(round2(size.height)) : ''}
+ onValueCommit={onHeight}
+ />
+ </Flex>
+ <PropertyControlRow label={t('widgets.transform.rotation')} labelWidth={LABEL_WIDTH}>
+ <Flex align="center" gap="1" gridColumn="2 / -1">
+ <FormNumberField
+ aria-label={t('widgets.canvas.toolOptions.rotation')}
+ disabled={!editable}
+ suffix="°"
+ value={transform ? String(round2(wrapDegrees(transform.rotation * RAD_TO_DEG))) : ''}
+ onValueCommit={onRotation}
+ />
+ <IconButton
+ aria-label={t('widgets.transform.flipHorizontal')}
+ disabled={flipDisabled}
+ ms="1"
+ tooltip={t('widgets.transform.flipHorizontal')}
+ variant="ghost"
+ onClick={onFlipHorizontal}
+ >
+ <TrianglesCenterlineDashedVerticalIcon />
+ </IconButton>
+ <IconButton
+ aria-label={t('widgets.transform.flipVertical')}
+ disabled={flipDisabled}
+ tooltip={t('widgets.transform.flipVertical')}
+ variant="ghost"
+ onClick={onFlipVertical}
+ >
+ <TrianglesCenterlineDashedHorizontalIcon />
+ </IconButton>
+ </Flex>
+ </PropertyControlRow>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx
index b213832060..0ada0cdbd2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/FormControls.tsx
@@ -1,14 +1,16 @@
/* oxlint-disable react-perf/jsx-no-jsx-as-prop */
import type { NumberInput as ChakraNumberInput } from '@chakra-ui/react';
-import type { ReactNode } from 'react';
+import type { ClipboardEvent, InputEvent, KeyboardEvent, ReactNode, SyntheticEvent } from 'react';
-import { Box, Flex, Icon, InputGroup, NumberInput } from '@chakra-ui/react';
+import { Box, Flex, Icon, InputGroup, NumberInput, VisuallyHidden } from '@chakra-ui/react';
import { Button } from '@platform/ui/Button';
import { CONTROL_HEIGHT_PX } from '@theme/scale';
import { MoveHorizontalIcon } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { parseRelativeInput, resolveRelativeValue, type RelativeOperator } from './relativeValue';
+
/** Width of every numeric field, so X / Y / W / H line up across tools; fits "-1234.56" beside its affixes. */
const FORM_NUMBER_FIELD_WIDTH_PX = 80;
@@ -19,6 +21,8 @@ interface FormNumberFieldProps {
label?: string;
max?: number;
min?: number;
+ /** Commit mode only: also accept `N%`, `*N` and `/N` of the current value; `min` then bounds the result. */
+ relative?: boolean;
step?: number;
suffix?: string;
value: string;
@@ -36,6 +40,12 @@ const AFFIX_GUTTER_PX = 8;
const affixOffset = (chars: number): string => `${INPUT_HEIGHT_PX - AFFIX_GUTTER_PX - chars * AFFIX_CHAR_PX}px`;
const START_ELEMENT_PROPS = { ...AFFIX_PROPS, fontWeight: 'medium', pointerEvents: 'auto', ps: '1.5' } as const;
const END_ELEMENT_PROPS = { ...AFFIX_PROPS, pe: '1.5', pointerEvents: 'none' } as const;
+const OPERATOR_PREFIX: Partial<Record<RelativeOperator, string>> = { '*': '×', '/': '÷' };
+const OPERATOR_DESCRIPTION_KEYS: Record<RelativeOperator, string> = {
+ '%': 'widgets.canvas.toolOptions.relativePercent',
+ '*': 'widgets.canvas.toolOptions.relativeMultiply',
+ '/': 'widgets.canvas.toolOptions.relativeDivide',
+};
/** Drafts commit once on blur, Enter or release, and only after edits, so tabbing keeps precise values. */
export const FormNumberField = ({
@@ -44,35 +54,99 @@ export const FormNumberField = ({
label,
max,
min,
+ relative = false,
step,
suffix,
value,
onValueChange,
onValueCommit,
}: FormNumberFieldProps) => {
+ const { t } = useTranslation();
+ const operatorDescriptionId = useId();
const [draft, setDraft] = useState<string | null>(null);
const draftRef = useRef<string | null>(null);
+ const [operator, setOperator] = useState<RelativeOperator | null>(null);
+ const operatorRef = useRef<RelativeOperator | null>(null);
const scrubEnd = useRef<(() => void) | null>(null);
- const onDraftChange = useCallback(({ value: next }: ChakraNumberInput.ValueChangeDetails) => {
+ const setDraftText = useCallback((next: string | null) => {
draftRef.current = next;
setDraft(next);
}, []);
+ const setOperatorState = useCallback((next: RelativeOperator | null) => {
+ operatorRef.current = next;
+ setOperator(next);
+ }, []);
+ const onDraftChange = useCallback(
+ ({ value: next }: ChakraNumberInput.ValueChangeDetails) => setDraftText(next),
+ [setDraftText]
+ );
const onDraftCommit = useCallback(
(details: ChakraNumberInput.ValueChangeDetails) => {
const edited = draftRef.current !== null;
- draftRef.current = null;
- setDraft(null);
+ const pending = operatorRef.current;
+ setDraftText(null);
+ setOperatorState(null);
+ if (pending) {
+ const result = resolveRelativeValue(Number.parseFloat(value), pending, details.valueAsNumber);
+ if (result !== null && result > 0 && String(result) !== value) {
+ onValueCommit?.({ value: String(result), valueAsNumber: result });
+ }
+ return;
+ }
if (edited && details.value !== value) {
onValueCommit?.(details);
}
},
- [onValueCommit, value]
+ [onValueCommit, setDraftText, setOperatorState, value]
+ );
+ // Caught before the number input, which rejects any character that is not part of a number.
+ const takeOperator = useCallback(
+ (event: SyntheticEvent<HTMLDivElement>, text: string): void => {
+ const parsed = parseRelativeInput(text);
+ if (!parsed) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ setOperatorState(parsed.operator);
+ setDraftText(parsed.operand || (parsed.operator === '%' ? (event.target as HTMLInputElement).value : ''));
+ },
+ [setDraftText, setOperatorState]
+ );
+ const onBeforeInputCapture = useCallback(
+ (event: InputEvent<HTMLDivElement>) => takeOperator(event, event.data),
+ [takeOperator]
+ );
+ // React raises no beforeinput for a paste in every engine; cancelling the paste stops the typed path seeing it too.
+ const onPasteCapture = useCallback(
+ (event: ClipboardEvent<HTMLDivElement>) => takeOperator(event, event.clipboardData.getData('text')),
+ [takeOperator]
+ );
+ const onKeyDownCapture = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (!operatorRef.current) {
+ return;
+ }
+ const input = event.target as HTMLInputElement;
+ if (event.key === 'Escape' || (event.key === 'Backspace' && input.value === '')) {
+ event.preventDefault();
+ setOperatorState(null);
+ if (event.key === 'Escape') {
+ setDraftText(null);
+ }
+ }
+ },
+ [setDraftText, setOperatorState]
);
// The number input commits on blur and Enter only; a scrub ends with the mouse button, so the draft it produced is
// committed when the button lifts. The listener reads the ref: a release in the same frame as the last move must not
// commit a draft one step behind.
const onScrubStart = useCallback(() => {
scrubEnd.current?.();
+ if (operatorRef.current) {
+ setOperatorState(null);
+ setDraftText(null);
+ }
const scrub = new AbortController();
scrubEnd.current = () => scrub.abort();
window.addEventListener(
@@ -87,35 +161,57 @@ export const FormNumberField = ({
},
{ signal: scrub.signal }
);
- }, [onDraftCommit]);
+ }, [onDraftCommit, setDraftText, setOperatorState]);
useEffect(() => () => scrubEnd.current?.(), []);
const live = onValueChange !== undefined;
+ const prefix = operator ? OPERATOR_PREFIX[operator] : undefined;
+ const shownSuffix = operator === '%' ? '%' : suffix;
+ const startChars = (label?.length ?? 2) + (prefix ? 2 : 0);
return (
<NumberInput.Root
disabled={disabled}
flexShrink={0}
max={max}
- min={min}
+ // The bound applies to the result, so an operand such as `*0.5` is not clamped on blur.
+ min={operator ? undefined : min}
step={step}
value={live ? value : (draft ?? value)}
w={`${FORM_NUMBER_FIELD_WIDTH_PX}px`}
+ onBeforeInputCapture={relative && !live ? onBeforeInputCapture : undefined}
+ onKeyDownCapture={relative && !live ? onKeyDownCapture : undefined}
+ onPasteCapture={relative && !live ? onPasteCapture : undefined}
onValueChange={live ? onValueChange : onDraftChange}
onValueCommit={live ? undefined : onDraftCommit}
>
<InputGroup
- endElement={suffix ? <span aria-hidden>{suffix}</span> : undefined}
+ endElement={shownSuffix ? <span aria-hidden>{shownSuffix}</span> : undefined}
endElementProps={END_ELEMENT_PROPS}
- endOffset={suffix ? affixOffset(suffix.length) : undefined}
+ endOffset={shownSuffix ? affixOffset(shownSuffix.length) : undefined}
startElement={
- <NumberInput.Scrubber aria-hidden onMouseDownCapture={live ? undefined : onScrubStart}>
- {label ?? <Icon as={MoveHorizontalIcon} boxSize="3" />}
- </NumberInput.Scrubber>
+ <>
+ <NumberInput.Scrubber aria-hidden onMouseDownCapture={live ? undefined : onScrubStart}>
+ {label ?? <Icon as={MoveHorizontalIcon} boxSize="3" />}
+ </NumberInput.Scrubber>
+ {prefix ? (
+ <Box aria-hidden as="span" color="fg" ms="1">
+ {prefix}
+ </Box>
+ ) : null}
+ </>
}
startElementProps={START_ELEMENT_PROPS}
- startOffset={label ? affixOffset(label.length) : affixOffset(2)}
+ startOffset={affixOffset(startChars)}
>
- <NumberInput.Input aria-label={ariaLabel} fontVariantNumeric="tabular-nums" textAlign="end" />
+ <NumberInput.Input
+ aria-describedby={operator ? operatorDescriptionId : undefined}
+ aria-label={ariaLabel}
+ fontVariantNumeric="tabular-nums"
+ textAlign="end"
+ />
</InputGroup>
+ {operator ? (
+ <VisuallyHidden id={operatorDescriptionId}>{t(OPERATOR_DESCRIPTION_KEYS[operator])}</VisuallyHidden>
+ ) : null}
</NumberInput.Root>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx
index 2cf9191924..2e670a01db 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx
@@ -12,7 +12,7 @@ import { setPropertyGroupCollapsed, usePropertyGroupCollapsed } from './property
const GROUP_HEADER_HOVER = { color: 'fg' } as const;
/** A row label with a tooltip only while hovered and truncated, so rows at rest mount no portal. */
-const PropertyRowLabel = ({ label, labelId }: { label: string; labelId?: string }) => {
+export const PropertyRowLabel = ({ label, labelId }: { label: string; labelId?: string }) => {
const [isTipShown, setIsTipShown] = useState(false);
const showIfCut = useCallback((event: ReactPointerEvent<HTMLParagraphElement>) => {
const element = event.currentTarget;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.test.ts
new file mode 100644
index 0000000000..6913e77318
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseRelativeInput, resolveRelativeValue } from './relativeValue';
+
+describe('relative values', () => {
+ it('resolves operators typed or pasted against the current value, and refuses incomplete ones', () => {
+ const resolve = (text: string) => {
+ const parsed = parseRelativeInput(text);
+ return parsed && resolveRelativeValue(400, parsed.operator, Number.parseFloat(parsed.operand));
+ };
+ expect(resolve('50%')).toBe(200);
+ expect(resolve('*2')).toBe(800);
+ expect(resolve('÷4')).toBe(100);
+ expect(resolve('*')).toBeNull();
+ expect(resolve('%')).toBeNull();
+ expect(resolve('/0')).toBeNull();
+ expect(parseRelativeInput('120')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.ts
new file mode 100644
index 0000000000..edb99923d5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/relativeValue.ts
@@ -0,0 +1,25 @@
+export type RelativeOperator = '%' | '*' | '/';
+
+const OPERATOR_ALIASES: Record<string, RelativeOperator> = { '%': '%', '*': '*', '/': '/', '×': '*', '÷': '/' };
+
+export const parseRelativeInput = (text: string): { operator: RelativeOperator; operand: string } | null => {
+ const match = /^\s*([*/×÷])?\s*(-?\d*\.?\d*)\s*(%)?\s*$/.exec(text);
+ if (!match || (match[1] !== undefined) === (match[3] !== undefined)) {
+ return null;
+ }
+ return { operand: match[2]!, operator: OPERATOR_ALIASES[match[1] ?? match[3]!]! };
+};
+
+export const resolveRelativeValue = (current: number, operator: RelativeOperator, operand: number): number | null => {
+ if (!Number.isFinite(current) || !Number.isFinite(operand)) {
+ return null;
+ }
+ switch (operator) {
+ case '%':
+ return (current * operand) / 100;
+ case '*':
+ return current * operand;
+ case '/':
+ return operand === 0 ? null : current / operand;
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
index c77ae52184..4f61ec1806 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
@@ -9,6 +9,7 @@ import type {
CanvasLayerPreviewMutation,
CanvasDocumentModel,
DocumentRefusal,
+ FlipLayerResult,
LayerUnreadable,
MaskEditResult,
PrepareEditResult,
@@ -152,6 +153,23 @@ export const reportLayerOperation = (
typeof refusal === 'string' ? t(LAYER_OPERATION_KEYS[refusal]) : describeNamedRefusal(refusal, t)
);
+type FlipLayerRefusal = Extract<FlipLayerResult, { status: 'locked' | 'missing' | 'empty' }>;
+
+export const isFlipLayerRefusal = (result: FlipLayerResult): result is FlipLayerRefusal =>
+ result.status === 'locked' || result.status === 'missing' || result.status === 'empty';
+
+export const reportFlipLayer = (
+ result: FlipLayerResult,
+ reportError: (title: string, message: string) => void,
+ t: TFunction
+): void => {
+ if (isFlipLayerRefusal(result)) {
+ reportLayerOperation(result.status, reportError, t);
+ } else if (result.status !== 'previewed') {
+ reportStructuralCommit(result, reportError, t);
+ }
+};
+
/** Explains a refused mask clear or invert; `busy` and a mask with nothing to change stay silent. */
export const reportMaskEdit = (
result: MaskEditResult,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 38621e91b6..c143af82e6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -50,6 +50,7 @@ import {
import {
describeNamedRefusal,
reportLayerOperation,
+ reportFlipLayer,
usePreparedCommit,
} from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
@@ -58,6 +59,7 @@ import {
ArrowUpDownIcon,
ChevronRightIcon,
CopyIcon,
+ TrianglesCenterlineDashedVerticalIcon,
MergeIcon,
MoreVerticalIcon,
PaletteIcon,
@@ -608,6 +610,20 @@ const LayerMenu = ({
patchBase(getActionLabel('fit-to-bbox'), { transform });
}, [bbox, documentRect, getActionLabel, layer, makeStatusError, patchBase]);
+ const handleFlip = useCallback(
+ (direction: 'horizontal' | 'vertical') => {
+ if (!engine) {
+ throw makeStatusError('not-ready');
+ }
+ reportFlipLayer(
+ engine.layers.flipLayer(layer.id, direction, getActionLabel(`flip-${direction}`)),
+ notify.error,
+ t
+ );
+ },
+ [engine, getActionLabel, layer.id, makeStatusError, notify, t]
+ );
+
const handleSaveToBoard = useCallback(
async (board: LayerContextBoardChoice) => {
if (!engine) {
@@ -909,6 +925,7 @@ const LayerMenu = ({
extractMaskedArea: handleExtractMaskedArea,
group: handleGroup,
fitToBbox: handleFitToBbox,
+ flip: handleFlip,
mergeDown: handleMerge,
mergeMasks: handleMergeMasks,
mergeSelected: handleMergeSelected,
@@ -944,6 +961,7 @@ const LayerMenu = ({
handleDuplicate,
handleExtractMaskedArea,
handleFitToBbox,
+ handleFlip,
handleGroup,
handleMergeMasks,
handleMergeSelected,
@@ -1177,6 +1195,7 @@ const SUBMENU_META: Record<LayerContextSubmenuId, { defaultLabel: string; icon:
'color-label': { defaultLabel: 'Color label', icon: PaletteIcon, labelKey: 'widgets.layers.menu.colorLabel' },
'convert-to': { defaultLabel: 'Convert to', icon: ArrowRightLeftIcon, labelKey: 'widgets.layers.menu.convertTo' },
'copy-to': { defaultLabel: 'Copy to', icon: CopyIcon, labelKey: 'widgets.layers.menu.copyTo' },
+ flip: { defaultLabel: 'Flip', icon: TrianglesCenterlineDashedVerticalIcon, labelKey: 'widgets.layers.menu.flip' },
};
/** Runs a layer action, reporting its failure; a `picker: 'board'` action runs with the board picked for it. */
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 9928d8d899..5ebc79025a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -108,6 +108,7 @@ const makeEffects = (): LayerContextActionEffects => ({
duplicate: vi.fn(),
extractMaskedArea: vi.fn(() => Promise.resolve()),
fitToBbox: vi.fn(),
+ flip: vi.fn(),
group: vi.fn(),
mergeDown: vi.fn(() => Promise.resolve()),
mergeMasks: vi.fn(() => Promise.resolve()),
@@ -274,6 +275,8 @@ describe('getLayerContextActions', () => {
'rename',
'transform',
'fit-to-bbox',
+ 'flip-horizontal',
+ 'flip-vertical',
'add-brightness-contrast',
'add-exposure',
'add-levels',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index b026f4af78..c7a9653ba4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -12,6 +12,7 @@ import type { LucideIcon } from 'lucide-react';
import {
getDocumentIndex,
getSourceContentRect,
+ hittableLayerRect,
isGroupNode,
isEmptyPolygonShape,
isHideableLayer,
@@ -37,6 +38,8 @@ import {
DropletIcon,
EyeIcon,
FilmIcon,
+ TrianglesCenterlineDashedVerticalIcon,
+ TrianglesCenterlineDashedHorizontalIcon,
FingerprintPatternIcon,
FocusIcon,
EyeOffIcon,
@@ -95,6 +98,8 @@ export type LayerContextActionId =
| 'rename'
| 'transform'
| 'fit-to-bbox'
+ | 'flip-horizontal'
+ | 'flip-vertical'
| 'save-to-board'
| 'copy-to-clipboard'
| 'crop-to-bbox'
@@ -128,7 +133,14 @@ export type LayerContextActionId =
export type LayerType = CanvasLayerContract['type'];
export type LayerContextMenuSectionId = 'quick' | 'primary' | 'operations' | 'output' | 'state' | 'danger';
-export type LayerContextSubmenuId = 'arrange' | 'boolean' | 'copy-to' | 'convert-to' | 'add-adjustment' | 'color-label';
+export type LayerContextSubmenuId =
+ | 'arrange'
+ | 'boolean'
+ | 'copy-to'
+ | 'convert-to'
+ | 'add-adjustment'
+ | 'color-label'
+ | 'flip';
export interface LayerContextActionState {
canRunWorkflow: boolean;
@@ -173,6 +185,7 @@ export interface LayerContextActionEffects {
startFilter(layerId: string): void;
transform(): void;
fitToBbox(): void;
+ flip(direction: 'horizontal' | 'vertical'): void;
openProperties(): void;
saveToBoard(board: LayerContextBoardChoice): Promise<void>;
copyToClipboard(): Promise<void>;
@@ -646,6 +659,19 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'primary',
supportedLayerTypes: ALL_LAYER_TYPES,
},
+ ...(['horizontal', 'vertical'] as const).map((direction, index): LayerContextActionDefinition => ({
+ defaultLabel: direction === 'horizontal' ? 'Flip horizontal' : 'Flip vertical',
+ handler: ({ effects }) => effects.flip(direction),
+ icon: direction === 'horizontal' ? TrianglesCenterlineDashedVerticalIcon : TrianglesCenterlineDashedHorizontalIcon,
+ id: `flip-${direction}`,
+ isEnabled: (context) => isLayerMutable(context) && hittableLayerRect(context.layer, context.document) !== null,
+ isVisible: alwaysVisible,
+ labelKey: direction === 'horizontal' ? 'widgets.transform.flipHorizontal' : 'widgets.transform.flipVertical',
+ order: 30.1 + index * 0.01,
+ section: 'primary',
+ submenu: 'flip',
+ supportedLayerTypes: ['raster', 'control', 'vector', 'inpaint_mask', 'regional_guidance'],
+ })),
...ADJUSTMENT_ADD_ITEMS.map((item, index): LayerContextActionDefinition => ({
defaultLabel: item.defaultLabel,
handler: ({ effects }) => effects.addAdjustment(item.type),
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 52a72ec4cc..69111e6166 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -87,6 +87,7 @@ describe('getLayerContextMenuLayout', () => {
'transform',
'rename',
'fit-to-bbox',
+ 'flip(flip-horizontal,flip-vertical)',
'add-adjustment(add-brightness-contrast,add-exposure,add-levels,add-curves,add-hsl,add-hue,add-invert,add-texture,add-clarity,add-dehaze,add-noise-adjustment)',
'add-regenerate-region',
'filter',
@@ -127,12 +128,27 @@ describe('getLayerContextMenuLayout', () => {
expect(summarize(inpaint)[1]).toEqual({
id: 'primary',
- items: ['transform', 'rename', 'fit-to-bbox', 'add-noise', 'add-denoise-limit', 'extract-masked-area'],
+ items: [
+ 'transform',
+ 'rename',
+ 'fit-to-bbox',
+ 'flip(flip-horizontal,flip-vertical)',
+ 'add-noise',
+ 'add-denoise-limit',
+ 'extract-masked-area',
+ ],
presentation: 'list',
});
expect(summarize(regional)[1]).toEqual({
id: 'primary',
- items: ['transform', 'rename', 'fit-to-bbox', 'regional-auto-negative', 'add-reference-image'],
+ items: [
+ 'transform',
+ 'rename',
+ 'fit-to-bbox',
+ 'flip(flip-horizontal,flip-vertical)',
+ 'regional-auto-negative',
+ 'add-reference-image',
+ ],
presentation: 'list',
});
});
@@ -145,7 +161,15 @@ describe('getLayerContextMenuLayout', () => {
expect(summarize(control)[1]).toEqual({
id: 'primary',
- items: ['transform', 'rename', 'fit-to-bbox', 'select-object', 'run-workflow', 'control-transparency-effect'],
+ items: [
+ 'transform',
+ 'rename',
+ 'fit-to-bbox',
+ 'flip(flip-horizontal,flip-vertical)',
+ 'select-object',
+ 'run-workflow',
+ 'control-transparency-effect',
+ ],
presentation: 'list',
});
expect(summarize(control)[2]).toEqual({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index 9acae298cd..2e833c9f0a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -683,33 +683,30 @@ describe('Transform tool options', () => {
expect(labels, `one visible ${text} label, without a duplicate heading`).toHaveLength(1);
return labels[0]!;
};
- const position = visibleLabel('Position');
- const scale = visibleLabel('Scale');
- const rotation = visibleLabel('Rotation');
+ const rows = ['Position', 'Size', 'Rotation'].map(visibleLabel);
const resample = visibleLabel('Resample Mode');
- const x = page.getByRole('spinbutton', { exact: true, name: 'X' }).element().getBoundingClientRect();
- const w = page.getByRole('spinbutton', { exact: true, name: 'W %' }).element().getBoundingClientRect();
- const angle = page.getByRole('spinbutton', { exact: true, name: 'Rotation' }).element().getBoundingClientRect();
- expect(Math.abs(x.left - w.left)).toBeLessThan(1);
- expect(Math.abs(x.left - angle.left)).toBeLessThan(1);
+ const fields = ['X', 'W', 'Rotation'].map((name) =>
+ page.getByRole('spinbutton', { exact: true, name }).element().getBoundingClientRect()
+ );
const centerY = (rect: DOMRect) => rect.top + rect.height / 2;
- expect(Math.abs(centerY(position.getBoundingClientRect()) - centerY(x))).toBeLessThan(1);
- expect(Math.abs(centerY(scale.getBoundingClientRect()) - centerY(w))).toBeLessThan(1);
- expect(Math.abs(centerY(rotation.getBoundingClientRect()) - centerY(angle))).toBeLessThan(1);
- const positionRow = position.parentElement!.getBoundingClientRect();
- const scaleRow = scale.parentElement!.getBoundingClientRect();
- const rotationRow = rotation.parentElement!.getBoundingClientRect();
- const positionToScale = scaleRow.top - positionRow.bottom;
- const scaleToRotation = rotationRow.top - scaleRow.bottom;
- expect(positionToScale).toBeGreaterThan(0);
- expect(
- Math.abs(positionToScale - scaleToRotation),
- 'equal space between the actual geometry row edges'
- ).toBeLessThan(1);
+ fields.forEach((field, index) => {
+ expect(Math.abs(field.left - fields[0]!.left)).toBeLessThan(1);
+ expect(Math.abs(centerY(rows[index]!.getBoundingClientRect()) - centerY(field))).toBeLessThan(1);
+ });
+ const gaps = fields.slice(1).map((rect, index) => rect.top - fields[index]!.bottom);
+ expect(gaps[0]).toBeGreaterThan(0);
+ for (const gap of gaps) {
+ expect(Math.abs(gap - gaps[0]!), 'equal space between the geometry rows').toBeLessThan(1);
+ }
expect(resample.scrollWidth).toBeLessThanOrEqual(resample.clientWidth);
- expect(
- page.getByRole('spinbutton', { exact: true, name: 'Y' }).element().getBoundingClientRect().right
- ).toBeLessThanOrEqual(tool.getBoundingClientRect().right);
+ const right = tool.getBoundingClientRect().right;
+ const rightEdges = [
+ ...['Y', 'H'].map((name) => page.getByRole('spinbutton', { exact: true, name })),
+ ...[/^Reference point/, /aspect ratio$/, /^Flip vertical$/].map((name) => page.getByRole('button', { name })),
+ ].map((control) => control.element().getBoundingClientRect().right);
+ for (const edge of rightEdges) {
+ expect(edge).toBeLessThanOrEqual(right);
+ }
});
it('places resampling above Position in the actual tool form and edits the active session', async () => {
@@ -734,7 +731,7 @@ describe('Transform tool options', () => {
await userEvent.fill(tool.getByRole('spinbutton', { exact: true, name: 'X' }), '40');
await userEvent.keyboard('{Enter}');
});
- expect(engine!.interaction.get('transformSession')).toMatchObject({ layerId: 'l0', transform: { x: 40 } });
+ expect(engine!.interaction.get('transformSession')).toMatchObject({ layerId: 'l0', transform: { x: 8, y: 0 } });
expect(direct).not.toHaveBeenCalled();
await act(() => userEvent.click(tool.getByRole('button', { name: 'Fit to Frame', exact: true })));
expect(engine!.interaction.get('transformSession')).toMatchObject({
@@ -768,7 +765,7 @@ describe('Transform tool options', () => {
engine!.stores.transformSession.set({ ...engine!.interaction.get('transformSession')!, processing: true })
);
await expect.element(page.getByRole('spinbutton', { exact: true, name: 'X' })).toBeDisabled();
- await expect.element(page.getByRole('spinbutton', { exact: true, name: 'W %' })).toBeDisabled();
+ await expect.element(page.getByRole('spinbutton', { exact: true, name: 'W' })).toBeDisabled();
await expect.element(page.getByRole('button', { exact: true, name: 'Fit to Frame' })).toBeDisabled();
await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeDisabled();
await expect.element(page.getByRole('button', { exact: true, name: 'Cancel' })).toBeEnabled();
@@ -799,6 +796,68 @@ describe('Transform tool options', () => {
});
describe('Transform pane', () => {
+ it('sizes by expression with the aspect link, reads X and Y at the reference point, and flips in place', async () => {
+ await mount(TransformPane, 'layer');
+ harness.appliesMutations = true;
+ await act(() => {
+ harness.project = applyCanvasProjectMutation(harness.project!, {
+ type: 'updateCanvasLayerSource',
+ id: 'l0',
+ source: { type: 'paint', bitmap: { imageName: 'test.png', width: 100, height: 50 } },
+ });
+ harness.listeners.forEach((listener) => listener());
+ });
+ const width = page.getByRole('spinbutton', { exact: true, name: 'W' });
+ const height = page.getByRole('spinbutton', { exact: true, name: 'H' });
+ const x = page.getByRole('spinbutton', { exact: true, name: 'X' });
+ const y = page.getByRole('spinbutton', { exact: true, name: 'Y' });
+ const typeInto = (field: typeof width, text: string) =>
+ act(async () => {
+ await userEvent.tripleClick(field);
+ await userEvent.keyboard(`${text}{Enter}`);
+ });
+ await expect.element(height).toHaveValue('50');
+ await expect.element(x).toHaveValue('42.29');
+ await expect.element(y).toHaveValue('45.91');
+
+ await typeInto(width, '50%');
+ await expect.element(width).toHaveValue('50');
+ await expect.element(height).toHaveValue('25');
+ await typeInto(height, '*4');
+ await expect.element(height).toHaveValue('100');
+ await expect.element(width).toHaveValue('200');
+ const layer = () => getDocumentLayer(engine!.document.getDocument()!, 'l0')!;
+ expect(layer().transform).toMatchObject({ rotation: 0.5, scaleX: 2, scaleY: 2 });
+ expect(engine!.history.getEntries().past).toEqual(['Transform layer', 'Transform layer']);
+ const { x: originX, y: originY } = layer().transform;
+ const centre = (t: { rotation: number; scaleX: number; scaleY: number; x: number; y: number }) => ({
+ x: t.x + Math.cos(t.rotation) * 50 * t.scaleX - Math.sin(t.rotation) * 25 * t.scaleY,
+ y: t.y + Math.sin(t.rotation) * 50 * t.scaleX + Math.cos(t.rotation) * 25 * t.scaleY,
+ });
+ expect(centre(layer().transform).x).toBeCloseTo(42.2935, 3);
+ expect(centre(layer().transform).y).toBeCloseTo(45.9109, 3);
+ await expect.element(x).toHaveValue('42.29');
+ await expect.element(y).toHaveValue('45.91');
+
+ await act(() => userEvent.click(page.getByRole('button', { name: 'Reference point: Center' })));
+ await act(() => userEvent.click(page.getByRole('radio', { name: 'Top left' })));
+ await expect.element(x).toHaveValue(String(Math.round(originX * 100) / 100));
+ await expect.element(y).toHaveValue(String(Math.round(originY * 100) / 100));
+
+ await act(() => userEvent.click(page.getByRole('button', { name: 'Flip horizontal' })));
+ expect(layer().transform).toMatchObject({ rotation: -0.5, scaleX: -2, scaleY: 2 });
+
+ await act(async () => {
+ await userEvent.tripleClick(width);
+ const clipboardData = new DataTransfer();
+ clipboardData.setData('text', '50%');
+ width.element().dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }));
+ });
+ await expect.element(width).toHaveValue('50');
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.element(width).toHaveValue('100');
+ });
+
it('keeps resampling controls in the tool options rather than layer properties', async () => {
await mount(TransformPane, 'layer');
expect(page.getByRole('checkbox', { name: 'Smoothing' }).query()).toBeNull();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx
index ef2115b934..662b388484 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/TransformPane.tsx
@@ -1,15 +1,10 @@
-import type { LayerTransform } from '@workbench/canvas-engine/api';
-
import { Flex, Stack, Text } from '@chakra-ui/react';
import { Button } from '@platform/ui/Button';
import { Scrollable } from '@platform/ui/Scrollable';
import { getDocumentNode, lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';
import { useCanvasHasFloatingSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';
-import { clampScalePercent, round2, wrapDegrees } from '@workbench/widgets/canvas/tool-options/geometryForm';
-import { FormNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/FormControls';
-import { PropertyControlRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';
-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { LayerPositionRow, LayerTransformRows } from '@workbench/widgets/canvas/tool-options/layerTransformFields';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,18 +12,13 @@ import { useTranslation } from 'react-i18next';
import { GroupSelectedNotice } from './GroupSelectedNotice';
import { PropertiesSection } from './PropertiesSection';
-const RAD_TO_DEG = 180 / Math.PI;
-const DEG_TO_RAD = Math.PI / 180;
-
interface SelectedNode {
id: string;
isGroup: boolean;
- locked: boolean;
name: string;
- transform: LayerTransform | null;
}
-/** Each field commits one patch; a Transform session or floating selection routes them to its Apply / Cancel. */
+/** Each field commits one patch; a Transform session absorbs them until its Apply / Cancel. */
export const TransformPane = () => {
const { t } = useTranslation();
const engine = useCanvasEngine();
@@ -49,7 +39,6 @@ export const TransformPane = () => {
const ConnectedTransform = ({ engine }: { engine: CanvasEngineHandle }) => {
const { t } = useTranslation();
- const commitPrepared = usePreparedCommit(engine);
const session = useTransformSession(engine);
const hasFloat = useCanvasHasFloatingSelection(engine);
const selected = useActiveProjectSelector(
@@ -57,57 +46,17 @@ const ConnectedTransform = ({ engine }: { engine: CanvasEngineHandle }) => {
const { document } = project.canvas;
const node = getDocumentNode(document, document.selectedLayerId);
if (node?.type === 'group') {
- return { id: node.id, isGroup: true, locked: true, name: node.name, transform: null };
+ return { id: node.id, isGroup: true, name: node.name };
}
const leaf = node ? lookupDocumentLeaf(document, node.id) : null;
- return leaf
- ? {
- id: leaf.id,
- isGroup: false,
- locked: leaf.effectiveLocked,
- name: leaf.layer.name,
- transform: leaf.layer.transform,
- }
- : null;
+ return leaf ? { id: leaf.id, isGroup: false, name: leaf.layer.name } : null;
},
- (a, b) => a?.id === b?.id && a?.locked === b?.locked && a?.name === b?.name && a?.transform === b?.transform
+ (a, b) => a?.id === b?.id && a?.isGroup === b?.isGroup && a?.name === b?.name
);
-
- const transform = session?.transform ?? selected?.transform ?? null;
const processing = session?.processing ?? false;
- const editable = !processing && (session !== null || (selected !== null && !selected.locked));
- const patch = useCallback(
- (next: Partial<LayerTransform>) => {
- if (session) {
- engine.layers.updateTransformSession({ ...session.transform, ...next });
- return;
- }
- if (!selected || selected.locked) {
- return;
- }
- commitPrepared(t('widgets.transform.edit'), (model) =>
- model.prepare({ id: selected.id, patch: { transform: next }, type: 'patch' })
- );
- },
- [commitPrepared, engine, selected, session, t]
- );
- const onX = useNumberCommit(useCallback((value: number) => patch({ x: Math.round(value) }), [patch]));
- const onY = useNumberCommit(useCallback((value: number) => patch({ y: Math.round(value) }), [patch]));
- const onScaleX = useNumberCommit(
- useCallback((value: number) => patch({ scaleX: clampScalePercent(value) / 100 }), [patch])
- );
- const onScaleY = useNumberCommit(
- useCallback((value: number) => patch({ scaleY: clampScalePercent(value) / 100 }), [patch])
- );
- const onRotation = useNumberCommit(
- useCallback((value: number) => patch({ rotation: wrapDegrees(value) * DEG_TO_RAD }), [patch])
- );
const onApply = useCallback(() => engine.layers.applyTransform(), [engine]);
const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);
const pending = session !== null || hasFloat;
- const field = (props: Omit<Parameters<typeof FormNumberField>[0], 'disabled'>) => (
- <FormNumberField {...props} disabled={!editable} />
- );
return (
<Stack gap="0">
@@ -118,48 +67,8 @@ const ConnectedTransform = ({ engine }: { engine: CanvasEngineHandle }) => {
title={t('widgets.transform.title')}
>
{selected?.isGroup && !session ? <GroupSelectedNotice hint={t('widgets.transform.groupSelected')} /> : null}
- <PropertyControlRow label={t('widgets.transform.position')}>
- <Flex gap="2" gridColumn="2 / -1">
- {field({
- 'aria-label': t('widgets.canvas.toolOptions.positionX'),
- label: t('widgets.canvas.toolOptions.positionX'),
- value: transform ? String(Math.round(transform.x)) : '',
- onValueCommit: onX,
- })}
- {field({
- 'aria-label': t('widgets.canvas.toolOptions.positionY'),
- label: t('widgets.canvas.toolOptions.positionY'),
- value: transform ? String(Math.round(transform.y)) : '',
- onValueCommit: onY,
- })}
- </Flex>
- </PropertyControlRow>
- <PropertyControlRow label={t('widgets.transform.scale')}>
- <Flex gap="2" gridColumn="2 / -1">
- {field({
- 'aria-label': t('widgets.canvas.toolOptions.scaleWidth'),
- label: t('widgets.canvas.toolOptions.frameWidth'),
- suffix: '%',
- value: transform ? String(round2(transform.scaleX * 100)) : '',
- onValueCommit: onScaleX,
- })}
- {field({
- 'aria-label': t('widgets.canvas.toolOptions.scaleHeight'),
- label: t('widgets.canvas.toolOptions.frameHeight'),
- suffix: '%',
- value: transform ? String(round2(transform.scaleY * 100)) : '',
- onValueCommit: onScaleY,
- })}
- </Flex>
- </PropertyControlRow>
- <PropertyControlRow label={t('widgets.transform.rotation')}>
- {field({
- 'aria-label': t('widgets.canvas.toolOptions.rotation'),
- suffix: '°',
- value: transform ? String(round2(wrapDegrees(transform.rotation * RAD_TO_DEG))) : '',
- onValueCommit: onRotation,
- })}
- </PropertyControlRow>
+ <LayerPositionRow engine={engine} showLabel />
+ <LayerTransformRows engine={engine} />
{pending ? (
<Flex gap="2" justify="flex-end">
<Button variant="ghost" onClick={onCancel}>